Skip to content

armgit / Spun

Public Imported from GitHub
0

A CD-shaped music player for Linux, with local playback and Cider integration.

Fix recursive music folder imports

yappologisticf896b36d753c
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 7eb0919..33f2831 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -97,6 +97,10 @@ if(BUILD_TESTING)
target_sources(spun-diagnostics PRIVATE src/librarytest.cpp src/librarytest.h src/eventstest.cpp)
target_compile_definitions(spun-diagnostics PRIVATE SPUN_DIAGNOSTICS)
target_link_libraries(spun-diagnostics PRIVATE Qt6::Test)
+ qt_add_executable(spun-import-test src/importtest.cpp)
+ target_link_libraries(spun-import-test PRIVATE spun_core Qt6::Test)
+ add_test(NAME spun-folder-import COMMAND spun-import-test)
+ set_tests_properties(spun-folder-import PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen;QT_QPA_PLATFORMTHEME=")
add_test(NAME spun-playback-and-ui COMMAND spun --self-test)
set_tests_properties(spun-playback-and-ui PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen;QT_QUICK_BACKEND=software;QSG_RENDER_LOOP=basic;QT_QPA_PLATFORMTHEME=")
endif()
diff --git a/README.md b/README.md
index 6a484ba..5845eae 100644
--- a/README.md
+++ b/README.md
@@ -50,7 +50,7 @@ Other Linux distributions need a C++20 compiler, CMake 3.22+, Ninja, pkg-config,
## Start listening
-**Local music:** choose **Local**, then **+** to add tracks. You can also drop audio files or a folder onto Spun. Folder imports include the audio files directly inside that folder. Your music files are not modified. **More → Play demo** plays the included original soundcheck.
+**Local music:** choose **Local**, then **+** to add tracks. You can also drop audio files or a folder onto Spun. Use **More → Add music folder** to include songs in artist and album subfolders. Spun shows import progress, skips songs already in the queue, and lets you cancel without adding a partial import. Directory symlinks inside the folder are not followed. Your music files are not copied or modified. **More → Play demo** plays the included original soundcheck.
**Apple Music through Cider:** open Cider, sign in there, and choose **Cider** in Spun. Cider still handles authentication and streaming and must remain running. Apple Music playback requires the appropriate Apple Music access through Cider.
@@ -185,6 +185,8 @@ Build the diagnostic companion and run isolated playback, API-fixture and UI che
QT_QPA_PLATFORM=offscreen QT_QUICK_BACKEND=software QSG_RENDER_LOOP=basic QT_QPA_PLATFORMTHEME= ./build/spun --self-test
```
+For recursive folder-import checks, run `QT_QPA_PLATFORM=offscreen QT_QPA_PLATFORMTHEME= ./build/spun-import-test`. Add `--stress` to test 20,000 nested sparse WAV files representing 625 GiB of audio without allocating that much disk space. The temporary files are removed after the run.
+
The tests use temporary preferences and synthetic local API fixtures. Audio checks need a working user audio session, and API fixtures need permission to listen on loopback. The normal player is built separately from the diagnostic executable.
For a connected Cider instance, `--inspect-cider` and `--inspect-library` check live data without changing playback. The opt-in `--verify-cider-writes` also exercises playback, volume, repeat, queue insertion/removal/Undo and audio settings, then starts song radio. It restores its temporary queue and setting edits but leaves radio playing. Use `--config /path/to/test/settings.ini` with a privately paired test profile; never share its connection file or captured library data.
diff --git a/qml/Main.qml b/qml/Main.qml
index bca0e83..f518068 100644
--- a/qml/Main.qml
+++ b/qml/Main.qml
@@ -9,7 +9,9 @@ ApplicationWindow {
title: "Spun"
visible: true
readonly property real layoutWidth: miniMode ? 300 : sideOpen ? 860 : 530
- readonly property real layoutHeight: miniMode ? (showHorizontalSeek ? 382 : 354) : 730
+ readonly property real miniBaseHeight: showHorizontalSeek ? 382 : 354
+ readonly property real layoutHeight: miniMode ? miniBaseHeight + (actionNotice.visible ? 48 : 0) : 730
+ onLayoutHeightChanged: Qt.callLater(updateMask)
readonly property real uiScale: testMode ? typography.uiScale : Math.min(typography.uiScale,
Math.max(.5, (Screen.desktopAvailableWidth - 40) / layoutWidth),
Math.max(.5, (Screen.desktopAvailableHeight - 40) / layoutHeight))
@@ -414,7 +416,7 @@ ApplicationWindow {
nameFilters: ["Music (*.mp3 *.flac *.wav *.ogg *.opus *.m4a *.aac *.aiff *.aif *.wma)", "All files (*)"]
onAccepted: { root.useLocal(); player.addUrls(selectedFiles) }
}
- FolderDialog { id: folder; title: "Add an album folder"; onAccepted: { root.useLocal(); player.addUrls([selectedFolder], player.count === 0) } }
+ FolderDialog { id: folder; title: "Add a music folder"; onAccepted: { root.useLocal(); player.addUrls([selectedFolder], player.count === 0) } }
FileDialog { id: cover; title: "Choose the disc artwork"; nameFilters: ["Artwork (*.jpg *.jpeg *.png *.webp)"]; onAccepted: player.setCover(selectedFile) }
Timer {
@@ -1473,7 +1475,7 @@ ApplicationWindow {
onClicked: root.ciderService.raise()
}
IconButton { visible: !root.useCider; x: 0; anchors.verticalCenter: parent.verticalCenter; glyphName: "plus"; tip: "Add tracks"; ink: root.ink; hoverFill: root.hoverFill; onClicked: files.open() }
- IconButton { visible: !root.useCider; x: SpunStyle.target + SpunStyle.smallGap; anchors.verticalCenter: parent.verticalCenter; glyphName: "folder"; tip: "Add album folder"; ink: root.ink; hoverFill: root.hoverFill; onClicked: folder.open() }
+ IconButton { visible: !root.useCider; x: SpunStyle.target + SpunStyle.smallGap; anchors.verticalCenter: parent.verticalCenter; glyphName: "folder"; tip: "Add music folder"; ink: root.ink; hoverFill: root.hoverFill; onClicked: folder.open() }
Button {
id: clearQueueButton
visible: !root.useCider; anchors.right: parent.right; anchors.verticalCenter: parent.verticalCenter; width: 76; height: SpunStyle.target
@@ -1726,6 +1728,14 @@ ApplicationWindow {
target: root.savedService
function onSavedEditCommitted() { actionNotice.savedUndo = true; actionNotice.show() }
}
+ Connections {
+ target: player
+ function onBusyChanged() {
+ if (player.busy) actionNotice.dismiss()
+ else if (noticeCancel.activeFocus) menuButton.forceActiveFocus(Qt.TabFocusReason)
+ }
+ function onImported() { root.notifyAction(player.error || player.importStatus, player.error.length > 0) }
+ }
Timer { id: noticeTimer; objectName: "noticeTimer"; onTriggered: actionNotice.dismiss() }
Rectangle {
id: actionNotice
@@ -1733,9 +1743,10 @@ ApplicationWindow {
property string text: ""
property bool shown: false
property Item returnFocus: null
- readonly property bool interacting: noticeHover.hovered || noticeUndo.activeFocus || noticeDismiss.activeFocus
+ readonly property bool importing: player.busy
+ readonly property bool interacting: noticeHover.hovered || noticeUndo.activeFocus || noticeDismiss.activeFocus || noticeCancel.activeFocus
function syncTimeout() {
- if (!shown || canUndo || interacting) noticeTimer.stop()
+ if (!shown || importing || canUndo || interacting) noticeTimer.stop()
else noticeTimer.restart()
}
function show() { if (!noticeUndo.activeFocus && !noticeDismiss.activeFocus) returnFocus = root.activeFocusItem; shown = true; syncTimeout(); Accessible.announce(text, Accessible.Polite) }
@@ -1749,29 +1760,36 @@ ApplicationWindow {
}
onInteractingChanged: syncTimeout()
onCanUndoChanged: syncTimeout()
- Accessible.role: Accessible.StaticText; Accessible.name: text
+ onImportingChanged: syncTimeout()
+ Accessible.role: Accessible.StaticText; Accessible.name: importing ? player.importStatus : text
property bool failed: false
property bool undo: false
property bool savedUndo: false
readonly property bool canUndo: savedUndo ? root.savedService.canUndoSavedQueue : undo && root.ciderService.canUndoQueue
- visible: (shown || opacity > 0) && (!root.miniMode || failed)
- opacity: shown && (!root.miniMode || failed) ? 1 : 0
- enabled: shown && (!root.miniMode || failed)
+ visible: importing || (shown || opacity > 0) && (!root.miniMode || failed)
+ opacity: importing || shown && (!root.miniMode || failed) ? 1 : 0
+ enabled: importing || shown && (!root.miniMode || failed)
Behavior on opacity { NumberAnimation { duration: SpunStyle.feedback; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
HoverHandler { id: noticeHover }
Keys.onShortcutOverride: event => { if (event.key === Qt.Key_Escape) event.accepted = true }
- Keys.onEscapePressed: dismiss()
+ Keys.onEscapePressed: { if (importing) player.cancelImport(); else dismiss() }
onVisibleChanged: Qt.callLater(root.updateMask)
- z: 30; x: root.miniMode ? 12 : deck.x; y: root.miniMode ? 234 : deck.y + deck.height + 8; width: root.miniMode ? 276 : deck.width; height: root.miniMode ? 56 : 40; radius: SpunStyle.rowRadius
+ z: 30; x: root.miniMode ? 12 : deck.x; y: root.miniMode ? root.miniBaseHeight + 4 : deck.y + deck.height + 8; width: root.miniMode ? 276 : deck.width; height: 40; radius: SpunStyle.rowRadius
color: root.surface
- SpunText { x: 12; y: 2; width: noticeDismiss.x - x - 8 - (actionNotice.canUndo ? 80 : 0); height: parent.height - 4; text: actionNotice.text; color: actionNotice.failed ? theme.colors.error : root.ink; font.pixelSize: SpunStyle.body; wrapMode: Text.WordWrap; elide: Text.ElideRight; verticalAlignment: Text.AlignVCenter }
+ SpunText { x: 12; y: 2; width: (actionNotice.importing ? noticeCancel.x : noticeDismiss.x - (actionNotice.canUndo ? 80 : 0)) - x - 8; height: parent.height - 4; text: actionNotice.importing ? player.importStatus : actionNotice.text; color: !actionNotice.importing && actionNotice.failed ? theme.colors.error : root.ink; font.pixelSize: SpunStyle.body; wrapMode: Text.WordWrap; elide: Text.ElideRight; verticalAlignment: Text.AlignVCenter }
SpunButton {
- id: noticeUndo; objectName: "undoQueueButton"; visible: actionNotice.canUndo
+ id: noticeUndo; objectName: "undoQueueButton"; visible: actionNotice.canUndo && !actionNotice.importing
x: noticeDismiss.x - width - 8; anchors.verticalCenter: parent.verticalCenter; width: 72; height: 40; enabled: actionNotice.savedUndo || root.queueControlsReady
text: "Undo"
onClicked: { actionNotice.dismiss(); if(actionNotice.savedUndo)root.savedService.undoSavedQueue();else root.ciderService.undoQueueRemoval() }
}
- IconButton { id: noticeDismiss; objectName: "dismissActionNotice"; anchors.right: parent.right; anchors.rightMargin: 4; anchors.verticalCenter: parent.verticalCenter; glyphName: "close"; tip: "Dismiss"; ink: root.mutedInk; hoverFill: root.hoverFill; onClicked: actionNotice.dismiss() }
+ SpunButton {
+ id: noticeCancel; objectName: "cancelImportButton"; visible: actionNotice.importing
+ anchors.right: parent.right; anchors.rightMargin: 4; anchors.verticalCenter: parent.verticalCenter
+ width: 80; height: 40; text: "Cancel"
+ onClicked: { menuButton.forceActiveFocus(Qt.TabFocusReason); player.cancelImport() }
+ }
+ IconButton { id: noticeDismiss; objectName: "dismissActionNotice"; visible: !actionNotice.importing; anchors.right: parent.right; anchors.rightMargin: 4; anchors.verticalCenter: parent.verticalCenter; glyphName: "close"; tip: "Dismiss"; ink: root.mutedInk; hoverFill: root.hoverFill; onClicked: actionNotice.dismiss() }
}
component SettingsAction: MenuEntry { app: root }
component SettingsGap: MenuSeparator {
@@ -1793,7 +1811,7 @@ ApplicationWindow {
onOpened: { if (root.useCider) root.ciderService.refreshModes() }
SettingsAction { text: "Add tracks"; glyphName: "plus"; hint: "Ctrl+O"; onTriggered: files.open() }
- SettingsAction { text: "Add album folder"; glyphName: "folder"; hint: "Ctrl+Shift+O"; onTriggered: folder.open() }
+ SettingsAction { text: "Add music folder"; glyphName: "folder"; hint: "Ctrl+Shift+O"; onTriggered: folder.open() }
SettingsAction { text: "Change artwork"; glyphName: "artwork"; enabled: !root.useCider && player.count > 0; onTriggered: cover.open() }
SettingsGap {}
SettingsAction { objectName: "quickJumpAction"; text: "Quick jump"; hint: "Ctrl+K"; glyphName: "search"; onTriggered: root.openQuickJump() }
@@ -2097,7 +2115,7 @@ ApplicationWindow {
model: [
["Space", "Play / pause"], ["← / →", "Seek 5 seconds"], ["Shift + drag", "Fine seeking"],
["Ctrl + ← / →", "Previous / next"], ["↑ / ↓", "Volume"], ["M", "Mute"],
- ["Ctrl + O", "Add music"], ["Ctrl + Shift + O", "Add album folder"],
+ ["Ctrl + O", "Add music"], ["Ctrl + Shift + O", "Add music folder"],
["Ctrl + L", "Show queue"], ["Ctrl + F", "Search panel"], ["Ctrl + K", "Quick jump"],
["Ctrl + M", "Mini / full player"], ["Ctrl + B", "Browse Cider music"],
["Ctrl + V", "Open music link"], ["F", "Flip disc"], ["Y", "Lyrics / album tracks"],
diff --git a/src/importtest.cpp b/src/importtest.cpp
new file mode 100644
index 0000000..779cb12
--- /dev/null
+++ b/src/importtest.cpp
@@ -0,0 +1,119 @@
+#include "player.h"
+#include <QGuiApplication>
+#include <QTemporaryDir>
+#include <QDir>
+#include <QFile>
+#include <QDataStream>
+#include <QElapsedTimer>
+#include <QSignalSpy>
+#include <QTest>
+#include <QTimer>
+#include <sys/stat.h>
+#include <iostream>
+
+static constexpr quint32 dataBytes = 32 * 1024 * 1024;
+static bool makeWave(const QString &path) {
+ if (!QDir().mkpath(QFileInfo(path).absolutePath())) return false;
+ QFile file(path);
+ if (!file.open(QIODevice::WriteOnly)) return false;
+ QDataStream stream(&file); stream.setByteOrder(QDataStream::LittleEndian);
+ stream.writeRawData("RIFF", 4); stream << quint32(dataBytes + 36);
+ stream.writeRawData("WAVEfmt ", 8); stream << quint32(16) << quint16(1) << quint16(1)
+ << quint32(44100) << quint32(88200) << quint16(2) << quint16(16);
+ stream.writeRawData("data", 4); stream << dataBytes;
+ return stream.status() == QDataStream::Ok && file.resize(dataBytes + 44);
+}
+static bool waitImport(Player &player) {
+ QElapsedTimer clock; clock.start();
+ while (player.busy() && clock.elapsed() < 120000) QTest::qWait(5);
+ return !player.busy();
+}
+int main(int argc, char **argv) {
+ QGuiApplication app(argc, argv);
+ QTemporaryDir temp;
+ if (!temp.isValid()) return 1;
+ const int files = app.arguments().contains("--stress") ? 20000 : 250;
+ const auto music = temp.path() + "/Music";
+ QString firstFile;
+ quint64 physicalBytes = 0;
+ for (int i = 0; i < files; ++i) {
+ const auto path = music + QString("/Artist %1/Album %2/%3.%4")
+ .arg(i / 1000, 3, 10, QChar('0')).arg(i / 100, 3, 10, QChar('0'))
+ .arg(i, 5, 10, QChar('0')).arg(i % 2 ? "WAV" : "wav");
+ if (!makeWave(path)) return 1;
+ if (i == 0) firstFile = path;
+ struct stat info{};
+ if (::stat(QFile::encodeName(path).constData(), &info) == 0) physicalBytes += quint64(info.st_blocks) * 512;
+ }
+ int failures = 0, checks = 0;
+ auto check = [&](bool passed, const char *name) {
+ ++checks;
+ std::cout << (passed ? "PASS " : "FAIL ") << name << std::endl;
+ if (!passed) ++failures;
+ };
+ const auto settings = temp.path() + "/player.ini";
+ {
+ Player player(settings);
+ QSignalSpy progress(&player, &Player::importProgressChanged);
+ QSignalSpy queueChanges(&player, &Player::queueChanged);
+ QTimer heartbeat;
+ QElapsedTimer clock; clock.start();
+ qint64 lastBeat = 0, maxGap = 0;
+ int beats = 0;
+ QObject::connect(&heartbeat, &QTimer::timeout, [&] {
+ const auto now = clock.elapsed(); maxGap = qMax(maxGap, now - lastBeat); lastBeat = now; ++beats;
+ });
+ heartbeat.start(5);
+ player.addUrls({QUrl::fromLocalFile(music)}, false);
+ player.addUrls({QUrl("https://example.invalid/song.mp3")}, false);
+ check(player.busy() && player.error().isEmpty(), "repeated import request preserves active progress without a stale error");
+ check(waitImport(player), "recursive import completes");
+ maxGap = qMax(maxGap, clock.elapsed() - lastBeat);
+ heartbeat.stop();
+ std::cout << "IMPORT tracks=" << player.count() << " expected=" << files
+ << " elapsed_ms=" << clock.elapsed() << " logical_bytes=" << quint64(files) * (dataBytes + 44)
+ << " allocated_audio_bytes=" << physicalBytes << " heartbeat_count=" << beats
+ << " maximum_event_loop_gap_ms=" << maxGap << std::endl;
+ check(player.count() == files, "all nested songs imported including uppercase extensions");
+ check(player.error().isEmpty(), "successful import has no error");
+ check(player.currentUrl().toLocalFile() == firstFile, "deterministic folder ordering");
+ check(player.duration() > 300000, "valid sparse WAV metadata read");
+ check(!player.playing(), "import does not autoplay when disabled");
+ check(progress.count() >= 2 && player.importStatus().startsWith("Added "), "progress and completion status emitted");
+ check(queueChanges.count() == 1, "queue published once per import");
+ player.select(5, false);
+ const auto selection = player.currentUrl();
+ queueChanges.clear();
+ check(QFile::link(firstFile, music + "/alias.wav"), "create file symlink fixture");
+ check(QFile::link(music, music + "/cycle"), "create directory cycle fixture");
+ const auto outside = temp.path() + "/Outside/new.wav";
+ check(makeWave(outside) && QFile::link(QFileInfo(outside).absolutePath(), music + "/outside"), "create external directory link fixture");
+ player.addUrls({QUrl::fromLocalFile(music), QUrl::fromLocalFile(QFileInfo(firstFile).absolutePath()), QUrl::fromLocalFile(firstFile)}, false);
+ check(waitImport(player) && player.count() == files, "overlaps and file aliases deduplicated; directory symlinks skipped");
+ check(queueChanges.isEmpty(), "duplicate-only import does not rebuild queue");
+ check(player.currentUrl() == selection && player.error().isEmpty(), "reimport preserves selection and succeeds");
+ player.addUrls({QUrl::fromLocalFile(outside)}, false);
+ player.cancelImport();
+ check(waitImport(player) && player.count() == files && player.importStatus() == "Import cancelled", "cancel discards pending additions");
+ check(player.currentUrl() == selection, "cancel preserves current track");
+ player.addUrls({QUrl("https://example.invalid/song.mp3"), QUrl::fromLocalFile(temp.path() + "/missing.wav")}, false);
+ check(waitImport(player) && !player.error().isEmpty() && player.count() == files, "invalid inputs report error without clearing queue");
+ player.addUrls({QUrl::fromLocalFile(outside)}, false);
+ check(waitImport(player) && player.count() == files + 1 && player.error().isEmpty(), "direct-file import recovers after cancellation and error");
+ check(player.currentUrl() == selection, "adding songs preserves current track");
+ }
+ {
+ Player restored(settings);
+ check(restored.count() == files + 1, "large queue persists and restores");
+ restored.addUrls({QUrl::fromLocalFile(music)}, false);
+ restored.clear();
+ check(waitImport(restored) && restored.count() == 0, "clear cancels pending import without repopulating queue");
+ }
+ {
+ Player interrupted(temp.path() + "/interrupted.ini");
+ interrupted.addUrls({QUrl::fromLocalFile(music)}, false);
+ }
+ check(true, "destroying player during import finishes safely");
+ std::cout << "RESULT " << failures << " failures / " << checks << " checks" << std::endl;
+ return failures ? 1 : 0;
+}
diff --git a/src/main.cpp b/src/main.cpp
index d2a02e6..e2c3e59 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -38,6 +38,9 @@
#ifdef SPUN_DIAGNOSTICS
#include <QTest>
#include <QQuickItemGrabResult>
+#include <QSemaphore>
+#include <QThreadPool>
+#include <QtConcurrent>
#endif
#include <QTimer>
#include <QElapsedTimer>
@@ -113,7 +116,7 @@ public:
const bool mini = window->property("miniMode").toBool();
const bool cassette=window->property("cassette").toBool();
const int targetWidth = mini ? 300 : queue ? 860 : 530;
- const int targetHeight = mini ? (window->property("showHorizontalSeek").toBool()?382:354) : 730;
+ const int targetHeight = window->property("layoutHeight").toInt();
const qreal scale=qBound(.5,window->property("uiScale").toDouble(),1.5);
QTransform zoom;zoom.scale(scale,scale);
const auto setMask=[&](const QRegion &region){window->setMask(zoom.map(region));};
@@ -404,7 +407,7 @@ static int exerciseCiderQueue(const QString &temp) {
}
static int exercise(Player &player, Theme &theme, Lyrics &lyrics, QQuickWindow *window,
- const QString &temp, const QString &captures, bool live) {
+ const QString &temp, const QString &captures, bool live, bool importOnly = false) {
int failures = 0;
auto check = [&](bool ok, const char *message) {
std::cout << (ok ? "PASS " : "FAIL ") << message << std::endl;
@@ -428,6 +431,38 @@ static int exercise(Player &player, Theme &theme, Lyrics &lyrics, QQuickWindow *
QDir().mkpath(captures); QTest::qWait(300);
check(window->grabWindow().save(captures + "/" + name + ".png"), "capture saved");
};
+ {
+ auto *pool = QThreadPool::globalInstance();
+ pool->waitForDone();
+ const int threads = pool->maxThreadCount();
+ pool->setMaxThreadCount(1);
+ QSemaphore started, release;
+ auto blockedWorker = QtConcurrent::run([&] { started.release(); release.acquire(); });
+ started.acquire();
+ player.addUrls({QUrl::fromLocalFile(QStringLiteral(SPUN_SOURCE_DIR "/assets/First-Light.flac"))}, false);
+ QTest::qWait(150);
+ auto *notice = findItem(window->contentItem(), "actionNotice");
+ auto *cancel = findItem(window->contentItem(), "cancelImportButton");
+ check(player.busy() && notice && notice->isVisible() && cancel && cancel->isVisible(), "local import shows progress and cancellation");
+ capture("26-folder-import-progress");
+ window->setProperty("miniMode", true); QTest::qWait(150);
+ check(notice && notice->isVisible() && cancel && cancel->isVisible(), "mini player keeps import cancellation accessible");
+ auto *controls = findItem(window->contentItem(), "miniControls");
+ check(notice && controls && notice->y() >= controls->y() + controls->height()
+ && notice->y() + notice->height() <= window->property("layoutHeight").toReal(), "mini import progress sits below controls within the window");
+ check(cancel && window->mask().contains(cancel->mapToScene(QPointF(40,20)).toPoint()), "mini import Cancel stays inside the window input region");
+ capture("26-mini-import-progress");
+ click("cancelImportButton");
+ release.release(); blockedWorker.waitForFinished(); pool->setMaxThreadCount(threads);
+ check(waitFor([&] { return !player.busy(); }) && player.count() == 0, "import Cancel button discards pending songs");
+ window->setProperty("miniMode", false); QTest::qWait(150);
+ check(notice && notice->property("text").toString() == "Import cancelled", "import cancellation shows completion feedback");
+ QMetaObject::invokeMethod(notice, "dismiss");
+ }
+ if (importOnly) {
+ std::cout << "IMPORT UI RESULT " << failures << " failures" << std::endl;
+ return failures ? 1 : 0;
+ }
const auto parsed=Lyrics::parse("[offset:250]\n[00:01.00][00:03.50]A quiet room\n[00:05.00]An open window");
check(parsed.size()==3 && parsed[1].toMap()["start"].toLongLong()==3750 && Lyrics::indexAt(parsed,1300)==0 && Lyrics::indexAt(parsed,3900)==1, "LRC offsets and repeated timestamps align with playback");
check(Lyrics::parse("First line\nSecond line").size()==2 && Lyrics::indexAt(Lyrics::parse("Plain words"),5000)==-1, "plain lyrics remain readable without invented timing");
@@ -1441,7 +1476,7 @@ int main(int argc, char **argv) {
for (int i=1; i<argc; ++i) {
const QByteArray option = QByteArray(argv[i]).split('=').first();
if (option == "--") break;
- if (option == "--self-test" || option == "--test-library" || option == "--smoke-live"
+ if (option == "--self-test" || option == "--test-import-ui" || option == "--test-library" || option == "--smoke-live"
|| option == "--verify-cider" || option == "--verify-cider-writes" || option == "--inspect-cider" || option == "--inspect-library") {
const auto executable = QFileInfo(QStringLiteral("/proc/self/exe")).symLinkTarget();
const auto diagnostics = QFile::encodeName(QFileInfo(executable).absolutePath() + "/spun-diagnostics");
@@ -1470,6 +1505,7 @@ int main(int argc, char **argv) {
parser.addOption({"benchmark-medium", "Appearance for isolated measurements", "medium", "cd"});
parser.addOption({"test-library", "Run isolated music browser checks"});
parser.addOption({"self-test", "Run isolated playback and UI checks"});
+ parser.addOption({"test-import-ui", "Run isolated folder import UI checks"});
parser.addOption({"smoke-live", "Run isolated checks on the live desktop"});
parser.addOption({"verify-cider", "Verify a live Cider connection, briefly testing and restoring playback"});
parser.addOption({"verify-cider-writes", "Exercise live Cider controls, reversible queue/audio edits and start song radio"});
@@ -1481,7 +1517,7 @@ int main(int argc, char **argv) {
parser.addPositionalArgument("files", "Music files or album folders to play", "[files…]");
parser.process(app);
if (parser.isSet("export-cover")) return Disc::fallbackArt().save(parser.value("export-cover")) ? 0 : 1;
- const bool test = parser.isSet("benchmark") || parser.isSet("self-test") || parser.isSet("smoke-live") || parser.isSet("test-library");
+ const bool test = parser.isSet("benchmark") || parser.isSet("test-import-ui") || parser.isSet("self-test") || parser.isSet("smoke-live") || parser.isSet("test-library");
if (!test && !parser.isSet("config")) {
auto bus = QDBusConnection::sessionBus();
if (bus.interface() && bus.interface()->isServiceRegistered("org.mpris.MediaPlayer2.spun")) {
@@ -1959,7 +1995,7 @@ int main(int argc, char **argv) {
});
else if (parser.isSet("test-library")) QTimer::singleShot(650, &app, [&] { app.exit(exerciseLibrary(window,temp.path(),parser.value("capture-dir")) ? 1 : 0); });
else if (test) QTimer::singleShot(650, &app, [&] {
- app.exit(exercise(player, theme, lyrics, window, temp.path(), parser.value("capture-dir"), parser.isSet("smoke-live")));
+ app.exit(exercise(player, theme, lyrics, window, temp.path(), parser.value("capture-dir"), parser.isSet("smoke-live"), parser.isSet("test-import-ui")));
});
#endif
else if (!parser.positionalArguments().isEmpty()) {
diff --git a/src/player.cpp b/src/player.cpp
index 0949073..a5fa31c 100644
--- a/src/player.cpp
+++ b/src/player.cpp
@@ -1,6 +1,8 @@
#include "player.h"
#include "artwork.h"
#include <QDir>
+#include <QDirIterator>
+#include <QElapsedTimer>
#include <QCryptographicHash>
#include <QFileInfo>
#include <QFutureWatcher>
@@ -80,6 +82,8 @@ Player::Player(const QString &settingsPath, QObject *parent)
}
Player::~Player() {
+ m_importJob.cancel();
+ m_importJob.waitForFinished();
save();
if (m_preparingAudio) m_audioPreparation.waitForFinished();
// No worker keeps a Player pointer. Finish its bounded cache write before exit.
@@ -150,50 +154,109 @@ Track Player::readTrack(const QString &path) {
}
return t;
}
+void Player::cancelImport() {
+ if (!m_busy) return;
+ m_importJob.cancel();
+ m_importStatus = "Cancelling import";
+ emit importProgressChanged();
+}
void Player::addUrls(const QList<QUrl> &urls, bool autoplay) {
- if (m_busy) { fail("Still adding music. Please try again in a moment."); return; }
- m_busy = true;
+ if (m_busy) return;
dismissError();
+ m_importStatus = "Finding songs";
+ m_busy = true;
+ emit importProgressChanged();
emit busyChanged();
- auto *watcher = new QFutureWatcher<QList<Track>>(this);
- connect(watcher, &QFutureWatcherBase::finished, this, [this, watcher, autoplay] {
- const auto tracks = watcher->result();
- watcher->deleteLater();
- const int firstNew = count();
- QSet<QString> existingPaths;
- existingPaths.reserve(count() + tracks.size());
- for (const auto &track : m_tracks) existingPaths.insert(track.path);
- for (const auto &t : tracks) {
- if (!t.path.isEmpty() && !existingPaths.contains(t.path)) {
- existingPaths.insert(t.path);
- m_tracks.append(t);
+ QSet<QString> existingPaths;
+ existingPaths.reserve(count());
+ for (const auto &track : m_tracks) existingPaths.insert(track.path);
+ // Reuse one watcher; its connections belong to this import only.
+ m_importJob.disconnect(this);
+ connect(&m_importJob, &QFutureWatcherBase::progressTextChanged, this, [this](const QString &status) {
+ if (m_importJob.isCanceled() || status.isEmpty()) return;
+ m_importStatus = status;
+ emit importProgressChanged();
+ });
+ connect(&m_importJob, &QFutureWatcherBase::finished, this, [this, autoplay] {
+ if (m_importJob.isCanceled()) {
+ m_importStatus = "Import cancelled";
+ } else {
+ auto result = m_importJob.future().takeResult();
+ const int firstNew = count();
+ m_tracks.append(std::move(result.tracks));
+ if (count() > firstNew) {
+ emit queueChanged();
+ if (m_index < 0 || autoplay) select(firstNew, autoplay);
+ m_importStatus = QString("Added %1 %2").arg(count() - firstNew).arg(count() - firstNew == 1 ? "song" : "songs");
+ } else if (!result.firstPath.isEmpty()) {
+ m_importStatus = "These songs are already in the queue";
+ if (autoplay) {
+ for (int i = 0; i < count(); ++i) if (m_tracks[i].path == result.firstPath) { select(i); break; }
+ }
+ } else {
+ m_importStatus = "No supported audio found";
+ fail("No supported audio found. Try MP3, FLAC, WAV, OGG, Opus or M4A.");
}
+ save();
}
m_busy = false;
+ emit importProgressChanged();
emit busyChanged();
- emit queueChanged();
- if (count() > firstNew && (m_index < 0 || autoplay)) select(firstNew, autoplay);
- else if (autoplay && !tracks.isEmpty()) {
- for (int i = 0; i < count(); ++i) if (m_tracks[i].path == tracks.first().path) { select(i); break; }
- }
- else if (tracks.isEmpty()) fail("No supported audio found. Try MP3, FLAC, WAV, OGG, Opus or M4A.");
- save();
emit imported();
});
- watcher->setFuture(QtConcurrent::run([urls] {
+ m_importJob.setFuture(QtConcurrent::run([urls, existingPaths](QPromise<ImportedTracks> &promise) {
QStringList paths;
+ QSet<QString> seen = existingPaths;
+ ImportedTracks result;
+ QElapsedTimer progress;
+ progress.start();
+ auto addFile = [&](const QFileInfo &info) {
+ if (!info.isFile() || !info.isReadable() || !supported(info.filePath())) return;
+ const auto path = info.canonicalFilePath();
+ if (path.isEmpty()) return;
+ if (result.firstPath.isEmpty()) result.firstPath = path;
+ if (!seen.contains(path)) { seen.insert(path); paths.append(path); }
+ };
+ int visited = 0;
+ promise.setProgressRange(0, 0);
for (const auto &url : urls) {
+ if (promise.isCanceled()) return;
if (!url.isLocalFile()) continue;
- QFileInfo info(url.toLocalFile());
+ const QFileInfo info(url.toLocalFile());
if (info.isDir()) {
- const auto entries = QDir(info.absoluteFilePath()).entryInfoList(QDir::Files | QDir::Readable, QDir::Name | QDir::IgnoreCase);
- for (const auto &entry : entries) if (supported(entry.filePath())) paths.append(entry.filePath());
- } else if (info.isFile() && supported(info.filePath())) paths.append(info.absoluteFilePath());
+ // Do not follow directory symlinks into cycles or outside the chosen tree.
+ QDirIterator entries(info.absoluteFilePath(), QDir::Files | QDir::Readable | QDir::NoDotAndDotDot, QDirIterator::Subdirectories);
+ QStringList folderPaths;
+ while (entries.hasNext()) {
+ if (promise.isCanceled()) return;
+ entries.next();
+ const auto entry = entries.fileInfo();
+ if (supported(entry.filePath())) folderPaths.append(entry.filePath());
+ if (++visited % 128 == 0 && progress.elapsed() >= 100) {
+ promise.setProgressValueAndText(0, QString("Finding songs: %1 files checked").arg(visited));
+ progress.restart();
+ }
+ }
+ std::sort(folderPaths.begin(), folderPaths.end(), [](const QString &a, const QString &b) {
+ const auto order = QString::compare(a, b, Qt::CaseInsensitive);
+ return order == 0 ? a < b : order < 0;
+ });
+ for (const auto &path : folderPaths) {
+ if (promise.isCanceled()) return;
+ addFile(QFileInfo(path));
+ }
+ } else addFile(info);
}
- paths.removeDuplicates();
- QList<Track> result;
- for (const auto &path : paths) result.append(readTrack(path));
- return result;
+ promise.setProgressRange(0, paths.size());
+ result.tracks.reserve(paths.size());
+ for (int i = 0; i < paths.size(); ++i) {
+ if (promise.isCanceled()) return;
+ promise.setProgressValueAndText(i, QString("Reading songs: %1 of %2").arg(i + 1).arg(paths.size()));
+ auto track = readTrack(paths[i]);
+ if (!track.path.isEmpty()) result.tracks.append(std::move(track));
+ }
+ promise.setProgressValue(paths.size());
+ promise.addResult(std::move(result));
}));
}
void Player::select(int index, bool autoplay) {
@@ -324,6 +387,7 @@ void Player::remove(int index) {
save();
}
void Player::clear() {
+ cancelImport();
stop();
if (m_media) m_media->setSource(QUrl());
m_tracks.clear();
diff --git a/src/player.h b/src/player.h
index 1237e01..d035950 100644
--- a/src/player.h
+++ b/src/player.h
@@ -18,6 +18,7 @@ struct Track {
};
struct LoadedArtwork { QImage image; QString file; bool created = false; };
+struct ImportedTracks { QList<Track> tracks; QString firstPath; };
class Player : public QObject {
Q_OBJECT
@@ -54,6 +55,7 @@ class Player : public QObject {
Q_PROPERTY(bool miniMode READ miniMode WRITE setMiniMode NOTIFY miniModeChanged)
Q_PROPERTY(bool backgroundBlur READ backgroundBlur WRITE setBackgroundBlur NOTIFY backgroundBlurChanged)
Q_PROPERTY(bool busy READ busy NOTIFY busyChanged)
+ Q_PROPERTY(QString importStatus READ importStatus NOTIFY importProgressChanged)
Q_PROPERTY(QString error READ error NOTIFY errorChanged)
public:
explicit Player(const QString &settingsPath, QObject *parent = nullptr);
@@ -102,6 +104,7 @@ public:
bool miniMode() const { return m_miniMode; }
bool backgroundBlur() const { return m_backgroundBlur; }
bool busy() const { return m_busy; }
+ QString importStatus() const { return m_importStatus; }
QString error() const { return m_error; }
QUrl currentUrl() const;
QString artworkFile() const { return m_artFile; }
@@ -115,6 +118,7 @@ public:
void setMiniMode(bool value);
void setMiniOnTop(bool value);
Q_INVOKABLE void addUrls(const QList<QUrl> &urls, bool autoplay = true);
+ Q_INVOKABLE void cancelImport();
Q_INVOKABLE void select(int index, bool autoplay = true);
Q_INVOKABLE void toggle();
Q_INVOKABLE void play();
@@ -147,6 +151,7 @@ signals:
void miniModeChanged();
void miniOnTopChanged();
void busyChanged();
+ void importProgressChanged();
void errorChanged();
void imported();
private:
@@ -155,6 +160,8 @@ private:
void startArtLoad();
void fail(const QString &message);
QList<Track> m_tracks;
+ QFutureWatcher<ImportedTracks> m_importJob;
+ QString m_importStatus;
bool m_tracksDirty = false;
int m_index = -1;
QFutureWatcher<void> m_audioPreparation;