Compare commits

...

6 Commits

9 changed files with 523 additions and 387 deletions

View File

@ -8,7 +8,7 @@ jobs:
strategy: strategy:
matrix: matrix:
include: include:
- qt_ver: '6.8.1' - qt_ver: '6.9.0'
vs: '2022' vs: '2022'
aqt_arch: 'win64_msvc2022_64' aqt_arch: 'win64_msvc2022_64'
msvc_arch: 'x64' msvc_arch: 'x64'
@ -35,22 +35,26 @@ jobs:
:: ------ dep ------ :: ------ dep ------
set CMAKE_PREFIX_PATH=%PWD%/dependencies_bin set CMAKE_PREFIX_PATH=%PWD%/dependencies_bin
mkdir dependencies_src mkdir dependencies_src
:: ===== ECM ===== echo ::group::===== ECM =====
git clone -q https://invent.kde.org/frameworks/extra-cmake-modules.git dependencies_src/extra-cmake-modules 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 .\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 cmake --build build_dependencies/extra-cmake-modules --config Release --target=install || goto :error
:: ===== Gperf (required by KCodecs) ===== echo ::endgroup::
echo ::group::===== Gperf (required by KCodecs) =====
choco install gperf choco install gperf
:: ===== KCodecs ===== echo ::endgroup::
echo ::group::===== KCodecs =====
git clone -q https://invent.kde.org/frameworks/kcodecs.git dependencies_src/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 .\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 cmake --build build_dependencies/kcodecs --config Release --target=install || goto :error
:: ===== taglib ===== echo ::endgroup::
echo ::group::===== taglib =====
git clone --recurse-submodules -q https://github.com/taglib/taglib.git dependencies_src/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 .\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 cmake --build build_dependencies/taglib --config Release --target=install -j || goto :error
echo ::endgroup::
:: ------ app ------ :: ------ 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 -j || goto :error
cmake --build build --config Release --target=install || goto :error cmake --build build --config Release --target=install || goto :error
:: ------ pkg ------ :: ------ pkg ------

View File

@ -18,6 +18,7 @@ set(CMAKE_CXX_STANDARD_REQUIRED ON)
option(USE_QTEXTCODEC "Use QTextCodec instead of QStringConverter, in case Qt is not built with ICU" OFF) 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(Qt6 6.6 COMPONENTS Widgets Multimedia Network LinguistTools REQUIRED)
find_package(FFmpeg COMPONENTS avutil avformat)
find_package(TagLib 2.0.0) find_package(TagLib 2.0.0)
find_package(KF6Codecs 6.1.0) find_package(KF6Codecs 6.1.0)
@ -96,6 +97,11 @@ if (TARGET KF6::Codecs)
target_link_libraries (${EXE_NAME} PRIVATE KF6::Codecs) target_link_libraries (${EXE_NAME} PRIVATE KF6::Codecs)
endif () 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) target_link_libraries(${EXE_NAME} PRIVATE Qt::Widgets Qt::Multimedia Qt::Network kissfft::kissfft)
if (USE_QTEXTCODEC) if (USE_QTEXTCODEC)

View File

@ -114,12 +114,12 @@ void MainWindow::setAudioPropertyInfoForDisplay(int sampleRate, int bitrate, int
} }
}; };
if (sampleRate >= 0) { if (sampleRate > 0) {
uiStrs << QString("%1 Hz").arg(sampleRate); uiStrs << QString("%1 Hz").arg(sampleRate);
tooltipStrs << tr("Sample Rate: %1 Hz").arg(sampleRate); tooltipStrs << tr("Sample Rate: %1 Hz").arg(sampleRate);
} }
if (bitrate >= 0) { if (bitrate > 0) {
uiStrs << QString("%1 Kbps").arg(bitrate); uiStrs << QString("%1 Kbps").arg(bitrate);
tooltipStrs << tr("Bitrate: %1 Kbps").arg(bitrate); tooltipStrs << tr("Bitrate: %1 Kbps").arg(bitrate);
} }
@ -271,20 +271,21 @@ void MainWindow::loadFile()
m_playlistManager->loadPlaylist(urlList); m_playlistManager->loadPlaylist(urlList);
const QUrl & firstUrl = urlList.first(); const QUrl & firstUrl = urlList.first();
const QString firstFilePath = firstUrl.toLocalFile(); loadFile(firstUrl);
m_mediaPlayer->setSource(firstUrl); }
m_lrcbar->loadLyrics(firstFilePath);
QList<std::pair<qint64, QString>> chapters(PlaybackProgressIndicator::tryLoadSidecarChapterFile(firstFilePath)); 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); ui->playbackProgressIndicator->setChapters(chapters);
} }
void MainWindow::loadByModelIndex(const QModelIndex & index) void MainWindow::loadByModelIndex(const QModelIndex & index)
{ {
m_mediaPlayer->setSource(m_playlistManager->urlByIndex(index)); loadFile(m_playlistManager->urlByIndex(index));
QString filePath(m_playlistManager->localFileByIndex(index));
m_lrcbar->loadLyrics(filePath);
QList<std::pair<qint64, QString>> chapters(PlaybackProgressIndicator::tryLoadSidecarChapterFile(filePath));
ui->playbackProgressIndicator->setChapters(chapters);
} }
void MainWindow::play() void MainWindow::play()
@ -440,6 +441,8 @@ void MainWindow::initConnections()
if (!fileRef.isNull() && fileRef.audioProperties()) { if (!fileRef.isNull() && fileRef.audioProperties()) {
TagLib::AudioProperties *prop = fileRef.audioProperties(); TagLib::AudioProperties *prop = fileRef.audioProperties();
setAudioPropertyInfoForDisplay(prop->sampleRate(), prop->bitrate(), prop->channels(), suffix); setAudioPropertyInfoForDisplay(prop->sampleRate(), prop->bitrate(), prop->channels(), suffix);
} else {
qDebug() << "No Audio Properties from TagLib";
} }
if (!fileRef.isNull() && fileRef.tag()) { if (!fileRef.isNull() && fileRef.tag()) {
@ -447,6 +450,10 @@ void MainWindow::initConnections()
setAudioMetadataForDisplay(QString::fromStdString(tag->title().to8Bit(true)), setAudioMetadataForDisplay(QString::fromStdString(tag->title().to8Bit(true)),
QString::fromStdString(tag->artist().to8Bit(true)), QString::fromStdString(tag->artist().to8Bit(true)),
QString::fromStdString(tag->album().to8Bit(true))); QString::fromStdString(tag->album().to8Bit(true)));
m_urlMissingTagLibMetadata.clear();
} else {
qDebug() << "No Audio Metadata from TagLib";
m_urlMissingTagLibMetadata = fileUrl;
} }
#endif // NO_TAGLIB #endif // NO_TAGLIB
} }
@ -458,12 +465,17 @@ void MainWindow::initConnections()
// see `02 Yoiyami Hanabi.mp3`'s Title. So we don't use Qt's one if tablib is available. // 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); qDebug() << metadata.stringValue(QMediaMetaData::Title) << metadata.stringValue(QMediaMetaData::Author);
#ifdef NO_TAGLIB #ifdef NO_TAGLIB
setAudioMetadataForDisplay(metadata.stringValue(QMediaMetaData::Title), bool needMetadataFromQt = true;
metadata.stringValue(QMediaMetaData::Author), #else
metadata.stringValue(QMediaMetaData::AlbumTitle)); bool needMetadataFromQt = m_urlMissingTagLibMetadata == m_mediaPlayer->source();
setAudioPropertyInfoForDisplay(-1, metadata.value(QMediaMetaData::AudioBitRate).toInt() / 1000,
-1, metadata.stringValue(QMediaMetaData::FileFormat));
#endif // NO_TAGLIB #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)); QVariant coverArt(metadata.value(QMediaMetaData::ThumbnailImage));
if (!coverArt.isNull()) { if (!coverArt.isNull()) {
ui->coverLabel->setPixmap(QPixmap::fromImage(coverArt.value<QImage>())); ui->coverLabel->setPixmap(QPixmap::fromImage(coverArt.value<QImage>()));
@ -678,7 +690,7 @@ void MainWindow::on_actionHelp_triggered()
"\n" "\n"
"[Source Code](https://github.com/BLumia/pineapple-music)\n" "[Source Code](https://github.com/BLumia/pineapple-music)\n"
"\n" "\n"
"Copyright &copy; 2024 [BLumia](https://github.com/BLumia/)" "Copyright &copy; 2025 [BLumia](https://github.com/BLumia/)"
); );
infoBox.setTextFormat(Qt::MarkdownText); infoBox.setTextFormat(Qt::MarkdownText);
infoBox.exec(); infoBox.exec();

View File

@ -7,6 +7,7 @@
#include <QMainWindow> #include <QMainWindow>
#include <QVariant> #include <QVariant>
#include <QUrl>
QT_BEGIN_NAMESPACE QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; } namespace Ui { class MainWindow; }
@ -55,6 +56,7 @@ protected:
void dropEvent(QDropEvent *e) override; void dropEvent(QDropEvent *e) override;
void loadFile(); void loadFile();
void loadFile(const QUrl &url);
void loadByModelIndex(const QModelIndex &index); void loadByModelIndex(const QModelIndex &index);
void play(); void play();
@ -89,6 +91,7 @@ private:
bool m_playbackSliderPressed = false; bool m_playbackSliderPressed = false;
QLinearGradient m_bgLinearGradient; QLinearGradient m_bgLinearGradient;
QPixmap m_skin; QPixmap m_skin;
QUrl m_urlMissingTagLibMetadata;
enum PlaybackMode m_playbackMode = CurrentItemInLoop; enum PlaybackMode m_playbackMode = CurrentItemInLoop;
Ui::MainWindow *ui; Ui::MainWindow *ui;

View File

@ -11,6 +11,15 @@
#include <QPainterPath> #include <QPainterPath>
#include <QRegularExpression> #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) : PlaybackProgressIndicator::PlaybackProgressIndicator(QWidget *parent) :
QWidget(parent) QWidget(parent)
{ {
@ -30,6 +39,7 @@ void PlaybackProgressIndicator::setDuration(qint64 dur)
void PlaybackProgressIndicator::setChapters(QList<std::pair<qint64, QString> > chapters) void PlaybackProgressIndicator::setChapters(QList<std::pair<qint64, QString> > chapters)
{ {
qDebug() << chapters;
m_chapterModel.clear(); m_chapterModel.clear();
for (const std::pair<qint64, QString> & chapter : chapters) { for (const std::pair<qint64, QString> & chapter : chapters) {
QStandardItem * chapterItem = new QStandardItem(chapter.second); QStandardItem * chapterItem = new QStandardItem(chapter.second);
@ -39,6 +49,15 @@ void PlaybackProgressIndicator::setChapters(QList<std::pair<qint64, QString> > c
update(); 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) QList<std::pair<qint64, QString> > PlaybackProgressIndicator::tryLoadSidecarChapterFile(const QString &filePath)
{ {
if (filePath.endsWith(".chp", Qt::CaseInsensitive)) { if (filePath.endsWith(".chp", Qt::CaseInsensitive)) {
@ -63,6 +82,98 @@ QList<std::pair<qint64, QString> > PlaybackProgressIndicator::tryLoadSidecarChap
return {}; 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> > PlaybackProgressIndicator::parseCHPChapterFile(const QString &filePath)
{ {
QList<std::pair<qint64, QString>> chapters; QList<std::pair<qint64, QString>> chapters;

View File

@ -28,7 +28,9 @@ public:
void setDuration(qint64 dur); void setDuration(qint64 dur);
void setChapters(QList<std::pair<qint64, QString>> chapters); void setChapters(QList<std::pair<qint64, QString>> chapters);
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>> 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>> parseCHPChapterFile(const QString & filePath);
static QList<std::pair<qint64, QString>> parsePBFChapterFile(const QString & filePath); static QList<std::pair<qint64, QString>> parsePBFChapterFile(const QString & filePath);

View File

@ -1,255 +1,253 @@
// SPDX-FileCopyrightText: 2024 Gary Wang <git@blumia.net> // SPDX-FileCopyrightText: 2025 Gary Wang <git@blumia.net>
// //
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
#include "playlistmanager.h" #include "playlistmanager.h"
#include <QCollator> #include <QCollator>
#include <QDir> #include <QDir>
#include <QFileInfo> #include <QFileInfo>
#include <QUrl> #include <QUrl>
PlaylistModel::PlaylistModel(QObject *parent) PlaylistModel::PlaylistModel(QObject *parent)
: QAbstractListModel(parent) : QAbstractListModel(parent)
{ {
} }
PlaylistModel::~PlaylistModel() PlaylistModel::~PlaylistModel()
{ = default;
} void PlaylistModel::setPlaylist(const QList<QUrl> &urls)
{
void PlaylistModel::setPlaylist(const QList<QUrl> &urls) beginResetModel();
{ m_playlist = urls;
beginResetModel(); endResetModel();
m_playlist = urls; }
endResetModel();
} QModelIndex PlaylistModel::loadPlaylist(const QList<QUrl> & urls)
{
QModelIndex PlaylistModel::loadPlaylist(const QList<QUrl> & urls) if (urls.isEmpty()) return {};
{ if (urls.count() == 1) {
if (urls.isEmpty()) return QModelIndex(); return loadPlaylist(urls.constFirst());
if (urls.count() == 1) { } else {
return loadPlaylist(urls.constFirst()); setPlaylist(urls);
} else { return index(0);
setPlaylist(urls); }
return index(0); }
}
} QModelIndex PlaylistModel::loadPlaylist(const QUrl &url)
{
QModelIndex PlaylistModel::loadPlaylist(const QUrl &url) QFileInfo info(url.toLocalFile());
{ QDir dir(info.path());
QFileInfo info(url.toLocalFile()); QString && currentFileName = info.fileName();
QDir dir(info.path());
QString && currentFileName = info.fileName(); if (dir.path() == m_currentDir) {
int idx = indexOf(url);
if (dir.path() == m_currentDir) { return idx == -1 ? appendToPlaylist(url) : index(idx);
int idx = indexOf(url); }
return idx == -1 ? appendToPlaylist(url) : index(idx);
} QStringList entryList = dir.entryList(
m_autoLoadSuffixes,
QStringList entryList = dir.entryList( QDir::Files | QDir::NoSymLinks, QDir::NoSort);
m_autoLoadSuffixes,
QDir::Files | QDir::NoSymLinks, QDir::NoSort); QCollator collator;
collator.setNumericMode(true);
QCollator collator;
collator.setNumericMode(true); std::sort(entryList.begin(), entryList.end(), collator);
std::sort(entryList.begin(), entryList.end(), collator); QList<QUrl> playlist;
QList<QUrl> playlist; int idx = -1;
for (int i = 0; i < entryList.count(); i++) {
int idx = -1; const QString & fileName = entryList.at(i);
for (int i = 0; i < entryList.count(); i++) { const QString & oneEntry = dir.absoluteFilePath(fileName);
const QString & fileName = entryList.at(i); const QUrl & url = QUrl::fromLocalFile(oneEntry);
const QString & oneEntry = dir.absoluteFilePath(fileName); playlist.append(url);
const QUrl & url = QUrl::fromLocalFile(oneEntry); if (fileName == currentFileName) {
playlist.append(url); idx = i;
if (fileName == currentFileName) { }
idx = i; }
} if (idx == -1) {
} idx = playlist.count();
if (idx == -1) { playlist.append(url);
idx = playlist.count(); }
playlist.append(url); m_currentDir = dir.path();
}
m_currentDir = dir.path(); setPlaylist(playlist);
setPlaylist(playlist); return index(idx);
}
return index(idx);
} QModelIndex PlaylistModel::appendToPlaylist(const QUrl &url)
{
QModelIndex PlaylistModel::appendToPlaylist(const QUrl &url) const int lastIndex = rowCount();
{ beginInsertRows(QModelIndex(), lastIndex, lastIndex);
const int lastIndex = rowCount(); m_playlist.append(url);
beginInsertRows(QModelIndex(), lastIndex, lastIndex); endInsertRows();
m_playlist.append(url); return index(lastIndex);
endInsertRows(); }
return index(lastIndex);
} bool PlaylistModel::removeAt(int index)
{
bool PlaylistModel::removeAt(int index) if (index < 0 || index >= rowCount()) return false;
{ beginRemoveRows(QModelIndex(), index, index);
if (index < 0 || index >= rowCount()) return false; m_playlist.removeAt(index);
beginRemoveRows(QModelIndex(), index, index); endRemoveRows();
m_playlist.removeAt(index); return true;
endRemoveRows(); }
return true;
} int PlaylistModel::indexOf(const QUrl &url) const
{
int PlaylistModel::indexOf(const QUrl &url) const return m_playlist.indexOf(url);
{ }
return m_playlist.indexOf(url);
} QUrl PlaylistModel::urlByIndex(int index) const
{
QUrl PlaylistModel::urlByIndex(int index) const return m_playlist.value(index);
{ }
return m_playlist.value(index);
} QStringList PlaylistModel::autoLoadFilterSuffixes() const
{
QStringList PlaylistModel::autoLoadFilterSuffixes() const return m_autoLoadSuffixes;
{ }
return m_autoLoadSuffixes;
} QHash<int, QByteArray> PlaylistModel::roleNames() const
{
QHash<int, QByteArray> PlaylistModel::roleNames() const QHash<int, QByteArray> result = QAbstractListModel::roleNames();
{ result.insert(UrlRole, "url");
QHash<int, QByteArray> result = QAbstractListModel::roleNames(); return result;
result.insert(UrlRole, "url"); }
return result;
} int PlaylistModel::rowCount(const QModelIndex &parent) const
{
int PlaylistModel::rowCount(const QModelIndex &parent) const return m_playlist.count();
{ }
return m_playlist.count();
} QVariant PlaylistModel::data(const QModelIndex &index, int role) const
{
QVariant PlaylistModel::data(const QModelIndex &index, int role) const if (!index.isValid()) return {};
{
if (!index.isValid()) return QVariant(); switch (role) {
case Qt::DisplayRole:
switch (role) { return m_playlist.at(index.row()).fileName();
case Qt::DisplayRole: case UrlRole:
return m_playlist.at(index.row()).fileName(); return m_playlist.at(index.row());
case UrlRole: }
return m_playlist.at(index.row());
} return {};
}
return QVariant();
} PlaylistManager::PlaylistManager(QObject *parent)
: QObject(parent)
PlaylistManager::PlaylistManager(QObject *parent) {
: QObject(parent) connect(&m_model, &PlaylistModel::rowsRemoved, this,
{ [this](const QModelIndex &, int, int) {
connect(&m_model, &PlaylistModel::rowsRemoved, this, if (m_model.rowCount() <= m_currentIndex) {
[this](const QModelIndex &, int, int) { setProperty("currentIndex", m_currentIndex - 1);
if (m_model.rowCount() <= m_currentIndex) { }
setProperty("currentIndex", m_currentIndex - 1); });
}
}); auto onRowCountChanged = [this](){
emit totalCountChanged(m_model.rowCount());
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::rowsInserted, this, onRowCountChanged); connect(&m_model, &PlaylistModel::modelReset, this, onRowCountChanged);
connect(&m_model, &PlaylistModel::rowsRemoved, this, onRowCountChanged); }
connect(&m_model, &PlaylistModel::modelReset, this, onRowCountChanged);
} PlaylistManager::~PlaylistManager()
{
PlaylistManager::~PlaylistManager()
{ }
} PlaylistModel *PlaylistManager::model()
{
PlaylistModel *PlaylistManager::model() return &m_model;
{ }
return &m_model;
} void PlaylistManager::setPlaylist(const QList<QUrl> &urls)
{
void PlaylistManager::setPlaylist(const QList<QUrl> &urls) m_model.setPlaylist(urls);
{ }
m_model.setPlaylist(urls);
} QModelIndex PlaylistManager::loadPlaylist(const QList<QUrl> &urls)
{
QModelIndex PlaylistManager::loadPlaylist(const QList<QUrl> &urls) QModelIndex idx = m_model.loadPlaylist(urls);
{ setProperty("currentIndex", idx.row());
QModelIndex idx = m_model.loadPlaylist(urls); return idx;
setProperty("currentIndex", idx.row()); }
return idx;
} QModelIndex PlaylistManager::loadPlaylist(const QUrl &url)
{
QModelIndex PlaylistManager::loadPlaylist(const QUrl &url) QModelIndex idx = m_model.loadPlaylist(url);
{ setProperty("currentIndex", idx.row());
QModelIndex idx = m_model.loadPlaylist(url); return idx;
setProperty("currentIndex", idx.row()); }
return idx;
} int PlaylistManager::totalCount() const
{
int PlaylistManager::totalCount() const return m_model.rowCount();
{ }
return m_model.rowCount();
} QModelIndex PlaylistManager::previousIndex() const
{
QModelIndex PlaylistManager::previousIndex() const int count = totalCount();
{ if (count == 0) return {};
int count = totalCount();
if (count == 0) return QModelIndex(); return m_model.index(m_currentIndex - 1 < 0 ? count - 1 : m_currentIndex - 1);
}
return m_model.index(m_currentIndex - 1 < 0 ? count - 1 : m_currentIndex - 1);
} QModelIndex PlaylistManager::nextIndex() const
{
QModelIndex PlaylistManager::nextIndex() const int count = totalCount();
{ if (count == 0) return {};
int count = totalCount();
if (count == 0) return QModelIndex(); return m_model.index(m_currentIndex + 1 == count ? 0 : m_currentIndex + 1);
}
return m_model.index(m_currentIndex + 1 == count ? 0 : m_currentIndex + 1);
} QModelIndex PlaylistManager::curIndex() const
{
QModelIndex PlaylistManager::curIndex() const return m_model.index(m_currentIndex);
{ }
return m_model.index(m_currentIndex);
} void PlaylistManager::setCurrentIndex(const QModelIndex &index)
{
void PlaylistManager::setCurrentIndex(const QModelIndex &index) if (index.isValid() && index.row() >= 0 && index.row() < totalCount()) {
{ setProperty("currentIndex", index.row());
if (index.isValid() && index.row() >= 0 && index.row() < totalCount()) { }
setProperty("currentIndex", index.row()); }
}
} QUrl PlaylistManager::urlByIndex(const QModelIndex &index)
{
QUrl PlaylistManager::urlByIndex(const QModelIndex &index) return m_model.urlByIndex(index.row());
{ }
return m_model.urlByIndex(index.row());
} QString PlaylistManager::localFileByIndex(const QModelIndex &index)
{
QString PlaylistManager::localFileByIndex(const QModelIndex &index) return urlByIndex(index).toLocalFile();
{ }
return urlByIndex(index).toLocalFile();
} bool PlaylistManager::removeAt(const QModelIndex &index)
{
bool PlaylistManager::removeAt(const QModelIndex &index) return m_model.removeAt(index.row());
{ }
return m_model.removeAt(index.row());
} void PlaylistManager::setAutoLoadFilterSuffixes(const QStringList &nameFilters)
{
void PlaylistManager::setAutoLoadFilterSuffixes(const QStringList &nameFilters) m_model.setProperty("autoLoadFilterSuffixes", nameFilters);
{ }
m_model.setProperty("autoLoadFilterSuffixes", nameFilters);
} QList<QUrl> PlaylistManager::convertToUrlList(const QStringList &files)
{
QList<QUrl> PlaylistManager::convertToUrlList(const QStringList &files) QList<QUrl> urlList;
{ for (const QString & str : std::as_const(files)) {
QList<QUrl> urlList; QUrl url = QUrl::fromLocalFile(str);
for (const QString & str : std::as_const(files)) { if (url.isValid()) {
QUrl url = QUrl::fromLocalFile(str); urlList.append(url);
if (url.isValid()) { }
urlList.append(url); }
}
} return urlList;
}
return urlList;
}

View File

@ -1,85 +1,85 @@
// SPDX-FileCopyrightText: 2024 Gary Wang <git@blumia.net> // SPDX-FileCopyrightText: 2025 Gary Wang <git@blumia.net>
// //
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
#pragma once #pragma once
#include <QUrl> #include <QUrl>
#include <QAbstractListModel> #include <QAbstractListModel>
class PlaylistModel : public QAbstractListModel class PlaylistModel : public QAbstractListModel
{ {
Q_OBJECT Q_OBJECT
public: public:
enum PlaylistRole { enum PlaylistRole {
UrlRole = Qt::UserRole UrlRole = Qt::UserRole
}; };
Q_ENUM(PlaylistRole) Q_ENUM(PlaylistRole)
Q_PROPERTY(QStringList autoLoadFilterSuffixes MEMBER m_autoLoadSuffixes NOTIFY autoLoadFilterSuffixesChanged) Q_PROPERTY(QStringList autoLoadFilterSuffixes MEMBER m_autoLoadSuffixes NOTIFY autoLoadFilterSuffixesChanged)
explicit PlaylistModel(QObject *parent = nullptr); explicit PlaylistModel(QObject *parent = nullptr);
~PlaylistModel(); ~PlaylistModel() override;
void setPlaylist(const QList<QUrl> & urls); void setPlaylist(const QList<QUrl> & urls);
QModelIndex loadPlaylist(const QList<QUrl> & urls); QModelIndex loadPlaylist(const QList<QUrl> & urls);
QModelIndex loadPlaylist(const QUrl & url); QModelIndex loadPlaylist(const QUrl & url);
QModelIndex appendToPlaylist(const QUrl & url); QModelIndex appendToPlaylist(const QUrl & url);
bool removeAt(int index); bool removeAt(int index);
int indexOf(const QUrl & url) const; int indexOf(const QUrl & url) const;
QUrl urlByIndex(int index) const; QUrl urlByIndex(int index) const;
QStringList autoLoadFilterSuffixes() const; QStringList autoLoadFilterSuffixes() const;
QHash<int, QByteArray> roleNames() const override; QHash<int, QByteArray> roleNames() const override;
int rowCount(const QModelIndex &parent = QModelIndex()) const override; int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
signals: signals:
void autoLoadFilterSuffixesChanged(QStringList suffixes); void autoLoadFilterSuffixesChanged(QStringList suffixes);
private: private:
// model data // model data
QList<QUrl> m_playlist; QList<QUrl> m_playlist;
// properties // properties
QStringList m_autoLoadSuffixes = {}; QStringList m_autoLoadSuffixes = {};
// internal // internal
QString m_currentDir; QString m_currentDir;
}; };
class PlaylistManager : public QObject class PlaylistManager : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
Q_PROPERTY(int currentIndex MEMBER m_currentIndex NOTIFY currentIndexChanged) Q_PROPERTY(int currentIndex MEMBER m_currentIndex NOTIFY currentIndexChanged)
Q_PROPERTY(QStringList autoLoadFilterSuffixes WRITE setAutoLoadFilterSuffixes) Q_PROPERTY(QStringList autoLoadFilterSuffixes WRITE setAutoLoadFilterSuffixes)
Q_PROPERTY(PlaylistModel * model READ model CONSTANT) Q_PROPERTY(PlaylistModel * model READ model CONSTANT)
explicit PlaylistManager(QObject *parent = nullptr); explicit PlaylistManager(QObject *parent = nullptr);
~PlaylistManager(); ~PlaylistManager();
PlaylistModel * model(); PlaylistModel * model();
void setPlaylist(const QList<QUrl> & url); void setPlaylist(const QList<QUrl> & url);
Q_INVOKABLE QModelIndex loadPlaylist(const QList<QUrl> & urls); Q_INVOKABLE QModelIndex loadPlaylist(const QList<QUrl> & urls);
Q_INVOKABLE QModelIndex loadPlaylist(const QUrl & url); Q_INVOKABLE QModelIndex loadPlaylist(const QUrl & url);
int totalCount() const; int totalCount() const;
QModelIndex previousIndex() const; QModelIndex previousIndex() const;
QModelIndex nextIndex() const; QModelIndex nextIndex() const;
QModelIndex curIndex() const; QModelIndex curIndex() const;
void setCurrentIndex(const QModelIndex & index); void setCurrentIndex(const QModelIndex & index);
QUrl urlByIndex(const QModelIndex & index); QUrl urlByIndex(const QModelIndex & index);
QString localFileByIndex(const QModelIndex & index); QString localFileByIndex(const QModelIndex & index);
bool removeAt(const QModelIndex & index); bool removeAt(const QModelIndex & index);
void setAutoLoadFilterSuffixes(const QStringList &nameFilters); void setAutoLoadFilterSuffixes(const QStringList &nameFilters);
static QList<QUrl> convertToUrlList(const QStringList & files); static QList<QUrl> convertToUrlList(const QStringList & files);
signals: signals:
void currentIndexChanged(int index); void currentIndexChanged(int index);
void totalCountChanged(int count); void totalCountChanged(int count);
private: private:
int m_currentIndex = -1; int m_currentIndex = -1;
PlaylistModel m_model; PlaylistModel m_model;
}; };

View File

@ -1,24 +1,24 @@
// SPDX-FileCopyrightText: 2024 Gary Wang <git@blumia.net> // SPDX-FileCopyrightText: 2025 Gary Wang <git@blumia.net>
// //
// SPDX-License-Identifier: MIT // SPDX-License-Identifier: MIT
#pragma once #pragma once
#include <QSlider> #include <QSlider>
#include <QMouseEvent> #include <QMouseEvent>
class SeekableSlider : public QSlider class SeekableSlider : public QSlider
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit SeekableSlider(QWidget *parent = nullptr); explicit SeekableSlider(QWidget *parent = nullptr);
~SeekableSlider() = default; ~SeekableSlider() override = default;
signals: signals:
public slots: public slots:
protected: protected:
void mouseReleaseEvent(QMouseEvent *event) override; void mouseReleaseEvent(QMouseEvent *event) override;
}; };