Compare commits
1 Commits
master
...
120d7c1d25
Author | SHA1 | Date | |
---|---|---|---|
120d7c1d25 |
21
.github/workflows/windows.yml
vendored
21
.github/workflows/windows.yml
vendored
@ -8,7 +8,7 @@ jobs:
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
- qt_ver: '6.9.1'
|
||||
- qt_ver: '6.8.0'
|
||||
vs: '2022'
|
||||
aqt_arch: 'win64_msvc2022_64'
|
||||
msvc_arch: 'x64'
|
||||
@ -35,31 +35,22 @@ jobs:
|
||||
:: ------ dep ------
|
||||
set CMAKE_PREFIX_PATH=%PWD%/dependencies_bin
|
||||
mkdir dependencies_src
|
||||
echo ::group::===== ECM =====
|
||||
:: ===== ECM =====
|
||||
git clone -q https://invent.kde.org/frameworks/extra-cmake-modules.git dependencies_src/extra-cmake-modules
|
||||
cmake .\dependencies_src\extra-cmake-modules -Bbuild_dependencies/extra-cmake-modules -DCMAKE_INSTALL_PREFIX="dependencies_bin" -DBUILD_TESTING=OFF || goto :error
|
||||
cmake --build build_dependencies/extra-cmake-modules --config Release --target=install || goto :error
|
||||
echo ::endgroup::
|
||||
echo ::group::===== FFmpeg =====
|
||||
curl -fsSL -o ffmpeg-shared.7z https://github.com/GyanD/codexffmpeg/releases/download/7.1.1/ffmpeg-7.1.1-full_build-shared.7z
|
||||
7z x ffmpeg-shared.7z -y -o"dependencies_src"
|
||||
set FFMPEG_ROOT=%PWD%\dependencies_src\ffmpeg-7.1.1-full_build-shared
|
||||
echo ::endgroup::
|
||||
echo ::group::===== Gperf (required by KCodecs) =====
|
||||
:: ===== Gperf (required by KCodecs) =====
|
||||
choco install gperf
|
||||
echo ::endgroup::
|
||||
echo ::group::===== KCodecs =====
|
||||
:: ===== KCodecs =====
|
||||
git clone -q https://invent.kde.org/frameworks/kcodecs.git dependencies_src/kcodecs
|
||||
cmake .\dependencies_src\kcodecs -Bbuild_dependencies/kcodecs -DCMAKE_INSTALL_PREFIX="dependencies_bin" -DBUILD_TESTING=OFF || goto :error
|
||||
cmake --build build_dependencies/kcodecs --config Release --target=install || goto :error
|
||||
echo ::endgroup::
|
||||
echo ::group::===== taglib =====
|
||||
:: ===== taglib =====
|
||||
git clone --recurse-submodules -q https://github.com/taglib/taglib.git dependencies_src/taglib
|
||||
cmake .\dependencies_src\taglib -Bbuild_dependencies/taglib -DBUILD_SHARED_LIBS=ON -DCMAKE_INSTALL_PREFIX="dependencies_bin" || goto :error
|
||||
cmake --build build_dependencies/taglib --config Release --target=install -j || goto :error
|
||||
echo ::endgroup::
|
||||
:: ------ app ------
|
||||
cmake -Bbuild . -DUSE_QTEXTCODEC=ON -DCMAKE_INSTALL_PREFIX='%PWD%\build\' || goto :error
|
||||
cmake -Bbuild . -DUSE_QTEXTCODEC=ON -DCMAKE_INSTALL_PREFIX="%PWD%\build\" || goto :error
|
||||
cmake --build build --config Release -j || goto :error
|
||||
cmake --build build --config Release --target=install || goto :error
|
||||
:: ------ pkg ------
|
||||
|
5
.gitignore
vendored
5
.gitignore
vendored
@ -1,13 +1,8 @@
|
||||
# Common build folder
|
||||
[Bb]uild/
|
||||
build-*/
|
||||
|
||||
# IDE folder
|
||||
.vscode/
|
||||
.idea/
|
||||
|
||||
# User config file
|
||||
CMakeLists.txt.user*
|
||||
|
||||
# Why, macOS, why?
|
||||
.DS_Store
|
||||
|
288
CMakeLists.txt
288
CMakeLists.txt
@ -1,166 +1,138 @@
|
||||
cmake_minimum_required(VERSION 3.12)
|
||||
|
||||
project(pineapple-music LANGUAGES CXX VERSION 0.3.0)
|
||||
|
||||
include (GNUInstallDirs)
|
||||
cmake_minimum_required(VERSION 3.12)
|
||||
|
||||
project(pineapple-music LANGUAGES CXX)
|
||||
|
||||
include (GNUInstallDirs)
|
||||
include (FeatureSummary)
|
||||
include (FetchContent)
|
||||
|
||||
set(CMAKE_INCLUDE_CURRENT_DIR ON)
|
||||
|
||||
set(CMAKE_AUTOUIC ON)
|
||||
set(CMAKE_AUTOMOC ON)
|
||||
set(CMAKE_AUTORCC ON)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
|
||||
option(USE_QTEXTCODEC "Use QTextCodec instead of QStringConverter, in case Qt is not built with ICU" OFF)
|
||||
|
||||
find_package(Qt6 6.6 COMPONENTS Widgets Multimedia Network LinguistTools REQUIRED)
|
||||
find_package(FFmpeg COMPONENTS avutil avformat)
|
||||
find_package(TagLib 2.0.0)
|
||||
include(FetchContent)
|
||||
|
||||
set(CMAKE_INCLUDE_CURRENT_DIR ON)
|
||||
|
||||
set(CMAKE_AUTOUIC ON)
|
||||
set(CMAKE_AUTOMOC ON)
|
||||
set(CMAKE_AUTORCC ON)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
|
||||
option(USE_QTEXTCODEC "Use QTextCodec instead of QStringConverter, in case Qt is not built with ICU" OFF)
|
||||
|
||||
find_package(Qt6 6.6 COMPONENTS Widgets Multimedia Network LinguistTools REQUIRED)
|
||||
find_package(TagLib 2.0.0)
|
||||
find_package(KF6Codecs 6.1.0)
|
||||
|
||||
FetchContent_Declare(
|
||||
kissfft
|
||||
GIT_REPOSITORY https://github.com/mborgerding/kissfft.git
|
||||
GIT_TAG f5f2a3b2f2cd02bf80639adb12cbeed125bdf420
|
||||
|
||||
FetchContent_Declare(
|
||||
kissfft
|
||||
GIT_REPOSITORY https://github.com/mborgerding/kissfft.git
|
||||
GIT_TAG f5f2a3b2f2cd02bf80639adb12cbeed125bdf420
|
||||
)
|
||||
set(KISSFFT_PKGCONFIG OFF CACHE BOOL "dep(kissfft): pkgconfig support")
|
||||
set(KISSFFT_STATIC ON CACHE BOOL "dep(kissfft): static linking")
|
||||
set(KISSFFT_TEST OFF CACHE BOOL "dep(kissfft): enable testing")
|
||||
set(KISSFFT_TOOLS OFF CACHE BOOL "dep(kissfft): build tools")
|
||||
FetchContent_MakeAvailable(kissfft)
|
||||
|
||||
if (USE_QTEXTCODEC)
|
||||
find_package(Qt6 6.6 COMPONENTS Core5Compat REQUIRED)
|
||||
endif()
|
||||
|
||||
set (PMUSIC_CPP_FILES
|
||||
main.cpp
|
||||
mainwindow.cpp
|
||||
seekableslider.cpp
|
||||
playlistmanager.cpp
|
||||
singleapplicationmanager.cpp
|
||||
lrcbar.cpp
|
||||
set(KISSFFT_TOOLS OFF CACHE BOOL "dep(kissfft): build tools")
|
||||
FetchContent_MakeAvailable(kissfft)
|
||||
|
||||
if (USE_QTEXTCODEC)
|
||||
find_package(Qt6 6.6 COMPONENTS Core5Compat REQUIRED)
|
||||
endif()
|
||||
|
||||
set (PMUSIC_CPP_FILES
|
||||
main.cpp
|
||||
mainwindow.cpp
|
||||
seekableslider.cpp
|
||||
playlistmanager.cpp
|
||||
singleapplicationmanager.cpp
|
||||
lrcbar.cpp
|
||||
lyricsmanager.cpp
|
||||
fftspectrum.cpp
|
||||
playbackprogressindicator.cpp
|
||||
)
|
||||
|
||||
set (PMUSIC_HEADER_FILES
|
||||
mainwindow.h
|
||||
seekableslider.h
|
||||
playlistmanager.h
|
||||
singleapplicationmanager.h
|
||||
lrcbar.h
|
||||
fftspectrum.cpp
|
||||
)
|
||||
|
||||
set (PMUSIC_HEADER_FILES
|
||||
mainwindow.h
|
||||
seekableslider.h
|
||||
playlistmanager.h
|
||||
singleapplicationmanager.h
|
||||
lrcbar.h
|
||||
lyricsmanager.h
|
||||
fftspectrum.h
|
||||
playbackprogressindicator.h
|
||||
taskbarmanager.h
|
||||
)
|
||||
|
||||
set (PMUSIC_UI_FILES
|
||||
mainwindow.ui
|
||||
)
|
||||
|
||||
set (EXE_NAME pmusic)
|
||||
|
||||
# Translation
|
||||
file (GLOB PMUSIC_TS_FILES languages/*.ts)
|
||||
set (PMUSIC_CPP_FILES_FOR_I18N ${PMUSIC_CPP_FILES} ${PMUSIC_UI_FILES})
|
||||
|
||||
add_executable(${EXE_NAME}
|
||||
${PMUSIC_HEADER_FILES}
|
||||
${PMUSIC_CPP_FILES}
|
||||
${PMUSIC_UI_FILES}
|
||||
resources.qrc
|
||||
)
|
||||
|
||||
qt_add_translations(${EXE_NAME}
|
||||
TS_FILES
|
||||
${PMUSIC_TS_FILES}
|
||||
)
|
||||
|
||||
if (WIN32)
|
||||
target_sources(${EXE_NAME} PRIVATE assets/pineapple-music.rc)
|
||||
target_sources(${EXE_NAME} PRIVATE taskbarmanager.cpp)
|
||||
else ()
|
||||
target_sources(${EXE_NAME} PRIVATE taskbarmanager_dummy.cpp)
|
||||
endif ()
|
||||
|
||||
if (NOT TagLib_FOUND)
|
||||
target_compile_definitions(${EXE_NAME} PRIVATE NO_TAGLIB=1)
|
||||
else ()
|
||||
target_link_libraries(${EXE_NAME} PRIVATE TagLib::tag)
|
||||
endif ()
|
||||
|
||||
if (TARGET KF6::Codecs)
|
||||
target_compile_definitions(${EXE_NAME} PRIVATE HAVE_KCODECS=1)
|
||||
target_link_libraries (${EXE_NAME} PRIVATE KF6::Codecs)
|
||||
endif ()
|
||||
|
||||
if (FFmpeg_FOUND)
|
||||
target_compile_definitions(${EXE_NAME} PRIVATE HAVE_FFMPEG=1)
|
||||
target_link_libraries (${EXE_NAME} PRIVATE FFmpeg::avutil FFmpeg::avformat)
|
||||
endif ()
|
||||
|
||||
target_link_libraries(${EXE_NAME} PRIVATE Qt::Widgets Qt::Multimedia Qt::Network kissfft::kissfft)
|
||||
|
||||
if (USE_QTEXTCODEC)
|
||||
target_compile_definitions(${EXE_NAME} PRIVATE USE_QTEXTCODEC=1)
|
||||
target_link_libraries(${EXE_NAME} PRIVATE Qt6::Core5Compat)
|
||||
endif()
|
||||
|
||||
# Install settings
|
||||
if (WIN32)
|
||||
set_target_properties(${EXE_NAME} PROPERTIES
|
||||
WIN32_EXECUTABLE TRUE
|
||||
)
|
||||
elseif (APPLE)
|
||||
set_source_files_properties(assets/icons/app-icon.icns PROPERTIES
|
||||
MACOSX_PACKAGE_LOCATION "Resources"
|
||||
)
|
||||
target_sources(${EXE_NAME} PUBLIC assets/icons/app-icon.icns)
|
||||
# See https://cmake.org/cmake/help/v3.15/prop_tgt/MACOSX_BUNDLE_INFO_PLIST.html
|
||||
set_target_properties(${EXE_NAME} PROPERTIES
|
||||
MACOSX_BUNDLE TRUE
|
||||
MACOSX_BUNDLE_BUNDLE_NAME "Pineapple Music"
|
||||
MACOSX_BUNDLE_GUI_IDENTIFIER net.blumia.pineapple-music
|
||||
MACOSX_BUNDLE_ICON_FILE app-icon.icns # contains the .icns file name, *without* the path.
|
||||
MACOSX_BUNDLE_BUNDLE_VERSION ${PROJECT_VERSION}
|
||||
MACOSX_BUNDLE_SHORT_VERSION_STRING ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}
|
||||
)
|
||||
elseif (UNIX)
|
||||
if (CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
|
||||
set(CMAKE_INSTALL_PREFIX /usr)
|
||||
endif ()
|
||||
|
||||
# install icon
|
||||
install(
|
||||
FILES icons/app-icon.svg
|
||||
DESTINATION "${CMAKE_INSTALL_DATADIR}/icons/hicolor/48x48/apps"
|
||||
RENAME net.blumia.pineapple-music.svg
|
||||
)
|
||||
|
||||
# install shortcut
|
||||
install(
|
||||
FILES dist/net.blumia.pineapple-music.desktop
|
||||
DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/applications"
|
||||
)
|
||||
endif()
|
||||
|
||||
set (INSTALL_TARGETS_DEFAULT_ARGS
|
||||
BUNDLE DESTINATION .
|
||||
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
|
||||
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT Devel
|
||||
)
|
||||
|
||||
install (
|
||||
TARGETS ${EXE_NAME}
|
||||
${INSTALL_TARGETS_DEFAULT_ARGS}
|
||||
)
|
||||
|
||||
feature_summary(WHAT ALL INCLUDE_QUIET_PACKAGES FATAL_ON_MISSING_REQUIRED_PACKAGES)
|
||||
fftspectrum.h
|
||||
)
|
||||
|
||||
set (PMUSIC_UI_FILES
|
||||
mainwindow.ui
|
||||
)
|
||||
|
||||
set (EXE_NAME pmusic)
|
||||
|
||||
# Translation
|
||||
file (GLOB PMUSIC_TS_FILES languages/*.ts)
|
||||
set (PMUSIC_CPP_FILES_FOR_I18N ${PMUSIC_CPP_FILES} ${PMUSIC_UI_FILES})
|
||||
|
||||
add_executable(${EXE_NAME} WIN32
|
||||
${PMUSIC_HEADER_FILES}
|
||||
${PMUSIC_CPP_FILES}
|
||||
${PMUSIC_UI_FILES}
|
||||
resources.qrc
|
||||
)
|
||||
|
||||
qt_add_translations(${EXE_NAME}
|
||||
TS_FILES
|
||||
${PMUSIC_TS_FILES}
|
||||
)
|
||||
|
||||
if (WIN32)
|
||||
target_sources(${EXE_NAME} PRIVATE assets/pineapple-music.rc)
|
||||
endif ()
|
||||
|
||||
if (NOT TagLib_FOUND)
|
||||
target_compile_definitions(${EXE_NAME} PRIVATE NO_TAGLIB=1)
|
||||
else ()
|
||||
target_link_libraries(${EXE_NAME} PRIVATE TagLib::tag)
|
||||
endif ()
|
||||
|
||||
if (TARGET KF6::Codecs)
|
||||
target_compile_definitions(${EXE_NAME} PRIVATE HAVE_KCODECS=1)
|
||||
target_link_libraries (${EXE_NAME} PRIVATE KF6::Codecs)
|
||||
endif ()
|
||||
|
||||
target_link_libraries(${EXE_NAME} PRIVATE Qt::Widgets Qt::Multimedia Qt::Network kissfft::kissfft)
|
||||
|
||||
if (USE_QTEXTCODEC)
|
||||
target_compile_definitions(${EXE_NAME} PRIVATE USE_QTEXTCODEC=1)
|
||||
target_link_libraries(${EXE_NAME} PRIVATE Qt6::Core5Compat)
|
||||
endif()
|
||||
|
||||
# Install settings
|
||||
if (WIN32)
|
||||
# FIXME: try to avoid install to a "bin" subfolder under windows...
|
||||
# when fixed, don't forget to update the CI config file...
|
||||
elseif (UNIX)
|
||||
if (CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
|
||||
set(CMAKE_INSTALL_PREFIX /usr)
|
||||
endif ()
|
||||
|
||||
# install icon
|
||||
install(
|
||||
FILES icons/app-icon.svg
|
||||
DESTINATION "${CMAKE_INSTALL_DATADIR}/icons/hicolor/48x48/apps"
|
||||
RENAME net.blumia.pineapple-music.svg
|
||||
)
|
||||
|
||||
# install shortcut
|
||||
install(
|
||||
FILES dist/net.blumia.pineapple-music.desktop
|
||||
DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/applications"
|
||||
)
|
||||
endif()
|
||||
|
||||
set (INSTALL_TARGETS_DEFAULT_ARGS
|
||||
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
|
||||
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT Devel
|
||||
)
|
||||
|
||||
install (
|
||||
TARGETS ${EXE_NAME}
|
||||
${INSTALL_TARGETS_DEFAULT_ARGS}
|
||||
)
|
||||
|
||||
feature_summary(WHAT ALL INCLUDE_QUIET_PACKAGES FATAL_ON_MISSING_REQUIRED_PACKAGES)
|
||||
|
20
README.md
20
README.md
@ -7,14 +7,9 @@ Since **I** just need a simple player which *just works* right now, so I did man
|
||||
We have the following features:
|
||||
|
||||
- [Sidecar](https://en.wikipedia.org/wiki/Sidecar_file) lyrics file (`.lrc`) support with an optional desktop lyrics bar widget
|
||||
- Chapter file support
|
||||
- Sidecar chapter file support:
|
||||
- [YouTube-style chapter](https://support.google.com/youtube/answer/9884579) saved to a plain text file with `.chp` suffix
|
||||
- PotPlayer `.pbf` file, `[Bookmark]`s as chapters
|
||||
- Built-in chapter support (require build with FFmpeg)
|
||||
- Auto-load all audio files in the same folder of the file that you attempted to play, into a playlist
|
||||
|
||||
These features are not available, some of them are TBD and others are not planned:
|
||||
But these features are not available, some of them are TBD and others are not planned:
|
||||
|
||||
- File format support will be limited by the [FFmpeg version that Qt 6 uses](https://doc.qt.io/qt-6/qtmultimedia-attribution-ffmpeg.html).
|
||||
- ...which if you use Qt's official binary, only contains the LGPLv2.1+ part. (already good enough, tho)
|
||||
@ -23,6 +18,7 @@ These features are not available, some of them are TBD and others are not planne
|
||||
- Limited system integration:
|
||||
- No [SMTC](https://learn.microsoft.com/en-us/uwp/api/windows.media.systemmediatransportcontrols) support under Windows for now
|
||||
- No [MPRIS](https://www.freedesktop.org/wiki/Specifications/mpris-spec/) support under Linux desktop for now
|
||||
- No "playback progress on taskbar icon" and "taskbar thumbnail buttons" support whatever on Windows or Linux desktop for now
|
||||
- Limited lyrics (`.lrc`) loading support:
|
||||
- Currently no `.tlrc` (for translated lyrics) or `.rlrc` (for romanized lyrics) support.
|
||||
- Multi-line lyrics and duplicated timestamps are not supported
|
||||
@ -32,14 +28,10 @@ These features are not available, some of them are TBD and others are not planne
|
||||
|
||||
Current state, we need:
|
||||
|
||||
- `cmake` as the build system.
|
||||
- `qt6` with `qt6-multimedia` since we use it for playback.
|
||||
- `kissfft` for FFT support (will be downloaded at configure-time by `cmake`).
|
||||
- (optional) `taglib` to get the audio file properties.
|
||||
- (optional) `kf6codecs` to get the lyrics encoding correct.
|
||||
- (optional) `ffmpeg` to get the audio chapter properties.
|
||||
- It's suggested to use the same FFmpeg version that Qt Multimedia uses, so we can reuse the FFmpeg library binaries that Qt uses.
|
||||
- You can know the version by checking [Qt documentation's FFmpeg attribution page](https://doc.qt.io/qt-6.9/qtmultimedia-attribution-ffmpeg.html)
|
||||
- `cmake` as the build system.
|
||||
- `qt6` with `qt6-multimedia` since we use it for playback.
|
||||
- `taglib` to get the audio file properties.
|
||||
- `kissfft` for FFT support (will be downloaded at configure-time by `cmake`).
|
||||
|
||||
Then we can build it with any proper c++ compiler like g++ or msvc.
|
||||
|
||||
|
@ -5,8 +5,8 @@ environment:
|
||||
PACKAGE_INSTALL_ROOT: C:\projects\pir
|
||||
matrix:
|
||||
- build_name: mingw1120_64_qt6_7
|
||||
QTPATH: C:\Qt\6.8\mingw_64
|
||||
MINGW64: C:\Qt\Tools\mingw1310_64
|
||||
QTPATH: C:\Qt\6.7\mingw_64
|
||||
MINGW64: C:\Qt\Tools\mingw1120_64
|
||||
|
||||
install:
|
||||
- mkdir %CMAKE_INSTALL_ROOT%
|
||||
|
Binary file not shown.
@ -11,11 +11,6 @@
|
||||
#include <QPainter>
|
||||
|
||||
#include <kissfft.hh>
|
||||
#include <cmath>
|
||||
|
||||
#ifndef M_PI
|
||||
#define M_PI 3.14159265358979323846
|
||||
#endif
|
||||
|
||||
FFTSpectrum::FFTSpectrum(QWidget* parent)
|
||||
: QWidget(parent)
|
||||
@ -31,7 +26,6 @@ FFTSpectrum::FFTSpectrum(QWidget* parent)
|
||||
});
|
||||
|
||||
connect(m_audioBufferOutput, &QAudioBufferOutput::audioBufferReceived, this, [=](const QAudioBuffer& buffer) {
|
||||
if (!isVisible()) return;
|
||||
const QAudioFormat& fmt = buffer.format();
|
||||
const QAudioFormat::SampleFormat sampleFormat = fmt.sampleFormat();
|
||||
QAudioFormat::ChannelConfig channelConfig = fmt.channelConfig();
|
||||
@ -86,35 +80,15 @@ FFTSpectrum::FFTSpectrum(QWidget* parent)
|
||||
qWarning() << "Unsupported format or channel config:" << sampleFormat << channelConfig;
|
||||
return;
|
||||
}
|
||||
// Apply Hanning window to reduce spectral leakage
|
||||
for (int i = 0; i < frameCount; ++i) {
|
||||
float window = 0.5f * (1.0f - cos(2.0f * M_PI * i / (frameCount - 1)));
|
||||
samples[i].real(samples[i].real() * window);
|
||||
}
|
||||
fft.transform(samples.data(), mass.data());
|
||||
// Use only the first half of FFT result (positive frequencies)
|
||||
int spectrumSize = frameCount / 2;
|
||||
m_freq.resize(spectrumSize);
|
||||
for (int i = 0; i < spectrumSize; i++) {
|
||||
m_freq.resize(frameCount);
|
||||
for (int i = 0; i < frameCount; i++) {
|
||||
m_freq[i] = sqrt(mass[i].real() * mass[i].real() + mass[i].imag() * mass[i].imag());
|
||||
}
|
||||
|
||||
// Remove DC component and very low frequencies (like most spectrum analyzers do)
|
||||
// DC component (0 Hz) is usually not musically relevant
|
||||
m_freq[0] = 0;
|
||||
|
||||
// Optionally remove the first few bins (very low frequencies below ~20Hz)
|
||||
// Calculate how many bins correspond to frequencies below 20Hz
|
||||
int sampleRate = fmt.sampleRate();
|
||||
int lowFreqCutoff = std::min(3, (20 * frameCount) / (sampleRate * 2)); // Limit to first 3 bins max
|
||||
for (int i = 1; i <= lowFreqCutoff && i < spectrumSize; i++) {
|
||||
m_freq[i] *= (float(i) / float(lowFreqCutoff + 1)); // Gradual fade-in instead of hard cut
|
||||
}
|
||||
|
||||
for (auto& val : m_freq) {
|
||||
val = log10(val + 1);
|
||||
}
|
||||
|
||||
qDebug() << m_freq.size() << "updated" << sampleFormat << channelConfig;
|
||||
update();
|
||||
});
|
||||
#endif // QT_VERSION >= QT_VERSION_CHECK(6, 8, 0)
|
||||
@ -139,19 +113,10 @@ void FFTSpectrum::paintEvent(QPaintEvent* e)
|
||||
if (!m_freq.empty()) {
|
||||
int width = this->width();
|
||||
int height = this->height();
|
||||
int barWidth = std::max(1, width / static_cast<int>(m_freq.size()));
|
||||
|
||||
for (size_t i = 0; i < m_freq.size(); i++) {
|
||||
// Use sqrt to compress the range similar to original, but safer
|
||||
int barHeight = static_cast<int>(sqrt(std::max(0.0f, m_freq[i])) * height * 0.5);
|
||||
barHeight = std::max(0, std::min(barHeight, height));
|
||||
|
||||
// Calculate alpha based on frequency value, similar to original
|
||||
int alpha = std::min(255, static_cast<int>(140 * m_freq[i]) + 90);
|
||||
alpha = std::max(90, alpha);
|
||||
|
||||
QColor color(70, 130, 180, alpha);
|
||||
painter.fillRect(static_cast<int>(i) * barWidth, height - barHeight, barWidth, barHeight, color);
|
||||
int barWidth = std::max(1ULL, width / m_freq.size());
|
||||
for (int i = 0; i < m_freq.size(); i++) {
|
||||
int barHeight = static_cast<int>(sqrt(m_freq[i]) * height * 0.5);
|
||||
painter.fillRect(i * barWidth, height - barHeight, barWidth, barHeight, QColor(70, 130, 180, (int)(140 * m_freq[i]) + 90));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -12,113 +12,82 @@
|
||||
<context>
|
||||
<name>MainWindow</name>
|
||||
<message>
|
||||
<location filename="../mainwindow.cpp" line="125"/>
|
||||
<location filename="../mainwindow.cpp" line="93"/>
|
||||
<source>Mono</source>
|
||||
<translation type="unfinished"></translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.cpp" line="127"/>
|
||||
<location filename="../mainwindow.cpp" line="95"/>
|
||||
<source>Stereo</source>
|
||||
<translation type="unfinished"></translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.cpp" line="129"/>
|
||||
<location filename="../mainwindow.cpp" line="97"/>
|
||||
<source>%1 Channels</source>
|
||||
<translation type="unfinished"></translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.cpp" line="298"/>
|
||||
<location filename="../mainwindow.cpp" line="241"/>
|
||||
<source>Select songs to play</source>
|
||||
<translation type="unfinished"></translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.cpp" line="300"/>
|
||||
<location filename="../mainwindow.cpp" line="243"/>
|
||||
<source>Audio Files</source>
|
||||
<translation type="unfinished"></translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.cpp" line="685"/>
|
||||
<location filename="../mainwindow.cpp" line="576"/>
|
||||
<source>Select image as background skin</source>
|
||||
<translation type="unfinished"></translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.cpp" line="687"/>
|
||||
<location filename="../mainwindow.cpp" line="578"/>
|
||||
<source>Image files (*.jpg *.jpeg *.png *.gif)</source>
|
||||
<translation type="unfinished"></translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.cpp" line="764"/>
|
||||
<source>Based on the following free software libraries:</source>
|
||||
<translation type="unfinished"></translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.ui" line="23"/>
|
||||
<location filename="../mainwindow.cpp" line="762"/>
|
||||
<location filename="../lrcbar.cpp" line="89"/>
|
||||
<source>Pineapple Music</source>
|
||||
<translation type="unfinished"></translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.ui" line="327"/>
|
||||
<location filename="../mainwindow.ui" line="313"/>
|
||||
<source>No song loaded...</source>
|
||||
<translation type="unfinished"></translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.ui" line="339"/>
|
||||
<location filename="../mainwindow.ui" line="325"/>
|
||||
<source>Drag and drop file to load</source>
|
||||
<translation type="unfinished"></translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.ui" line="352"/>
|
||||
<location filename="../mainwindow.ui" line="338"/>
|
||||
<source>Lrc</source>
|
||||
<comment>Lyrics</comment>
|
||||
<translation type="unfinished"></translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.ui" line="711"/>
|
||||
<location filename="../mainwindow.ui" line="714"/>
|
||||
<location filename="../mainwindow.cpp" line="759"/>
|
||||
<source>About</source>
|
||||
<translation type="unfinished"></translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.ui" line="728"/>
|
||||
<source>Open</source>
|
||||
<translation type="unfinished"></translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.cpp" line="135"/>
|
||||
<location filename="../mainwindow.cpp" line="103"/>
|
||||
<source>Sample Rate: %1 Hz</source>
|
||||
<translation type="unfinished"></translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.cpp" line="140"/>
|
||||
<location filename="../mainwindow.cpp" line="108"/>
|
||||
<source>Bitrate: %1 Kbps</source>
|
||||
<translation type="unfinished"></translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.cpp" line="145"/>
|
||||
<location filename="../mainwindow.cpp" line="113"/>
|
||||
<source>Channel Count: %1</source>
|
||||
<translation type="unfinished"></translation>
|
||||
</message>
|
||||
</context>
|
||||
<context>
|
||||
<name>PlaybackProgressIndicator</name>
|
||||
<message>
|
||||
<location filename="../playbackprogressindicator.cpp" line="85"/>
|
||||
<source>Time</source>
|
||||
<translation type="unfinished"></translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../playbackprogressindicator.cpp" line="85"/>
|
||||
<source>Chapter Name</source>
|
||||
<translation type="unfinished"></translation>
|
||||
</message>
|
||||
</context>
|
||||
<context>
|
||||
<name>main</name>
|
||||
<message>
|
||||
<location filename="../main.cpp" line="27"/>
|
||||
<location filename="../main.cpp" line="28"/>
|
||||
<source>File list.</source>
|
||||
<translation type="unfinished"></translation>
|
||||
</message>
|
@ -12,113 +12,82 @@
|
||||
<context>
|
||||
<name>MainWindow</name>
|
||||
<message>
|
||||
<location filename="../mainwindow.cpp" line="125"/>
|
||||
<location filename="../mainwindow.cpp" line="93"/>
|
||||
<source>Mono</source>
|
||||
<translation>单声道</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.cpp" line="127"/>
|
||||
<location filename="../mainwindow.cpp" line="95"/>
|
||||
<source>Stereo</source>
|
||||
<translation>立体声</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.cpp" line="129"/>
|
||||
<location filename="../mainwindow.cpp" line="97"/>
|
||||
<source>%1 Channels</source>
|
||||
<translation>%1 声道</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.cpp" line="298"/>
|
||||
<location filename="../mainwindow.cpp" line="241"/>
|
||||
<source>Select songs to play</source>
|
||||
<translation>选择要播放的曲目</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.cpp" line="300"/>
|
||||
<location filename="../mainwindow.cpp" line="243"/>
|
||||
<source>Audio Files</source>
|
||||
<translation>音频文件</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.cpp" line="685"/>
|
||||
<location filename="../mainwindow.cpp" line="576"/>
|
||||
<source>Select image as background skin</source>
|
||||
<translation>选择图片作为背景皮肤</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.cpp" line="687"/>
|
||||
<location filename="../mainwindow.cpp" line="578"/>
|
||||
<source>Image files (*.jpg *.jpeg *.png *.gif)</source>
|
||||
<translation>图片文件 (*.jpg *.jpeg *.png *.gif)</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.cpp" line="764"/>
|
||||
<source>Based on the following free software libraries:</source>
|
||||
<translation>基于下列自由软件库:</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.ui" line="23"/>
|
||||
<location filename="../mainwindow.cpp" line="762"/>
|
||||
<location filename="../lrcbar.cpp" line="89"/>
|
||||
<source>Pineapple Music</source>
|
||||
<translation>菠萝音乐</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.ui" line="327"/>
|
||||
<location filename="../mainwindow.ui" line="313"/>
|
||||
<source>No song loaded...</source>
|
||||
<translation>未加载曲目...</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.ui" line="339"/>
|
||||
<location filename="../mainwindow.ui" line="325"/>
|
||||
<source>Drag and drop file to load</source>
|
||||
<translation>拖放文件来播放</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.ui" line="352"/>
|
||||
<location filename="../mainwindow.ui" line="338"/>
|
||||
<source>Lrc</source>
|
||||
<comment>Lyrics</comment>
|
||||
<translation>歌词</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.ui" line="711"/>
|
||||
<location filename="../mainwindow.ui" line="714"/>
|
||||
<location filename="../mainwindow.cpp" line="759"/>
|
||||
<source>About</source>
|
||||
<translation>关于</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.ui" line="728"/>
|
||||
<source>Open</source>
|
||||
<translation>打开</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.cpp" line="135"/>
|
||||
<location filename="../mainwindow.cpp" line="103"/>
|
||||
<source>Sample Rate: %1 Hz</source>
|
||||
<translation>采样率: %1 Hz</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.cpp" line="140"/>
|
||||
<location filename="../mainwindow.cpp" line="108"/>
|
||||
<source>Bitrate: %1 Kbps</source>
|
||||
<translation>比特率: %1 Kbps</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../mainwindow.cpp" line="145"/>
|
||||
<location filename="../mainwindow.cpp" line="113"/>
|
||||
<source>Channel Count: %1</source>
|
||||
<translation>声道数: %1</translation>
|
||||
</message>
|
||||
</context>
|
||||
<context>
|
||||
<name>PlaybackProgressIndicator</name>
|
||||
<message>
|
||||
<location filename="../playbackprogressindicator.cpp" line="85"/>
|
||||
<source>Time</source>
|
||||
<translation>时间</translation>
|
||||
</message>
|
||||
<message>
|
||||
<location filename="../playbackprogressindicator.cpp" line="85"/>
|
||||
<source>Chapter Name</source>
|
||||
<translation>章节名称</translation>
|
||||
</message>
|
||||
</context>
|
||||
<context>
|
||||
<name>main</name>
|
||||
<message>
|
||||
<location filename="../main.cpp" line="27"/>
|
||||
<location filename="../main.cpp" line="28"/>
|
||||
<source>File list.</source>
|
||||
<translation>文件列表。</translation>
|
||||
</message>
|
||||
|
@ -112,7 +112,8 @@ bool LyricsManager::loadLyrics(QString filepath)
|
||||
QRegularExpressionMatch match = lrcRegex.match(line);
|
||||
while (match.hasMatch()) {
|
||||
tagSectionPassed = true;
|
||||
timestamps.append(parseTimeToMilliseconds(match.captured(1)));
|
||||
QTime timestamp(QTime::fromString(match.captured(1), "m:s.zz"));
|
||||
timestamps.append(timestamp.msecsSinceStartOfDay());
|
||||
currentLrc = match.captured(2);
|
||||
match = lrcRegex.match(currentLrc);
|
||||
}
|
||||
@ -176,23 +177,6 @@ double LyricsManager::maskPercent(int curTimeMs)
|
||||
return (double)(curTimeMs - currentLyricsTime()) / (m_nextLyricsTime - m_currentLyricsTime);
|
||||
}
|
||||
|
||||
int LyricsManager::parseTimeToMilliseconds(const QString &timeString)
|
||||
{
|
||||
QRegularExpression timeRegex(R"((\d{2,3}):(\d{2})\.(\d{2,3}))");
|
||||
QRegularExpressionMatch match = timeRegex.match(timeString);
|
||||
|
||||
if (match.hasMatch()) {
|
||||
int minutes = match.captured(1).toInt();
|
||||
int seconds = match.captured(2).toInt();
|
||||
int milliseconds = match.captured(3).toInt();
|
||||
|
||||
return minutes * 60000 + seconds * 1000 + milliseconds;
|
||||
} else {
|
||||
qCWarning(lcLyricsParser) << "Invalid time format:" << timeString;
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
void LyricsManager::reset()
|
||||
{
|
||||
m_currentLyricsTime = 0;
|
||||
|
@ -25,8 +25,6 @@ public:
|
||||
QString lyrics(int lineOffset = 0) const;
|
||||
double maskPercent(int curTimeMs);
|
||||
|
||||
static int parseTimeToMilliseconds(const QString& timeString);
|
||||
|
||||
protected:
|
||||
|
||||
|
||||
|
1
main.cpp
1
main.cpp
@ -21,6 +21,7 @@ int main(int argc, char *argv[])
|
||||
if (translator.load(QLocale(), QLatin1String("pineapple-music"), QLatin1String("_"), QLatin1String(":/i18n"))) {
|
||||
a.installTranslator(&translator);
|
||||
}
|
||||
a.installTranslator(&translator);
|
||||
|
||||
// parse commandline arguments
|
||||
QCommandLineParser parser;
|
||||
|
236
mainwindow.cpp
236
mainwindow.cpp
@ -1,4 +1,4 @@
|
||||
// SPDX-FileCopyrightText: 2025 Gary Wang <opensource@blumia.net>
|
||||
// SPDX-FileCopyrightText: 2024 Gary Wang <git@blumia.net>
|
||||
//
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
@ -8,7 +8,6 @@
|
||||
#include "playlistmanager.h"
|
||||
#include "fftspectrum.h"
|
||||
#include "lrcbar.h"
|
||||
#include "taskbarmanager.h"
|
||||
|
||||
// taglib
|
||||
#ifndef NO_TAGLIB
|
||||
@ -27,16 +26,12 @@
|
||||
#include <QListView>
|
||||
#include <QCollator>
|
||||
#include <QMimeData>
|
||||
#include <QMenu>
|
||||
#include <QWindow>
|
||||
#include <QStandardPaths>
|
||||
#include <QMediaDevices>
|
||||
#include <QAudioDevice>
|
||||
#include <QMessageBox>
|
||||
#include <QStringBuilder>
|
||||
#include <QSettings>
|
||||
#include <QGraphicsDropShadowEffect>
|
||||
#include <QTimer>
|
||||
|
||||
constexpr QSize miniSize(490, 160);
|
||||
constexpr QSize fullSize(490, 420);
|
||||
@ -50,7 +45,6 @@ MainWindow::MainWindow(QWidget *parent)
|
||||
, m_fftSpectrum(new FFTSpectrum(this))
|
||||
, m_lrcbar(new LrcBar(nullptr))
|
||||
, m_playlistManager(new PlaylistManager(this))
|
||||
, m_taskbarManager(new TaskBarManager(this))
|
||||
{
|
||||
ui->setupUi(this);
|
||||
m_playlistManager->setAutoLoadFilterSuffixes({
|
||||
@ -61,43 +55,21 @@ MainWindow::MainWindow(QWidget *parent)
|
||||
m_mediaPlayer->setLoops(QMediaPlayer::Infinite);
|
||||
ui->playlistView->setModel(m_playlistManager->model());
|
||||
|
||||
ui->chapterNameBtn->setVisible(false);
|
||||
ui->chapterlistView->setModel(ui->playbackProgressIndicator->chapterModel());
|
||||
ui->chapterlistView->setRootIsDecorated(false);
|
||||
|
||||
ui->actionHelp->setShortcut(QKeySequence::HelpContents);
|
||||
addAction(ui->actionHelp);
|
||||
ui->actionOpen->setShortcut(QKeySequence::Open);
|
||||
addAction(ui->actionOpen);
|
||||
|
||||
ui->titleLabel->setGraphicsEffect(createLabelShadowEffect());
|
||||
ui->propLabel->setGraphicsEffect(createLabelShadowEffect());
|
||||
ui->nowTimeLabel->setGraphicsEffect(createLabelShadowEffect());
|
||||
ui->totalTimeLabel->setGraphicsEffect(createLabelShadowEffect());
|
||||
|
||||
setWindowFlags(Qt::FramelessWindowHint | Qt::WindowSystemMenuHint | Qt::WindowMinimizeButtonHint);
|
||||
setAttribute(Qt::WA_TranslucentBackground, true);
|
||||
|
||||
m_taskbarManager->setCanTogglePlayback(true);
|
||||
m_taskbarManager->setCanSkipBackward(true);
|
||||
m_taskbarManager->setCanSkipForward(true);
|
||||
m_taskbarManager->setShowProgress(true);
|
||||
|
||||
loadConfig();
|
||||
loadSkinData();
|
||||
initConnections();
|
||||
initUiAndAnimation();
|
||||
|
||||
centerWindow();
|
||||
|
||||
QTimer::singleShot(1000, [this](){
|
||||
m_taskbarManager->setWinId(window()->winId());
|
||||
});
|
||||
}
|
||||
|
||||
MainWindow::~MainWindow()
|
||||
{
|
||||
saveConfig();
|
||||
delete m_lrcbar;
|
||||
delete ui;
|
||||
}
|
||||
@ -131,12 +103,12 @@ void MainWindow::setAudioPropertyInfoForDisplay(int sampleRate, int bitrate, int
|
||||
}
|
||||
};
|
||||
|
||||
if (sampleRate > 0) {
|
||||
if (sampleRate >= 0) {
|
||||
uiStrs << QString("%1 Hz").arg(sampleRate);
|
||||
tooltipStrs << tr("Sample Rate: %1 Hz").arg(sampleRate);
|
||||
}
|
||||
|
||||
if (bitrate > 0) {
|
||||
if (bitrate >= 0) {
|
||||
uiStrs << QString("%1 Kbps").arg(bitrate);
|
||||
tooltipStrs << tr("Bitrate: %1 Kbps").arg(bitrate);
|
||||
}
|
||||
@ -259,21 +231,6 @@ void MainWindow::dropEvent(QDropEvent *e)
|
||||
return;
|
||||
}
|
||||
|
||||
if (fileName.endsWith(".chp") || fileName.endsWith(".pbf")) {
|
||||
QList<std::pair<qint64, QString>> chapters(PlaybackProgressIndicator::tryLoadSidecarChapterFile(fileName));
|
||||
ui->playbackProgressIndicator->setChapters(chapters);
|
||||
return;
|
||||
}
|
||||
|
||||
if (fileName.endsWith(".m3u") || fileName.endsWith(".m3u8")) {
|
||||
const QModelIndex & modelIndex = m_playlistManager->loadM3U8Playlist(urls.constFirst());
|
||||
if (modelIndex.isValid()) {
|
||||
loadByModelIndex(modelIndex);
|
||||
play();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const QModelIndex & modelIndex = m_playlistManager->loadPlaylist(urls);
|
||||
if (modelIndex.isValid()) {
|
||||
loadByModelIndex(modelIndex);
|
||||
@ -281,16 +238,6 @@ void MainWindow::dropEvent(QDropEvent *e)
|
||||
}
|
||||
}
|
||||
|
||||
void MainWindow::contextMenuEvent(QContextMenuEvent *event)
|
||||
{
|
||||
QMenu * menu = new QMenu;
|
||||
menu->addAction(ui->actionHelp);
|
||||
menu->exec(mapToGlobal(event->pos()));
|
||||
menu->deleteLater();
|
||||
|
||||
return QMainWindow::contextMenuEvent(event);
|
||||
}
|
||||
|
||||
void MainWindow::loadFile()
|
||||
{
|
||||
QStringList musicFolders(QStandardPaths::standardLocations(QStandardPaths::MusicLocation));
|
||||
@ -305,22 +252,15 @@ void MainWindow::loadFile()
|
||||
urlList.append(QUrl::fromLocalFile(fileName));
|
||||
}
|
||||
|
||||
const QModelIndex & modelIndex = m_playlistManager->loadPlaylist(urlList);
|
||||
loadByModelIndex(modelIndex);
|
||||
}
|
||||
|
||||
void MainWindow::loadFile(const QUrl &url)
|
||||
{
|
||||
const QString filePath = url.toLocalFile();
|
||||
m_mediaPlayer->setSource(url);
|
||||
m_lrcbar->loadLyrics(filePath);
|
||||
QList<std::pair<qint64, QString>> chapters(PlaybackProgressIndicator::tryLoadChapters(filePath));
|
||||
ui->playbackProgressIndicator->setChapters(chapters);
|
||||
m_playlistManager->loadPlaylist(urlList);
|
||||
m_mediaPlayer->setSource(urlList.first());
|
||||
m_lrcbar->loadLyrics(urlList.first().toLocalFile());
|
||||
}
|
||||
|
||||
void MainWindow::loadByModelIndex(const QModelIndex & index)
|
||||
{
|
||||
loadFile(m_playlistManager->urlByIndex(index));
|
||||
m_mediaPlayer->setSource(m_playlistManager->urlByIndex(index));
|
||||
m_lrcbar->loadLyrics(m_playlistManager->localFileByIndex(index));
|
||||
}
|
||||
|
||||
void MainWindow::play()
|
||||
@ -372,6 +312,16 @@ void MainWindow::on_playBtn_clicked()
|
||||
}
|
||||
}
|
||||
|
||||
QString MainWindow::ms2str(qint64 ms)
|
||||
{
|
||||
QTime duaTime(QTime::fromMSecsSinceStartOfDay(ms));
|
||||
if (duaTime.hour() > 0) {
|
||||
return duaTime.toString("h:mm:ss");
|
||||
} else {
|
||||
return duaTime.toString("m:ss");
|
||||
}
|
||||
}
|
||||
|
||||
QList<QUrl> MainWindow::strlst2urllst(QStringList strlst)
|
||||
{
|
||||
QList<QUrl> urlList;
|
||||
@ -398,6 +348,14 @@ void MainWindow::on_stopBtn_clicked()
|
||||
m_mediaPlayer->stop();
|
||||
}
|
||||
|
||||
void MainWindow::on_playbackSlider_valueChanged(int value)
|
||||
{
|
||||
qint64 currPos = m_mediaPlayer->duration() == 0 ? value : m_mediaPlayer->position() * ui->playbackSlider->maximum() / m_mediaPlayer->duration();
|
||||
if (qAbs(currPos - value) > 2) {
|
||||
m_mediaPlayer->setPosition(ui->playbackSlider->value() * 1.0 / ui->playbackSlider->maximum() * m_mediaPlayer->duration());
|
||||
}
|
||||
}
|
||||
|
||||
void MainWindow::on_prevBtn_clicked()
|
||||
{
|
||||
QModelIndex index(m_playlistManager->previousIndex());
|
||||
@ -445,10 +403,6 @@ void MainWindow::initConnections()
|
||||
m_audioOutput->setDevice(m_mediaDevices->defaultAudioOutput());
|
||||
});
|
||||
|
||||
connect(ui->playbackProgressIndicator, &PlaybackProgressIndicator::seekingRequested, this, [=](qint64 pos){
|
||||
m_mediaPlayer->setPosition(pos);
|
||||
});
|
||||
|
||||
connect(m_mediaPlayer, &QMediaPlayer::sourceChanged, this, [=](){
|
||||
QUrl fileUrl(m_mediaPlayer->source());
|
||||
|
||||
@ -466,8 +420,6 @@ void MainWindow::initConnections()
|
||||
if (!fileRef.isNull() && fileRef.audioProperties()) {
|
||||
TagLib::AudioProperties *prop = fileRef.audioProperties();
|
||||
setAudioPropertyInfoForDisplay(prop->sampleRate(), prop->bitrate(), prop->channels(), suffix);
|
||||
} else {
|
||||
qDebug() << "No Audio Properties from TagLib";
|
||||
}
|
||||
|
||||
if (!fileRef.isNull() && fileRef.tag()) {
|
||||
@ -475,10 +427,6 @@ void MainWindow::initConnections()
|
||||
setAudioMetadataForDisplay(QString::fromStdString(tag->title().to8Bit(true)),
|
||||
QString::fromStdString(tag->artist().to8Bit(true)),
|
||||
QString::fromStdString(tag->album().to8Bit(true)));
|
||||
m_urlMissingTagLibMetadata.clear();
|
||||
} else {
|
||||
qDebug() << "No Audio Metadata from TagLib";
|
||||
m_urlMissingTagLibMetadata = fileUrl;
|
||||
}
|
||||
#endif // NO_TAGLIB
|
||||
}
|
||||
@ -490,17 +438,12 @@ void MainWindow::initConnections()
|
||||
// see `02 Yoiyami Hanabi.mp3`'s Title. So we don't use Qt's one if tablib is available.
|
||||
qDebug() << metadata.stringValue(QMediaMetaData::Title) << metadata.stringValue(QMediaMetaData::Author);
|
||||
#ifdef NO_TAGLIB
|
||||
bool needMetadataFromQt = true;
|
||||
#else
|
||||
bool needMetadataFromQt = m_urlMissingTagLibMetadata == m_mediaPlayer->source();
|
||||
setAudioMetadataForDisplay(metadata.stringValue(QMediaMetaData::Title),
|
||||
metadata.stringValue(QMediaMetaData::Author),
|
||||
metadata.stringValue(QMediaMetaData::AlbumTitle));
|
||||
setAudioPropertyInfoForDisplay(-1, metadata.value(QMediaMetaData::AudioBitRate).toInt() / 1000,
|
||||
-1, metadata.stringValue(QMediaMetaData::FileFormat));
|
||||
#endif // NO_TAGLIB
|
||||
if (needMetadataFromQt) {
|
||||
setAudioMetadataForDisplay(metadata.stringValue(QMediaMetaData::Title),
|
||||
metadata.stringValue(QMediaMetaData::Author),
|
||||
metadata.stringValue(QMediaMetaData::AlbumTitle));
|
||||
setAudioPropertyInfoForDisplay(-1, metadata.value(QMediaMetaData::AudioBitRate).toInt() / 1000,
|
||||
-1, metadata.stringValue(QMediaMetaData::FileFormat));
|
||||
}
|
||||
QVariant coverArt(metadata.value(QMediaMetaData::ThumbnailImage));
|
||||
if (!coverArt.isNull()) {
|
||||
ui->coverLabel->setPixmap(QPixmap::fromImage(coverArt.value<QImage>()));
|
||||
@ -514,28 +457,11 @@ void MainWindow::initConnections()
|
||||
});
|
||||
|
||||
connect(m_mediaPlayer, &QMediaPlayer::positionChanged, this, [=](qint64 pos) {
|
||||
ui->nowTimeLabel->setText(PlaybackProgressIndicator::formatTime(pos));
|
||||
ui->nowTimeLabel->setText(ms2str(pos));
|
||||
if (m_mediaPlayer->duration() != 0) {
|
||||
ui->playbackProgressIndicator->setPosition(pos);
|
||||
m_taskbarManager->setProgressValue(pos);
|
||||
ui->playbackSlider->setSliderPosition(ui->playbackSlider->maximum() * pos / m_mediaPlayer->duration());
|
||||
}
|
||||
m_lrcbar->playbackPositionChanged(pos, m_mediaPlayer->duration());
|
||||
|
||||
static QString lastChapterName;
|
||||
if (ui->playbackProgressIndicator->chapterModel()->rowCount() > 0) {
|
||||
QString currentChapterName = ui->playbackProgressIndicator->currentChapterName();
|
||||
if (currentChapterName != lastChapterName) {
|
||||
ui->chapterNameBtn->setText(currentChapterName);
|
||||
lastChapterName = currentChapterName;
|
||||
}
|
||||
ui->chapterNameBtn->setVisible(true);
|
||||
} else {
|
||||
if (!lastChapterName.isEmpty()) {
|
||||
ui->chapterNameBtn->setText("");
|
||||
lastChapterName.clear();
|
||||
}
|
||||
ui->chapterNameBtn->setVisible(false);
|
||||
}
|
||||
});
|
||||
|
||||
connect(m_audioOutput, &QAudioOutput::mutedChanged, this, [=](bool muted) {
|
||||
@ -547,9 +473,7 @@ void MainWindow::initConnections()
|
||||
});
|
||||
|
||||
connect(m_mediaPlayer, &QMediaPlayer::durationChanged, this, [=](qint64 dua) {
|
||||
ui->playbackProgressIndicator->setDuration(dua);
|
||||
m_taskbarManager->setProgressMaximum(dua);
|
||||
ui->totalTimeLabel->setText(PlaybackProgressIndicator::formatTime(dua));
|
||||
ui->totalTimeLabel->setText(ms2str(dua));
|
||||
});
|
||||
|
||||
connect(m_mediaPlayer, &QMediaPlayer::playbackStateChanged, this, [=](QMediaPlayer::PlaybackState newState) {
|
||||
@ -562,7 +486,6 @@ void MainWindow::initConnections()
|
||||
ui->playBtn->setIcon(QIcon(":/icons/icons/media-playback-start.png"));
|
||||
break;
|
||||
}
|
||||
m_taskbarManager->setPlaybackState(newState);
|
||||
});
|
||||
|
||||
connect(m_audioOutput, &QAudioOutput::volumeChanged, this, [=](float vol) {
|
||||
@ -603,44 +526,14 @@ void MainWindow::initConnections()
|
||||
}
|
||||
});
|
||||
|
||||
connect(m_taskbarManager, &TaskBarManager::togglePlayback, this, [this](){
|
||||
on_playBtn_clicked();
|
||||
});
|
||||
|
||||
connect(m_taskbarManager, &TaskBarManager::skipBackward, this, [this](){
|
||||
on_prevBtn_clicked();
|
||||
});
|
||||
|
||||
connect(m_taskbarManager, &TaskBarManager::skipForward, this, [this](){
|
||||
on_nextBtn_clicked();
|
||||
});
|
||||
|
||||
connect(m_mediaPlayer, &QMediaPlayer::errorOccurred, this, [=](QMediaPlayer::Error error, const QString &errorString) {
|
||||
connect(m_mediaPlayer, &QMediaPlayer::errorOccurred, this, [=](QMediaPlayer::Error error, const QString &errorString) {
|
||||
qDebug() << error << errorString;
|
||||
});
|
||||
}
|
||||
|
||||
void MainWindow::loadConfig()
|
||||
{
|
||||
QDir configDir(QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation));
|
||||
QSettings settings(configDir.filePath("settings.ini"), QSettings::IniFormat);
|
||||
ui->volumeSlider->setValue(settings.value("volume", 100).toInt());
|
||||
}
|
||||
|
||||
void MainWindow::saveConfig()
|
||||
{
|
||||
QDir configDir(QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation));
|
||||
if (!configDir.exists()) {
|
||||
configDir.mkpath(".");
|
||||
}
|
||||
QSettings settings(configDir.filePath("settings.ini"), QSettings::IniFormat);
|
||||
settings.setValue("volume", ui->volumeSlider->value());
|
||||
});
|
||||
}
|
||||
|
||||
void MainWindow::loadSkinData()
|
||||
{
|
||||
QDir configDir(QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation));
|
||||
QFile file(configDir.filePath("skin.dat"));
|
||||
QFile file(QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation) + "/skin.dat");
|
||||
bool canOpen = file.open(QIODevice::ReadOnly);
|
||||
if (!canOpen) return;
|
||||
QDataStream stream(&file);
|
||||
@ -697,16 +590,7 @@ void MainWindow::on_setSkinBtn_clicked()
|
||||
|
||||
void MainWindow::on_playListBtn_clicked()
|
||||
{
|
||||
if (size().height() < 200) {
|
||||
setFixedSize(fullSize);
|
||||
ui->pluginStackedWidget->setCurrentWidget(ui->playlistViewPage);
|
||||
} else {
|
||||
if (ui->pluginStackedWidget->currentWidget() == ui->playlistViewPage) {
|
||||
setFixedSize(miniSize);
|
||||
} else {
|
||||
ui->pluginStackedWidget->setCurrentWidget(ui->playlistViewPage);
|
||||
}
|
||||
}
|
||||
setFixedSize(size().height() < 200 ? fullSize : miniSize);
|
||||
}
|
||||
|
||||
void MainWindow::on_playlistView_activated(const QModelIndex &index)
|
||||
@ -725,37 +609,6 @@ void MainWindow::on_lrcBtn_clicked()
|
||||
}
|
||||
}
|
||||
|
||||
void MainWindow::on_chapterlistView_activated(const QModelIndex &index)
|
||||
{
|
||||
if (!index.isValid()) return;
|
||||
|
||||
QModelIndex timeColumnIndex = index.sibling(index.row(), 0);
|
||||
QStandardItem* timeItem = ui->playbackProgressIndicator->chapterModel()->itemFromIndex(timeColumnIndex);
|
||||
if (!timeItem) return;
|
||||
|
||||
qint64 chapterStartTime = timeItem->data(PlaybackProgressIndicator::StartTimeMsRole).toLongLong();
|
||||
m_mediaPlayer->setPosition(chapterStartTime);
|
||||
}
|
||||
|
||||
void MainWindow::on_chapterNameBtn_clicked()
|
||||
{
|
||||
if (size().height() < 200) {
|
||||
setFixedSize(fullSize);
|
||||
}
|
||||
ui->pluginStackedWidget->setCurrentWidget(ui->chaptersViewPage);
|
||||
if (ui->playbackProgressIndicator->chapterModel()->rowCount() > 0) {
|
||||
const QModelIndex & curChapterItem = ui->playbackProgressIndicator->currentChapterItem();
|
||||
if (curChapterItem.isValid()) {
|
||||
ui->chapterlistView->setCurrentIndex(curChapterItem);
|
||||
ui->chapterlistView->scrollTo(curChapterItem, QAbstractItemView::EnsureVisible);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void MainWindow::on_actionOpen_triggered()
|
||||
{
|
||||
loadFile();
|
||||
}
|
||||
|
||||
void MainWindow::on_actionHelp_triggered()
|
||||
{
|
||||
@ -779,23 +632,12 @@ void MainWindow::on_actionHelp_triggered()
|
||||
#ifdef HAVE_KCODECS
|
||||
QStringLiteral("- [KCodecs](https://invent.kde.org/frameworks/kcodecs)\n") %
|
||||
#endif // NO_TAGLIB
|
||||
#ifdef HAVE_FFMPEG
|
||||
QStringLiteral("- [FFmpeg](https://ffmpeg.org/)\n") %
|
||||
#endif // HAVE_FFMPEG
|
||||
"\n"
|
||||
"[Source Code](https://github.com/BLumia/pineapple-music)\n"
|
||||
"\n"
|
||||
"Copyright © 2025 [BLumia](https://github.com/BLumia/)"
|
||||
"Copyright © 2024 [BLumia](https://github.com/BLumia/)"
|
||||
);
|
||||
infoBox.setTextFormat(Qt::MarkdownText);
|
||||
infoBox.exec();
|
||||
}
|
||||
|
||||
QGraphicsDropShadowEffect *MainWindow::createLabelShadowEffect()
|
||||
{
|
||||
QGraphicsDropShadowEffect * effect = new QGraphicsDropShadowEffect(this);
|
||||
effect->setBlurRadius(3);
|
||||
effect->setColor(QColor(0, 0, 0, 180));
|
||||
effect->setOffset(1, 1);
|
||||
return effect;
|
||||
}
|
||||
|
17
mainwindow.h
17
mainwindow.h
@ -1,4 +1,4 @@
|
||||
// SPDX-FileCopyrightText: 2025 Gary Wang <opensource@blumia.net>
|
||||
// SPDX-FileCopyrightText: 2024 Gary Wang <git@blumia.net>
|
||||
//
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
@ -7,7 +7,6 @@
|
||||
|
||||
#include <QMainWindow>
|
||||
#include <QVariant>
|
||||
#include <QUrl>
|
||||
|
||||
QT_BEGIN_NAMESPACE
|
||||
namespace Ui { class MainWindow; }
|
||||
@ -16,13 +15,11 @@ class QMediaDevices;
|
||||
class QMediaPlayer;
|
||||
class QAudioOutput;
|
||||
class QPropertyAnimation;
|
||||
class QGraphicsDropShadowEffect;
|
||||
QT_END_NAMESPACE
|
||||
|
||||
class FFTSpectrum;
|
||||
class LrcBar;
|
||||
class PlaylistManager;
|
||||
class TaskBarManager;
|
||||
class MainWindow : public QMainWindow
|
||||
{
|
||||
Q_OBJECT
|
||||
@ -55,10 +52,8 @@ protected:
|
||||
void mouseReleaseEvent(QMouseEvent *event) override;
|
||||
void dragEnterEvent(QDragEnterEvent *e) override;
|
||||
void dropEvent(QDropEvent *e) override;
|
||||
void contextMenuEvent(QContextMenuEvent *event) override;
|
||||
|
||||
void loadFile();
|
||||
void loadFile(const QUrl &url);
|
||||
void loadByModelIndex(const QModelIndex &index);
|
||||
void play();
|
||||
|
||||
@ -72,6 +67,7 @@ private slots:
|
||||
void on_playBtn_clicked();
|
||||
void on_volumeSlider_valueChanged(int value);
|
||||
void on_stopBtn_clicked();
|
||||
void on_playbackSlider_valueChanged(int value);
|
||||
void on_prevBtn_clicked();
|
||||
void on_nextBtn_clicked();
|
||||
void on_volumeBtn_clicked();
|
||||
@ -80,22 +76,16 @@ private slots:
|
||||
void on_playListBtn_clicked();
|
||||
void on_playlistView_activated(const QModelIndex &index);
|
||||
void on_lrcBtn_clicked();
|
||||
void on_chapterlistView_activated(const QModelIndex &index);
|
||||
void on_chapterNameBtn_clicked();
|
||||
void on_actionOpen_triggered();
|
||||
void on_actionHelp_triggered();
|
||||
|
||||
signals:
|
||||
void playbackModeChanged(enum PlaybackMode mode);
|
||||
|
||||
private:
|
||||
QGraphicsDropShadowEffect * createLabelShadowEffect();
|
||||
|
||||
bool m_clickedOnWindow = false;
|
||||
bool m_playbackSliderPressed = false;
|
||||
QLinearGradient m_bgLinearGradient;
|
||||
QPixmap m_skin;
|
||||
QUrl m_urlMissingTagLibMetadata;
|
||||
enum PlaybackMode m_playbackMode = CurrentItemInLoop;
|
||||
|
||||
Ui::MainWindow *ui;
|
||||
@ -107,13 +97,10 @@ private:
|
||||
LrcBar *m_lrcbar;
|
||||
QPropertyAnimation *m_fadeOutAnimation;
|
||||
PlaylistManager *m_playlistManager;
|
||||
TaskBarManager *m_taskbarManager;
|
||||
|
||||
void initUiAndAnimation();
|
||||
void initConnections();
|
||||
|
||||
void loadConfig();
|
||||
void saveConfig();
|
||||
void loadSkinData();
|
||||
void saveSkinData();
|
||||
|
||||
|
104
mainwindow.ui
104
mainwindow.ui
@ -72,7 +72,6 @@ QSlider::add-page:vertical {
|
||||
/****** PushButton ******/
|
||||
|
||||
QPushButton {
|
||||
color: white;
|
||||
border: 0px solid grey;
|
||||
background-color: transparent;
|
||||
}
|
||||
@ -107,20 +106,7 @@ QLabel#coverLabel {
|
||||
/****** ListView ******/
|
||||
|
||||
QListView {
|
||||
color: white;
|
||||
background: rgba(0, 0, 0, 50);
|
||||
}
|
||||
|
||||
/****** TreeView ******/
|
||||
|
||||
QTreeView {
|
||||
color: white;
|
||||
background: rgba(0, 0, 0, 50);
|
||||
}
|
||||
|
||||
QHeaderView {
|
||||
color: white;
|
||||
background-color: rgba(200, 200, 200, 50);
|
||||
}</string>
|
||||
</property>
|
||||
<property name="locale">
|
||||
@ -229,7 +215,7 @@ QHeaderView {
|
||||
<item>
|
||||
<spacer name="horizontalSpacer">
|
||||
<property name="orientation">
|
||||
<enum>Qt::Horizontal</enum>
|
||||
<enum>Qt::Orientation::Horizontal</enum>
|
||||
</property>
|
||||
<property name="sizeHint" stdset="0">
|
||||
<size>
|
||||
@ -307,7 +293,7 @@ QHeaderView {
|
||||
<item>
|
||||
<layout class="QVBoxLayout" name="playerPanelLayout">
|
||||
<property name="sizeConstraint">
|
||||
<enum>QLayout::SetDefaultConstraint</enum>
|
||||
<enum>QLayout::SizeConstraint::SetDefaultConstraint</enum>
|
||||
</property>
|
||||
<property name="rightMargin">
|
||||
<number>10</number>
|
||||
@ -370,33 +356,27 @@ QHeaderView {
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QPushButton" name="chapterNameBtn">
|
||||
<property name="sizePolicy">
|
||||
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
|
||||
<horstretch>0</horstretch>
|
||||
<verstretch>0</verstretch>
|
||||
</sizepolicy>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string/>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QLabel" name="totalTimeLabel">
|
||||
<property name="text">
|
||||
<string notr="true">0:00</string>
|
||||
</property>
|
||||
<property name="alignment">
|
||||
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
|
||||
<set>Qt::AlignmentFlag::AlignRight|Qt::AlignmentFlag::AlignTrailing|Qt::AlignmentFlag::AlignVCenter</set>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="PlaybackProgressIndicator" name="playbackProgressIndicator" native="true"/>
|
||||
<widget class="SeekableSlider" name="playbackSlider">
|
||||
<property name="maximum">
|
||||
<number>1000</number>
|
||||
</property>
|
||||
<property name="orientation">
|
||||
<enum>Qt::Orientation::Horizontal</enum>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<layout class="QHBoxLayout" name="playbackControlLayout">
|
||||
@ -624,7 +604,7 @@ QHeaderView {
|
||||
<number>100</number>
|
||||
</property>
|
||||
<property name="orientation">
|
||||
<enum>Qt::Horizontal</enum>
|
||||
<enum>Qt::Orientation::Horizontal</enum>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
@ -651,10 +631,7 @@ QHeaderView {
|
||||
<height>0</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="currentIndex">
|
||||
<number>1</number>
|
||||
</property>
|
||||
<widget class="QWidget" name="playlistViewPage">
|
||||
<widget class="QWidget" name="pluginStackedWidgetPage1">
|
||||
<layout class="QVBoxLayout" name="verticalLayout_2">
|
||||
<property name="spacing">
|
||||
<number>0</number>
|
||||
@ -676,62 +653,19 @@ QHeaderView {
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
<widget class="QWidget" name="chaptersViewPage">
|
||||
<layout class="QVBoxLayout" name="verticalLayout_3">
|
||||
<property name="leftMargin">
|
||||
<number>4</number>
|
||||
</property>
|
||||
<property name="topMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="rightMargin">
|
||||
<number>4</number>
|
||||
</property>
|
||||
<property name="bottomMargin">
|
||||
<number>4</number>
|
||||
</property>
|
||||
<item>
|
||||
<widget class="QTreeView" name="chapterlistView">
|
||||
<property name="editTriggers">
|
||||
<set>QAbstractItemView::NoEditTriggers</set>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
<action name="actionHelp">
|
||||
<property name="icon">
|
||||
<iconset theme="system-help"/>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>About</string>
|
||||
</property>
|
||||
<property name="toolTip">
|
||||
<string>About</string>
|
||||
<string>help</string>
|
||||
</property>
|
||||
<property name="shortcut">
|
||||
<string notr="true">F1</string>
|
||||
<string>F1</string>
|
||||
</property>
|
||||
<property name="menuRole">
|
||||
<enum>QAction::AboutRole</enum>
|
||||
</property>
|
||||
</action>
|
||||
<action name="actionOpen">
|
||||
<property name="icon">
|
||||
<iconset theme="document-open"/>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Open</string>
|
||||
</property>
|
||||
<property name="shortcut">
|
||||
<string notr="true">Ctrl+O</string>
|
||||
</property>
|
||||
<property name="menuRole">
|
||||
<enum>QAction::NoRole</enum>
|
||||
<enum>QAction::MenuRole::NoRole</enum>
|
||||
</property>
|
||||
</action>
|
||||
</widget>
|
||||
@ -741,12 +675,6 @@ QHeaderView {
|
||||
<extends>QSlider</extends>
|
||||
<header>seekableslider.h</header>
|
||||
</customwidget>
|
||||
<customwidget>
|
||||
<class>PlaybackProgressIndicator</class>
|
||||
<extends>QWidget</extends>
|
||||
<header>playbackprogressindicator.h</header>
|
||||
<container>1</container>
|
||||
</customwidget>
|
||||
</customwidgets>
|
||||
<resources>
|
||||
<include location="resources.qrc"/>
|
||||
|
@ -1,362 +0,0 @@
|
||||
// SPDX-FileCopyrightText: 2025 Gary Wang <git@blumia.net>
|
||||
//
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#include "playbackprogressindicator.h"
|
||||
|
||||
#include <QDir>
|
||||
#include <QFile>
|
||||
#include <QFileInfo>
|
||||
#include <QPainter>
|
||||
#include <QPainterPath>
|
||||
#include <QRegularExpression>
|
||||
|
||||
#ifdef HAVE_FFMPEG
|
||||
extern "C" {
|
||||
#include <libavformat/avformat.h>
|
||||
#include <libavutil/avutil.h>
|
||||
#include <libavutil/dict.h>
|
||||
#include <libavutil/time.h> // Contains AV_TIME_BASE and AV_TIME_BASE_Q
|
||||
} // extern "C"
|
||||
#endif // HAVE_FFMPEG
|
||||
|
||||
PlaybackProgressIndicator::PlaybackProgressIndicator(QWidget *parent) :
|
||||
QWidget(parent)
|
||||
{
|
||||
}
|
||||
|
||||
QModelIndex PlaybackProgressIndicator::currentChapterItem() const
|
||||
{
|
||||
int currentChapterIndex = -1;
|
||||
|
||||
for (int i = 0; i < m_chapterModel.rowCount(); i++) {
|
||||
QStandardItem* timeItem = m_chapterModel.item(i, 0);
|
||||
qint64 chapterStartTime = timeItem->data(PlaybackProgressIndicator::StartTimeMsRole).toLongLong();
|
||||
|
||||
if (m_position >= chapterStartTime) {
|
||||
currentChapterIndex = i;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (currentChapterIndex >= 0) {
|
||||
return m_chapterModel.index(currentChapterIndex, 0);
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
QString PlaybackProgressIndicator::currentChapterName() const
|
||||
{
|
||||
const QModelIndex timeIndex(currentChapterItem());
|
||||
if (timeIndex.isValid()) {
|
||||
return m_chapterModel.item(timeIndex.row(), 1)->text();
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
void PlaybackProgressIndicator::setPosition(qint64 pos)
|
||||
{
|
||||
m_position = pos;
|
||||
emit positionChanged(m_position);
|
||||
}
|
||||
|
||||
void PlaybackProgressIndicator::setDuration(qint64 dur)
|
||||
{
|
||||
m_duration = dur;
|
||||
emit durationChanged(m_duration);
|
||||
}
|
||||
|
||||
QString PlaybackProgressIndicator::formatTime(qint64 milliseconds)
|
||||
{
|
||||
QTime duaTime(QTime::fromMSecsSinceStartOfDay(milliseconds));
|
||||
if (duaTime.hour() > 0) {
|
||||
return duaTime.toString("h:mm:ss");
|
||||
} else {
|
||||
return duaTime.toString("m:ss");
|
||||
}
|
||||
}
|
||||
|
||||
void PlaybackProgressIndicator::setChapters(QList<std::pair<qint64, QString> > chapters)
|
||||
{
|
||||
m_chapterModel.clear();
|
||||
|
||||
m_chapterModel.setHorizontalHeaderLabels(QStringList() << tr("Time") << tr("Chapter Name"));
|
||||
|
||||
for (const std::pair<qint64, QString> & chapter : chapters) {
|
||||
QList<QStandardItem*> row;
|
||||
|
||||
QStandardItem * timeItem = new QStandardItem(formatTime(chapter.first));
|
||||
timeItem->setData(chapter.first, StartTimeMsRole);
|
||||
row.append(timeItem);
|
||||
|
||||
QStandardItem * chapterItem = new QStandardItem(chapter.second);
|
||||
chapterItem->setData(chapter.first, StartTimeMsRole);
|
||||
row.append(chapterItem);
|
||||
|
||||
m_chapterModel.appendRow(row);
|
||||
}
|
||||
update();
|
||||
}
|
||||
|
||||
QList<std::pair<qint64, QString> > PlaybackProgressIndicator::tryLoadChapters(const QString &filePath)
|
||||
{
|
||||
auto chapters = tryLoadSidecarChapterFile(filePath);
|
||||
if (chapters.size() == 0) {
|
||||
chapters = tryLoadChaptersFromMetadata(filePath);
|
||||
}
|
||||
return chapters;
|
||||
}
|
||||
|
||||
QList<std::pair<qint64, QString> > PlaybackProgressIndicator::tryLoadSidecarChapterFile(const QString &filePath)
|
||||
{
|
||||
if (filePath.endsWith(".chp", Qt::CaseInsensitive)) {
|
||||
return parseCHPChapterFile(filePath);
|
||||
} else if (filePath.endsWith(".pbf", Qt::CaseInsensitive)) {
|
||||
return parsePBFChapterFile(filePath);
|
||||
}
|
||||
|
||||
QFileInfo fileInfo(filePath);
|
||||
fileInfo.setFile(fileInfo.dir().filePath(fileInfo.completeBaseName() + ".chp"));
|
||||
if (fileInfo.exists()) {
|
||||
return parseCHPChapterFile(fileInfo.absoluteFilePath());
|
||||
}
|
||||
fileInfo.setFile(fileInfo.dir().filePath(fileInfo.completeBaseName() + ".pbf"));
|
||||
if (fileInfo.exists()) {
|
||||
return parsePBFChapterFile(fileInfo.absoluteFilePath());
|
||||
}
|
||||
fileInfo.setFile(filePath + ".chp");
|
||||
if (fileInfo.exists()) {
|
||||
return parseCHPChapterFile(fileInfo.absoluteFilePath());
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
#ifdef HAVE_FFMPEG
|
||||
|
||||
// Helper function to convert FFmpeg time (in time_base units) to milliseconds
|
||||
qint64 convertTimestampToMilliseconds(int64_t timestamp, AVRational time_base) {
|
||||
// Convert to seconds first, then to milliseconds and cast to qint64
|
||||
return static_cast<qint64>((double)timestamp * av_q2d(time_base) * 1000.0);
|
||||
}
|
||||
|
||||
// Helper function to print FFmpeg errors
|
||||
void printFFmpegError(int errnum) {
|
||||
char errbuf[AV_ERROR_MAX_STRING_SIZE];
|
||||
av_strerror(errnum, errbuf, sizeof(errbuf));
|
||||
qCritical() << "FFmpeg error:" << errbuf;
|
||||
}
|
||||
|
||||
#endif // HAVE_FFMPEG
|
||||
|
||||
QList<std::pair<qint64, QString> > PlaybackProgressIndicator::tryLoadChaptersFromMetadata(const QString &filePath)
|
||||
{
|
||||
#ifdef HAVE_FFMPEG
|
||||
if (!QFile::exists(filePath)) {
|
||||
qCritical() << "Error: File not found" << filePath;
|
||||
return {};
|
||||
}
|
||||
|
||||
AVFormatContext* format_ctx = nullptr; // FFmpeg format context
|
||||
int ret = 0; // Return value for FFmpeg functions
|
||||
|
||||
qInfo() << "Attempting to open file:" << filePath;
|
||||
|
||||
// Open the input file and read the header.
|
||||
// The last two arguments (AVInputFormat*, AVDictionary**) are optional.
|
||||
// Passing nullptr for them means FFmpeg will try to guess the format
|
||||
// and no options will be passed to the demuxer.
|
||||
ret = avformat_open_input(&format_ctx, filePath.toUtf8().constData(), nullptr, nullptr);
|
||||
if (ret < 0) {
|
||||
qCritical() << "Could not open input file:" << filePath;
|
||||
printFFmpegError(ret);
|
||||
return {};
|
||||
}
|
||||
qInfo() << "File opened successfully.";
|
||||
|
||||
// Read stream information from the file.
|
||||
// This populates format_ctx->streams and other metadata, including chapters.
|
||||
ret = avformat_find_stream_info(format_ctx, nullptr);
|
||||
if (ret < 0) {
|
||||
qCritical() << "Could not find stream information for file:" << filePath;
|
||||
printFFmpegError(ret);
|
||||
avformat_close_input(&format_ctx); // Close the context before returning
|
||||
return {};
|
||||
}
|
||||
qInfo() << "Stream information found.";
|
||||
|
||||
QList<std::pair<qint64, QString>> chapterList;
|
||||
|
||||
// Check if there are any chapters
|
||||
if (format_ctx->nb_chapters == 0) {
|
||||
qInfo() << "No chapters found in file:" << filePath;
|
||||
} else {
|
||||
qInfo() << "Found" << format_ctx->nb_chapters << "chapters.";
|
||||
// Iterate through each chapter
|
||||
for (unsigned int i = 0; i < format_ctx->nb_chapters; ++i) {
|
||||
AVChapter* chapter = format_ctx->chapters[i];
|
||||
|
||||
// Chapter timestamps are typically in AV_TIME_BASE units by default
|
||||
// unless the chapter itself has a specific time_base.
|
||||
// For simplicity and common cases, we use AV_TIME_BASE_Q.
|
||||
qint64 start_ms = convertTimestampToMilliseconds(chapter->start, chapter->time_base);
|
||||
|
||||
// Get the chapter title from its metadata.
|
||||
// av_dict_get(dictionary, key, prev, flags)
|
||||
// prev is used for iterating through multiple entries with the same key,
|
||||
// we want the first one so we pass nullptr. flags=0 for case-insensitive.
|
||||
AVDictionaryEntry* title_tag = av_dict_get(chapter->metadata, "title", nullptr, 0);
|
||||
QString chapter_title = (title_tag && title_tag->value) ? QString::fromUtf8(title_tag->value) : "Untitled Chapter";
|
||||
|
||||
chapterList.append(std::make_pair(start_ms, chapter_title));
|
||||
}
|
||||
}
|
||||
|
||||
// Close the input file.
|
||||
// This also frees the format_ctx and associated data.
|
||||
avformat_close_input(&format_ctx);
|
||||
qInfo() << "File closed.";
|
||||
|
||||
return chapterList;
|
||||
#else
|
||||
qInfo() << "FFmpeg not found during build.";
|
||||
return {};
|
||||
#endif // HAVE_FFMPEG
|
||||
}
|
||||
|
||||
QList<std::pair<qint64, QString> > PlaybackProgressIndicator::parseCHPChapterFile(const QString &filePath)
|
||||
{
|
||||
QList<std::pair<qint64, QString>> chapters;
|
||||
QFile file(filePath);
|
||||
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
|
||||
return chapters;
|
||||
}
|
||||
|
||||
QTextStream in(&file);
|
||||
QRegularExpression timeRegex(R"((\d{1,2}):(\d{2})(?::(\d{2}))?(?:\.(\d{1,3}))?)");
|
||||
|
||||
while (!in.atEnd()) {
|
||||
QString line = in.readLine().trimmed();
|
||||
QRegularExpressionMatch match = timeRegex.match(line);
|
||||
if (match.hasMatch()) {
|
||||
int hours = match.capturedView(3).isEmpty() ? 0 : match.capturedView(1).toInt();
|
||||
int minutes = match.capturedView(3).isEmpty() ? match.capturedView(1).toInt() : match.capturedView(2).toInt();
|
||||
int seconds = match.capturedView(3).isEmpty() ? match.capturedView(2).toInt() : match.capturedView(3).toInt();
|
||||
int milliseconds = 0;
|
||||
|
||||
QStringView millisecondsStr(match.capturedView(4));
|
||||
if (!millisecondsStr.isEmpty()) {
|
||||
milliseconds = millisecondsStr.toInt() * pow(10, 3 - millisecondsStr.length());
|
||||
}
|
||||
|
||||
qint64 totalMilliseconds = (hours * 3600 + minutes * 60 + seconds) * 1000 + milliseconds;
|
||||
|
||||
QString chapterTitle = line.mid(match.capturedLength()).trimmed();
|
||||
chapters.append(std::make_pair(totalMilliseconds, chapterTitle));
|
||||
}
|
||||
}
|
||||
|
||||
file.close();
|
||||
return chapters;
|
||||
}
|
||||
|
||||
QList<std::pair<qint64, QString> > PlaybackProgressIndicator::parsePBFChapterFile(const QString &filePath)
|
||||
{
|
||||
QList<std::pair<qint64, QString>> chapters;
|
||||
QFile file(filePath);
|
||||
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
|
||||
return chapters;
|
||||
}
|
||||
|
||||
QTextStream in(&file);
|
||||
QRegularExpression chapterRegex(R"(^\d+=(\d+)\*([^*]*)\*.*$)");
|
||||
|
||||
while (!in.atEnd()) {
|
||||
QString line = in.readLine().trimmed();
|
||||
QRegularExpressionMatch match = chapterRegex.match(line);
|
||||
if (match.hasMatch()) {
|
||||
qint64 timestamp = match.captured(1).toLongLong();
|
||||
QString title = match.captured(2).trimmed();
|
||||
chapters.append(std::make_pair(timestamp, title));
|
||||
}
|
||||
}
|
||||
|
||||
file.close();
|
||||
return chapters;
|
||||
}
|
||||
|
||||
void PlaybackProgressIndicator::paintEvent(QPaintEvent *event)
|
||||
{
|
||||
constexpr int progressBarHeight = 6;
|
||||
constexpr QColor activeColor = QColor(85, 170, 0);
|
||||
const QPointF topLeft(0, height() / 2.0 - progressBarHeight / 2.0);
|
||||
const QSizeF barSize(width(), progressBarHeight);
|
||||
|
||||
const float currentProgress = m_duration <= 0 ? 0 : (m_seekingPosition >= 0 ? m_seekingPosition : m_position) / (float)m_duration;
|
||||
const QSizeF progressSize(width() * currentProgress, progressBarHeight);
|
||||
|
||||
QPainterPath theProgress;
|
||||
theProgress.addRoundedRect(QRectF(topLeft, progressSize), progressBarHeight / 2, progressBarHeight / 2);
|
||||
|
||||
QPainter painter(this);
|
||||
painter.setRenderHint(QPainter::Antialiasing);
|
||||
painter.save();
|
||||
|
||||
// the bar itself
|
||||
painter.setPen(Qt::gray);
|
||||
painter.drawRoundedRect(QRectF(topLeft, barSize), progressBarHeight / 2, progressBarHeight / 2);
|
||||
painter.fillPath(theProgress, activeColor);
|
||||
|
||||
// progress
|
||||
painter.setPen(activeColor);
|
||||
painter.drawPath(theProgress);
|
||||
|
||||
// chapter markers
|
||||
if (m_duration > 0) {
|
||||
painter.setPen(Qt::lightGray);
|
||||
for (int i = 0; i < m_chapterModel.rowCount(); i++) {
|
||||
qint64 chapterStartTime = m_chapterModel.item(i)->data(StartTimeMsRole).toInt();
|
||||
if (chapterStartTime == 0) continue;
|
||||
if (chapterStartTime > m_duration) break;
|
||||
float chapterPercent = chapterStartTime / (float)m_duration;
|
||||
float chapterPosX = width() * chapterPercent;
|
||||
painter.drawLine(topLeft + QPoint(chapterPosX, 0),
|
||||
topLeft + QPoint(chapterPosX, progressBarHeight));
|
||||
}
|
||||
}
|
||||
|
||||
painter.restore();
|
||||
}
|
||||
|
||||
void PlaybackProgressIndicator::mousePressEvent(QMouseEvent *event)
|
||||
{
|
||||
if (m_duration > 0) {
|
||||
event->accept();
|
||||
} else {
|
||||
return QWidget::mousePressEvent(event);
|
||||
}
|
||||
}
|
||||
|
||||
void PlaybackProgressIndicator::mouseMoveEvent(QMouseEvent *event)
|
||||
{
|
||||
if (m_duration > 0) {
|
||||
m_seekingPosition = event->position().x() * m_duration / width();
|
||||
if (m_seekOnMove) {
|
||||
emit seekingRequested(m_seekingPosition);
|
||||
}
|
||||
update();
|
||||
}
|
||||
return QWidget::mouseMoveEvent(event);
|
||||
}
|
||||
|
||||
void PlaybackProgressIndicator::mouseReleaseEvent(QMouseEvent *event)
|
||||
{
|
||||
if (m_duration > 0) {
|
||||
int seekingPosition = event->position().x() * m_duration / width();
|
||||
m_seekingPosition = -1;
|
||||
emit seekingRequested(seekingPosition);
|
||||
}
|
||||
update();
|
||||
return QWidget::mouseReleaseEvent(event);
|
||||
}
|
@ -1,63 +0,0 @@
|
||||
// SPDX-FileCopyrightText: 2025 Gary Wang <git@blumia.net>
|
||||
//
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <QWidget>
|
||||
#include <QMouseEvent>
|
||||
#include <QStandardItemModel>
|
||||
|
||||
class PlaybackProgressIndicator : public QWidget
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
Q_PROPERTY(bool seekOnMove MEMBER m_seekOnMove NOTIFY seekOnMoveChanged)
|
||||
Q_PROPERTY(qint64 position MEMBER m_position NOTIFY positionChanged)
|
||||
Q_PROPERTY(qint64 duration MEMBER m_duration NOTIFY durationChanged)
|
||||
public:
|
||||
enum Roles {
|
||||
ChapterTitleRole = Qt::DisplayRole,
|
||||
StartTimeMsRole = Qt::UserRole + 1,
|
||||
};
|
||||
|
||||
explicit PlaybackProgressIndicator(QWidget *parent = nullptr);
|
||||
~PlaybackProgressIndicator() = default;
|
||||
|
||||
QStandardItemModel* chapterModel() { return &m_chapterModel; }
|
||||
QModelIndex currentChapterItem() const;
|
||||
QString currentChapterName() const;
|
||||
|
||||
void setPosition(qint64 pos);
|
||||
void setDuration(qint64 dur);
|
||||
void setChapters(QList<std::pair<qint64, QString>> chapters);
|
||||
|
||||
static QString formatTime(qint64 milliseconds);
|
||||
static QList<std::pair<qint64, QString>> tryLoadChapters(const QString & filePath);
|
||||
static QList<std::pair<qint64, QString>> tryLoadSidecarChapterFile(const QString & filePath);
|
||||
static QList<std::pair<qint64, QString>> tryLoadChaptersFromMetadata(const QString & filePath);
|
||||
static QList<std::pair<qint64, QString>> parseCHPChapterFile(const QString & filePath);
|
||||
static QList<std::pair<qint64, QString>> parsePBFChapterFile(const QString & filePath);
|
||||
|
||||
signals:
|
||||
void seekOnMoveChanged(bool sow);
|
||||
void positionChanged(qint64 newPosition);
|
||||
void durationChanged(qint64 newDuration);
|
||||
void seekingRequested(qint64 position);
|
||||
|
||||
public slots:
|
||||
|
||||
protected:
|
||||
void paintEvent(QPaintEvent *event) override;
|
||||
void mousePressEvent(QMouseEvent *event) override;
|
||||
void mouseMoveEvent(QMouseEvent *event) override;
|
||||
void mouseReleaseEvent(QMouseEvent *event) override;
|
||||
|
||||
private:
|
||||
bool m_seekOnMove = true;
|
||||
qint64 m_position = -1;
|
||||
qint64 m_seekingPosition = -1;
|
||||
qint64 m_duration = -1;
|
||||
QStandardItemModel m_chapterModel;
|
||||
};
|
||||
|
@ -1,283 +1,255 @@
|
||||
// SPDX-FileCopyrightText: 2025 Gary Wang <git@blumia.net>
|
||||
//
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#include "playlistmanager.h"
|
||||
|
||||
#include <QCollator>
|
||||
#include <QDir>
|
||||
#include <QFileInfo>
|
||||
#include <QUrl>
|
||||
|
||||
PlaylistModel::PlaylistModel(QObject *parent)
|
||||
: QAbstractListModel(parent)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
PlaylistModel::~PlaylistModel()
|
||||
= default;
|
||||
|
||||
void PlaylistModel::setPlaylist(const QList<QUrl> &urls)
|
||||
{
|
||||
beginResetModel();
|
||||
m_playlist = urls;
|
||||
endResetModel();
|
||||
}
|
||||
|
||||
QModelIndex PlaylistModel::loadPlaylist(const QList<QUrl> & urls)
|
||||
{
|
||||
if (urls.isEmpty()) return {};
|
||||
if (urls.count() == 1) {
|
||||
return loadPlaylist(urls.constFirst());
|
||||
} else {
|
||||
setPlaylist(urls);
|
||||
return index(0);
|
||||
}
|
||||
}
|
||||
|
||||
QModelIndex PlaylistModel::loadPlaylist(const QUrl &url)
|
||||
{
|
||||
QFileInfo info(url.toLocalFile());
|
||||
QDir dir(info.path());
|
||||
QString && currentFileName = info.fileName();
|
||||
|
||||
if (dir.path() == m_currentDir) {
|
||||
int idx = indexOf(url);
|
||||
return idx == -1 ? appendToPlaylist(url) : index(idx);
|
||||
}
|
||||
|
||||
QStringList entryList = dir.entryList(
|
||||
m_autoLoadSuffixes,
|
||||
QDir::Files | QDir::NoSymLinks, QDir::NoSort);
|
||||
|
||||
QCollator collator;
|
||||
collator.setNumericMode(true);
|
||||
|
||||
std::sort(entryList.begin(), entryList.end(), collator);
|
||||
|
||||
QList<QUrl> playlist;
|
||||
|
||||
int idx = -1;
|
||||
for (int i = 0; i < entryList.count(); i++) {
|
||||
const QString & fileName = entryList.at(i);
|
||||
const QString & oneEntry = dir.absoluteFilePath(fileName);
|
||||
const QUrl & url = QUrl::fromLocalFile(oneEntry);
|
||||
playlist.append(url);
|
||||
if (fileName == currentFileName) {
|
||||
idx = i;
|
||||
}
|
||||
}
|
||||
if (idx == -1) {
|
||||
idx = playlist.count();
|
||||
playlist.append(url);
|
||||
}
|
||||
m_currentDir = dir.path();
|
||||
|
||||
setPlaylist(playlist);
|
||||
|
||||
return index(idx);
|
||||
}
|
||||
|
||||
QModelIndex PlaylistModel::appendToPlaylist(const QUrl &url)
|
||||
{
|
||||
const int lastIndex = rowCount();
|
||||
beginInsertRows(QModelIndex(), lastIndex, lastIndex);
|
||||
m_playlist.append(url);
|
||||
endInsertRows();
|
||||
return index(lastIndex);
|
||||
}
|
||||
|
||||
bool PlaylistModel::removeAt(int index)
|
||||
{
|
||||
if (index < 0 || index >= rowCount()) return false;
|
||||
beginRemoveRows(QModelIndex(), index, index);
|
||||
m_playlist.removeAt(index);
|
||||
endRemoveRows();
|
||||
return true;
|
||||
}
|
||||
|
||||
int PlaylistModel::indexOf(const QUrl &url) const
|
||||
{
|
||||
return m_playlist.indexOf(url);
|
||||
}
|
||||
|
||||
QUrl PlaylistModel::urlByIndex(int index) const
|
||||
{
|
||||
return m_playlist.value(index);
|
||||
}
|
||||
|
||||
QStringList PlaylistModel::autoLoadFilterSuffixes() const
|
||||
{
|
||||
return m_autoLoadSuffixes;
|
||||
}
|
||||
|
||||
QHash<int, QByteArray> PlaylistModel::roleNames() const
|
||||
{
|
||||
QHash<int, QByteArray> result = QAbstractListModel::roleNames();
|
||||
result.insert(UrlRole, "url");
|
||||
return result;
|
||||
}
|
||||
|
||||
int PlaylistModel::rowCount(const QModelIndex &parent) const
|
||||
{
|
||||
return m_playlist.count();
|
||||
}
|
||||
|
||||
QVariant PlaylistModel::data(const QModelIndex &index, int role) const
|
||||
{
|
||||
if (!index.isValid()) return {};
|
||||
|
||||
switch (role) {
|
||||
case Qt::DisplayRole:
|
||||
return m_playlist.at(index.row()).fileName();
|
||||
case UrlRole:
|
||||
return m_playlist.at(index.row());
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
PlaylistManager::PlaylistManager(QObject *parent)
|
||||
: QObject(parent)
|
||||
{
|
||||
connect(&m_model, &PlaylistModel::rowsRemoved, this,
|
||||
[this](const QModelIndex &, int, int) {
|
||||
if (m_model.rowCount() <= m_currentIndex) {
|
||||
setProperty("currentIndex", m_currentIndex - 1);
|
||||
}
|
||||
});
|
||||
|
||||
auto onRowCountChanged = [this](){
|
||||
emit totalCountChanged(m_model.rowCount());
|
||||
};
|
||||
|
||||
connect(&m_model, &PlaylistModel::rowsInserted, this, onRowCountChanged);
|
||||
connect(&m_model, &PlaylistModel::rowsRemoved, this, onRowCountChanged);
|
||||
connect(&m_model, &PlaylistModel::modelReset, this, onRowCountChanged);
|
||||
}
|
||||
|
||||
PlaylistManager::~PlaylistManager()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
PlaylistModel *PlaylistManager::model()
|
||||
{
|
||||
return &m_model;
|
||||
}
|
||||
|
||||
void PlaylistManager::setPlaylist(const QList<QUrl> &urls)
|
||||
{
|
||||
m_model.setPlaylist(urls);
|
||||
}
|
||||
|
||||
QModelIndex PlaylistManager::loadPlaylist(const QList<QUrl> &urls)
|
||||
{
|
||||
QModelIndex idx = m_model.loadPlaylist(urls);
|
||||
setProperty("currentIndex", idx.row());
|
||||
return idx;
|
||||
}
|
||||
|
||||
QModelIndex PlaylistManager::loadPlaylist(const QUrl &url)
|
||||
{
|
||||
QModelIndex idx = m_model.loadPlaylist(url);
|
||||
setProperty("currentIndex", idx.row());
|
||||
return idx;
|
||||
}
|
||||
|
||||
QModelIndex PlaylistManager::loadM3U8Playlist(const QUrl &url)
|
||||
{
|
||||
QFile file(url.toLocalFile());
|
||||
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
|
||||
QList<QUrl> urls;
|
||||
while (!file.atEnd()) {
|
||||
QString line = file.readLine();
|
||||
if (line.startsWith('#')) {
|
||||
continue;
|
||||
}
|
||||
QFileInfo fileInfo(file);
|
||||
QUrl item = QUrl::fromUserInput(line, fileInfo.absolutePath());
|
||||
urls.append(item);
|
||||
}
|
||||
return loadPlaylist(urls);
|
||||
} else {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
int PlaylistManager::totalCount() const
|
||||
{
|
||||
return m_model.rowCount();
|
||||
}
|
||||
|
||||
QModelIndex PlaylistManager::previousIndex() const
|
||||
{
|
||||
int count = totalCount();
|
||||
if (count == 0) return {};
|
||||
|
||||
return m_model.index(isFirstIndex() ? count - 1 : m_currentIndex - 1);
|
||||
}
|
||||
|
||||
QModelIndex PlaylistManager::nextIndex() const
|
||||
{
|
||||
int count = totalCount();
|
||||
if (count == 0) return {};
|
||||
|
||||
return m_model.index(isLastIndex() ? 0 : m_currentIndex + 1);
|
||||
}
|
||||
|
||||
QModelIndex PlaylistManager::curIndex() const
|
||||
{
|
||||
return m_model.index(m_currentIndex);
|
||||
}
|
||||
|
||||
bool PlaylistManager::isFirstIndex() const
|
||||
{
|
||||
return m_currentIndex == 0;
|
||||
}
|
||||
|
||||
bool PlaylistManager::isLastIndex() const
|
||||
{
|
||||
return m_currentIndex + 1 == totalCount();
|
||||
}
|
||||
|
||||
void PlaylistManager::setCurrentIndex(const QModelIndex &index)
|
||||
{
|
||||
if (index.isValid() && index.row() >= 0 && index.row() < totalCount()) {
|
||||
setProperty("currentIndex", index.row());
|
||||
}
|
||||
}
|
||||
|
||||
QUrl PlaylistManager::urlByIndex(const QModelIndex &index)
|
||||
{
|
||||
return m_model.urlByIndex(index.row());
|
||||
}
|
||||
|
||||
QString PlaylistManager::localFileByIndex(const QModelIndex &index)
|
||||
{
|
||||
return urlByIndex(index).toLocalFile();
|
||||
}
|
||||
|
||||
bool PlaylistManager::removeAt(const QModelIndex &index)
|
||||
{
|
||||
return m_model.removeAt(index.row());
|
||||
}
|
||||
|
||||
void PlaylistManager::setAutoLoadFilterSuffixes(const QStringList &nameFilters)
|
||||
{
|
||||
m_model.setProperty("autoLoadFilterSuffixes", nameFilters);
|
||||
}
|
||||
|
||||
QList<QUrl> PlaylistManager::convertToUrlList(const QStringList &files)
|
||||
{
|
||||
QList<QUrl> urlList;
|
||||
for (const QString & str : std::as_const(files)) {
|
||||
QUrl url = QUrl::fromLocalFile(str);
|
||||
if (url.isValid()) {
|
||||
urlList.append(url);
|
||||
}
|
||||
}
|
||||
|
||||
return urlList;
|
||||
}
|
||||
// SPDX-FileCopyrightText: 2024 Gary Wang <git@blumia.net>
|
||||
//
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#include "playlistmanager.h"
|
||||
|
||||
#include <QCollator>
|
||||
#include <QDir>
|
||||
#include <QFileInfo>
|
||||
#include <QUrl>
|
||||
|
||||
PlaylistModel::PlaylistModel(QObject *parent)
|
||||
: QAbstractListModel(parent)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
PlaylistModel::~PlaylistModel()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
void PlaylistModel::setPlaylist(const QList<QUrl> &urls)
|
||||
{
|
||||
beginResetModel();
|
||||
m_playlist = urls;
|
||||
endResetModel();
|
||||
}
|
||||
|
||||
QModelIndex PlaylistModel::loadPlaylist(const QList<QUrl> & urls)
|
||||
{
|
||||
if (urls.isEmpty()) return QModelIndex();
|
||||
if (urls.count() == 1) {
|
||||
return loadPlaylist(urls.constFirst());
|
||||
} else {
|
||||
setPlaylist(urls);
|
||||
return index(0);
|
||||
}
|
||||
}
|
||||
|
||||
QModelIndex PlaylistModel::loadPlaylist(const QUrl &url)
|
||||
{
|
||||
QFileInfo info(url.toLocalFile());
|
||||
QDir dir(info.path());
|
||||
QString && currentFileName = info.fileName();
|
||||
|
||||
if (dir.path() == m_currentDir) {
|
||||
int idx = indexOf(url);
|
||||
return idx == -1 ? appendToPlaylist(url) : index(idx);
|
||||
}
|
||||
|
||||
QStringList entryList = dir.entryList(
|
||||
m_autoLoadSuffixes,
|
||||
QDir::Files | QDir::NoSymLinks, QDir::NoSort);
|
||||
|
||||
QCollator collator;
|
||||
collator.setNumericMode(true);
|
||||
|
||||
std::sort(entryList.begin(), entryList.end(), collator);
|
||||
|
||||
QList<QUrl> playlist;
|
||||
|
||||
int idx = -1;
|
||||
for (int i = 0; i < entryList.count(); i++) {
|
||||
const QString & fileName = entryList.at(i);
|
||||
const QString & oneEntry = dir.absoluteFilePath(fileName);
|
||||
const QUrl & url = QUrl::fromLocalFile(oneEntry);
|
||||
playlist.append(url);
|
||||
if (fileName == currentFileName) {
|
||||
idx = i;
|
||||
}
|
||||
}
|
||||
if (idx == -1) {
|
||||
idx = playlist.count();
|
||||
playlist.append(url);
|
||||
}
|
||||
m_currentDir = dir.path();
|
||||
|
||||
setPlaylist(playlist);
|
||||
|
||||
return index(idx);
|
||||
}
|
||||
|
||||
QModelIndex PlaylistModel::appendToPlaylist(const QUrl &url)
|
||||
{
|
||||
const int lastIndex = rowCount();
|
||||
beginInsertRows(QModelIndex(), lastIndex, lastIndex);
|
||||
m_playlist.append(url);
|
||||
endInsertRows();
|
||||
return index(lastIndex);
|
||||
}
|
||||
|
||||
bool PlaylistModel::removeAt(int index)
|
||||
{
|
||||
if (index < 0 || index >= rowCount()) return false;
|
||||
beginRemoveRows(QModelIndex(), index, index);
|
||||
m_playlist.removeAt(index);
|
||||
endRemoveRows();
|
||||
return true;
|
||||
}
|
||||
|
||||
int PlaylistModel::indexOf(const QUrl &url) const
|
||||
{
|
||||
return m_playlist.indexOf(url);
|
||||
}
|
||||
|
||||
QUrl PlaylistModel::urlByIndex(int index) const
|
||||
{
|
||||
return m_playlist.value(index);
|
||||
}
|
||||
|
||||
QStringList PlaylistModel::autoLoadFilterSuffixes() const
|
||||
{
|
||||
return m_autoLoadSuffixes;
|
||||
}
|
||||
|
||||
QHash<int, QByteArray> PlaylistModel::roleNames() const
|
||||
{
|
||||
QHash<int, QByteArray> result = QAbstractListModel::roleNames();
|
||||
result.insert(UrlRole, "url");
|
||||
return result;
|
||||
}
|
||||
|
||||
int PlaylistModel::rowCount(const QModelIndex &parent) const
|
||||
{
|
||||
return m_playlist.count();
|
||||
}
|
||||
|
||||
QVariant PlaylistModel::data(const QModelIndex &index, int role) const
|
||||
{
|
||||
if (!index.isValid()) return QVariant();
|
||||
|
||||
switch (role) {
|
||||
case Qt::DisplayRole:
|
||||
return m_playlist.at(index.row()).fileName();
|
||||
case UrlRole:
|
||||
return m_playlist.at(index.row());
|
||||
}
|
||||
|
||||
return QVariant();
|
||||
}
|
||||
|
||||
PlaylistManager::PlaylistManager(QObject *parent)
|
||||
: QObject(parent)
|
||||
{
|
||||
connect(&m_model, &PlaylistModel::rowsRemoved, this,
|
||||
[this](const QModelIndex &, int, int) {
|
||||
if (m_model.rowCount() <= m_currentIndex) {
|
||||
setProperty("currentIndex", m_currentIndex - 1);
|
||||
}
|
||||
});
|
||||
|
||||
auto onRowCountChanged = [this](){
|
||||
emit totalCountChanged(m_model.rowCount());
|
||||
};
|
||||
|
||||
connect(&m_model, &PlaylistModel::rowsInserted, this, onRowCountChanged);
|
||||
connect(&m_model, &PlaylistModel::rowsRemoved, this, onRowCountChanged);
|
||||
connect(&m_model, &PlaylistModel::modelReset, this, onRowCountChanged);
|
||||
}
|
||||
|
||||
PlaylistManager::~PlaylistManager()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
PlaylistModel *PlaylistManager::model()
|
||||
{
|
||||
return &m_model;
|
||||
}
|
||||
|
||||
void PlaylistManager::setPlaylist(const QList<QUrl> &urls)
|
||||
{
|
||||
m_model.setPlaylist(urls);
|
||||
}
|
||||
|
||||
QModelIndex PlaylistManager::loadPlaylist(const QList<QUrl> &urls)
|
||||
{
|
||||
QModelIndex idx = m_model.loadPlaylist(urls);
|
||||
setProperty("currentIndex", idx.row());
|
||||
return idx;
|
||||
}
|
||||
|
||||
QModelIndex PlaylistManager::loadPlaylist(const QUrl &url)
|
||||
{
|
||||
QModelIndex idx = m_model.loadPlaylist(url);
|
||||
setProperty("currentIndex", idx.row());
|
||||
return idx;
|
||||
}
|
||||
|
||||
int PlaylistManager::totalCount() const
|
||||
{
|
||||
return m_model.rowCount();
|
||||
}
|
||||
|
||||
QModelIndex PlaylistManager::previousIndex() const
|
||||
{
|
||||
int count = totalCount();
|
||||
if (count == 0) return QModelIndex();
|
||||
|
||||
return m_model.index(m_currentIndex - 1 < 0 ? count - 1 : m_currentIndex - 1);
|
||||
}
|
||||
|
||||
QModelIndex PlaylistManager::nextIndex() const
|
||||
{
|
||||
int count = totalCount();
|
||||
if (count == 0) return QModelIndex();
|
||||
|
||||
return m_model.index(m_currentIndex + 1 == count ? 0 : m_currentIndex + 1);
|
||||
}
|
||||
|
||||
QModelIndex PlaylistManager::curIndex() const
|
||||
{
|
||||
return m_model.index(m_currentIndex);
|
||||
}
|
||||
|
||||
void PlaylistManager::setCurrentIndex(const QModelIndex &index)
|
||||
{
|
||||
if (index.isValid() && index.row() >= 0 && index.row() < totalCount()) {
|
||||
setProperty("currentIndex", index.row());
|
||||
}
|
||||
}
|
||||
|
||||
QUrl PlaylistManager::urlByIndex(const QModelIndex &index)
|
||||
{
|
||||
return m_model.urlByIndex(index.row());
|
||||
}
|
||||
|
||||
QString PlaylistManager::localFileByIndex(const QModelIndex &index)
|
||||
{
|
||||
return urlByIndex(index).toLocalFile();
|
||||
}
|
||||
|
||||
bool PlaylistManager::removeAt(const QModelIndex &index)
|
||||
{
|
||||
return m_model.removeAt(index.row());
|
||||
}
|
||||
|
||||
void PlaylistManager::setAutoLoadFilterSuffixes(const QStringList &nameFilters)
|
||||
{
|
||||
m_model.setProperty("autoLoadFilterSuffixes", nameFilters);
|
||||
}
|
||||
|
||||
QList<QUrl> PlaylistManager::convertToUrlList(const QStringList &files)
|
||||
{
|
||||
QList<QUrl> urlList;
|
||||
for (const QString & str : std::as_const(files)) {
|
||||
QUrl url = QUrl::fromLocalFile(str);
|
||||
if (url.isValid()) {
|
||||
urlList.append(url);
|
||||
}
|
||||
}
|
||||
|
||||
return urlList;
|
||||
}
|
||||
|
@ -1,88 +1,85 @@
|
||||
// SPDX-FileCopyrightText: 2025 Gary Wang <git@blumia.net>
|
||||
//
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <QUrl>
|
||||
#include <QAbstractListModel>
|
||||
|
||||
class PlaylistModel : public QAbstractListModel
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
enum PlaylistRole {
|
||||
UrlRole = Qt::UserRole
|
||||
};
|
||||
Q_ENUM(PlaylistRole)
|
||||
Q_PROPERTY(QStringList autoLoadFilterSuffixes MEMBER m_autoLoadSuffixes NOTIFY autoLoadFilterSuffixesChanged)
|
||||
|
||||
explicit PlaylistModel(QObject *parent = nullptr);
|
||||
~PlaylistModel() override;
|
||||
|
||||
void setPlaylist(const QList<QUrl> & urls);
|
||||
QModelIndex loadPlaylist(const QList<QUrl> & urls);
|
||||
QModelIndex loadPlaylist(const QUrl & url);
|
||||
QModelIndex appendToPlaylist(const QUrl & url);
|
||||
bool removeAt(int index);
|
||||
int indexOf(const QUrl & url) const;
|
||||
QUrl urlByIndex(int index) const;
|
||||
QStringList autoLoadFilterSuffixes() const;
|
||||
|
||||
QHash<int, QByteArray> roleNames() const override;
|
||||
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
|
||||
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
|
||||
|
||||
signals:
|
||||
void autoLoadFilterSuffixesChanged(QStringList suffixes);
|
||||
|
||||
private:
|
||||
// model data
|
||||
QList<QUrl> m_playlist;
|
||||
// properties
|
||||
QStringList m_autoLoadSuffixes = {};
|
||||
// internal
|
||||
QString m_currentDir;
|
||||
};
|
||||
|
||||
class PlaylistManager : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
Q_PROPERTY(int currentIndex MEMBER m_currentIndex NOTIFY currentIndexChanged)
|
||||
Q_PROPERTY(QStringList autoLoadFilterSuffixes WRITE setAutoLoadFilterSuffixes)
|
||||
Q_PROPERTY(PlaylistModel * model READ model CONSTANT)
|
||||
|
||||
explicit PlaylistManager(QObject *parent = nullptr);
|
||||
~PlaylistManager();
|
||||
|
||||
PlaylistModel * model();
|
||||
|
||||
void setPlaylist(const QList<QUrl> & url);
|
||||
Q_INVOKABLE QModelIndex loadPlaylist(const QList<QUrl> & urls);
|
||||
Q_INVOKABLE QModelIndex loadPlaylist(const QUrl & url);
|
||||
Q_INVOKABLE QModelIndex loadM3U8Playlist(const QUrl & url);
|
||||
|
||||
int totalCount() const;
|
||||
QModelIndex previousIndex() const;
|
||||
QModelIndex nextIndex() const;
|
||||
QModelIndex curIndex() const;
|
||||
bool isFirstIndex() const;
|
||||
bool isLastIndex() const;
|
||||
void setCurrentIndex(const QModelIndex & index);
|
||||
QUrl urlByIndex(const QModelIndex & index);
|
||||
QString localFileByIndex(const QModelIndex & index);
|
||||
bool removeAt(const QModelIndex & index);
|
||||
|
||||
void setAutoLoadFilterSuffixes(const QStringList &nameFilters);
|
||||
|
||||
static QList<QUrl> convertToUrlList(const QStringList & files);
|
||||
|
||||
signals:
|
||||
void currentIndexChanged(int index);
|
||||
void totalCountChanged(int count);
|
||||
|
||||
private:
|
||||
int m_currentIndex = -1;
|
||||
PlaylistModel m_model;
|
||||
};
|
||||
// SPDX-FileCopyrightText: 2024 Gary Wang <git@blumia.net>
|
||||
//
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <QUrl>
|
||||
#include <QAbstractListModel>
|
||||
|
||||
class PlaylistModel : public QAbstractListModel
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
enum PlaylistRole {
|
||||
UrlRole = Qt::UserRole
|
||||
};
|
||||
Q_ENUM(PlaylistRole)
|
||||
Q_PROPERTY(QStringList autoLoadFilterSuffixes MEMBER m_autoLoadSuffixes NOTIFY autoLoadFilterSuffixesChanged)
|
||||
|
||||
explicit PlaylistModel(QObject *parent = nullptr);
|
||||
~PlaylistModel();
|
||||
|
||||
void setPlaylist(const QList<QUrl> & urls);
|
||||
QModelIndex loadPlaylist(const QList<QUrl> & urls);
|
||||
QModelIndex loadPlaylist(const QUrl & url);
|
||||
QModelIndex appendToPlaylist(const QUrl & url);
|
||||
bool removeAt(int index);
|
||||
int indexOf(const QUrl & url) const;
|
||||
QUrl urlByIndex(int index) const;
|
||||
QStringList autoLoadFilterSuffixes() const;
|
||||
|
||||
QHash<int, QByteArray> roleNames() const override;
|
||||
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
|
||||
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
|
||||
|
||||
signals:
|
||||
void autoLoadFilterSuffixesChanged(QStringList suffixes);
|
||||
|
||||
private:
|
||||
// model data
|
||||
QList<QUrl> m_playlist;
|
||||
// properties
|
||||
QStringList m_autoLoadSuffixes = {};
|
||||
// internal
|
||||
QString m_currentDir;
|
||||
};
|
||||
|
||||
class PlaylistManager : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
Q_PROPERTY(int currentIndex MEMBER m_currentIndex NOTIFY currentIndexChanged)
|
||||
Q_PROPERTY(QStringList autoLoadFilterSuffixes WRITE setAutoLoadFilterSuffixes)
|
||||
Q_PROPERTY(PlaylistModel * model READ model CONSTANT)
|
||||
|
||||
explicit PlaylistManager(QObject *parent = nullptr);
|
||||
~PlaylistManager();
|
||||
|
||||
PlaylistModel * model();
|
||||
|
||||
void setPlaylist(const QList<QUrl> & url);
|
||||
Q_INVOKABLE QModelIndex loadPlaylist(const QList<QUrl> & urls);
|
||||
Q_INVOKABLE QModelIndex loadPlaylist(const QUrl & url);
|
||||
|
||||
int totalCount() const;
|
||||
QModelIndex previousIndex() const;
|
||||
QModelIndex nextIndex() const;
|
||||
QModelIndex curIndex() const;
|
||||
void setCurrentIndex(const QModelIndex & index);
|
||||
QUrl urlByIndex(const QModelIndex & index);
|
||||
QString localFileByIndex(const QModelIndex & index);
|
||||
bool removeAt(const QModelIndex & index);
|
||||
|
||||
void setAutoLoadFilterSuffixes(const QStringList &nameFilters);
|
||||
|
||||
static QList<QUrl> convertToUrlList(const QStringList & files);
|
||||
|
||||
signals:
|
||||
void currentIndexChanged(int index);
|
||||
void totalCountChanged(int count);
|
||||
|
||||
private:
|
||||
int m_currentIndex = -1;
|
||||
PlaylistModel m_model;
|
||||
};
|
||||
|
@ -1,24 +1,24 @@
|
||||
// SPDX-FileCopyrightText: 2025 Gary Wang <git@blumia.net>
|
||||
//
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <QSlider>
|
||||
#include <QMouseEvent>
|
||||
|
||||
class SeekableSlider : public QSlider
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit SeekableSlider(QWidget *parent = nullptr);
|
||||
~SeekableSlider() override = default;
|
||||
|
||||
signals:
|
||||
|
||||
public slots:
|
||||
|
||||
protected:
|
||||
void mouseReleaseEvent(QMouseEvent *event) override;
|
||||
};
|
||||
|
||||
// SPDX-FileCopyrightText: 2024 Gary Wang <git@blumia.net>
|
||||
//
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <QSlider>
|
||||
#include <QMouseEvent>
|
||||
|
||||
class SeekableSlider : public QSlider
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit SeekableSlider(QWidget *parent = nullptr);
|
||||
~SeekableSlider() = default;
|
||||
|
||||
signals:
|
||||
|
||||
public slots:
|
||||
|
||||
protected:
|
||||
void mouseReleaseEvent(QMouseEvent *event) override;
|
||||
};
|
||||
|
||||
|
@ -1,383 +0,0 @@
|
||||
// SPDX-FileCopyrightText: 2024 (c) Jack Hill <jackhill3103@gmail.com>
|
||||
// SPDX-FileCopyrightText: 2025 (c) Gary Wang <opensource@blumia.net>
|
||||
//
|
||||
// SPDX-License-Identifier: LGPL-3.0-or-later
|
||||
//
|
||||
// This file is modified based on Elisa's taskmanager.cpp implementation,
|
||||
// with its Qt Quick usage removed.
|
||||
|
||||
#include "taskbarmanager.h"
|
||||
|
||||
#include <QAbstractEventDispatcher>
|
||||
#include <QAbstractNativeEventFilter>
|
||||
#include <QDebug>
|
||||
|
||||
#include <Shobjidl.h>
|
||||
#include <WinDef.h>
|
||||
#include <Windows.h>
|
||||
|
||||
constexpr int numOfButtons = 3;
|
||||
|
||||
#if QT_VERSION < QT_VERSION_CHECK(6, 7, 0)
|
||||
using namespace Qt::Literals::StringLiterals;
|
||||
|
||||
static HICON hiconFromTheme(const QString &iconName)
|
||||
#else
|
||||
static HICON hiconFromTheme(const QIcon::ThemeIcon iconName)
|
||||
#endif
|
||||
{
|
||||
const auto width = GetSystemMetrics(SM_CXSMICON);
|
||||
const auto height = GetSystemMetrics(SM_CYSMICON);
|
||||
return QIcon::fromTheme(iconName).pixmap(width, height).toImage().toHICON();
|
||||
}
|
||||
|
||||
class TaskBarManagerPrivate
|
||||
{
|
||||
public:
|
||||
|
||||
ITaskbarList3 *taskBar = nullptr;
|
||||
HWND hwnd = nullptr;
|
||||
|
||||
/**
|
||||
* Whether the toolbar has been added to the taskbar
|
||||
*/
|
||||
bool addedThumbButtons = false;
|
||||
|
||||
QMediaPlayer::PlaybackState playbackState = QMediaPlayer::StoppedState;
|
||||
|
||||
bool showProgress = false;
|
||||
qlonglong progressMaximum = 0;
|
||||
qlonglong progressValue = 0;
|
||||
|
||||
#if QT_VERSION < QT_VERSION_CHECK(6, 7, 0)
|
||||
HICON skipBackwardIcon = hiconFromTheme(u"media-skip-backward"_s);
|
||||
HICON skipForwardIcon = hiconFromTheme(u"media-skip-forward"_s);
|
||||
HICON playIcon = hiconFromTheme(u"media-playback-start"_s);
|
||||
HICON pauseIcon = hiconFromTheme(u"media-playback-pause"_s);
|
||||
#else
|
||||
HICON skipBackwardIcon = hiconFromTheme(QIcon::ThemeIcon::MediaSkipBackward);
|
||||
HICON skipForwardIcon = hiconFromTheme(QIcon::ThemeIcon::MediaSkipForward);
|
||||
HICON playIcon = hiconFromTheme(QIcon::ThemeIcon::MediaPlaybackStart);
|
||||
HICON pauseIcon = hiconFromTheme(QIcon::ThemeIcon::MediaPlaybackPause);
|
||||
#endif
|
||||
|
||||
/**
|
||||
* Contains the current state of each button
|
||||
*/
|
||||
struct ButtonData {
|
||||
HICON icon = nullptr;
|
||||
bool enabled = false;
|
||||
};
|
||||
std::array<ButtonData, numOfButtons> buttonData = {{
|
||||
{skipBackwardIcon, false},
|
||||
{playIcon, false},
|
||||
{skipForwardIcon, false}
|
||||
}};
|
||||
|
||||
/**
|
||||
* For convenience when reading code
|
||||
*/
|
||||
enum ButtonID {
|
||||
SkipBackward = 0,
|
||||
TogglePlayback = 1,
|
||||
SkipForward = 2,
|
||||
};
|
||||
|
||||
TaskBarManagerPrivate()
|
||||
{
|
||||
HRESULT result = CoCreateInstance(CLSID_TaskbarList,
|
||||
nullptr,
|
||||
CLSCTX_INPROC_SERVER,
|
||||
IID_PPV_ARGS(&taskBar));
|
||||
if (FAILED(result)) {
|
||||
taskBar = nullptr;
|
||||
qWarning() << "Failed to create Windows taskbar instance";
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
~TaskBarManagerPrivate()
|
||||
{
|
||||
if (taskBar) {
|
||||
taskBar->Release();
|
||||
}
|
||||
DestroyIcon(skipForwardIcon);
|
||||
DestroyIcon(skipBackwardIcon);
|
||||
DestroyIcon(pauseIcon);
|
||||
DestroyIcon(playIcon);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the native window handle for the taskbar instance
|
||||
*/
|
||||
void setHWND(HWND newHwnd)
|
||||
{
|
||||
if (hwnd == newHwnd) {
|
||||
return;
|
||||
}
|
||||
|
||||
hwnd = newHwnd;
|
||||
addedThumbButtons = false;
|
||||
if (hwnd) {
|
||||
updateProgressFlags();
|
||||
updateProgressValue();
|
||||
setupTaskBarManagerButtons();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the taskbar progress flags
|
||||
*/
|
||||
void updateProgressFlags()
|
||||
{
|
||||
if (taskBar && hwnd) {
|
||||
taskBar->SetProgressState(hwnd, progressFlags());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the taskbar progress value, only if the taskbar is showing progress
|
||||
*/
|
||||
void updateProgressValue()
|
||||
{
|
||||
if (taskBar && hwnd && showProgress && playbackState != QMediaPlayer::StoppedState) {
|
||||
taskBar->SetProgressValue(hwnd, progressValue, progressMaximum);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the state of a single toolbutton
|
||||
*/
|
||||
void updateButton(const ButtonID buttonId)
|
||||
{
|
||||
if (!taskBar || !hwnd || !addedThumbButtons) {
|
||||
return;
|
||||
}
|
||||
THUMBBUTTON thumbButtons[1];
|
||||
initThumbButton(thumbButtons, buttonId);
|
||||
taskBar->ThumbBarUpdateButtons(hwnd, 1, thumbButtons);
|
||||
}
|
||||
|
||||
private:
|
||||
/**
|
||||
* Convert playbackState into windows taskbar flags
|
||||
*/
|
||||
TBPFLAG progressFlags() const
|
||||
{
|
||||
if (!showProgress) {
|
||||
return TBPF_NOPROGRESS;
|
||||
}
|
||||
|
||||
switch (playbackState) {
|
||||
case QMediaPlayer::StoppedState:
|
||||
return TBPF_NOPROGRESS;
|
||||
case QMediaPlayer::PlayingState:
|
||||
return TBPF_NORMAL;
|
||||
case QMediaPlayer::PausedState:
|
||||
return TBPF_PAUSED;
|
||||
default:
|
||||
return TBPF_NOPROGRESS;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize a single toolbutton
|
||||
*/
|
||||
void initThumbButton(THUMBBUTTON *button, const ButtonID id)
|
||||
{
|
||||
button->dwMask = THB_ICON | THB_FLAGS;
|
||||
button->iId = id;
|
||||
button->hIcon = buttonData.at(id).icon;
|
||||
button->dwFlags = buttonData.at(id).enabled ? THBF_ENABLED : THBF_DISABLED;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the toolbar
|
||||
*/
|
||||
void setupTaskBarManagerButtons()
|
||||
{
|
||||
if (!taskBar || !hwnd || addedThumbButtons) {
|
||||
return;
|
||||
}
|
||||
|
||||
THUMBBUTTON thumbButtons[numOfButtons];
|
||||
THUMBBUTTON *currButton = thumbButtons;
|
||||
for (int i = 0; i < numOfButtons; ++i) {
|
||||
initThumbButton(currButton++, static_cast<ButtonID>(i));
|
||||
}
|
||||
|
||||
// win32 api reference says we should pass &thumbButtons but this doesn't compile
|
||||
HRESULT result = taskBar->ThumbBarAddButtons(hwnd, numOfButtons, thumbButtons);
|
||||
if (FAILED(result)) {
|
||||
qWarning() << "Failed to create Windows taskbar buttons";
|
||||
} else {
|
||||
addedThumbButtons = true;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
TaskBarManager::TaskBarManager(QObject *parent)
|
||||
: QObject(parent)
|
||||
, d(std::make_unique<TaskBarManagerPrivate>())
|
||||
{
|
||||
QAbstractEventDispatcher::instance()->installNativeEventFilter(this);
|
||||
}
|
||||
|
||||
TaskBarManager::~TaskBarManager() = default;
|
||||
|
||||
bool TaskBarManager::nativeEventFilter(const QByteArray &eventType, void *message, qintptr *)
|
||||
{
|
||||
if (eventType == "windows_generic_MSG") {
|
||||
MSG *msg = static_cast<MSG *>(message);
|
||||
if (msg->hwnd != d->hwnd || msg->message != WM_COMMAND || HIWORD(msg->wParam) != THBN_CLICKED) {
|
||||
return false;
|
||||
}
|
||||
|
||||
switch (LOWORD(msg->wParam)) {
|
||||
case TaskBarManagerPrivate::SkipBackward:
|
||||
Q_EMIT skipBackward();
|
||||
return true;
|
||||
case TaskBarManagerPrivate::TogglePlayback:
|
||||
Q_EMIT togglePlayback();
|
||||
return true;
|
||||
case TaskBarManagerPrivate::SkipForward:
|
||||
Q_EMIT skipForward();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
QMediaPlayer::PlaybackState TaskBarManager::playbackState() const
|
||||
{
|
||||
return d->playbackState;
|
||||
}
|
||||
|
||||
bool TaskBarManager::showProgress() const
|
||||
{
|
||||
return d->showProgress;
|
||||
}
|
||||
|
||||
qulonglong TaskBarManager::progressMaximum() const
|
||||
{
|
||||
return d->progressMaximum;
|
||||
}
|
||||
|
||||
qulonglong TaskBarManager::progressValue() const
|
||||
{
|
||||
return d->progressValue;
|
||||
}
|
||||
|
||||
bool TaskBarManager::canSkipBackward() const
|
||||
{
|
||||
return d->buttonData.at(TaskBarManagerPrivate::SkipBackward).enabled;
|
||||
}
|
||||
|
||||
bool TaskBarManager::canSkipForward() const
|
||||
{
|
||||
return d->buttonData.at(TaskBarManagerPrivate::SkipForward).enabled;
|
||||
}
|
||||
|
||||
bool TaskBarManager::canTogglePlayback() const
|
||||
{
|
||||
return d->buttonData.at(TaskBarManagerPrivate::TogglePlayback).enabled;
|
||||
}
|
||||
|
||||
void TaskBarManager::setWinId(WId winId)
|
||||
{
|
||||
d->setHWND(reinterpret_cast<HWND>(winId));
|
||||
}
|
||||
|
||||
void TaskBarManager::setPlaybackState(const QMediaPlayer::PlaybackState newPlaybackState)
|
||||
{
|
||||
if (d->playbackState == newPlaybackState) {
|
||||
return;
|
||||
}
|
||||
|
||||
d->playbackState = newPlaybackState;
|
||||
Q_EMIT playbackStateChanged();
|
||||
|
||||
d->buttonData.at(TaskBarManagerPrivate::TogglePlayback).icon =
|
||||
d->playbackState == QMediaPlayer::PlayingState ? d->pauseIcon : d->playIcon;
|
||||
d->updateButton(TaskBarManagerPrivate::TogglePlayback);
|
||||
d->updateProgressFlags();
|
||||
}
|
||||
|
||||
void TaskBarManager::setShowProgress(const bool showProgress)
|
||||
{
|
||||
if (d->showProgress == showProgress) {
|
||||
return;
|
||||
}
|
||||
|
||||
d->showProgress = showProgress;
|
||||
Q_EMIT showProgressChanged();
|
||||
|
||||
d->updateProgressFlags();
|
||||
}
|
||||
|
||||
void TaskBarManager::setProgressMaximum(const qlonglong newMaximum)
|
||||
{
|
||||
if (d->progressMaximum == newMaximum) {
|
||||
return;
|
||||
}
|
||||
|
||||
d->progressMaximum = newMaximum;
|
||||
Q_EMIT progressMaximumChanged();
|
||||
|
||||
if (d->progressValue > d->progressMaximum) {
|
||||
d->progressValue = d->progressMaximum;
|
||||
Q_EMIT progressValueChanged();
|
||||
}
|
||||
|
||||
d->updateProgressValue();
|
||||
}
|
||||
|
||||
void TaskBarManager::setProgressValue(const qlonglong newValue)
|
||||
{
|
||||
if (d->progressValue == newValue) {
|
||||
return;
|
||||
}
|
||||
|
||||
d->progressValue = newValue < d->progressMaximum ? newValue : d->progressMaximum;
|
||||
Q_EMIT progressValueChanged();
|
||||
|
||||
d->updateProgressValue();
|
||||
}
|
||||
|
||||
void TaskBarManager::setCanSkipBackward(const bool canSkip)
|
||||
{
|
||||
if (d->buttonData[TaskBarManagerPrivate::SkipBackward].enabled == canSkip) {
|
||||
return;
|
||||
}
|
||||
|
||||
d->buttonData[TaskBarManagerPrivate::SkipBackward].enabled = canSkip;
|
||||
Q_EMIT canSkipBackwardChanged();
|
||||
|
||||
d->updateButton(TaskBarManagerPrivate::SkipBackward);
|
||||
}
|
||||
|
||||
void TaskBarManager::setCanSkipForward(const bool canSkip)
|
||||
{
|
||||
if (d->buttonData[TaskBarManagerPrivate::SkipForward].enabled == canSkip) {
|
||||
return;
|
||||
}
|
||||
|
||||
d->buttonData[TaskBarManagerPrivate::SkipForward].enabled = canSkip;
|
||||
Q_EMIT canSkipForwardChanged();
|
||||
|
||||
d->updateButton(TaskBarManagerPrivate::SkipForward);
|
||||
}
|
||||
|
||||
void TaskBarManager::setCanTogglePlayback(const bool canToggle)
|
||||
{
|
||||
if (d->buttonData[TaskBarManagerPrivate::TogglePlayback].enabled == canToggle) {
|
||||
return;
|
||||
}
|
||||
|
||||
d->buttonData[TaskBarManagerPrivate::TogglePlayback].enabled = canToggle;
|
||||
Q_EMIT canTogglePlaybackChanged();
|
||||
|
||||
d->updateButton(TaskBarManagerPrivate::TogglePlayback);
|
||||
}
|
||||
|
||||
#include "moc_taskbarmanager.cpp"
|
151
taskbarmanager.h
151
taskbarmanager.h
@ -1,151 +0,0 @@
|
||||
// SPDX-FileCopyrightText: 2024 (c) Jack Hill <jackhill3103@gmail.com>
|
||||
// SPDX-FileCopyrightText: 2025 (c) Gary Wang <opensource@blumia.net>
|
||||
//
|
||||
// SPDX-License-Identifier: LGPL-3.0-or-later
|
||||
//
|
||||
// This file is modified based on Elisa's taskmanager.cpp implementation,
|
||||
// with its Qt Quick usage removed.
|
||||
|
||||
#ifndef TASKBAR_H
|
||||
#define TASKBAR_H
|
||||
|
||||
#include <QAbstractNativeEventFilter>
|
||||
#include <QMediaPlayer>
|
||||
#include <QWindow>
|
||||
|
||||
#include <memory>
|
||||
|
||||
class TaskBarManagerPrivate;
|
||||
|
||||
/**
|
||||
* Windows taskbar
|
||||
*/
|
||||
class TaskBarManager : public QObject, public QAbstractNativeEventFilter
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
/**
|
||||
* Whether the media is playing, paused, or stopped
|
||||
*/
|
||||
Q_PROPERTY(QMediaPlayer::PlaybackState playbackState
|
||||
READ playbackState
|
||||
WRITE setPlaybackState
|
||||
NOTIFY playbackStateChanged)
|
||||
|
||||
/**
|
||||
* Whether to show track progress on the taskbar
|
||||
*/
|
||||
Q_PROPERTY(bool showProgress
|
||||
READ showProgress
|
||||
WRITE setShowProgress
|
||||
NOTIFY showProgressChanged)
|
||||
|
||||
/**
|
||||
* Maximum possible progress
|
||||
*/
|
||||
Q_PROPERTY(qulonglong progressMaximum
|
||||
READ progressMaximum
|
||||
WRITE setProgressMaximum
|
||||
NOTIFY progressMaximumChanged)
|
||||
|
||||
/**
|
||||
* Current progress; this is always clamped to be in the range [0, progressMaximum]
|
||||
*/
|
||||
Q_PROPERTY(qulonglong progressValue
|
||||
READ progressValue
|
||||
WRITE setProgressValue
|
||||
NOTIFY progressValueChanged)
|
||||
|
||||
/**
|
||||
* Whether the "Skip Backward" button is enabled
|
||||
*/
|
||||
Q_PROPERTY(bool canSkipBackward
|
||||
READ canSkipBackward
|
||||
WRITE setCanSkipBackward
|
||||
NOTIFY canSkipBackwardChanged)
|
||||
|
||||
/**
|
||||
* Whether the "Skip Forward" button is enabled
|
||||
*/
|
||||
Q_PROPERTY(bool canSkipForward
|
||||
READ canSkipForward
|
||||
WRITE setCanSkipForward
|
||||
NOTIFY canSkipForwardChanged)
|
||||
|
||||
/**
|
||||
* Whether the "Toggle Playback" button is enabled
|
||||
*/
|
||||
Q_PROPERTY(bool canTogglePlayback
|
||||
READ canTogglePlayback
|
||||
WRITE setCanTogglePlayback
|
||||
NOTIFY canTogglePlaybackChanged)
|
||||
|
||||
public:
|
||||
|
||||
explicit TaskBarManager(QObject *parent = nullptr);
|
||||
|
||||
~TaskBarManager() override;
|
||||
|
||||
bool nativeEventFilter(const QByteArray &eventType, void *message, qintptr *result) override;
|
||||
|
||||
[[nodiscard]] QMediaPlayer::PlaybackState playbackState() const;
|
||||
|
||||
[[nodiscard]] bool showProgress() const;
|
||||
|
||||
[[nodiscard]] qulonglong progressMaximum() const;
|
||||
|
||||
[[nodiscard]] qulonglong progressValue() const;
|
||||
|
||||
[[nodiscard]] bool canSkipBackward() const;
|
||||
|
||||
[[nodiscard]] bool canSkipForward() const;
|
||||
|
||||
[[nodiscard]] bool canTogglePlayback() const;
|
||||
|
||||
Q_SIGNALS:
|
||||
|
||||
void playbackStateChanged();
|
||||
|
||||
void showProgressChanged();
|
||||
|
||||
void progressMaximumChanged();
|
||||
|
||||
void progressValueChanged();
|
||||
|
||||
void canSkipBackwardChanged();
|
||||
|
||||
void canSkipForwardChanged();
|
||||
|
||||
void canTogglePlaybackChanged();
|
||||
|
||||
void skipBackward();
|
||||
|
||||
void skipForward();
|
||||
|
||||
void togglePlayback();
|
||||
|
||||
public Q_SLOTS:
|
||||
|
||||
void setWinId(WId win);
|
||||
|
||||
void setPlaybackState(QMediaPlayer::PlaybackState newPlaybackState);
|
||||
|
||||
void setShowProgress(bool showProgress);
|
||||
|
||||
void setProgressMaximum(qlonglong newMaximum);
|
||||
|
||||
void setProgressValue(qlonglong newValue);
|
||||
|
||||
void setCanSkipBackward(bool canSkip);
|
||||
|
||||
void setCanSkipForward(bool canSkip);
|
||||
|
||||
void setCanTogglePlayback(bool canToggle);
|
||||
|
||||
private:
|
||||
|
||||
std::unique_ptr<TaskBarManagerPrivate> d;
|
||||
|
||||
};
|
||||
|
||||
#endif // TASKBAR_H
|
@ -1,97 +0,0 @@
|
||||
// SPDX-FileCopyrightText: 2025 Gary Wang <opensource@blumia.net>
|
||||
//
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#include "taskbarmanager.h"
|
||||
|
||||
#include <QDebug>
|
||||
|
||||
class TaskBarManagerPrivate {};
|
||||
|
||||
TaskBarManager::TaskBarManager(QObject *parent)
|
||||
: QObject(parent)
|
||||
{
|
||||
}
|
||||
|
||||
TaskBarManager::~TaskBarManager() = default;
|
||||
|
||||
bool TaskBarManager::nativeEventFilter(const QByteArray &eventType, void *message, qintptr *)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
QMediaPlayer::PlaybackState TaskBarManager::playbackState() const
|
||||
{
|
||||
return QMediaPlayer::StoppedState;
|
||||
}
|
||||
|
||||
bool TaskBarManager::showProgress() const
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
qulonglong TaskBarManager::progressMaximum() const
|
||||
{
|
||||
return 100;
|
||||
}
|
||||
|
||||
qulonglong TaskBarManager::progressValue() const
|
||||
{
|
||||
return 50;
|
||||
}
|
||||
|
||||
bool TaskBarManager::canSkipBackward() const
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
bool TaskBarManager::canSkipForward() const
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
bool TaskBarManager::canTogglePlayback() const
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
void TaskBarManager::setWinId(WId winId)
|
||||
{
|
||||
}
|
||||
|
||||
void TaskBarManager::setPlaybackState(const QMediaPlayer::PlaybackState newPlaybackState)
|
||||
{
|
||||
Q_UNUSED(newPlaybackState);
|
||||
}
|
||||
|
||||
void TaskBarManager::setShowProgress(const bool showProgress)
|
||||
{
|
||||
Q_UNUSED(showProgress);
|
||||
}
|
||||
|
||||
void TaskBarManager::setProgressMaximum(const qlonglong newMaximum)
|
||||
{
|
||||
Q_UNUSED(newMaximum);
|
||||
}
|
||||
|
||||
void TaskBarManager::setProgressValue(const qlonglong newValue)
|
||||
{
|
||||
Q_UNUSED(newValue);
|
||||
}
|
||||
|
||||
void TaskBarManager::setCanSkipBackward(const bool canSkip)
|
||||
{
|
||||
Q_UNUSED(canSkip);
|
||||
}
|
||||
|
||||
void TaskBarManager::setCanSkipForward(const bool canSkip)
|
||||
{
|
||||
Q_UNUSED(canSkip);
|
||||
}
|
||||
|
||||
void TaskBarManager::setCanTogglePlayback(const bool canToggle)
|
||||
{
|
||||
Q_UNUSED(canToggle);
|
||||
}
|
||||
|
||||
#include "moc_taskbarmanager.cpp"
|
Reference in New Issue
Block a user