Skip to content

armgit / Spun

Public Imported from GitHub
0

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

Refine player design and expand Cider integration

yappologisticceadc7c09dae
diff --git a/.gitignore b/.gitignore
index 6f42ec8..4453643 100644
--- a/.gitignore
+++ b/.gitignore
@@ -47,3 +47,4 @@
*.bak
__pycache__/
cider-connection.json
+listening.json
diff --git a/CMakeLists.txt b/CMakeLists.txt
index ef29451..6704556 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -39,10 +39,11 @@ find_package(PkgConfig REQUIRED)
pkg_check_modules(TAGLIB REQUIRED IMPORTED_TARGET taglib>=2.0)
qt_add_library(spun_core STATIC
src/symbol.cpp src/symbol.h src/typography.cpp src/typography.h
+ src/listening.cpp src/listening.h
src/musicactions.cpp src/musicactions.h
src/library.cpp src/library.h src/lyrics.cpp src/lyrics.h src/artwork.cpp src/artwork.h
src/player.cpp src/player.h src/disc.cpp src/disc.h src/mpris.cpp src/mpris.h
- src/theme.cpp src/theme.h src/cider.cpp src/cider.h)
+ src/theme.cpp src/theme.h src/cider.cpp src/cider.h src/ciderevents.cpp src/ciderevents.h)
target_link_libraries(spun_core PUBLIC Qt6::Core Qt6::Gui Qt6::Quick Qt6::Qml Qt6::QuickControls2
Qt6::Svg Qt6::Multimedia Qt6::Concurrent Qt6::DBus Qt6::Network PkgConfig::TAGLIB)
target_compile_definitions(spun_core PUBLIC SPUN_SOURCE_DIR="${CMAKE_CURRENT_SOURCE_DIR}")
@@ -66,7 +67,7 @@ function(spun_application target)
# Compile QML at build time, preserving existing resource URLs and the UI.
qt_add_qml_module(${target} URI SpunUi VERSION 1.0 NO_PLUGIN
NO_RESOURCE_TARGET_PATH RESOURCE_PREFIX "/" OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/${target}-qml"
- QML_FILES qml/SpunText.qml qml/FontPicker.qml qml/SpunStateLayer.qml qml/SpunSpring.qml qml/SpunPopupEnter.qml qml/SpunStyle.qml qml/TrackContent.qml qml/SpunSearchField.qml qml/MenuEntry.qml qml/PreferenceSwitch.qml qml/TrackMenu.qml qml/Main.qml qml/LibraryPanel.qml qml/SpunToolTip.qml qml/IconButton.qml qml/Glyph.qml)
+ QML_FILES qml/SpunButton.qml qml/SpunSlider.qml qml/QuickJump.qml qml/NextTrackTip.qml qml/SavedQueuePicker.qml qml/Tonearm.qml qml/SpunText.qml qml/FontPicker.qml qml/SpunStateLayer.qml qml/SpunSpring.qml qml/SpunPopupEnter.qml qml/SpunStyle.qml qml/TrackContent.qml qml/SpunSearchField.qml qml/MenuEntry.qml qml/PreferenceSwitch.qml qml/TrackMenu.qml qml/Main.qml qml/LibraryPanel.qml qml/SpunToolTip.qml qml/IconButton.qml qml/Glyph.qml)
# Preserve the exact SVGs and URLs; Qt's default threshold leaves many of
# these small resources uncompressed. Parsed symbols are already cached.
if(QT_FEATURE_zstd)
@@ -93,7 +94,7 @@ endif()
if(BUILD_TESTING)
find_package(Qt6 REQUIRED COMPONENTS Test)
spun_application(spun-diagnostics)
- target_sources(spun-diagnostics PRIVATE src/librarytest.cpp src/librarytest.h)
+ 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)
add_test(NAME spun-playback-and-ui COMMAND spun --self-test)
diff --git a/README.md b/README.md
index 1dc0923..9bedd82 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,6 @@
<h1 align="center">Spun</h1>
-<p align="center">A CD-shaped music player for Linux.</p>
+<p align="center">A CD and vinyl music player for Linux.</p>
<p align="center">
<img src="assets/screenshots/spun-player.png" alt="Spun with album artwork on the CD and Cider music search alongside it" width="1000">
@@ -57,21 +57,56 @@ Other Linux distributions need a C++20 compiler, CMake 3.22+, Ninja, pkg-config,
For search, library browsing and the full queue:
1. Enable Cider's local API.
-2. In Cider, open **Settings → Connectivity → Manage External Application Access** and create an application token for Spun. Allow the access needed for playback, queue and library features.
-3. Open Spun's **Queue** and enter the token when prompted.
+2. Open Spun’s **Queue** and choose **Connect to Cider**.
+3. Approve Spun in Cider. Spun remembers the connection.
+
+With older versions, choose **Use an app token** instead. Create one in Cider’s **Settings → Connectivity → Manage External Application Access**, allow playback, queue, library and audio access, then paste it into Spun.
Spun connects to Cider's local API on port 10767. Basic playback controls use Linux's media-player interface; working playback alone does not mean the API connection is ready. Available library and playback actions depend on your Cider version and its permissions.
## Inside the player
-- **Queue:** use the top-right button to view tracks with artwork, search, reorder or remove them.
+- **Queue:** use the top-right button to view tracks with artwork, search, reorder or remove them. The header estimates the time left for the current and upcoming songs, excluding repeats and future autoplay. Missing durations are marked as incomplete or a lower bound; queue search does not change the estimate.
+- **Queue from here:** inside an album, playlist or saved queue, open a song’s **⋯** menu and choose **Queue from here**. Spun loads the remaining pages, then appends that song and everything after it in collection order, including tracks hidden by search. Navigating away cancels loading. Ranges containing unavailable tracks are rejected before any songs are queued; the limit is 5,000 songs. If Cider stops confirming additions, Spun reports partial progress without retrying uncertain writes.
+- **Listening bookmarks:** choose **Bookmark this moment** in the current Cider song’s **⋯** menu. Find the bookmark in **Ctrl+K**, then select it to play from that position. Use its remove button to delete it. Up to 100 bookmarks are kept locally, with no downloaded audio. Spun verifies the playing song before seeking and checks the resulting position.
+- **Session recovery:** enable **Remember Cider session** in Preferences. Spun checkpoints the current and upcoming songs when the queue changes and about every 15 seconds during playback. After a crash or an empty queue, choose **Recover session…** from Queue’s menu or Quick jump, then confirm. Recovery starts playback at the saved position and only restores into an empty Cider queue; it never clears an existing queue. Turning the preference off removes the checkpoint. Cider must be connected and the saved songs must remain available.
+- **Quick jump:** press **Ctrl+K**, or choose **More → Quick jump**, to find pins, saved queues and tracks in the current queue. Type to filter, use ↑/↓ and Enter, or click a result. Queue results play the selected track; pins and saved queues open for browsing. Station pins open station search. Quick jump works in Mini mode too and keeps it compact when you play a song; Escape closes it. Results are limited to 40 matches, so narrow the search for long queues.
- **Browse:** in Cider mode, use the top-left search button for Apple Music search, your library and recently played tracks. Albums and playlists open to their track lists, with search inside each collection.
+- **For You:** choose **For You** on the empty Search page for personalized albums, playlists and stations through your existing Cider connection. Open collections, play stations, or use their menus to queue or pin them. Recommendations retain their group context, omit repeated cards and load more pages on demand. Search filters the feed and checks remaining pages; Refresh fetches it again. There is no background recommendation polling. Empty results or missing permissions are shown explicitly; the feed is bounded to 1,000 cards and 100 pages.
+- **Discography filters:** on an artist’s **Albums** tab, use **All releases** to switch to **Full albums**, **Singles & EPs**, or **Live albums**. Categories come from the catalog through Cider. Collection search and pagination work within the chosen category, and Back from an album restores the filter and your place.
+- **Stations:** choose **Stations** in Search, or paste an Apple Music station link. Click a station to listen, and use its **⋯** menu to pin it. Station pins play directly from the empty Search page.
+- **Recently added:** in Songs or Albums, select **Recently added** for newest-first browsing. **A–Z** restores alphabetical order; **History** opens recently played songs. Your sorting choice is remembered. Pages are sorted by Apple Music, without downloading the whole library.
+- **Song radio:** choose **Start radio** in a song’s **⋯** menu, including the player and queue. Spun checks for an available station through Cider when the menu opens. Uploaded songs and some catalog songs have no station. Checking availability never starts playback.
+- **Artist discovery:** choose **Similar** on an artist page to explore related artists. Back restores the previous artist, tab and scroll position.
+- **Latest releases:** choose **Releases** beside your pins to see the latest available release from each pinned artist, newest first. This is a catalog view, not a notification feed or a complete release history. Search the list, open albums, or play and queue them normally. Results are fetched in batches only when opened and cached in memory for up to an hour; use Refresh to check again. Partial failures offer Retry and preserve previous results when possible.
+- **Live sync:** while Spun is visible in Cider mode, Cider’s change events trigger batched queue readbacks and refresh open song/audio details. The event connection retries after outages; periodic queue reconciliation remains as a fallback. No extra runtime dependency is needed.
+- **Artists:** search the **Artists** category, click a song’s artist name or choose **View artist** from its menu. Switch between **Top songs** and **Albums**, search either list, play or queue songs, and use Back to return. Top songs uses your existing Cider connection; no separate Apple developer account, token, or sign-in is needed. Ambiguous names stay in search so you can choose the right artist.
+- **Drag to queue:** drag a song’s artwork sideways to reveal Queue, then drop it at the highlighted position among upcoming tracks. Dragging a selected song includes the whole selection. The edges scroll the queue; Escape or dropping outside returns to browsing. Spun checks the queue between writes and stops if Cider changes it.
+- **Undo removal:** removing a queued song offers **Undo** for eight seconds. It restores the original position, including duplicates. Queue changes invalidate Undo; removing the currently playing song cannot undo playback.
+- **Select tracks:** Ctrl-click individual songs, Shift-click a range, or choose **Select track** from a song’s **⋯** menu. Use the selection’s **⋯** to play next or add to queue in the displayed order. Ctrl+A selects loaded, available songs; Space toggles the focused song. Escape clears the selection. If Cider cannot confirm a batch, Spun stops and reports how many tracks were confirmed before you retry.
+- **Shuffle collections:** use the Shuffle button beside Play in an album or playlist, or choose **Shuffle** in its menu, including pinned collections.
+- **Recent searches:** submitted searches and searches whose results you open or play stay on this device. The empty Search page shows the last eight; use **×** to remove one. Typing alone and pasted music links are not saved.
+- **Already queued:** a small check beside a song in browsing results marks it as current or upcoming in Cider. Matching uses song IDs, including library-to-catalog IDs when available. History is excluded, and you can still queue intentional repeats. Queue status refreshes while browsing; unavailable status hides the checks.
+- **Queue multiselect:** Ctrl-click upcoming tracks, Shift-click a range, or use **Select track** in a song’s **⋯** menu. The selection’s **⋯** can move songs up, down, next or to the end, or remove them after a preview. Ctrl+A selects visible upcoming tracks; Escape clears selection. Spun preserves their order, protects the current song and history, and stops if Cider changes the queue.
+- **Queue cleanup:** in Cider’s Queue, choose **⋯ → Remove duplicates…** or **Clear upcoming…**. Review the tracks before confirming. Cleanup preserves the current song and history, verifies each removal, and stops if the queue changes. Duplicate detection uses song IDs, not titles; it also removes upcoming repeats of the current song. Future autoplay can still add songs.
+- **Pinned artists:** pin an artist from its page or **⋯** menu. Artist pins sit alongside your other pins and open **Top songs**, with **Albums** one click away. Pins are local to Spun and do not change Apple Music favorites.
+- **Pinned collections:** choose **Pin collection** from an album or playlist’s **⋯** menu. Your pins appear on the empty Search page; click a cover to play, or use its menu to open or unpin it. Pins stay on this device.
+- **Motion:** subtle spring feedback for controls and bounded fades follow [Material’s motion guidance](https://m3.material.io/styles/motion/overview/how-it-works), including reduced-motion preferences.
+- **Connection recovery:** temporary API outages retry while the browser or queue is open. Browsing results stay visible; expired access offers reconnection. Spun never automatically replays a failed playback action.
- **Track actions:** use a song's **⋯** menu to play next or add it to the queue. Supported Cider actions also include favorites and saving songs to your library. Writing songs into playlists is not currently supported.
-- **Music links:** paste an Apple Music song, album or playlist link into search, or drop it on the player. Spun shows the result before you choose playback.
+- **Add to saved queue:** choose this from a browsing song or selection’s **⋯** menu, or from a Queue selection. Pick an existing snapshot and choose whether to skip duplicate song IDs. This changes only the local snapshot; it does not alter playback or Apple Music playlists.
+- **Saved queues:** in Cider’s Queue, open **⋯ → Save queue** and give it a name. Spun saves the current and upcoming tracks in order. Open **⋯ → Saved queues** to browse them, play them next or append them to the existing queue. These are local snapshots of track references, not Apple Music playlists or downloaded audio. Use its **⋯ → Rename saved queue**, or open it and use a song’s **⋯** menu to move or remove tracks. Moves are available when the track filter is empty. Edits save locally without touching Cider’s playing queue; empty snapshots can still be renamed or deleted. Deleting a snapshot asks for confirmation.
+- **Undo saved edits:** after renaming a saved queue, moving/removing a saved track or appending songs, the notice offers **Undo** for eight seconds. It restores the last edit only. Another edit replaces that opportunity; external changes or deletion invalidate it. The previous version stays briefly on disk rather than as a second track list in RAM. This never changes Cider’s playing queue.
+- **Audio settings:** **More → Preferences → Audio settings** contains crossfade, plus Automix and Off/Gaming/Unwind listening modes when your Cider version and token support them. Changes are read back from Cider before being shown as confirmed.
+- **Song preferences:** the current song’s **⋯** menu includes **Suggest less like this** and **Clear dislike**, using Cider’s confirmed rating.
+- **Audio quality:** choose **Audio quality** in the current song’s **⋯** menu. Spun displays the quality Cider reports and labels device output separately; it does not infer lossless or Atmos from device support. Details are fetched only when opened or refreshed.
+- **Copy song link:** use **Copy song link** in the current song, browser or Cider queue’s **⋯** menu. Library songs use their public catalog identity; uploaded or unavailable songs may have no shareable link.
+- **Music links:** paste an Apple Music song, album, playlist or station link into search, or drop it on the player. Spun shows the result before you choose playback.
- **Disc reverse:** double-click the disc or press **F** to see album details and tracks. Switch to lyrics with **Y** when available. Local lyrics can come from matching `.lrc` / `.txt` files or embedded metadata.
-- **Mini mode:** a little CD with controls underneath. Optionally keep it above other windows in Preferences.
+- **Disc appearance:** choose **CD** or **Vinyl** in **More → Preferences**. Vinyl keeps the artwork on its center label, with grooves, a small spindle hole, and a gold tonearm. The arm lowers for playback, tracks inward through the song, and parks on pause. It scales with Mini mode, stays out of the reverse view and disc swaps, and respects reduced motion. Both styles share playback, reverse, lyrics, the progress ring, disc swaps and mini mode. Your choice is remembered.
+- **Mini mode:** a little disc with controls underneath. Optionally keep it above other windows in Preferences. Hover or keyboard-focus **Next** to preview the upcoming artwork, title and artist. Cider’s queue is checked on demand; an unknown next track is shown honestly, including local shuffle. No extra polling runs while the preview is closed.
-**More → Preferences** contains the font picker, background blur, disc animation and other playback options. Spun follows Noctalia's colors and reduced-motion preference when available. Hyprland integration depends on the compositor's supported interfaces.
+**More → Preferences** contains CD/Vinyl appearance, the font picker, background blur, disc animation and other playback options. Spun follows Noctalia's colors and reduced-motion preference when available. Hyprland integration depends on the compositor's supported interfaces.
### Fonts
@@ -91,6 +126,10 @@ For the intended appearance, we recommend [Google Sans Flex](https://github.com/
| Queue | Ctrl + L |
| Cider browser | Ctrl + B |
| Search the current panel | Ctrl + F |
+| Quick jump | Ctrl + K |
+| Select browser / upcoming queue tracks | Ctrl + A (track list focused) |
+| Toggle focused browser track | Space (track list focused) |
+| Select tracks / range | Ctrl-click / Shift-click |
| Mini mode | Ctrl + M |
| Flip disc / switch lyrics | F / Y |
| Mute | M |
@@ -125,7 +164,7 @@ You can then delete the Spun source folder. Your music stays where it was. Prefe
**An audio file will not play:** supported formats depend on the codecs available to Qt Multimedia on your distribution.
-Spun does not ask for your Apple Music password. The Cider application token is stored locally with owner-only file permissions in `~/.config/spun/cider-connection.json`; preferences live in `~/.config/spun/settings.ini`. Artwork and music metadata may be fetched as part of playback and browsing. Do not share your token, private configuration, listening history or personal logs in issue reports.
+Spun does not ask for your Apple Music password. The Cider application token is stored locally with owner-only file permissions in `~/.config/spun/cider-connection.json`; preferences live in `~/.config/spun/settings.ini`, and pinned collections in `~/.config/spun/cider-pins.json`. Artwork and music metadata may be fetched as part of playback and browsing. Do not share your token, private configuration, listening history or personal logs in issue reports.
This repository contains source code, license notices, UI icons, an original synthesized demo with generated cover art, and the approved project screenshot above. Private account configuration, logs and other desktop captures are excluded.
diff --git a/qml/FontPicker.qml b/qml/FontPicker.qml
index 143df16..8b0be7c 100644
--- a/qml/FontPicker.qml
+++ b/qml/FontPicker.qml
@@ -18,7 +18,7 @@ Popup {
font.family: SpunStyle.family
background: Rectangle { color: SpunStyle.popup; radius: SpunStyle.popupRadius }
enter: SpunPopupEnter {}
- exit: Transition { NumberAnimation { property: "opacity"; from: 1; to: 0; duration: SpunStyle.exit } }
+ exit: Transition { NumberAnimation { property: "opacity"; from: 1; to: 0; duration: SpunStyle.exit; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
readonly property var matches: {
const query = search.text.trim().toLocaleLowerCase()
return typography.families.filter(family => family.toLocaleLowerCase().includes(query))
@@ -27,7 +27,7 @@ Popup {
onAboutToShow: { typography.loadFamilies(); search.text = ""; fonts.currentIndex = -1 }
onOpened: search.forceActiveFocus()
contentItem: Item {
- SpunText { x: 12; y: 10; text: "Font"; color: picker.app.ink; font.pixelSize: SpunStyle.heading }
+ SpunText { x: 12; y: 10; text: "Font"; color: picker.app.ink; font.pixelSize: SpunStyle.heading; font.weight: Font.Medium }
IconButton { objectName: "closeFontPicker"; anchors.right: parent.right; glyphName: "close"; tip: "Close font picker"; ink: picker.app.ink; onClicked: picker.close() }
SpunSearchField {
id: search
@@ -45,11 +45,14 @@ Popup {
objectName: "systemFontChoice"
y: search.y + search.height + 8; width: parent.width; height: SpunStyle.target
text: "System default"
+ Accessible.role: Accessible.RadioButton
+ Accessible.checkable: true; Accessible.checked: typography.selectedFamily.length === 0
font.family: SpunStyle.family; font.pixelSize: SpunStyle.body
onClicked: picker.choose("")
contentItem: SpunText { text: systemChoice.text; font: systemChoice.font; color: picker.app.ink; verticalAlignment: Text.AlignVCenter; rightPadding: 32; elide: Text.ElideRight }
background: Rectangle {
radius: SpunStyle.rowRadius; color: typography.selectedFamily.length === 0 ? SpunStyle.selected : "transparent"
+ border.width: systemChoice.visualFocus ? 2 : 0; border.color: picker.app.accent
SpunStateLayer { anchors.fill: parent; radius: parent.radius; color: picker.app.ink; hovered: systemChoice.hovered; pressed: systemChoice.down; focused: systemChoice.visualFocus }
}
Glyph { anchors.right: parent.right; anchors.rightMargin: 12; anchors.verticalCenter: parent.verticalCenter; visible: typography.selectedFamily.length === 0; name: "check"; ink: picker.app.accent }
@@ -88,10 +91,13 @@ Popup {
readonly property bool selected: typography.selectedFamily === modelData
font.family: SpunStyle.family; font.pixelSize: SpunStyle.body
Accessible.name: modelData
+ Accessible.role: Accessible.RadioButton
+ Accessible.checkable: true; Accessible.checked: selected
onClicked: picker.choose(modelData)
contentItem: SpunText { text: row.text; color: picker.app.ink; font: row.font; elide: Text.ElideRight; verticalAlignment: Text.AlignVCenter; rightPadding: 32 }
background: Rectangle {
radius: SpunStyle.rowRadius; color: row.selected ? SpunStyle.selected : "transparent"
+ border.width: row.highlighted || row.visualFocus ? 2 : 0; border.color: picker.app.accent
SpunStateLayer { anchors.fill: parent; radius: parent.radius; color: picker.app.ink; hovered: row.hovered; pressed: row.down; focused: row.highlighted || row.visualFocus }
}
Glyph { anchors.right: parent.right; anchors.rightMargin: 12; anchors.verticalCenter: parent.verticalCenter; visible: row.selected; name: "check"; ink: picker.app.accent }
diff --git a/qml/IconButton.qml b/qml/IconButton.qml
index 9b06522..8d4b7cc 100644
--- a/qml/IconButton.qml
+++ b/qml/IconButton.qml
@@ -5,6 +5,7 @@ AbstractButton {
id: control
property string glyphName: "play"
property string tip: ""
+ property bool showTip: true
property color ink: "#eee8de"
property color fill: "transparent"
property color hoverFill: "#30ffffff"
@@ -16,7 +17,7 @@ AbstractButton {
focusPolicy: Qt.StrongFocus
hoverEnabled: true
Accessible.name: tip
- SpunToolTip { visible: control.hovered && control.enabled && control.visible && !control.down && control.tip.length > 0; text: control.tip }
+ SpunToolTip { visible: control.showTip && (control.hovered || control.visualFocus) && control.enabled && control.visible && !control.down && control.tip.length > 0; text: control.tip }
background: Rectangle {
SpunSpring { id: cornerMotion; targetValue: Math.min(control.width, control.height) * (control.down ? .35 : .5) }
radius: cornerMotion.value
@@ -24,7 +25,7 @@ AbstractButton {
Rectangle {
anchors.fill: parent; radius: parent.radius; color: SpunStyle.selected
opacity: control.selected && control.fill.a === 0 ? 1 : 0
- Behavior on opacity { NumberAnimation { duration: SpunStyle.feedback } }
+ Behavior on opacity { NumberAnimation { duration: SpunStyle.feedback; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
}
SpunStateLayer { anchors.fill: parent; radius: parent.radius; color: control.ink; enabled: control.enabled; pressed: control.down; focused: control.visualFocus; hovered: control.hovered }
border.width: control.visualFocus ? 2 : 0
@@ -33,7 +34,7 @@ AbstractButton {
contentItem: Item {
SpunSpring { id: pressMotion; targetValue: control.down && control.motionEnabled ? .95 : 1; epsilon: .002 }
scale: pressMotion.value
- Glyph { anchors.centerIn: parent; width: control.glyphSize; height: width; name: control.glyphName; ink: control.ink; opacity: control.enabled ? 1 : 0.3 }
+ Glyph { anchors.centerIn: parent; width: control.glyphSize; height: width; name: control.glyphName; ink: control.ink; opacity: control.enabled ? 1 : SpunStyle.disabledOpacity }
}
}
diff --git a/qml/LibraryPanel.qml b/qml/LibraryPanel.qml
index a813d6a..eb592e8 100644
--- a/qml/LibraryPanel.qml
+++ b/qml/LibraryPanel.qml
@@ -6,17 +6,89 @@ Rectangle {
required property var app
property var browser: library
readonly property bool detail: Object.keys(browser.collection).length > 0
+ readonly property bool sessionPage: detail && browser.collection.type === "saved-queues"
+ readonly property bool sessions: browser.section === "sessions"
+ readonly property bool forYou: browser.section === "for-you"
+ readonly property bool releases: browser.section === "releases"
+ readonly property bool artistSimilar: artistPage && browser.artistView === "similar"
+ readonly property bool artistPage: detail && browser.collection.type === "artists"
+ function songKey(row) {
+ if (!row || (row.type !== "songs" && row.type !== "library-songs") || !row.id) return ""
+ return row.catalogId ? "songs:" + row.catalogId : row.type + ":" + row.id
+ }
+ readonly property bool queuedStatusReady: app.ciderService.queueReady && !app.ciderService.queueError.length && !app.ciderService.recovering
+ readonly property var queuedSongKeys: {
+ const cider = app.ciderService
+ const keys = new Set()
+ if (!visible || !app.useCider) return keys
+ const rows = cider.queue
+ for (let i = Math.max(0, cider.currentIndex); i < rows.length; ++i) {
+ const key = songKey(rows[i]); if (key.length) keys.add(key)
+ }
+ return keys
+ }
+ readonly property bool artistSongs: artistPage && browser.artistView === "songs"
+ property var savedPositions: []
+ property var selectionKeys: []
+ property int selectionAnchor: -1
+ readonly property int selectionCount: selectionKeys.length
+ readonly property bool trackListFocused: list.activeFocus
+ readonly property var selectedTracks: {
+ const rows = browser.items
+ const keys = new Set(selectionKeys)
+ return rows.filter((item, index) => keys.has(rowKey(index, item)))
+ }
+ function rowKey(index, item) { return index + ":" + item.type + ":" + item.id }
+ function clearSelection() { selectionKeys = []; selectionAnchor = -1 }
+ function chooseRow(index, modifiers) {
+ const item = browser.items[index]
+ if (!item) return
+ const selectable = item.type.endsWith("songs") && item.playable
+ const control = modifiers & Qt.ControlModifier
+ const shift = modifiers & Qt.ShiftModifier
+ if (selectable && (control || shift || selectionCount > 0)) {
+ let next = selectionKeys.slice()
+ if (shift && selectionAnchor >= 0) {
+ next = control ? next : []
+ for (let i = Math.min(index, selectionAnchor); i <= Math.max(index, selectionAnchor); ++i) {
+ const row = browser.items[i], key = rowKey(i, row)
+ if (row.type.endsWith("songs") && row.playable && next.indexOf(key) < 0) next.push(key)
+ }
+ } else {
+ const key = rowKey(index, item), at = next.indexOf(key)
+ if (at >= 0) next.splice(at, 1); else next.push(key)
+ selectionAnchor = index
+ }
+ selectionKeys = next; list.currentIndex = index; return
+ }
+ if (control || shift) return
+ clearSelection(); list.currentIndex = index; activate(index)
+ }
+ function selectAllTracks() {
+ selectionKeys = browser.items.map((item, index) => item.playable && item.type.endsWith("songs") ? rowKey(index, item) : "").filter(key => key.length)
+ }
readonly property bool linkPreview: browser.section === "search" && browser.query.trim().startsWith("https://music.apple.com/")
- readonly property bool actionsOpen: trackMenu.visible
- function closeActions() { trackMenu.close() }
- function showActions(item, anchor) {
+ Connections {
+ target: panel.browser
+ function onTailReady(tracks) {
+ if (panel.app.actionService.busy || panel.app.ciderService.controlBusy) panel.app.notifyAction("Cider is busy. Nothing was queued; try again when it finishes.", true)
+ else if (!panel.app.ciderService.queueReady || panel.app.ciderService.queueBusy || panel.app.ciderService.queueError.length) panel.app.notifyAction("Connect Cider and refresh Queue before adding this range.", true)
+ else panel.app.ciderService.insertQueue(tracks, panel.app.ciderService.queue.length, panel.app.ciderService.queueRevision)
+ }
+ function onFeedback(message, error) { panel.app.notifyAction(message, error) }
+ }
+ readonly property bool actionsOpen: trackMenu.visible || discographyMenu.visible
+ function closeActions() { trackMenu.close(); discographyMenu.close() }
+ function showActions(item, anchor, batch = false) {
+ trackMenu.selectionBatch = batch || selectedTracks.some(row => row.id === item.id && row.type === item.type) ? selectedTracks.slice() : []
trackMenu.selection = Object.assign({}, item)
+ trackMenu.savedTrackIndex = panel.sessionPage && !batch && item.savedIndex !== undefined ? item.savedIndex : -1
const point = anchor.mapToItem(panel, anchor.width, anchor.height)
trackMenu.x = Math.max(8, Math.min(panel.width - trackMenu.width - 8, point.x - trackMenu.width))
trackMenu.y = Math.max(8, Math.min(panel.height - trackMenu.height - 8, point.y))
trackMenu.open()
}
- TrackMenu { id: trackMenu; objectName: "browserTrackMenu"; app: panel.app }
+ TrackMenu { id: trackMenu; objectName: "browserTrackMenu"; app: panel.app; pinService: panel.browser; onSelectRequested: { const index = panel.browser.items.findIndex(row => row === selection || (row.id === selection.id && row.type === selection.type)); if (index >= 0) { list.forceActiveFocus(); panel.chooseRow(index, Qt.ControlModifier) } } }
DropArea {
anchors.fill: parent
onEntered: drag => { if (!drag.hasUrls && !drag.hasText) drag.accepted = false }
@@ -35,12 +107,12 @@ Rectangle {
Connections { target: panel.app; function onAnimateChanged() { if (!panel.app.animate) panel.settle() } }
ParallelAnimation {
id: entrance
- NumberAnimation { target: panel; property: "opacity"; from: 0; to: 1; duration: panel.feedbackTime }
+ NumberAnimation { target: panel; property: "opacity"; from: 0; to: 1; duration: panel.feedbackTime; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve }
NumberAnimation { target: entranceOffset; property: "x"; from: 12; to: 0; duration: panel.transitionTime; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.enterCurve }
}
ParallelAnimation {
id: listEntrance
- NumberAnimation { target: list; property: "opacity"; from: 0; to: 1; duration: panel.feedbackTime }
+ NumberAnimation { target: list; property: "opacity"; from: 0; to: 1; duration: panel.feedbackTime; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve }
NumberAnimation { target: listOffset; property: "x"; from: panel.detail ? 12 : 0; to: 0; duration: panel.transitionTime; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.enterCurve }
}
color: app.surface; radius: SpunStyle.panelRadius
@@ -55,9 +127,11 @@ Rectangle {
}
Connections {
target: panel.browser
- function onItemsChanging(append) { panel.closeActions(); panel.appending = append; panel.pageY = append ? list.contentY : 0; panel.pageIndex = append ? list.currentIndex : -1 }
- function onItemsChanged() { Qt.callLater(function() { list.contentY = panel.pageY; list.currentIndex = panel.pageIndex; if (!panel.appending && panel.app.animate && panel.visible && list.count) listEntrance.restart() }) }
- function onReturned() { Qt.callLater(function() { list.contentY = panel.savedY; list.forceActiveFocus() }) }
+ function onNavigating() { panel.savedPositions = panel.savedPositions.slice(-15).concat([list.contentY]) }
+ function onNavigationReset() { panel.savedPositions = []; panel.clearSelection() }
+ function onItemsChanging(append) { if (!append) panel.clearSelection(); panel.closeActions(); panel.appending = append; panel.pageY = append ? list.contentY : 0; panel.pageIndex = append ? list.currentIndex : -1 }
+ function onItemsChanged() { const keys = new Set(panel.browser.items.map((item, index) => panel.rowKey(index, item))); panel.selectionKeys = panel.selectionKeys.filter(key => keys.has(key)); Qt.callLater(function() { list.contentY = panel.pageY; list.currentIndex = panel.pageIndex; if (!panel.appending && panel.app.animate && panel.visible && list.count) listEntrance.restart() }) }
+ function onReturned() { const positions = panel.savedPositions.slice(); const y = positions.pop() || 0; panel.savedPositions = positions; Qt.callLater(function() { list.contentY = y; list.forceActiveFocus() }) }
}
component SmallButton: AbstractButton {
id: control
@@ -72,7 +146,7 @@ Rectangle {
color: "transparent"
Rectangle {
anchors.fill: parent; radius: parent.radius; color: SpunStyle.selected; opacity: control.selected && control.pill ? 1 : 0
- Behavior on opacity { NumberAnimation { duration: SpunStyle.feedback } }
+ Behavior on opacity { NumberAnimation { duration: SpunStyle.feedback; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
}
SpunStateLayer { anchors.fill: parent; radius: parent.radius; color: panel.app.ink; enabled: control.enabled; pressed: control.down; focused: control.visualFocus; hovered: control.hovered }
border.width: control.visualFocus ? 2 : 0
@@ -82,31 +156,55 @@ Rectangle {
text: control.text; color: control.selected ? panel.app.accent : panel.app.mutedInk
font.family: SpunStyle.family; font.pixelSize: SpunStyle.body; font.weight: Font.Medium
horizontalAlignment: Text.AlignHCenter; verticalAlignment: Text.AlignVCenter
- opacity: control.enabled ? control.down ? .65 : 1 : .4
- Behavior on color { ColorAnimation { duration: panel.feedbackTime } }
- Behavior on opacity { NumberAnimation { duration: panel.feedbackTime } }
+ opacity: control.enabled ? 1 : SpunStyle.disabledOpacity
+ Behavior on color { ColorAnimation { duration: panel.feedbackTime; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
+ Behavior on opacity { NumberAnimation { duration: panel.feedbackTime; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
}
}
Rectangle {
- visible: !panel.detail
+ visible: !panel.detail && !panel.sessions && !panel.releases && !panel.forYou && panel.selectionCount === 0
SpunSpring { id: sectionMotion; targetValue: 20 + ["search", "songs", "albums", "playlists"].indexOf(panel.browser.section === "recent" ? "songs" : panel.browser.section) * 68 }
x: sectionMotion.value
y: 16; width: 66; height: 36; radius: 18 * theme.radius; color: SpunStyle.selected
}
Row {
- visible: !panel.detail
+ id: libraryTabs
+ function focusTab(index) {
+ const button = libraryTabItems.itemAt(Math.max(0, Math.min(libraryTabItems.count - 1, index)))
+ if (button) button.forceActiveFocus(Qt.TabFocusReason)
+ }
+ visible: !panel.detail && !panel.sessions && !panel.releases && !panel.forYou && panel.selectionCount === 0
x: 20; y: 16; spacing: 2
Repeater {
+ id: libraryTabItems
model: ["search", "songs", "albums", "playlists"]
SmallButton {
required property string modelData
+ required property int index
objectName: "libraryTab_" + modelData
+ Accessible.role: Accessible.PageTab
+ Accessible.selectable: true; Accessible.selected: selected
+ Keys.onShortcutOverride: event => {
+ if (event.modifiers === Qt.NoModifier && [Qt.Key_Left, Qt.Key_Right, Qt.Key_Home, Qt.Key_End].includes(event.key)) event.accepted = true
+ }
+ Keys.onLeftPressed: libraryTabs.focusTab(index - 1)
+ Keys.onRightPressed: libraryTabs.focusTab(index + 1)
+ Keys.onPressed: event => {
+ if (event.key === Qt.Key_Home) { libraryTabs.focusTab(0); event.accepted = true }
+ else if (event.key === Qt.Key_End) { libraryTabs.focusTab(libraryTabItems.count - 1); event.accepted = true }
+ else event.accepted = false
+ }
+
+ Keys.onReturnPressed: clicked()
+ Keys.onEnterPressed: clicked()
pill: false; width: 66; text: modelData.charAt(0).toUpperCase() + modelData.slice(1)
selected: panel.browser.section === modelData || (modelData === "songs" && panel.browser.section === "recent")
onClicked: { panel.browser.section = modelData; search.forceActiveFocus() }
}
}
}
+ IconButton { visible: (panel.sessions || panel.releases || panel.forYou) && !panel.detail && !panel.selectionCount; x: 16; y: 14; glyphName: "back"; tip: "Back"; ink: panel.app.ink; onClicked: panel.browser.section = "search" }
+ SpunText { visible: (panel.sessions || panel.releases || panel.forYou) && !panel.detail && !panel.selectionCount; x: 64; y: 20; height: 28; text: panel.forYou ? "For You" : panel.releases ? "Latest releases" : "Saved queues"; color: panel.app.ink; font.pixelSize: SpunStyle.heading; font.weight: Font.Medium }
SpunSearchField {
app: panel.app
id: search
@@ -116,7 +214,7 @@ Rectangle {
text: panel.browser.query
onTextEdited: panel.browser.query = text
maximumLength: 2048
- placeholderText: panel.browser.section === "search" ? "Search or paste a link" : panel.browser.section === "recent" ? "Search recently played" : "Search your " + panel.browser.section
+ placeholderText: panel.forYou ? "Find a recommendation" : panel.releases ? "Find a release" : panel.sessions ? "Find a saved queue" : panel.browser.section === "search" ? "Search or paste a link" : panel.browser.section === "recent" ? "Search recently played" : "Search your " + panel.browser.section
Accessible.name: placeholderText
IconButton {
visible: search.text.length > 0 || panel.browser.section !== "search"
@@ -124,14 +222,15 @@ Rectangle {
glyphName: search.text.length ? "close" : "refresh"; tip: search.text.length ? "Clear search" : "Refresh library"; ink: panel.app.mutedInk; hoverFill: panel.app.hoverFill
onClicked: { if (search.text.length) panel.browser.query = ""; else panel.browser.reload(); search.forceActiveFocus() }
}
- onAccepted: { panel.browser.reload(); list.forceActiveFocus() }
+ onAccepted: { panel.browser.rememberSearch(); panel.browser.reload(); list.forceActiveFocus() }
Keys.onDownPressed: { list.forceActiveFocus(); if (list.count) list.currentIndex = 0 }
}
- Row {
+ Flow {
+ width: parent.width - 2 * SpunStyle.outerInset; height: 68
visible: !panel.detail && !panel.linkPreview && panel.browser.section === "search"
x: SpunStyle.outerInset; y: 112; spacing: SpunStyle.smallGap
Repeater {
- model: ["songs", "albums", "playlists"]
+ model: ["songs", "albums", "playlists", "artists", "stations"]
SmallButton {
required property string modelData
objectName: "libraryKind_" + modelData
@@ -141,11 +240,63 @@ Rectangle {
}
}
}
+ SmallButton {
+ objectName: "forYouButton"; x: SpunStyle.outerInset + 2 * (84 + SpunStyle.smallGap); y: 112 + 32 + SpunStyle.smallGap
+ width: 84; height: 32; text: "For You"
+ visible: !panel.detail && !panel.linkPreview && panel.browser.section === "search" && !panel.browser.query.trim().length
+ Keys.onReturnPressed: clicked()
+ Keys.onEnterPressed: clicked()
+ onClicked: panel.browser.section = "for-you"
+ }
Row {
- visible: !panel.detail && (panel.browser.section === "songs" || panel.browser.section === "recent")
+ visible: !panel.detail && (panel.browser.section === "songs" || panel.browser.section === "recent" || panel.browser.section === "albums")
x: SpunStyle.outerInset; y: 112; spacing: SpunStyle.smallGap
- SmallButton { objectName: "allSongsTab"; width: 100; height: 32; text: "All songs"; selected: panel.browser.section === "songs"; onClicked: panel.browser.section = "songs" }
- SmallButton { objectName: "recentSongsTab"; width: 155; height: 32; text: "Recently played"; selected: panel.browser.section === "recent"; onClicked: panel.browser.section = "recent" }
+ SmallButton { objectName: "allSongsTab"; width: 46; height: 32; text: "A–Z"; selected: !panel.browser.newestFirst && panel.browser.section !== "recent"; onClicked: { if (panel.browser.section === "recent") panel.browser.section = "songs"; panel.browser.newestFirst = false } }
+ SmallButton { objectName: "recentlyAddedTab"; width: 132; height: 32; text: "Recently added"; selected: panel.browser.newestFirst && panel.browser.section !== "recent"; onClicked: { if(panel.browser.section === "recent") panel.browser.section = "songs"; panel.browser.newestFirst = true } }
+ SmallButton { visible: panel.browser.section !== "albums"; objectName: "recentSongsTab"; width: 76; height: 32; text: "History"; selected: panel.browser.section === "recent"; onClicked: panel.browser.section = "recent" }
+ }
+ Column {
+ id: pinnedCollections
+ objectName: "pinnedCollections"
+ visible: !panel.detail && panel.browser.section === "search" && !panel.browser.query.trim().length && panel.browser.pins.length > 0
+ x: SpunStyle.outerInset; y: 192; width: parent.width - 2 * SpunStyle.outerInset; spacing: 12
+ Item {
+ width: parent.width; height: 36
+ SpunText { anchors.verticalCenter: parent.verticalCenter; text: "Pinned"; color: panel.app.mutedInk; font.pixelSize: SpunStyle.caption }
+ SmallButton { objectName: "pinnedReleasesButton"; visible: panel.browser.hasArtistPins; anchors.right: parent.right; width: 100; height: 36; text: "Releases"; onClicked: panel.browser.section = "releases"; Accessible.name: "Latest releases from pinned artists" }
+ }
+ ListView {
+ width: parent.width; height: 148; orientation: ListView.Horizontal; spacing: 12
+ model: panel.browser.pins; clip: true; boundsBehavior: Flickable.StopAtBounds
+ delegate: AbstractButton {
+ id: pinButton
+ required property int index
+ required property var modelData
+ objectName: "pinnedCollection" + index
+ width: 112; height: 144; hoverEnabled: true
+ enabled: !panel.browser.starting
+ Accessible.name: (modelData.type === "artists" ? "Open artist " : "Play ") + modelData.title
+ onClicked: panel.browser.playPin(index)
+ background: Rectangle {
+ radius: SpunStyle.rowRadius; color: "transparent"
+ SpunStateLayer { anchors.fill: parent; radius: parent.radius; color: panel.app.ink; enabled: pinButton.enabled; hovered: pinButton.hovered; pressed: pinButton.down; focused: pinButton.visualFocus }
+ }
+ contentItem: Item {
+ SpunSpring { id: pinPress; targetValue: pinButton.down && SpunStyle.motion ? .96 : 1; epsilon: .001 }
+ Rectangle { x: 4; y: 4; width: 104; height: 104; radius: 8; color: panel.app.inset; scale: pinPress.value
+ Glyph { anchors.centerIn: parent; name: "disc"; ink: panel.app.mutedInk }
+ Image { anchors.fill: parent; source: pinButton.modelData.artwork || ""; sourceSize.width: 144; sourceSize.height: 144; asynchronous: true; fillMode: Image.PreserveAspectCrop }
+ }
+ SpunText { x: 4; y: 112; width: 76; height: 26; text: pinButton.modelData.title; color: panel.app.ink; font.pixelSize: SpunStyle.caption; elide: Text.ElideRight; verticalAlignment: Text.AlignVCenter }
+ IconButton { x: 80; y: 108; width: 32; height: 36; glyphName: "more"; tip: pinButton.modelData.title; ink: panel.app.mutedInk; hoverFill: panel.app.hoverFill
+ onClicked: panel.showActions(Object.assign({}, pinButton.modelData, {pinIndex: pinButton.index}), this)
+ }
+ }
+ TapHandler { acceptedButtons: Qt.RightButton; onTapped: panel.showActions(Object.assign({}, pinButton.modelData, {pinIndex: pinButton.index}), pinButton) }
+ Keys.onMenuPressed: panel.showActions(Object.assign({}, modelData, {pinIndex: index}), pinButton)
+ SpunToolTip { visible: pinButton.hovered && !trackMenu.visible; text: pinButton.modelData.title }
+ }
+ }
}
SpunSearchField {
app: panel.app
@@ -156,8 +307,8 @@ Rectangle {
text: panel.browser.collectionQuery
onTextEdited: panel.browser.collectionQuery = text
maximumLength: 200
- placeholderText: "Search tracks"
- Accessible.name: "Search this collection"
+ placeholderText: panel.artistSimilar ? "Search similar artists" : panel.artistPage && !panel.artistSongs ? "Search albums" : "Search tracks"
+ Accessible.name: panel.artistSimilar ? "Search similar artists" : panel.artistPage ? (panel.artistSongs ? "Search artist top songs" : "Search artist albums") : "Search this collection"
IconButton {
visible: collectionSearch.text.length > 0
x: parent.width - SpunStyle.target; y: 0
@@ -169,7 +320,16 @@ Rectangle {
}
Item {
id: collectionHeader
- visible: panel.detail; width: parent.width; height: 144
+ IconButton {
+ objectName: "pinArtistButton"; visible: panel.artistPage
+ x: parent.width - 56; y: 14; glyphName: "pin"
+ selected: panel.browser.pins && panel.browser.isPinned(panel.browser.collection)
+ Accessible.checkable: true; Accessible.checked: selected
+ tip: selected ? "Unpin artist" : "Pin artist"
+ ink: selected ? panel.app.accent : panel.app.mutedInk
+ onClicked: panel.browser.togglePin(panel.browser.collection)
+ }
+ visible: panel.detail; width: parent.width; height: panel.artistPage ? 184 : 144
IconButton {
objectName: "libraryBack"
x: 16; y: 14; glyphName: "back"; tip: "Back · Esc"
@@ -177,9 +337,9 @@ Rectangle {
onClicked: panel.browser.back()
}
SpunText {
- x: 64; y: 20; width: parent.width - x - SpunStyle.outerInset; height: 28
+ x: 64; y: 20; width: parent.width - x - (panel.artistPage ? 60 : SpunStyle.outerInset); height: 28
text: panel.browser.collection.title || ""; color: panel.app.ink
- font.family: SpunStyle.family; font.pixelSize: SpunStyle.heading; elide: Text.ElideRight
+ font.family: SpunStyle.family; font.pixelSize: SpunStyle.heading; font.weight: Font.Medium; elide: Text.ElideRight
HoverHandler { id: titleHover }
SpunToolTip { visible: titleHover.hovered && parent.truncated; text: parent.text }
}
@@ -195,41 +355,130 @@ Rectangle {
}
SmallButton {
objectName: "libraryPlayCollection"
- x: 101; y: 94; width: 87; height: 34
- text: panel.browser.starting ? "Starting…" : "Play"
- enabled: !!panel.browser.collection.playable && !panel.browser.starting
+ x: 101; y: 94; width: 66; height: 34
+ visible: !panel.artistPage
+ text: panel.sessionPage ? "Play next" : panel.browser.starting ? "Starting…" : "Play"
+ enabled: !!panel.browser.collection.playable && !panel.browser.starting && !panel.app.actionService.busy
selected: true
- onClicked: panel.browser.playCollection()
+ onClicked: panel.sessionPage ? panel.app.actionService.enqueueMany(panel.browser.savedTracks(panel.browser.collection.id), true) : panel.browser.playCollection()
+ }
+ IconButton {
+ objectName: "libraryShuffleCollection"; x: 173; y: 90
+ visible: !panel.artistPage && !panel.sessionPage
+ glyphName: "shuffle"; tip: "Shuffle"; ink: panel.app.accent
+ enabled: !!panel.browser.collection.playable && !panel.browser.starting && !panel.app.ciderService.controlBusy
+ onClicked: panel.browser.shuffleCollection(panel.browser.collection)
+ }
+ SmallButton {
+ id: discographyChoice; objectName: "discographyFilter"; visible: panel.artistPage && panel.browser.artistView === "albums"
+ x: 101; y: 92; width: 182; height: 36
+ text: ({"all":"All releases", "full-albums":"Full albums", "singles":"Singles & EPs", "live-albums":"Live albums"})[panel.browser.discography]
+ Accessible.name: "Filter discography: " + text
+ Keys.onReturnPressed: clicked()
+ Keys.onEnterPressed: clicked()
+ contentItem: Item {
+ SpunText { x: 12; width: parent.width - 44; height: parent.height; text: discographyChoice.text; font.pixelSize: SpunStyle.body; font.weight: Font.Medium; color: panel.app.mutedInk; elide: Text.ElideRight; verticalAlignment: Text.AlignVCenter }
+ Glyph { anchors.right: parent.right; anchors.rightMargin: 10; anchors.verticalCenter: parent.verticalCenter; width: 18; height: 18; name: "down"; ink: panel.app.mutedInk }
+ }
+ onClicked: discographyMenu.open()
+ Menu {
+ id: discographyMenu; objectName: "discographyMenu"; y: parent.height + 4; width: 204; padding: 8; spacing: 2; popupType: Popup.Item
+ background: Rectangle { radius: SpunStyle.popupRadius; color: SpunStyle.popup }
+ enter: SpunPopupEnter {}
+ exit: Transition { NumberAnimation { property: "opacity"; to: 0; duration: SpunStyle.exit; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
+ Repeater { model: [{key:"all",label:"All releases"},{key:"full-albums",label:"Full albums"},{key:"singles",label:"Singles & EPs"},{key:"live-albums",label:"Live albums"}]
+ MenuEntry { required property var modelData; app: panel.app; objectName: "discography_" + modelData.key; text: modelData.label; Accessible.checkable: true; Accessible.checked: panel.browser.discography === modelData.key; glyphName: panel.browser.discography === modelData.key ? "check" : ""; onTriggered: panel.browser.discography = modelData.key }
+ }
+ }
+ }
+ Row {
+ visible: panel.artistPage; x: SpunStyle.outerInset; y: 140; spacing: 4
+ SmallButton { objectName: "artistTopSongsTab"; width: 90; height: 34; text: "Top songs"; selected: panel.artistSongs; onClicked: panel.browser.artistView = "songs" }
+ SmallButton { objectName: "artistAlbumsTab"; width: 76; height: 34; text: "Albums"; selected: panel.browser.artistView === "albums"; onClicked: panel.browser.artistView = "albums" }
+ SmallButton { objectName: "artistSimilarTab"; width: 88; height: 34; text: "Similar"; selected: panel.artistSimilar; onClicked: panel.browser.artistView = "similar"; Accessible.name: "Similar artists" }
}
SpunText {
- x: 195; y: 104; width: 52; horizontalAlignment: Text.AlignRight
- text: panel.browser.collection.trackCount >= 0 ? panel.browser.collection.trackCount + " tracks" : ""
+ visible: panel.sessionPage
+ x: panel.artistPage ? 101 : 195; y: 104; width: panel.artistPage ? 182 : 52; horizontalAlignment: panel.artistPage ? Text.AlignLeft : Text.AlignRight
+ text: panel.browser.collection.trackCount >= 0 ? panel.browser.collection.trackCount + (panel.browser.collection.trackCount === 1 ? " track" : " tracks") : ""
color: panel.app.mutedInk; font.pixelSize: SpunStyle.caption; elide: Text.ElideRight
}
}
IconButton {
objectName: "collectionActions"
- visible: panel.detail; enabled: !!panel.browser.collection.playable
+ visible: panel.detail && !panel.artistPage; enabled: panel.sessionPage || !!panel.browser.collection.playable
x: parent.width - SpunStyle.outerInset - SpunStyle.target; y: 92
glyphName: "more"; tip: "Collection actions"; ink: panel.app.mutedInk; hoverFill: panel.app.hoverFill
onClicked: panel.showActions(panel.browser.collection, this)
}
+ Rectangle {
+ objectName: "trackSelectionBar"
+ visible: panel.selectionCount > 0; x: 16; y: 12; width: parent.width - 32; height: 44; radius: 22
+ color: panel.app.surface; z: 3
+ SpunText { x: 12; anchors.verticalCenter: parent.verticalCenter; text: panel.selectionCount + " selected"; color: panel.app.ink; font.pixelSize: SpunStyle.body }
+ IconButton { objectName: "selectedTrackActions"; x: parent.width - 84; anchors.verticalCenter: parent.verticalCenter; glyphName: "more"; tip: "Selected track actions"; ink: panel.app.accent; enabled: !panel.app.actionService.busy; onClicked: panel.showActions({}, this, true) }
+ IconButton { objectName: "clearTrackSelection"; x: parent.width - 42; anchors.verticalCenter: parent.verticalCenter; glyphName: "close"; tip: "Clear selection · Esc"; ink: panel.app.mutedInk; onClicked: panel.clearSelection() }
+ }
+ MouseArea {
+ id: libraryDragArea; objectName: "libraryDragArea"
+ parent: panel.app.contentItem
+ readonly property point origin: { const layout = panel.parent.x + panel.parent.y + panel.width + panel.height + entranceOffset.x + listOffset.x; return panel.mapToItem(parent, list.x + SpunStyle.outerInset, list.y) }
+ x: origin.x; y: origin.y; width: SpunStyle.artwork; height: list.height; z: 24
+ visible: (panel.visible && list.count > 0 && panel.browser.items[0].type.endsWith("songs")) || panel.app.libraryDragging
+ enabled: (panel.visible && !panel.app.actionService.busy && !panel.app.ciderService.controlBusy) || panel.app.libraryDragging
+ preventStealing: panel.app.libraryDragging
+ hoverEnabled: true
+ SpunToolTip { visible: libraryDragArea.containsMouse && !libraryDragArea.pressed && panel.visible && !trackMenu.visible; text: "Drag artwork to queue" }
+ cursorShape: pressed ? Qt.ClosedHandCursor : Qt.OpenHandCursor
+ property point startPoint
+ property int pressedIndex: -1
+ property var tracks: []
+ onPressed: mouse => {
+ startPoint = Qt.point(mouse.x, mouse.y)
+ pressedIndex = list.indexAt(0, mouse.y + list.contentY)
+ const row = panel.browser.items[pressedIndex]
+ if (!row || !row.playable || !row.type.endsWith("songs")) { mouse.accepted = false; return }
+ tracks = panel.selectionKeys.indexOf(panel.rowKey(pressedIndex, row)) >= 0 ? panel.selectedTracks.slice() : [Object.assign({}, row)]
+ }
+ onPositionChanged: mouse => {
+ if (!pressed || pressedIndex < 0) return
+ if (!panel.app.libraryDragging && Math.abs(mouse.x - startPoint.x) < 10) return
+ if (!panel.app.libraryDragging) panel.app.beginLibraryDrag(tracks)
+ const point = mapToItem(panel.app.contentItem, mouse.x, mouse.y)
+ panel.app.updateLibraryDrag(point.x, point.y)
+ }
+ onReleased: mouse => {
+ if (panel.app.libraryDragging) panel.app.endLibraryDrag(true)
+ else if (pressedIndex >= 0) { list.forceActiveFocus();panel.chooseRow(pressedIndex,mouse.modifiers) }
+ pressedIndex = -1;tracks = []
+ }
+ onCanceled: { if(panel.app.libraryDragging)panel.app.endLibraryDrag(false);pressedIndex=-1;tracks=[] }
+ }
ListView {
id: list
objectName: "libraryList"
- x: SpunStyle.inset; y: panel.detail ? collectionSearch.y + collectionSearch.height + SpunStyle.gap : (!panel.linkPreview && panel.browser.section === "search") || panel.browser.section === "songs" || panel.browser.section === "recent" ? 152 : search.y + search.height + SpunStyle.gap
+ x: SpunStyle.inset; y: panel.detail ? collectionSearch.y + collectionSearch.height + SpunStyle.gap : (!panel.linkPreview && panel.browser.section === "search") ? 188 : panel.browser.section === "songs" || panel.browser.section === "recent" || panel.browser.section === "albums" ? 152 : search.y + search.height + SpunStyle.gap
width: parent.width - 2 * SpunStyle.inset; height: footer.y - SpunStyle.gap - y
+ visible: !pinnedCollections.visible
model: panel.browser.items; clip: true; spacing: 4
transform: Translate { id: listOffset }
currentIndex: -1; boundsBehavior: Flickable.StopAtBounds
onCountChanged: if (currentIndex >= count) currentIndex = -1
Keys.onPressed: function(event) {
- if (event.key === Qt.Key_Menu || (event.key === Qt.Key_F10 && (event.modifiers & Qt.ShiftModifier))) {
+ if (event.key === Qt.Key_A && (event.modifiers & Qt.ControlModifier)) {
+ panel.selectAllTracks(); event.accepted = true
+ } else if (event.key === Qt.Key_Space && list.currentIndex >= 0) {
+ panel.chooseRow(list.currentIndex, event.modifiers | Qt.ControlModifier); event.accepted = true
+ } else if ((event.key === Qt.Key_Down || event.key === Qt.Key_Up) && (event.modifiers & Qt.ShiftModifier)) {
+ const destination = Math.max(0, Math.min(list.count - 1, list.currentIndex + (event.key === Qt.Key_Down ? 1 : -1)))
+ if (panel.selectionAnchor < 0) panel.selectionAnchor = Math.max(0, list.currentIndex)
+ panel.chooseRow(destination, event.modifiers); list.positionViewAtIndex(destination, ListView.Contain); event.accepted = true
+ } else if (event.key === Qt.Key_Menu || (event.key === Qt.Key_F10 && (event.modifiers & Qt.ShiftModifier))) {
const row = itemAtIndex(currentIndex)
if (row) panel.showActions(row.modelData, row)
event.accepted = true
} else if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter) {
- if (panel.detail) panel.browser.play(currentIndex); else panel.activate(currentIndex)
+ if (panel.selectionCount > 0) panel.showActions({}, list, true); else panel.activate(currentIndex)
event.accepted = true
} else if (event.key === Qt.Key_Home) { currentIndex = 0; positionViewAtBeginning(); event.accepted = true }
else if (event.key === Qt.Key_End) { currentIndex = count - 1; positionViewAtEnd(); event.accepted = true }
@@ -244,30 +493,52 @@ Rectangle {
required property int index
required property var modelData
readonly property bool song: modelData.type.endsWith("songs")
+ readonly property bool alreadyQueued: song && panel.queuedStatusReady && panel.queuedSongKeys.has(panel.songKey(modelData))
objectName: "libraryRow" + index
width: list.width; height: SpunStyle.trackHeight
enabled: !song || (modelData.playable && !panel.browser.starting)
HoverHandler { id: rowHover }
- Accessible.name: (song ? "Play " : "Open ") + modelData.title + ", " + modelData.artist
- onClicked: { list.currentIndex = index; if (panel.detail) panel.browser.play(index); else panel.activate(index) }
+ Accessible.name: (song ? "Play " : "Open ") + modelData.title + ", " + modelData.artist + (alreadyQueued ? ", already queued" : "")
+ onClicked: panel.chooseRow(index, Qt.NoModifier)
+ MouseArea {
+ id: rowPointer
+ anchors.fill: parent
+ onClicked: mouse => { list.forceActiveFocus(); panel.chooseRow(row.index, mouse.modifiers) }
+ }
background: Rectangle {
radius: SpunStyle.rowRadius
color: "transparent"
- SpunStateLayer { anchors.fill: parent; radius: parent.radius; color: panel.app.ink; enabled: row.enabled; pressed: row.down; focused: list.activeFocus && list.currentIndex === row.index; hovered: rowHover.hovered }
+ Rectangle { anchors.fill: parent; radius: parent.radius; color: SpunStyle.selected; opacity: panel.selectionKeys.indexOf(panel.rowKey(row.index, row.modelData)) >= 0 ? 1 : 0
+ Behavior on opacity { NumberAnimation { duration: SpunStyle.feedback; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
+ }
+ SpunStateLayer { anchors.fill: parent; radius: parent.radius; color: panel.app.ink; enabled: row.enabled; pressed: row.down || rowPointer.pressed; focused: list.activeFocus && list.currentIndex === row.index; hovered: rowHover.hovered }
}
contentItem: TrackContent {
+ z: 1
app: panel.app; opacity: row.enabled ? 1 : .4
+ trailingInset: SpunStyle.target + SpunStyle.gap + (row.alreadyQueued ? 22 : 0)
+ artistLink: !(panel.forYou && !panel.detail) && !panel.artistPage && !panel.selectionCount && !!row.modelData.artist && row.modelData.type !== "artists" && (row.song || row.modelData.type.endsWith("albums"))
+ onArtistClicked: panel.browser.showArtist(row.modelData.artist)
+ onSelectionRequested: modifiers => { list.forceActiveFocus(); panel.chooseRow(row.index, modifiers) }
title: row.modelData.title
- subtitle: row.modelData.artist || (row.modelData.trackCount >= 0 ? row.modelData.trackCount + " tracks" : "Playlist")
+ subtitle: (panel.forYou && !panel.detail ? [row.modelData.recommendation, row.modelData.artist].filter(v => v).join(" · ") : panel.artistPage && !panel.artistSongs && !panel.artistSimilar ? row.modelData.year : panel.releases && !panel.detail ? [row.modelData.artist, row.modelData.year].filter(v => v).join(" · ") : row.modelData.artist) || (row.modelData.trackCount >= 0 ? row.modelData.trackCount + " tracks" : row.modelData.type === "artists" ? "Artist" : row.modelData.type === "stations" ? "Radio station" : "Playlist")
artwork: row.modelData.artwork || ""; artworkName: "libraryArtwork" + row.index
fallback: row.song || row.modelData.type.endsWith("albums") ? "disc" : "queue"
}
+ Item {
+ objectName: "alreadyQueued" + row.index; visible: row.alreadyQueued; z: 2
+ x: parent.width - SpunStyle.target - 22; width: 20; height: 32; anchors.verticalCenter: parent.verticalCenter
+ Glyph { anchors.centerIn: parent; width: 16; height: 16; name: "check"; ink: panel.app.mutedInk }
+ HoverHandler { id: queuedHover }
+ SpunToolTip { visible: queuedHover.hovered; text: "Already queued" }
+ }
IconButton {
id: rowActions
+ z: 2
objectName: "libraryActions" + row.index
x: parent.width - SpunStyle.target; anchors.verticalCenter: parent.verticalCenter
- enabled: !!row.modelData.playable && !panel.app.actionService.busy
- glyphName: "more"; tip: "Track actions"; ink: panel.app.mutedInk; hoverFill: panel.app.hoverFill
+ enabled: (row.modelData.type === "artists" || row.modelData.type === "saved-queues" || !!row.modelData.playable) && !panel.app.actionService.busy
+ glyphName: "more"; tip: row.modelData.type === "artists" ? "Artist actions" : "Track actions"; ink: panel.app.mutedInk; hoverFill: panel.app.hoverFill
onClicked: { list.currentIndex = row.index; panel.showActions(row.modelData, this) }
}
TapHandler { acceptedButtons: Qt.RightButton; onTapped: panel.showActions(row.modelData, rowActions) }
@@ -277,29 +548,57 @@ Rectangle {
SpunText {
anchors.centerIn: parent; width: 222
visible: list.count === 0
- text: panel.browser.busy ? "Loading…" : panel.browser.error || (panel.browser.section === "search" && !panel.browser.query.trim().length && !panel.detail ? "" : (panel.detail ? panel.browser.collectionQuery.trim().length : panel.browser.query.trim().length) ? "No matches" : panel.detail ? "No tracks available" : panel.browser.section === "recent" ? "No recently played songs" : "No " + panel.browser.section + " in your library")
+ text: panel.browser.busy ? "Loading…" : panel.browser.error || (panel.browser.section === "search" && !panel.browser.query.trim().length && !panel.detail ? "" : (panel.detail ? panel.browser.collectionQuery.trim().length : panel.browser.query.trim().length) ? "No matches" : panel.releases && !panel.detail ? (panel.browser.hasArtistPins ? "No recent releases available" : "Pin an artist to see their latest releases") : panel.detail ? panel.artistSimilar ? "No similar artists available" : panel.artistPage && !panel.artistSongs ? ({"all":"No releases available", "full-albums":"No full albums available", "singles":"No singles or EPs available", "live-albums":"No live albums available"})[panel.browser.discography] : "No tracks available" : panel.forYou ? "No recommendations available yet" : panel.sessions ? "No saved queues yet" : panel.browser.section === "recent" ? "No recently played songs" : "No " + panel.browser.section + " in your library")
horizontalAlignment: Text.AlignHCenter; wrapMode: Text.WordWrap; color: panel.app.mutedInk; font.pixelSize: 12; lineHeight: 1.3
}
}
+ ListView {
+ id: recentSearchList; objectName: "recentSearchList"
+ visible: !panel.detail && panel.browser.section === "search" && !panel.browser.query.trim().length && !panel.browser.busy && !panel.browser.error.length
+ x: SpunStyle.outerInset; y: pinnedCollections.visible ? pinnedCollections.y + pinnedCollections.height + 16 : 192
+ width: parent.width - 2 * SpunStyle.outerInset; height: Math.max(0, footer.y - y - 12)
+ clip: true; spacing: 2; boundsBehavior: Flickable.StopAtBounds
+ model: visible ? panel.browser.recentSearches : []
+ header: SpunText { height: 28; text: recentSearchList.count ? "Recent searches" : ""; color: panel.app.mutedInk; font.pixelSize: SpunStyle.caption }
+ ScrollBar.vertical: ScrollBar {}
+ delegate: Item {
+ required property string modelData
+ required property int index
+ width: recentSearchList.width; height: SpunStyle.target
+ SmallButton {
+ objectName: "recentSearch" + index; width: parent.width - SpunStyle.target; height: parent.height
+ text: modelData
+ onClicked: { const browser = panel.browser, field = search, term = modelData; browser.query = term; browser.rememberSearch(); field.forceActiveFocus() }
+ contentItem: SpunText { text: modelData; color: panel.app.ink; font.pixelSize: SpunStyle.body; elide: Text.ElideRight; verticalAlignment: Text.AlignVCenter }
+ }
+ IconButton { objectName: "removeRecentSearch" + index; x: parent.width - width; glyphName: "close"; tip: "Remove search"; ink: panel.app.mutedInk; onClicked: panel.browser.removeRecentSearch(modelData) }
+ }
+ }
+ SpunText {
+ visible: (panel.releases || panel.forYou) && !panel.detail && panel.browser.releaseNotice.length > 0
+ x: SpunStyle.outerInset; y: footer.y - 20; width: parent.width - 2 * SpunStyle.outerInset; height: 18
+ text: panel.browser.releaseNotice; color: panel.app.mutedInk; font.pixelSize: SpunStyle.caption
+ }
Item {
id: footer
objectName: "libraryFooter"
x: SpunStyle.outerInset; y: parent.height - height - SpunStyle.inset; width: parent.width - 2 * SpunStyle.outerInset; height: 48
SpunText {
anchors.fill: parent
- visible: panel.browser.playError.length > 0
+ visible: panel.browser.playError.length > 0 && !panel.browser.needsConnection
text: panel.browser.playError; color: theme.colors.error
font.pixelSize: SpunStyle.caption; wrapMode: Text.WordWrap; verticalAlignment: Text.AlignVCenter
}
SmallButton {
objectName: "libraryMore"
anchors.centerIn: parent; width: parent.width; height: SpunStyle.target
- visible: !panel.browser.playError.length && (panel.browser.hasMore || panel.browser.error.length > 0)
+ visible: panel.browser.needsConnection || (!panel.browser.playError.length && (panel.browser.hasMore || panel.browser.error.length > 0))
enabled: !panel.browser.busy
- text: panel.browser.busy ? ((panel.detail && panel.browser.collectionQuery.length) || (panel.browser.section === "recent" && panel.browser.query.length) ? "Searching tracks…" : "Loading…") : panel.browser.needsConnection ? "Connection settings" : panel.browser.error.length ? ((panel.detail && panel.browser.collectionQuery.length) || (panel.browser.section === "recent" && panel.browser.query.length) ? "Search incomplete · Retry" : "Try again") : "Load more"
+ text: panel.browser.busy ? ((panel.detail && panel.browser.collectionQuery.length) || (panel.browser.section === "recent" && panel.browser.query.length) ? panel.artistSimilar ? "Searching artists…" : panel.artistPage && !panel.artistSongs ? "Searching albums…" : "Searching tracks…" : "Loading…") : panel.browser.needsConnection ? "Connection settings" : panel.browser.error.length ? ((panel.detail && panel.browser.collectionQuery.length) || (panel.browser.section === "recent" && panel.browser.query.length) ? "Search incomplete · Retry" : "Try again") : "Load more"
selected: true
onClicked: {
if (panel.browser.needsConnection) panel.app.toggleQueue()
+ else if (panel.app.ciderService.recovering) panel.app.ciderService.reconnect()
else if (panel.browser.hasMore) panel.browser.more()
else panel.browser.reload()
}
diff --git a/qml/Main.qml b/qml/Main.qml
index 5ef6e87..9ab0be1 100644
--- a/qml/Main.qml
+++ b/qml/Main.qml
@@ -15,10 +15,28 @@ ApplicationWindow {
color: "transparent"
flags: Qt.Window | Qt.FramelessWindowHint | (miniPinned && !native.supportsBlur ? Qt.WindowStaysOnTopHint : 0)
font.family: SpunStyle.family
- property bool useCider: !testMode && cider.available
+ readonly property bool vinyl: player.vinyl
+ onVinylChanged: Qt.callLater(updateMask)
+ property bool useCider: !testMode && root.ciderService.available
+ property var ciderService: cider
+ property var listeningService: listening
property var actionService: musicActions
- property var deckPlayer: useCider ? cider : player
- onUseCiderChanged: { preferences.close(); crossfadeMenu.close(); queueMenu.close(); cancelQueueDrag(); songMenu.close(); musicBrowser.closeActions(); if (!useCider) libraryOpen = false; if (useCider) player.pause(); cider.queueVisible = queueOpen && useCider; discFlipped = false; closeQueueSearch(); Qt.callLater(presentDisc); syncLyrics() }
+ property var savedService: library
+ Binding { target: root.ciderService; property: "liveVisible"; value: root.useCider && root.visible && root.visibility !== Window.Minimized }
+ function refreshOpenCiderDetails() {
+ if (songMenu.visible) root.actionService.refresh()
+ if (crossfadeMenu.visible) { crossfadeMenu.service.refreshCrossfade(); crossfadeMenu.service.refreshAudioOptions() }
+ if (qualityPopup.visible) root.ciderService.refreshAudioQuality()
+ }
+ Connections { target: root.listeningService; function onFeedback(message, error) { root.notifyAction(message, error) } }
+ Connections { target: root.ciderService; function onRemoteSettingsChanged() { root.refreshOpenCiderDetails() } }
+ Timer {
+ interval: 30000; repeat: true
+ running: root.useCider && root.visible && root.visibility !== Window.Minimized && (songMenu.visible || crossfadeMenu.visible || qualityPopup.visible)
+ onTriggered: root.refreshOpenCiderDetails()
+ }
+ property var deckPlayer: useCider ? root.ciderService : player
+ onUseCiderChanged: { recoveryPopup.close(); quickJump.close(); savedQueuePicker.close(); clearQueueSelection(); cleanupPopup.close(); qualityPopup.close(); if(libraryDragging)endLibraryDrag(false); preferences.close(); crossfadeMenu.close(); queueMenu.close(); cancelQueueDrag(); songMenu.close(); musicBrowser.closeActions(); if (!useCider) libraryOpen = false; if (useCider) player.pause(); root.ciderService.queueVisible = queueOpen && useCider; discFlipped = false; closeQueueSearch(); Qt.callLater(presentDisc); syncLyrics() }
property bool lyricsView: false
property real swapOffset: 0
property real outgoingOffset: 0
@@ -44,7 +62,7 @@ ApplicationWindow {
onDiscFlippedChanged: {
scrubber.cancelScrub()
stopSwap()
- cider.discVisible = discFlipped && useCider
+ root.ciderService.discVisible = discFlipped && useCider
syncLyrics()
}
function flipDisc() { if (deckPlayer.count > 0) discFlipped = !discFlipped }
@@ -53,7 +71,7 @@ ApplicationWindow {
property bool miniMode: player.miniMode
onMiniModeChanged: Qt.callLater(function() {
scrubber.cancelScrub(); stopSwap()
- if (miniMode) { preferences.close(); crossfadeMenu.close(); songMenu.close(); musicBrowser.closeActions(); libraryOpen = false; queueOpen = false; helpOpen = false; menu.close(); miniReveal.restart() }
+ if (miniMode) { savedQueuePicker.close(); qualityPopup.close(); if(libraryDragging)endLibraryDrag(false); preferences.close(); crossfadeMenu.close(); songMenu.close(); musicBrowser.closeActions(); libraryOpen = false; queueOpen = false; helpOpen = false; menu.close(); miniReveal.restart() }
updateMask(); native.effects(root, backgroundBlur)
})
property bool editingText: activeFocusItem instanceof TextInput || activeFocusItem instanceof TextEdit
@@ -62,6 +80,36 @@ ApplicationWindow {
property bool queuePrepared: false
readonly property var queueRows: queuePrepared ? buildQueueRows(deckPlayer.queue) : []
readonly property var filteredQueue: filterQueue(queueRows, queueQuery)
+ // Recompute the queue sum only when tracks or the current index change.
+ // Playback ticks update a single minute bucket, without rescanning the list.
+ function queueTime(rows, current) {
+ const start = current >= 0 && current < rows.length ? current : 0
+ let total = 0, unknown = 0, currentDuration = 0
+ for (let i = start; i < rows.length; ++i) {
+ const duration = Number(rows[i].track.duration)
+ if (Number.isFinite(duration) && duration > 0) {
+ total += duration
+ if (i === current) currentDuration = duration
+ } else ++unknown
+ }
+ return { milliseconds: total, unknown: unknown, currentDuration: currentDuration, count: rows.length - start }
+ }
+ readonly property var queueTiming: queueTime(queueRows, deckPlayer.currentIndex)
+ readonly property bool timedCurrent: deckPlayer.currentIndex >= 0 && deckPlayer.currentIndex < queueRows.length
+ readonly property real queueCurrentDuration: timedCurrent ? Math.max(0, Number(deckPlayer.duration) || queueTiming.currentDuration) : 0
+ readonly property int queueUnknownDurations: queueTiming.unknown - (timedCurrent && queueTiming.currentDuration === 0 && queueCurrentDuration > 0 ? 1 : 0)
+ readonly property real queueRemainingMs: !queueOpen ? 0 : Math.max(0, queueTiming.milliseconds - queueTiming.currentDuration + queueCurrentDuration - (timedCurrent ? Math.min(queueCurrentDuration, Math.max(0, deckPlayer.position)) : 0))
+ readonly property int queueRemainingMinutes: queueUnknownDurations ? Math.floor(queueRemainingMs / 60000) : Math.ceil(queueRemainingMs / 60000)
+ readonly property string queueTimeSummary: {
+ const count = queueTiming.count
+ if (useCider && !root.ciderService.queueReady) return ""
+ const songs = count + (count === 1 ? " song" : " songs")
+ if (!count) return songs
+ const minutes = queueRemainingMinutes
+ if (queueUnknownDurations && minutes === 0) return songs + " · Duration incomplete"
+ const time = minutes >= 60 ? Math.floor(minutes / 60) + " h" + (minutes % 60 ? " " + minutes % 60 + " min" : "") : minutes + " min"
+ return songs + " · " + (queueUnknownDurations ? "≥ " : "") + time + " left"
+ }
function foldQueueText(value) { return (value || "").normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase() }
function buildQueueRows(queue) {
const rows = []
@@ -101,9 +149,84 @@ ApplicationWindow {
useCider = true; libraryOpen = true
return true
}
+ function openArtistName(name) { useCider = true; libraryOpen = true; library.showArtist(name) }
function openLibrary() { libraryOpen = !libraryOpen }
- readonly property bool queueControlsReady: !useCider || (cider.queueReady && !cider.queueBusy && !cider.controlBusy && !cider.queueError.length)
+ readonly property bool queueControlsReady: !useCider || (!root.actionService.busy && root.ciderService.queueReady && !root.ciderService.queueBusy && !root.ciderService.controlBusy && !root.ciderService.queueError.length)
readonly property bool queueReorderAllowed: queueControlsReady && !queueQuery.trim().length
+ property bool libraryDragging: false
+ property var libraryDragTracks: []
+ property int libraryDropIndex: -1
+ property int libraryDropRevision: -1
+ property real libraryDragY: 0
+ property real libraryDragX: 0
+ function beginLibraryDrag(tracks) {
+ noticeTimer.stop(); libraryDragTracks = tracks; libraryDragging = true; queueOpen = true
+ contentItem.forceActiveFocus()
+ }
+ function updateLibraryDrag(x, y) {
+ const point = trackList.mapFromItem(root.contentItem, x, y)
+ libraryDragY = point.y;libraryDragX = point.x
+ if (!root.queueControlsReady || point.x < 0 || point.x > trackList.width || point.y < 0 || point.y > trackList.height) { libraryDropIndex = -1;return }
+ libraryDropIndex = Math.max(root.ciderService.currentIndex + 1, Math.min(root.ciderService.queue.length, Math.floor((point.y + trackList.contentY + SpunStyle.trackHeight / 2) / (SpunStyle.trackHeight + SpunStyle.smallGap))))
+ libraryDropRevision = root.ciderService.queueRevision
+ }
+ function endLibraryDrag(drop) {
+ const index = libraryDropIndex, revision = libraryDropRevision, tracks = libraryDragTracks
+ libraryDragging = false;libraryDropIndex = -1;libraryDragTracks = []
+ if (drop && index >= 0 && root.queueControlsReady) root.ciderService.insertQueue(tracks,index,revision)
+ else libraryOpen = true
+ }
+ Timer {
+ interval: 40; repeat: true
+ running: root.libraryDragging && root.libraryDropIndex >= 0 && (root.libraryDragY < 36 || root.libraryDragY > trackList.height - 36)
+ onTriggered: {
+ trackList.contentY = Math.max(0, Math.min(Math.max(0,trackList.contentHeight - trackList.height),trackList.contentY + (root.libraryDragY < 36 ? -10 : 10)))
+ const point = trackList.mapToItem(root.contentItem,root.libraryDragX,root.libraryDragY)
+ root.updateLibraryDrag(point.x,point.y)
+ }
+ }
+ property var queueSelection: []
+ property int queueSelectionAnchor: -1
+ property int queueSelectionRevision: -1
+ readonly property int queueSelectionCount: queueSelection.length
+ function clearQueueSelection() { queueSelection = []; queueSelectionAnchor = -1; queueSelectionRevision = -1 }
+ function chooseQueueRow(index, modifiers) {
+ if (!queueControlsReady) return
+ const selecting = useCider && ((modifiers & (Qt.ControlModifier | Qt.ShiftModifier)) || queueSelectionCount > 0)
+ if (!selecting) { deckPlayer.select(index); return }
+ if (index <= ciderService.currentIndex || index < 0) return
+ let next = queueSelection.slice()
+ if ((modifiers & Qt.ShiftModifier) && queueSelectionAnchor >= 0) {
+ if (!(modifiers & Qt.ControlModifier)) next = []
+ const first = Math.min(index, queueSelectionAnchor), last = Math.max(index, queueSelectionAnchor)
+ for (const row of filteredQueue) if (row.sourceIndex >= first && row.sourceIndex <= last && row.sourceIndex > ciderService.currentIndex && next.indexOf(row.sourceIndex) < 0) next.push(row.sourceIndex)
+ } else {
+ const at = next.indexOf(index); if (at >= 0) next.splice(at, 1); else next.push(index)
+ queueSelectionAnchor = index
+ }
+ queueSelection = next.sort((a,b) => a-b); queueSelectionRevision = ciderService.queueRevision
+ }
+ function selectUpcomingQueue() {
+ if (!useCider || !queueControlsReady) return
+ queueSelection = filteredQueue.filter(row => row.sourceIndex > ciderService.currentIndex).map(row => row.sourceIndex)
+ queueSelectionAnchor = queueSelection.length ? queueSelection[0] : -1; queueSelectionRevision = ciderService.queueRevision
+ }
+ function editQueueSelection(operation) {
+ if (!queueSelectionCount || !queueControlsReady) return
+ if (operation === "remove") {
+ cleanupPopup.preview = {mode: "selection", indices: queueSelection.slice(), revision: queueSelectionRevision, rows: queueSelection.map(i => ciderService.queue[i])}
+ cleanupPopup.open()
+ } else ciderService.editQueueSelection(queueSelection.slice(), operation, queueSelectionRevision)
+ }
+ function openQueueSelectionActions(anchor) { showQueueActions(queueSelection[0], anchor) }
+ QuickJump { id: quickJump; app: root }
+ function openQuickJump() { menu.close(); musicBrowser.closeActions(); queueMenu.close(); quickJump.show() }
+ function revealQueueTrack(index) {
+ player.miniMode = false; libraryOpen = false; clearQueueSelection(); queueOpen = true; queueQuery = ""
+ Qt.callLater(function() { trackList.keyboardIndex = index; trackList.positionViewAtIndex(index, ListView.Contain); trackList.forceActiveFocus() })
+ }
+ SavedQueuePicker { id: savedQueuePicker; app: root }
+ function openSavedQueuePicker(tracks, service) { savedQueuePicker.show(tracks, service) }
property int queueDragSource: -1
property int queueDropIndex: -1
property int queueDragRevision: -1
@@ -114,11 +237,12 @@ ApplicationWindow {
queueDropIndex = row
}
function moveQueueRow(from, to, revision) {
- if (useCider) cider.moveQueue(from,to,revision)
+ if (useCider) root.ciderService.moveQueue(from,to,revision)
else player.move(from,to)
}
function showQueueActions(index, anchor) {
- queueMenu.rowIndex = index; queueMenu.revision = cider.queueRevision
+ if (queueSelectionCount && queueSelection.indexOf(index) < 0) clearQueueSelection()
+ queueMenu.rowIndex = index; queueMenu.revision = root.ciderService.queueRevision
const point = anchor.mapToItem(root.contentItem,0,anchor.height)
queueMenu.x = jewelCase.x + jewelCase.width - queueMenu.width - 16
queueMenu.y = Math.max(jewelCase.y + 12,Math.min(root.height - queueMenu.height - 16,point.y))
@@ -126,8 +250,13 @@ ApplicationWindow {
}
Connections {
target: root.deckPlayer
- function onQueueChanged() { queueMenu.close(); root.cancelQueueDrag() }
+ function onQueueChanged() { queueMenu.close(); root.cancelQueueDrag(); root.clearQueueSelection() }
}
+ Connections {
+ target: root.ciderService
+ function onCurrentIndexChanged() { root.clearQueueSelection(); queueMenu.close() }
+ }
+ onQueueQueryChanged: clearQueueSelection()
Timer {
interval: 40; repeat: true; running: root.queueDragSource >= 0 && (root.queueDragY < 36 || root.queueDragY > trackList.height - 36)
onTriggered: {
@@ -137,7 +266,7 @@ ApplicationWindow {
}
property bool queueOpen: false
property bool helpOpen: false
- readonly property bool menuOpen: fontPicker.shown || menu.visible || preferences.visible || crossfadeMenu.visible || queueMenu.visible || songMenu.visible || musicBrowser.actionsOpen
+ readonly property bool menuOpen: recoveryPopup.visible || quickJump.visible || savedQueuePicker.visible || cleanupPopup.visible || qualityPopup.visible || savedQueueMenu.visible || saveQueuePopup.visible || deleteQueuePopup.visible || fontPicker.shown || fontPicker.opening || menu.visible || preferences.visible || crossfadeMenu.visible || queueMenu.visible || songMenu.visible || musicBrowser.actionsOpen
property bool backgroundBlur: player.backgroundBlur && native.supportsBlur
onBackgroundBlurChanged: { native.effects(root, backgroundBlur); Qt.callLater(updateMask) }
property bool muted: false
@@ -159,7 +288,7 @@ ApplicationWindow {
readonly property int transitionTime: SpunStyle.navigate
property int tick: 0
function useLocal() {
- if (useCider && cider.playing) cider.pause()
+ if (useCider && root.ciderService.playing) root.ciderService.pause()
useCider = false
}
function time(ms) {
@@ -181,11 +310,11 @@ ApplicationWindow {
menu.y = Qt.binding(function() { return Math.max(12,deck.y - menu.height - 10) })
songMenu.close(); musicBrowser.closeActions(); menu.open()
}
- onQueueOpenChanged: { if (queueOpen) queuePrepared = true; queueMenu.close(); cancelQueueDrag(); if (queueOpen) libraryOpen = false; if (!queueOpen) closeQueueSearch(); if (queueOpen && miniMode) player.miniMode = false; cider.queueVisible = queueOpen && useCider; Qt.callLater(updateMask) }
+ onQueueOpenChanged: { clearQueueSelection(); if (queueOpen) queuePrepared = true; queueMenu.close(); cancelQueueDrag(); if (queueOpen) libraryOpen = false; if (!queueOpen) closeQueueSearch(); if (queueOpen && miniMode) player.miniMode = false; root.ciderService.queueVisible = queueOpen && useCider; Qt.callLater(updateMask) }
onHelpOpenChanged: { if (helpOpen && miniMode) player.miniMode = false; Qt.callLater(updateMask) }
onMenuOpenChanged: Qt.callLater(updateMask)
onWidthChanged: Qt.callLater(updateMask)
- Component.onCompleted: { if (!testMode && player.ciderAutoStart) { useCider = true; cider.ensureRunning() }; updateMask(); native.place(root); Qt.callLater(presentDisc); syncLyrics() }
+ Component.onCompleted: { if (!testMode && player.ciderAutoStart) { useCider = true; root.ciderService.ensureRunning() }; updateMask(); native.place(root); Qt.callLater(presentDisc); syncLyrics() }
onClosing: player.save()
Rectangle {
@@ -197,26 +326,27 @@ ApplicationWindow {
MouseArea { anchors.fill: parent; onPressed: root.startSystemMove() }
}
- Shortcut { sequence: "Space"; enabled: !root.editingText && !crossfadeMenu.visible && !preferences.visible; onActivated: root.useCider ? cider.toggle() : player.count ? player.toggle() : files.open() }
- Shortcut { sequence: "Ctrl+V"; enabled: !root.editingText && !crossfadeMenu.visible && !preferences.visible; onActivated: root.openMusicLink("", true) }
- Shortcut { sequence: "Ctrl+O"; onActivated: files.open() }
- Shortcut { sequence: "Ctrl+Shift+O"; onActivated: folder.open() }
+ Shortcut { sequence: "Ctrl+K"; enabled: !root.menuOpen || quickJump.visible; onActivated: quickJump.visible ? quickJump.close() : root.openQuickJump() }
+ Shortcut { sequence: "Space"; enabled: !(root.activeFocusItem instanceof AbstractButton) && !(root.useCider && root.queueOpen && trackList.activeFocus) && !(root.libraryOpen && musicBrowser.item && musicBrowser.item.trackListFocused) && !root.editingText && !root.menuOpen; onActivated: root.useCider ? root.ciderService.toggle() : player.count ? player.toggle() : files.open() }
+ Shortcut { sequence: "Ctrl+V"; enabled: !root.editingText && !root.menuOpen; onActivated: root.openMusicLink("", true) }
+ Shortcut { sequence: "Ctrl+O"; enabled: !root.menuOpen; onActivated: files.open() }
+ Shortcut { sequence: "Ctrl+Shift+O"; enabled: !root.menuOpen; onActivated: folder.open() }
Shortcut { sequence: "Ctrl+Q"; onActivated: Qt.quit() }
- Shortcut { sequence: "Ctrl+F"; onActivated: root.libraryOpen ? musicBrowser.focusSearch() : root.openQueueSearch() }
- Shortcut { sequence: "Ctrl+B"; enabled: root.useCider; onActivated: root.openLibrary() }
- Shortcut { sequence: "Ctrl+L"; onActivated: root.toggleQueue() }
- Shortcut { sequence: "Ctrl+M"; onActivated: player.miniMode = !player.miniMode }
- Shortcut { sequence: "Right"; enabled: !root.editingText && !crossfadeMenu.visible && !preferences.visible; onActivated: root.deckPlayer.seek(root.deckPlayer.position + 5000) }
- Shortcut { sequence: "Left"; enabled: !root.editingText && !crossfadeMenu.visible && !preferences.visible; onActivated: root.deckPlayer.seek(root.deckPlayer.position - 5000) }
- Shortcut { sequence: "Ctrl+Right"; enabled: !root.editingText && !crossfadeMenu.visible && !preferences.visible; onActivated: root.deckPlayer.next() }
- Shortcut { sequence: "Ctrl+Left"; enabled: !root.editingText && !crossfadeMenu.visible && !preferences.visible; onActivated: root.deckPlayer.previous() }
- Shortcut { sequence: "Up"; enabled: !root.libraryOpen && !trackList.activeFocus && !crossfadeMenu.visible && !preferences.visible && !root.editingText && !(root.discFlipped && (albumList.activeFocus || lyricList.activeFocus)); onActivated: root.deckPlayer.volume = Math.min(1, root.deckPlayer.volume + .05) }
- Shortcut { sequence: "Down"; enabled: !root.libraryOpen && !trackList.activeFocus && !crossfadeMenu.visible && !preferences.visible && !root.editingText && !(root.discFlipped && (albumList.activeFocus || lyricList.activeFocus)); onActivated: root.deckPlayer.volume = Math.max(0, root.deckPlayer.volume - .05) }
- Shortcut { sequence: "M"; enabled: !root.editingText && !crossfadeMenu.visible && !preferences.visible; onActivated: root.toggleMute() }
- Shortcut { sequence: "Escape"; onActivated: { if (fontPicker.shown || fontPicker.opening) { fontPicker.close(); return }; if (preferences.visible) { preferences.close(); return }; if (crossfadeMenu.visible) { crossfadeMenu.close(); return }; if (queueMenu.visible) { queueMenu.close(); return }; if (songMenu.visible) { songMenu.close(); return }; if (musicBrowser.actionsOpen) { musicBrowser.closeActions(); return }; if (root.queueSearchOpen) { root.closeQueueSearch(); return }; if (root.libraryOpen) { if (musicBrowser.detail && musicBrowser.browser.collectionQuery.length) musicBrowser.browser.collectionQuery = ""; else if (musicBrowser.detail) musicBrowser.browser.back(); else root.libraryOpen = false; return }; if (root.discFlipped) { root.discFlipped = false; return }; root.queueOpen = false; root.helpOpen = false; menu.close(); if (root.miniMode) player.miniMode = false } }
- Shortcut { sequence: "Y"; enabled: !root.editingText && !crossfadeMenu.visible && !preferences.visible; onActivated: { if (root.deckPlayer.count) { root.discFlipped = true; root.lyricsView = !root.lyricsView } } }
- Shortcut { sequence: "F"; enabled: !root.editingText && !crossfadeMenu.visible && !preferences.visible; onActivated: root.flipDisc() }
- Shortcut { sequence: "F1"; onActivated: root.helpOpen = !root.helpOpen }
+ Shortcut { sequence: "Ctrl+F"; enabled: !root.menuOpen; onActivated: root.libraryOpen ? musicBrowser.focusSearch() : root.openQueueSearch() }
+ Shortcut { sequence: "Ctrl+B"; enabled: root.useCider && !root.menuOpen; onActivated: root.openLibrary() }
+ Shortcut { sequence: "Ctrl+L"; enabled: !root.menuOpen; onActivated: root.toggleQueue() }
+ Shortcut { sequence: "Ctrl+M"; enabled: !root.menuOpen; onActivated: player.miniMode = !player.miniMode }
+ Shortcut { sequence: "Right"; enabled: !(root.activeFocusItem instanceof Slider) && !root.editingText && !root.menuOpen; onActivated: root.deckPlayer.seek(root.deckPlayer.position + 5000) }
+ Shortcut { sequence: "Left"; enabled: !(root.activeFocusItem instanceof Slider) && !root.editingText && !root.menuOpen; onActivated: root.deckPlayer.seek(root.deckPlayer.position - 5000) }
+ Shortcut { sequence: "Ctrl+Right"; enabled: !root.editingText && !root.menuOpen; onActivated: root.deckPlayer.next() }
+ Shortcut { sequence: "Ctrl+Left"; enabled: !root.editingText && !root.menuOpen; onActivated: root.deckPlayer.previous() }
+ Shortcut { sequence: "Up"; enabled: !root.libraryOpen && !trackList.activeFocus && !root.menuOpen && !root.editingText && !(root.discFlipped && (albumList.activeFocus || lyricList.activeFocus)); onActivated: root.deckPlayer.volume = Math.min(1, root.deckPlayer.volume + .05) }
+ Shortcut { sequence: "Down"; enabled: !root.libraryOpen && !trackList.activeFocus && !root.menuOpen && !root.editingText && !(root.discFlipped && (albumList.activeFocus || lyricList.activeFocus)); onActivated: root.deckPlayer.volume = Math.max(0, root.deckPlayer.volume - .05) }
+ Shortcut { sequence: "M"; enabled: !root.editingText && !root.menuOpen; onActivated: root.toggleMute() }
+ Shortcut { sequence: "Escape"; onActivated: { if(root.libraryDragging) { root.endLibraryDrag(false);return }; if(quickJump.visible) { quickJump.close();return }; if(savedQueuePicker.visible) { savedQueuePicker.close();return }; if(cleanupPopup.visible) { cleanupPopup.close();return }; if(qualityPopup.visible) { qualityPopup.close();return }; if (saveQueuePopup.visible) { saveQueuePopup.close(); return }; if (deleteQueuePopup.visible) { deleteQueuePopup.close(); return }; if (savedQueueMenu.visible) { savedQueueMenu.close(); return }; if (fontPicker.shown || fontPicker.opening) { fontPicker.close(); return }; if (preferences.visible) { preferences.close(); return }; if (crossfadeMenu.visible) { crossfadeMenu.close(); return }; if (queueMenu.visible) { queueMenu.close(); return }; if (songMenu.visible) { songMenu.close(); return }; if (musicBrowser.actionsOpen) { musicBrowser.closeActions(); return }; if (menu.visible) { menu.close(); return }; if (root.queueSelectionCount > 0) { root.clearQueueSelection(); return }; if (root.queueSearchOpen) { root.closeQueueSearch(); return }; if (root.libraryOpen) { if (musicBrowser.item && musicBrowser.item.selectionCount > 0) musicBrowser.item.clearSelection(); else if (musicBrowser.detail && musicBrowser.browser.collectionQuery.length) musicBrowser.browser.collectionQuery = ""; else if (musicBrowser.detail) musicBrowser.browser.back(); else root.libraryOpen = false; return }; if (root.discFlipped) { root.discFlipped = false; return }; root.queueOpen = false; root.helpOpen = false; menu.close(); if (root.miniMode) player.miniMode = false } }
+ Shortcut { sequence: "Y"; enabled: !root.editingText && !root.menuOpen; onActivated: { if (root.deckPlayer.count) { root.discFlipped = true; root.lyricsView = !root.lyricsView } } }
+ Shortcut { sequence: "F"; enabled: !root.editingText && !root.menuOpen; onActivated: root.flipDisc() }
+ Shortcut { sequence: "F1"; enabled: !root.menuOpen; onActivated: root.helpOpen = !root.helpOpen }
FileDialog {
id: files
@@ -272,8 +402,14 @@ ApplicationWindow {
color: root.inset
}
Row {
+ id: sourceTabs
+ function focusTab(index) {
+ const button = sourceTabItems.itemAt(Math.max(0, Math.min(1, index)))
+ if (button) button.forceActiveFocus(Qt.TabFocusReason)
+ }
x: 56; y: 6; spacing: 0
Repeater {
+ id: sourceTabItems
model: ["Local", "Cider"]
AbstractButton {
id: sourceTab
@@ -284,6 +420,21 @@ ApplicationWindow {
focusPolicy: Qt.StrongFocus
hoverEnabled: true
Accessible.name: modelData
+ Accessible.role: Accessible.PageTab
+ Accessible.selectable: true; Accessible.selected: root.useCider === (index === 1)
+ Keys.onShortcutOverride: event => {
+ if (event.modifiers === Qt.NoModifier && [Qt.Key_Left, Qt.Key_Right, Qt.Key_Home, Qt.Key_End].includes(event.key)) event.accepted = true
+ }
+ Keys.onLeftPressed: sourceTabs.focusTab(index - 1)
+ Keys.onRightPressed: sourceTabs.focusTab(index + 1)
+ Keys.onPressed: event => {
+ if (event.key === Qt.Key_Home) { sourceTabs.focusTab(0); event.accepted = true }
+ else if (event.key === Qt.Key_End) { sourceTabs.focusTab(1); event.accepted = true }
+ else event.accepted = false
+ }
+
+ Keys.onReturnPressed: clicked()
+ Keys.onEnterPressed: clicked()
background: Rectangle {
radius: 18
color: "transparent"
@@ -291,7 +442,7 @@ ApplicationWindow {
border.width: sourceTab.visualFocus ? 2 : 0; border.color: root.accent
}
contentItem: SpunText { text: parent.modelData; horizontalAlignment: Text.AlignHCenter; verticalAlignment: Text.AlignVCenter; color: (root.useCider === (parent.index === 1)) ? root.accent : root.mutedInk; font.pixelSize: SpunStyle.body; font.weight: Font.Medium }
- onClicked: { if (index === 0 && root.useCider && cider.playing) cider.pause(); root.useCider = index === 1; if (index === 1 && player.ciderAutoStart) cider.ensureRunning() }
+ onClicked: { if (index === 0 && root.useCider && root.ciderService.playing) root.ciderService.pause(); root.useCider = index === 1; if (index === 1 && player.ciderAutoStart) root.ciderService.ensureRunning() }
}
}
}
@@ -338,8 +489,8 @@ ApplicationWindow {
opacity: root.outgoingOpacity
transform: Translate { x: root.outgoingOffset }
sourceComponent: Item {
- Disc { anchors.fill: parent; artwork: presentation.outgoing; rotation: root.outgoingAngle }
- Disc { anchors.fill: parent; overlay: true }
+ Disc { vinyl: root.vinyl; anchors.fill: parent; artwork: presentation.outgoing; rotation: root.outgoingAngle }
+ Disc { vinyl: root.vinyl; anchors.fill: parent; overlay: true }
}
}
Item {
@@ -360,19 +511,19 @@ ApplicationWindow {
}
front: Item {
anchors.fill: parent
- Disc {
+ Disc { vinyl: root.vinyl;
id: face
objectName: "discFace"
anchors.fill: parent
artwork: presentation.artwork
rotation: root.spinAngle
}
- Disc { anchors.fill: parent; overlay: true }
+ Disc { vinyl: root.vinyl; anchors.fill: parent; overlay: true }
}
back: Item {
objectName: "discBack"
anchors.fill: parent
- Disc { anchors.fill: parent; labelColor: root.surface }
+ Disc { vinyl: root.vinyl; anchors.fill: parent; labelColor: root.surface }
SpunText {
objectName: "discAlbumTitle"
id: albumHeading
@@ -520,7 +671,7 @@ ApplicationWindow {
objectName: "lyricLine" + index
required property var modelData
required property int index
- readonly property bool seekable: lyrics.timed && !lyrics.loading && modelData.start >= 0 && modelData.start < root.deckPlayer.duration && (!root.useCider || cider.canSeek)
+ readonly property bool seekable: lyrics.timed && !lyrics.loading && modelData.start >= 0 && modelData.start < root.deckPlayer.duration && (!root.useCider || root.ciderService.canSeek)
function seekHere() {
if (seekable && lyrics.seekToLine(index)) {
lyricList.following = true
@@ -534,8 +685,8 @@ ApplicationWindow {
font.pixelSize: root.miniMode ? 19 : 15
color: (seekable && lyricHit.containsMouse) || (lyrics.timed && index === lyrics.currentIndex) ? root.accent : root.ink
opacity: lyrics.timed && index !== lyrics.currentIndex && !(seekable && lyricHit.containsMouse) ? .62 : 1
- Behavior on color { ColorAnimation { duration: SpunStyle.feedback; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.standardCurve } }
- Behavior on opacity { NumberAnimation { duration: SpunStyle.feedback } }
+ Behavior on color { ColorAnimation { duration: SpunStyle.feedback; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
+ Behavior on opacity { NumberAnimation { duration: SpunStyle.feedback; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
Accessible.role: seekable ? Accessible.Button : Accessible.StaticText
Accessible.name: text
Accessible.onPressAction: seekHere()
@@ -615,15 +766,15 @@ ApplicationWindow {
visible: !root.lyricsView && root.useCider && !root.albumTracks.length
SpunText {
width: parent.width; horizontalAlignment: Text.AlignHCenter; wrapMode: Text.WordWrap
- text: cider.discLoading ? "Loading album…" : cider.discError
+ text: root.ciderService.discLoading ? "Loading album…" : root.ciderService.discError
font.pixelSize: root.miniMode ? 18 : SpunStyle.body; color: root.mutedInk
}
IconButton {
objectName: "retryDiscButton"
anchors.horizontalCenter: parent.horizontalCenter
- visible: !cider.discLoading && !!cider.discError
+ visible: !root.ciderService.discLoading && !!root.ciderService.discError
glyphName: "repeat"; tip: "Retry album details"; ink: root.accent; hoverFill: root.hoverFill
- onClicked: cider.refreshDisc()
+ onClicked: root.ciderService.refreshDisc()
}
}
}
@@ -652,6 +803,13 @@ ApplicationWindow {
+ }
+ Loader {
+ objectName: "tonearmLoader"
+ anchors.fill: parent
+ active: root.vinyl
+ visible: active && !root.discFlipped && !root.swapRunning
+ sourceComponent: Tonearm { app: root }
}
Connections {
target: presentation
@@ -700,7 +858,7 @@ ApplicationWindow {
hoverEnabled: true
property bool scrubbing: false
property real previewFraction: 0
- readonly property bool canSeek: !root.swapRunning && root.deckPlayer.duration > 0 && (!root.useCider || cider.canSeek)
+ readonly property bool canSeek: !root.swapRunning && root.deckPlayer.duration > 0 && (!root.useCider || root.ciderService.canSeek)
readonly property bool showPreview: canSeek && (scrubbing || (containsMouse && onRim(mouseX,mouseY)))
cursorShape: canSeek && onRim(mouseX,mouseY) ? Qt.PointingHandCursor : Qt.ArrowCursor
function onRim(x,y) { let r=Math.hypot(x-220,y-220); return r > 205 && r < 224 }
@@ -766,13 +924,15 @@ ApplicationWindow {
x: 50; y: 302; width: 200; height: 48; radius: 24
color: root.surface
opacity: platterHover.hovered || miniDockHover.hovered || miniControlsHover.hovered || miniReveal.running || miniPrevious.visualFocus || miniPlay.visualFocus || miniNext.visualFocus || miniRestore.visualFocus ? 1 : 0
- Behavior on opacity { NumberAnimation { duration: root.transitionTime; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.standardCurve } }
+ Behavior on opacity { NumberAnimation { duration: root.transitionTime; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
HoverHandler { id: miniControlsHover }
Row {
x: 8; y: 4; spacing: 0
- IconButton { id: miniPrevious; objectName: "miniPrevious"; glyphName: "previous"; tip: "Previous track"; ink: root.ink; hoverFill: root.hoverFill; enabled: root.useCider ? cider.canPrevious : player.count > 0; onClicked: root.deckPlayer.previous() }
- IconButton { id: miniPlay; objectName: "miniPlay"; glyphSize: 26; width: 48; glyphName: root.deckPlayer.playing ? "pause" : "play"; tip: root.deckPlayer.playing ? "Pause" : "Play"; fill: root.accent; ink: theme.colors.onAccent; hoverFill: Qt.lighter(root.accent,1.08); onClicked: root.useCider ? cider.toggle() : player.count ? player.toggle() : files.open() }
- IconButton { id: miniNext; objectName: "miniNext"; glyphName: "next"; tip: "Next track"; ink: root.ink; hoverFill: root.hoverFill; enabled: root.useCider ? cider.canNext : player.count > 0; onClicked: root.deckPlayer.next() }
+ IconButton { id: miniPrevious; objectName: "miniPrevious"; glyphName: "previous"; tip: "Previous track"; ink: root.ink; hoverFill: root.hoverFill; enabled: root.useCider ? root.ciderService.canPrevious : player.count > 0; onClicked: root.deckPlayer.previous() }
+ IconButton { id: miniPlay; objectName: "miniPlay"; glyphSize: 26; width: 48; glyphName: root.deckPlayer.playing ? "pause" : "play"; tip: root.deckPlayer.playing ? "Pause" : "Play"; fill: root.accent; ink: theme.colors.onAccent; hoverFill: Qt.lighter(root.accent,1.08); onClicked: root.useCider ? root.ciderService.toggle() : player.count ? player.toggle() : files.open() }
+ IconButton { id: miniNext; objectName: "miniNext"; Accessible.description: miniPeek.visible ? miniPeek.summary : ""; showTip: false; glyphName: "next"; tip: "Next track"; ink: root.ink; hoverFill: root.hoverFill; enabled: root.useCider ? root.ciderService.canNext : player.count > 0; onClicked: root.deckPlayer.next()
+ NextTrackTip { id: miniPeek; app: root; visible: root.miniMode && miniNext.enabled && (miniNext.hovered || miniNext.visualFocus) && !miniNext.down && !quickJump.visible }
+ }
IconButton { id: miniRestore; objectName: "miniRestore"; glyphName: "external"; tip: "Full player · Ctrl+M"; ink: root.mutedInk; hoverFill: root.hoverFill; onClicked: player.miniMode = false }
}
}
@@ -792,15 +952,20 @@ ApplicationWindow {
}
IconButton {
objectName: "currentSongActions"
- visible: root.useCider; enabled: cider.count > 0
+ visible: root.useCider; enabled: root.ciderService.count > 0
x: 264; y: 12; width: 40; height: 40
glyphName: "more"; tip: "Song actions"; ink: root.mutedInk; hoverFill: root.hoverFill
onClicked: { menu.close(); songMenu.x = deck.x + deck.width - songMenu.width; songMenu.y = Qt.binding(function() { return deck.y - songMenu.height - 8 }); songMenu.open() }
}
- SpunText {
- x: 24; y: 48; width: 284
- text: root.deckPlayer.artist; color: root.mutedInk; elide: Text.ElideRight
- font.pixelSize: SpunStyle.body
+ AbstractButton {
+ id: playerArtist
+ objectName: "playerArtistLink"
+ x: 24; y: 44; width: 284; height: 28
+ enabled: root.useCider && root.deckPlayer.artist.length > 0; hoverEnabled: true
+ Accessible.name: "View artist " + root.deckPlayer.artist
+ background: null
+ onClicked: root.openArtistName(root.deckPlayer.artist)
+ contentItem: SpunText { text: root.deckPlayer.artist; color: playerArtist.hovered || playerArtist.visualFocus ? root.accent : root.mutedInk; elide: Text.ElideRight; font.pixelSize: SpunStyle.body; verticalAlignment: Text.AlignVCenter; font.underline: playerArtist.hovered || playerArtist.visualFocus }
}
SpunText {
x: 307; y: 18; width: 77; horizontalAlignment: Text.AlignRight
@@ -809,8 +974,8 @@ ApplicationWindow {
}
Row {
x: 16; y: 80; spacing: 4
- IconButton { objectName: "shuffleButton"; y: 4; selected: root.deckPlayer.shuffle; glyphName: "shuffle"; tip: root.deckPlayer.shuffle ? "Shuffle on" : "Shuffle off"; enabled: !root.useCider || !cider.controlBusy; ink: root.deckPlayer.shuffle ? root.accent : root.mutedInk; hoverFill: root.hoverFill; onClicked: root.deckPlayer.shuffle = !root.deckPlayer.shuffle }
- IconButton { objectName: "previousButton"; y: 4; glyphName: "previous"; tip: "Previous track · Ctrl+←"; ink: root.ink; hoverFill: root.hoverFill; enabled: root.useCider ? cider.canPrevious : player.count > 0; onClicked: root.deckPlayer.previous() }
+ IconButton { objectName: "shuffleButton"; y: 4; selected: root.deckPlayer.shuffle; glyphName: "shuffle"; tip: root.deckPlayer.shuffle ? "Shuffle on" : "Shuffle off"; enabled: !root.useCider || !root.ciderService.controlBusy; ink: root.deckPlayer.shuffle ? root.accent : root.mutedInk; hoverFill: root.hoverFill; onClicked: root.deckPlayer.shuffle = !root.deckPlayer.shuffle }
+ IconButton { objectName: "previousButton"; y: 4; glyphName: "previous"; tip: "Previous track · Ctrl+←"; ink: root.ink; hoverFill: root.hoverFill; enabled: root.useCider ? root.ciderService.canPrevious : player.count > 0; onClicked: root.deckPlayer.previous() }
IconButton {
objectName: "playButton"
glyphSize: 26
@@ -818,9 +983,9 @@ ApplicationWindow {
glyphName: root.deckPlayer.playing ? "pause" : "play"
tip: root.deckPlayer.playing ? "Pause · Space" : "Play · Space"
fill: root.accent; ink: theme.colors.onAccent; hoverFill: Qt.lighter(root.accent, 1.08)
- onClicked: root.useCider ? cider.toggle() : player.count ? player.toggle() : files.open()
+ onClicked: root.useCider ? root.ciderService.toggle() : player.count ? player.toggle() : files.open()
}
- IconButton { objectName: "nextButton"; y: 4; glyphName: "next"; tip: "Next track · Ctrl+→"; ink: root.ink; hoverFill: root.hoverFill; enabled: root.useCider ? cider.canNext : player.count > 0; onClicked: root.deckPlayer.next() }
+ IconButton { objectName: "nextButton"; y: 4; glyphName: "next"; tip: "Next track · Ctrl+→"; ink: root.ink; hoverFill: root.hoverFill; enabled: root.useCider ? root.ciderService.canNext : player.count > 0; onClicked: root.deckPlayer.next() }
IconButton {
objectName: "repeatButton"
y: 4
@@ -831,24 +996,15 @@ ApplicationWindow {
}
IconButton { x: 256; y: 84; glyphName: root.deckPlayer.volume > 0 ? "volume" : "mute"; tip: "Mute · M"; ink: root.mutedInk; hoverFill: root.hoverFill; onClicked: root.toggleMute() }
- Slider {
+ SpunSlider {
id: volumeSlider
objectName: "volumeSlider"
x: 300; y: 86; width: 44; height: 36
- from: 0; to: 1; value: root.deckPlayer.volume
+ from: 0; to: 1; stepSize: .05; value: root.deckPlayer.volume
onMoved: root.deckPlayer.volume = value
Accessible.name: "Volume"
- background: Rectangle {
- x: volumeSlider.leftPadding; y: volumeSlider.topPadding + volumeSlider.availableHeight/2-2
- width: volumeSlider.availableWidth; height: 3; radius: 2; color: root.hairline
- Rectangle { width: parent.width * volumeSlider.visualPosition; height: 3; radius: 2; color: root.accent }
- }
- handle: Rectangle {
- x: volumeSlider.leftPadding + volumeSlider.visualPosition * (volumeSlider.availableWidth-width)
- y: volumeSlider.topPadding + volumeSlider.availableHeight/2-height/2
- width: 4; height: 16; radius: 2; color: root.accent
- }
}
+
IconButton { id: menuButton; objectName: "menuButton"; x: 350; y: 84; glyphName: "more"; tip: "More actions"; ink: root.mutedInk; hoverFill: root.hoverFill; onClicked: root.openSettings() }
}
@@ -874,7 +1030,7 @@ ApplicationWindow {
Connections { target: root; function onAnimateChanged() { if (!root.animate) { queueAppear.stop(); jewelCase.opacity = 1; queueEntrance.x = 0 } } }
ParallelAnimation {
id: queueAppear
- NumberAnimation { target: jewelCase; property: "opacity"; from: 0; to: 1; duration: root.feedbackTime }
+ NumberAnimation { target: jewelCase; property: "opacity"; from: 0; to: 1; duration: root.feedbackTime; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve }
NumberAnimation { target: queueEntrance; property: "x"; from: 12; to: 0; duration: root.transitionTime; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.enterCurve }
}
Rectangle { x: 8; y: 18; width: 6; height: parent.height-36; radius: 3; color: root.inset }
@@ -882,8 +1038,15 @@ ApplicationWindow {
model: Math.max(0, Math.floor((jewelCase.height - 60) / 12))
Rectangle { required property int index; x: 9; y: 30+index*12; width: 4; height: 1; color: root.hairline }
}
- SpunText { visible: !root.queueSearchOpen; x: SpunStyle.outerInset; y: 20; height: SpunStyle.target; verticalAlignment: Text.AlignVCenter; text: "Queue"; color: root.ink; font.pixelSize: SpunStyle.heading }
- SpunText { visible: !root.queueSearchOpen; x: 150; y: 33; width: 66; horizontalAlignment: Text.AlignRight; text: root.useCider ? (cider.queueReady ? cider.queue.length : "") : player.count; color: root.mutedInk; font.pixelSize: 12 }
+ SpunText { visible: !root.queueSearchOpen; x: SpunStyle.outerInset; y: root.libraryDragging ? 20 : 16; height: root.libraryDragging ? SpunStyle.target : 26; verticalAlignment: Text.AlignVCenter; text: root.libraryDragging ? "Insert " + root.libraryDragTracks.length + (root.libraryDragTracks.length === 1 ? " song" : " songs") : "Queue"; color: root.libraryDragging ? root.accent : root.ink; font.pixelSize: SpunStyle.heading; font.weight: Font.Medium }
+ SpunText {
+ objectName: "queueTimeSummary"
+ visible: !root.queueSearchOpen && !root.libraryDragging
+ x: SpunStyle.outerInset; y: 43; width: 174; height: 18
+ text: root.queueTimeSummary; color: root.mutedInk; font.pixelSize: SpunStyle.caption; elide: Text.ElideRight
+ HoverHandler { id: queueTimeHover }
+ SpunToolTip { visible: queueTimeHover.hovered; text: root.queueTimeSummary + "\nCurrent and upcoming songs. Excludes repeats and future autoplay." }
+ }
SpunSearchField {
app: root
id: queueSearch
@@ -895,10 +1058,11 @@ ApplicationWindow {
placeholderText: "Song or artist"
Accessible.name: "Search queue"
onAccepted: {
- if (root.filteredQueue.length && (!root.useCider || (cider.queueReady && !cider.queueError.length)))
+ if (root.filteredQueue.length && (!root.useCider || (root.ciderService.queueReady && !root.ciderService.queueError.length)))
root.deckPlayer.select(root.filteredQueue[0].sourceIndex)
}
}
+ IconButton { objectName: "savedQueueMenuButton"; visible: root.useCider && !root.queueSearchOpen; x: 204; y: 20; glyphName: "more"; tip: "Queue actions"; ink: root.mutedInk; onClicked: savedQueueMenu.open() }
IconButton {
objectName: "queueSearchButton"
x: 246; y: 20; width: 40; height: 40
@@ -907,6 +1071,13 @@ ApplicationWindow {
ink: root.queueSearchOpen ? root.accent : root.mutedInk; hoverFill: root.hoverFill
onClicked: root.queueSearchOpen ? root.closeQueueSearch() : root.openQueueSearch()
}
+ Rectangle {
+ objectName: "queueSelectionBar"; visible: root.queueSelectionCount > 0; z: 3
+ x: 20; y: 12; width: parent.width - 40; height: 52; radius: 20; color: root.surface
+ SpunText { x: 8; anchors.verticalCenter: parent.verticalCenter; text: root.queueSelectionCount + " selected"; color: root.ink; font.pixelSize: SpunStyle.body }
+ IconButton { objectName: "queueSelectionActions"; x: parent.width - 84; anchors.verticalCenter: parent.verticalCenter; glyphName: "more"; tip: "Selected queue actions"; ink: root.accent; enabled: root.queueControlsReady; onClicked: root.openQueueSelectionActions(this) }
+ IconButton { objectName: "clearQueueSelection"; x: parent.width - 42; anchors.verticalCenter: parent.verticalCenter; glyphName: "close"; tip: "Clear selection · Esc"; ink: root.mutedInk; onClicked: root.clearQueueSelection() }
+ }
Rectangle { x: 30; y: 65; width: 252; height: 1; color: root.hairline }
ListView {
id: trackList
@@ -914,12 +1085,19 @@ ApplicationWindow {
activeFocusOnTab: visible
property int keyboardIndex: -1
Keys.onPressed: event => {
- if (event.key === Qt.Key_Up || event.key === Qt.Key_Down) {
+ if (root.useCider && event.key === Qt.Key_A && (event.modifiers & Qt.ControlModifier)) { root.selectUpcomingQueue(); event.accepted = true
+ } else if (root.useCider && event.key === Qt.Key_Space) {
+ const row = root.filteredQueue[keyboardIndex < 0 ? currentIndex : keyboardIndex]
+ if (row) root.chooseQueueRow(row.sourceIndex, event.modifiers | Qt.ControlModifier)
+ event.accepted = true
+ } else if (event.key === Qt.Key_Up || event.key === Qt.Key_Down) {
+ if ((event.modifiers & Qt.ShiftModifier) && root.queueSelectionAnchor < 0) root.queueSelectionAnchor = root.filteredQueue[Math.max(0, keyboardIndex < 0 ? currentIndex : keyboardIndex)]?.sourceIndex ?? -1
keyboardIndex = Math.max(0, Math.min(count - 1, (keyboardIndex < 0 ? currentIndex : keyboardIndex) + (event.key === Qt.Key_Down ? 1 : -1)))
+ if ((event.modifiers & Qt.ShiftModifier) && root.filteredQueue[keyboardIndex]) root.chooseQueueRow(root.filteredQueue[keyboardIndex].sourceIndex, event.modifiers)
positionViewAtIndex(keyboardIndex, ListView.Contain); event.accepted = true
} else if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter) {
const row = root.filteredQueue[keyboardIndex < 0 ? currentIndex : keyboardIndex]
- if (row && root.queueControlsReady) root.deckPlayer.select(row.sourceIndex)
+ if (row && root.queueControlsReady) { if (root.queueSelectionCount) root.openQueueSelectionActions(trackList); else root.deckPlayer.select(row.sourceIndex) }
event.accepted = true
} else if (event.key === Qt.Key_Menu || (event.key === Qt.Key_F10 && (event.modifiers & Qt.ShiftModifier))) {
const row = itemAtIndex(keyboardIndex < 0 ? currentIndex : keyboardIndex)
@@ -927,9 +1105,9 @@ ApplicationWindow {
event.accepted = true
}
}
- x: SpunStyle.inset; y: 80; width: parent.width - 2 * SpunStyle.inset; height: queueFooter.y - 2 * SpunStyle.gap - y - (root.useCider && cider.queueError.length ? 32 : 0)
+ x: SpunStyle.inset; y: 80; width: parent.width - 2 * SpunStyle.inset; height: queueFooter.y - 2 * SpunStyle.gap - y - (root.useCider && root.ciderService.queueError.length ? 32 : 0)
model: root.filteredQueue; clip: true; spacing: SpunStyle.smallGap
- visible: !root.useCider || cider.queueReady
+ visible: !root.useCider || root.ciderService.queueReady
currentIndex: root.filteredQueue.findIndex(row => row.sourceIndex === root.deckPlayer.currentIndex)
onCurrentIndexChanged: if (currentIndex >= 0 && !root.queueQuery.trim().length) positionViewAtIndex(currentIndex, ListView.Contain)
onModelChanged: Qt.callLater(function() {
@@ -941,7 +1119,7 @@ ApplicationWindow {
id: queueDragArea
objectName: "queueDragArea"
parent: trackList; x: 0; y: 0; width: 22; height: trackList.height; z: 10
- enabled: root.queueReorderAllowed; preventStealing: true
+ enabled: root.queueReorderAllowed && !root.queueSelectionCount; preventStealing: true
cursorShape: pressed ? Qt.ClosedHandCursor : Qt.OpenHandCursor
property real startY: 0
property int pressedSource: -1
@@ -949,7 +1127,7 @@ ApplicationWindow {
startY = mouse.y
const index = trackList.indexAt(0,mouse.y + trackList.contentY)
pressedSource = index >= 0 ? root.filteredQueue[index].sourceIndex : -1
- root.queueDragRevision = cider.queueRevision
+ root.queueDragRevision = root.ciderService.queueRevision
}
onPositionChanged: mouse => {
if (!pressed || pressedSource < 0) return
@@ -974,17 +1152,19 @@ ApplicationWindow {
color: "transparent"
Rectangle {
anchors.fill: parent; radius: parent.radius; color: SpunStyle.selected
- opacity: root.deckPlayer.currentIndex === trackRow.sourceIndex ? 1 : 0
- Behavior on opacity { NumberAnimation { duration: SpunStyle.feedback } }
+ opacity: root.deckPlayer.currentIndex === trackRow.sourceIndex || root.queueSelection.indexOf(trackRow.sourceIndex) >= 0 ? 1 : 0
+ Behavior on opacity { NumberAnimation { duration: SpunStyle.feedback; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
}
SpunStateLayer { anchors.fill: parent; radius: parent.radius; color: root.ink; enabled: root.queueControlsReady; pressed: rowHit.pressed; focused: trackList.activeFocus && trackList.keyboardIndex === trackRow.index; hovered: rowHover.hovered }
border.width: trackList.activeFocus && trackList.keyboardIndex === index ? 2 : 0
border.color: root.accent
Accessible.role: Accessible.ListItem
Accessible.name: modelData.track.title + ", " + modelData.track.artist
- Accessible.onPressAction: if (root.queueControlsReady) root.deckPlayer.select(sourceIndex)
+ Accessible.onPressAction: root.chooseQueueRow(sourceIndex, Qt.NoModifier)
+ Accessible.checkable: root.useCider && sourceIndex > root.ciderService.currentIndex
+ Accessible.checked: root.queueSelection.indexOf(sourceIndex) >= 0
HoverHandler { id: rowHover }
- MouseArea { id: rowHit; anchors.fill: parent; enabled: root.queueControlsReady; onClicked: root.deckPlayer.select(trackRow.sourceIndex) }
+ MouseArea { id: rowHit; anchors.fill: parent; enabled: root.queueControlsReady; onClicked: mouse => { trackList.forceActiveFocus(); trackList.keyboardIndex = trackRow.index; root.chooseQueueRow(trackRow.sourceIndex, mouse.modifiers) } }
TrackContent {
anchors.fill: parent; app: root
title: trackRow.modelData.track.title; subtitle: trackRow.modelData.track.artist
@@ -992,10 +1172,11 @@ ApplicationWindow {
}
IconButton { id: queueActions; objectName: "queueActions" + trackRow.sourceIndex; x: parent.width - SpunStyle.target; anchors.verticalCenter: parent.verticalCenter; glyphName: "more"; tip: "Queue actions"; ink: root.mutedInk; hoverFill: root.hoverFill; enabled: root.queueControlsReady; onClicked: root.showQueueActions(trackRow.sourceIndex,this) }
TapHandler { acceptedButtons: Qt.RightButton; onTapped: root.showQueueActions(trackRow.sourceIndex,queueActions) }
+ Glyph { visible: root.queueSelection.indexOf(trackRow.sourceIndex) >= 0; x: 1; anchors.verticalCenter: parent.verticalCenter; width: 18; height: 18; name: "check"; ink: root.accent }
Item {
x: 0; y: 0; width: 22; height: SpunStyle.trackHeight
- opacity: root.queueReorderAllowed && (rowHover.hovered || root.queueDragSource === trackRow.sourceIndex) ? .7 : 0
- Behavior on opacity { NumberAnimation { duration: SpunStyle.feedback } }
+ opacity: root.queueReorderAllowed && !root.queueSelectionCount && (rowHover.hovered || root.queueDragSource === trackRow.sourceIndex) ? .7 : 0
+ Behavior on opacity { NumberAnimation { duration: SpunStyle.feedback; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
Glyph { anchors.centerIn: parent; width: SpunStyle.smallIcon; height: width; name: "grip"; ink: root.mutedInk }
}
@@ -1005,6 +1186,11 @@ ApplicationWindow {
width: parent.width - 30; height: 2; radius: 1; color: root.accent
}
}
+ Rectangle {
+ parent: trackList; z: 15; x: 24; width: trackList.width - 30; height: 3; radius: 1; color: root.accent
+ y: Math.max(0, Math.min(trackList.height - height, root.libraryDropIndex * (SpunStyle.trackHeight + SpunStyle.smallGap) - trackList.contentY - 2))
+ visible: root.libraryDragging && root.libraryDropIndex >= 0
+ }
SpunText {
anchors.centerIn: parent; width: 200; visible: trackList.count === 0
text: root.queueQuery.trim().length ? "No matches" : "No tracks"
@@ -1012,42 +1198,65 @@ ApplicationWindow {
}
}
SpunText {
- visible: root.useCider && cider.queueReady && cider.queueError.length > 0
+ visible: root.useCider && root.ciderService.queueReady && root.ciderService.queueError.length > 0
x: SpunStyle.outerInset; y: queueFooter.y - 40; width: parent.width - 2 * SpunStyle.outerInset; elide: Text.ElideRight
- text: cider.queueError; color: root.mutedInk; font.pixelSize: SpunStyle.caption
+ text: root.ciderService.queueError; color: root.mutedInk; font.pixelSize: SpunStyle.caption
}
Column {
- x: 30; y: 100; width: 250; spacing: 16
- visible: root.useCider && !cider.queueReady
+ id: connectionForm
+ objectName: "ciderConnectionForm"
+ property var service: root.ciderService
+ property bool manual: false
+ x: SpunStyle.outerInset; y: 100; width: parent.width - 2 * SpunStyle.outerInset; spacing: 12
+ visible: root.useCider && (!connectionForm.service.queueReady || connectionForm.service.needsToken)
+ component ConnectionButton: SpunButton {
+ width: connectionForm.width; tonal: true
+ }
SpunText {
width: parent.width
- text: cider.queueBusy && !cider.queueError.length ? "Loading queue…" : cider.queueError
- wrapMode: Text.WordWrap; color: root.ink; font.pixelSize: 13
+ text: connectionForm.service.connectionMessage || (connectionForm.service.queueBusy && !connectionForm.service.queueError.length ? "Loading queue…" : connectionForm.service.queueError)
+ wrapMode: Text.WordWrap; color: root.ink; font.pixelSize: SpunStyle.body
+ }
+ ConnectionButton {
+ objectName: "authorizeCiderButton"
+ text: connectionForm.service.authorizing ? "Cancel" : "Connect to Cider"
+ onClicked: { if(connectionForm.service.authorizing) connectionForm.service.cancelAuthorization(); else connectionForm.service.authorize() }
+ }
+ ConnectionButton {
+ visible: connectionForm.service.recovering && !connectionForm.service.authorizing
+ text: connectionForm.service.launching ? "Starting Cider…" : connectionForm.service.available ? "Retry connection" : "Open Cider"
+ enabled: !connectionForm.service.launching
+ onClicked: { if (!connectionForm.service.available) connectionForm.service.ensureRunning(); connectionForm.service.reconnect() }
+ }
+ ConnectionButton {
+ objectName: "manualCiderTokenButton"
+ visible: !connectionForm.service.authorizing
+ text: connectionForm.manual ? "Hide manual token" : "Use an app token"
+ onClicked: connectionForm.manual = !connectionForm.manual
}
SpunText {
- width: parent.width; visible: cider.needsToken
- text: "In Cider: Settings → Connectivity → Manage External Application Access. Create a token for Spun."
+ width: parent.width; visible: connectionForm.manual && !connectionForm.service.authorizing
+ text: "In Cider: Settings → Connectivity → Manage External Application Access."
wrapMode: Text.WordWrap; color: root.mutedInk; font.pixelSize: SpunStyle.caption; lineHeight: 1.25
}
TextField {
id: ciderToken
objectName: "ciderTokenInput"
- width: parent.width; height: 38; visible: cider.needsToken
- echoMode: TextInput.Password; placeholderText: "Cider app token"
- font.family: SpunStyle.family; font.pixelSize: 12
+ width: parent.width; height: SpunStyle.target; visible: connectionForm.manual && !connectionForm.service.authorizing
+ echoMode: TextInput.Password; placeholderText: "Cider app token"; maximumLength: 8192
+ leftPadding: 16; rightPadding: 16
+ font.family: SpunStyle.family; font.pixelSize: SpunStyle.body
color: root.ink; placeholderTextColor: root.mutedInk
selectionColor: root.accent; selectedTextColor: theme.colors.onAccent
- background: Rectangle { color: root.inset; radius: 9 * theme.radius }
- onAccepted: { cider.connectQueue(text); clear() }
+ background: Rectangle { color: root.inset; radius: 12 * theme.radius; border.width: ciderToken.activeFocus ? 2 : 0; border.color: root.accent }
+ onAccepted: { connectionForm.service.connectQueue(text); clear() }
}
- Button {
+ ConnectionButton {
objectName: "connectCiderButton"
- width: parent.width; height: 36; visible: cider.needsToken
- enabled: ciderToken.text.trim().length > 0 && !cider.queueBusy
- text: "Connect"
- contentItem: SpunText { text: parent.text; horizontalAlignment: Text.AlignHCenter; verticalAlignment: Text.AlignVCenter; color: theme.colors.onAccent; font.family: SpunStyle.family; font.pixelSize: 12 }
- background: Rectangle { color: root.accent; radius: 9 * theme.radius; opacity: parent.enabled ? 1 : .35 }
- onClicked: { cider.connectQueue(ciderToken.text); ciderToken.clear() }
+ visible: connectionForm.manual && !connectionForm.service.authorizing
+ enabled: ciderToken.text.trim().length > 0 && !connectionForm.service.queueBusy
+ text: "Connect with token"
+ onClicked: { connectionForm.service.connectQueue(ciderToken.text); ciderToken.clear() }
}
}
Rectangle { x: SpunStyle.outerInset; y: queueFooter.y - SpunStyle.gap; width: parent.width - 2 * SpunStyle.outerInset; height: 1; color: root.hairline }
@@ -1069,7 +1278,7 @@ ApplicationWindow {
radius: height / 2 * theme.radius
border.width: openCiderButton.visualFocus ? 2 : 0; border.color: root.accent
}
- onClicked: cider.raise()
+ 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() }
@@ -1108,21 +1317,120 @@ ApplicationWindow {
sourceComponent: LibraryPanel { app: root }
}
+ function previewQueueCleanup(mode) {
+ const preview = root.ciderService.previewCleanup(mode)
+ if (!preview.rows) return
+ cleanupPopup.preview = preview
+ cleanupPopup.open()
+ }
+ Popup {
+ id: cleanupPopup; objectName: "cleanupPopup"; property var preview: ({})
+ onClosed: preview = ({})
+ readonly property bool stale: root.ciderService.queueRevision !== preview.revision || !root.ciderService.queueReady || root.ciderService.queueError.length > 0
+ focus: true; modal: true; popupType: Popup.Item; padding: 24
+ x: (root.width - width) / 2; y: (root.height - height) / 2
+ width: 360; height: Math.min(440, root.height - 48, 196 + (preview.rows || []).length * 64)
+ background: Rectangle { color: SpunStyle.popup; radius: SpunStyle.dialogRadius }
+ Overlay.modal: Rectangle { color: Qt.alpha("black", .32) }
+ enter: SpunPopupEnter {}
+ exit: Transition { NumberAnimation { property: "opacity"; to: 0; duration: SpunStyle.exit; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
+ contentItem: Loader { active: cleanupPopup.visible; sourceComponent: Item {
+ SpunText { text: cleanupPopup.preview.mode === "selection" ? "Remove selected songs?" : cleanupPopup.preview.mode === "duplicates" ? "Remove duplicates?" : "Clear upcoming?"; color: root.ink; font.pixelSize: SpunStyle.heading; font.weight: Font.Medium }
+ SpunText {
+ y: 34; width: parent.width; height: 48; wrapMode: Text.WordWrap
+ text: cleanupPopup.stale ? "The queue changed. Close and preview again." : !(cleanupPopup.preview.rows || []).length ? (cleanupPopup.preview.mode === "duplicates" ? "No upcoming duplicates." : "No upcoming songs.") : (cleanupPopup.preview.rows || []).length + " to remove. Keeps the current song and history."
+ color: root.mutedInk; font.pixelSize: SpunStyle.caption
+ }
+ ListView {
+ objectName: "cleanupPreviewList"; y: 88; width: parent.width; height: parent.height - y - 60
+ clip: true; model: cleanupPopup.preview.rows || []; boundsBehavior: Flickable.StopAtBounds
+ ScrollBar.vertical: ScrollBar { width: 3; contentItem: Rectangle { radius: 2; color: root.mutedInk; opacity: .4 } }
+ delegate: Item {
+ required property var modelData; width: ListView.view.width; height: 64
+ TrackContent { anchors.fill: parent; app: root; leadingInset: 0; trailingInset: 4; title: modelData.title; subtitle: modelData.artist; artwork: modelData.artwork || ""; fallback: "disc" }
+ }
+ }
+ SpunButton { objectName: "cancelCleanup"; x: parent.width - 184; y: parent.height - 40; width: 80; text: "Cancel"; onClicked: cleanupPopup.close() }
+ SpunButton { objectName: "confirmCleanup"; x: parent.width - width; y: parent.height - 40; width: 96; text: "Remove"; tonal: true; enabled: !cleanupPopup.stale && root.queueControlsReady && (cleanupPopup.preview.rows || []).length > 0; onClicked: { if (cleanupPopup.preview.mode === "selection") root.ciderService.editQueueSelection(cleanupPopup.preview.indices, "remove", cleanupPopup.preview.revision); else root.ciderService.cleanQueue(cleanupPopup.preview.mode, cleanupPopup.preview.revision); cleanupPopup.close() } }
+ } }
+ }
+ function openSavedQueues() { root.useCider = true; root.libraryOpen = true; musicBrowser.browser.section = "sessions" }
+ function renameQueue(queue, service) { saveQueuePopup.service = service; saveQueuePopup.renameTarget = queue; saveQueuePopup.open() }
+ function confirmDeleteQueue(id, service) { deleteQueuePopup.queueId = id; deleteQueuePopup.service = service; deleteQueuePopup.open() }
+ Menu {
+ id: savedQueueMenu; parent: jewelCase; x: 30; y: 64; width: 264; padding: 8; popupType: Popup.Item
+ background: Rectangle { color: SpunStyle.popup; radius: SpunStyle.popupRadius }
+ enter: SpunPopupEnter {}
+ SettingsAction { objectName: "saveQueueAction"; text: "Save queue"; glyphName: "plus"; enabled: root.ciderService.queueReady && !root.ciderService.queueBusy && root.ciderService.queue.length > 0; onTriggered: saveQueuePopup.open() }
+ SettingsAction { objectName: "recoverSessionAction"; visible: root.useCider && !!root.listeningService.session.trackCount; text: "Recover session…"; glyphName: "refresh"; enabled: !root.listeningService.busy; onTriggered: root.showRecovery() }
+ SettingsAction { objectName: "savedQueuesAction"; text: "Saved queues"; glyphName: "queue"; onTriggered: root.openSavedQueues() }
+ SettingsAction { objectName: "deduplicateQueueAction"; text: "Remove duplicates…"; glyphName: "minus"; enabled: root.queueControlsReady; onTriggered: root.previewQueueCleanup("duplicates") }
+ SettingsAction { objectName: "clearUpcomingAction"; text: "Clear upcoming…"; glyphName: "close"; enabled: root.queueControlsReady; onTriggered: root.previewQueueCleanup("upcoming") }
+ }
+ Popup {
+ id: saveQueuePopup; objectName: "saveQueuePopup"; property var service: library
+ property var renameTarget: ({})
+ onClosed: renameTarget = ({})
+ function submit(name) { if (renameTarget.id ? service.renameSavedQueue(renameTarget, name) : service.saveQueue(name)) close() }
+ focus: true; modal: true; popupType: Popup.Item
+ x: (root.width - width) / 2; y: 220; width: 330; height: 200; padding: 24
+ background: Rectangle { color: SpunStyle.popup; radius: SpunStyle.dialogRadius }
+ Overlay.modal: Rectangle { color: Qt.alpha("black", .32) }
+ enter: SpunPopupEnter {}
+ contentItem: Loader { active: saveQueuePopup.visible; sourceComponent: Item {
+ Component.onCompleted: Qt.callLater(function() { savedQueueName.forceActiveFocus(); if(saveQueuePopup.renameTarget.id)savedQueueName.selectAll() })
+ SpunText { text: saveQueuePopup.renameTarget.id ? "Rename saved queue" : "Save queue"; color: root.ink; font.pixelSize: SpunStyle.heading; font.weight: Font.Medium }
+ SpunText { y: 30; text: saveQueuePopup.renameTarget.id ? "Saved locally in Spun" : "Current and upcoming tracks"; color: root.mutedInk; font.pixelSize: SpunStyle.caption }
+ SpunSearchField { id: savedQueueName; objectName: "savedQueueName"; app: root; searchIcon: false; rightPadding: 16; Accessible.name: "Queue name"; y: 58; width: parent.width; height: 40; placeholderText: "Queue name"; text: saveQueuePopup.renameTarget.title || ""; maximumLength: 80; onAccepted: if(text.trim().length)saveQueuePopup.submit(text) }
+ SpunButton { objectName: "cancelSaveQueue"; x: parent.width - 168; y: 110; width: 80; text: "Cancel"; onClicked: saveQueuePopup.close() }
+ SpunButton { objectName: "confirmSaveQueue"; x: parent.width - width; y: 110; width: 80; text: "Save"; tonal: true; enabled: savedQueueName.text.trim().length > 0; onClicked: saveQueuePopup.submit(savedQueueName.text) }
+ } }
+ }
+ Popup {
+ id: deleteQueuePopup; focus: true; modal: true; popupType: Popup.Item; property string queueId: ""; property var service: library
+ x: (root.width - width) / 2; y: 240; width: 330; height: 132; padding: 24
+ background: Rectangle { color: SpunStyle.popup; radius: SpunStyle.dialogRadius }
+ Overlay.modal: Rectangle { color: Qt.alpha("black", .32) }
+ enter: SpunPopupEnter {}
+ contentItem: Loader { active: deleteQueuePopup.visible; sourceComponent: Item {
+ SpunText { text: "Delete saved queue?"; color: root.ink; font.pixelSize: SpunStyle.heading; font.weight: Font.Medium }
+ SpunButton { x: parent.width - 176; y: 42; width: 80; text: "Cancel"; onClicked: deleteQueuePopup.close() }
+ SpunButton { objectName: "confirmDeleteQueue"; x: parent.width - width; y: 42; width: 88; text: "Delete"; tonal: true; onClicked: { deleteQueuePopup.service.deleteSavedQueue(deleteQueuePopup.queueId);deleteQueuePopup.close() } }
+ } }
+ }
Menu {
id: queueMenu
objectName: "queueEditMenu"
+ readonly property bool batch: root.queueSelectionCount > 0
+ onOpened: { if (!batch && root.useCider && rowIndex >= 0 && rowIndex < root.ciderService.queue.length) library.prepareRadio(root.ciderService.queue[rowIndex]) }
property int rowIndex: -1
property int revision: -1
popupType: Popup.Item
width: 272; padding: 8; spacing: 2; margins: 12
background: Rectangle { color: SpunStyle.popup; radius: SpunStyle.popupRadius }
enter: SpunPopupEnter {}
- exit: Transition { NumberAnimation { property: "opacity"; from: 1; to: 0; duration: SpunStyle.exit } }
+ exit: Transition { NumberAnimation { property: "opacity"; from: 1; to: 0; duration: SpunStyle.exit; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
- SettingsAction { objectName: "queueMoveUp"; text: "Move up"; glyphName: "up"; enabled: root.queueReorderAllowed && queueMenu.rowIndex > 0; onTriggered: root.moveQueueRow(queueMenu.rowIndex,queueMenu.rowIndex - 1,queueMenu.revision) }
- SettingsAction { objectName: "queueMoveDown"; text: "Move down"; glyphName: "down"; enabled: root.queueReorderAllowed && queueMenu.rowIndex < root.queueRows.length - 1; onTriggered: root.moveQueueRow(queueMenu.rowIndex,queueMenu.rowIndex + 1,queueMenu.revision) }
- SettingsAction { objectName: "queueRemove"; text: "Remove from queue"; glyphName: "close"; enabled: root.queueControlsReady; onTriggered: root.useCider ? cider.removeQueue(queueMenu.rowIndex,queueMenu.revision) : player.remove(queueMenu.rowIndex) }
+ SettingsAction { objectName: "queueSelectTrack"; visible: root.useCider && !queueMenu.batch && queueMenu.rowIndex > root.ciderService.currentIndex; text: "Select track"; glyphName: "check"; onTriggered: root.chooseQueueRow(queueMenu.rowIndex, Qt.ControlModifier) }
+ SettingsAction { objectName: "queueSelectAll"; visible: root.useCider && queueMenu.batch; text: "Select all upcoming"; glyphName: "check"; onTriggered: root.selectUpcomingQueue() }
+ SettingsAction { objectName: "queueBatchNext"; visible: queueMenu.batch; text: "Play next"; glyphName: "next"; enabled: root.queueControlsReady; onTriggered: root.editQueueSelection("next") }
+ SettingsAction { objectName: "queueBatchUp"; visible: queueMenu.batch; text: "Move up"; glyphName: "up"; enabled: root.queueReorderAllowed; onTriggered: root.editQueueSelection("up") }
+ SettingsAction { objectName: "queueBatchDown"; visible: queueMenu.batch; text: "Move down"; glyphName: "down"; enabled: root.queueReorderAllowed; onTriggered: root.editQueueSelection("down") }
+ SettingsAction { objectName: "queueBatchEnd"; visible: queueMenu.batch; text: "Move to end"; glyphName: "queue"; enabled: root.queueControlsReady; onTriggered: root.editQueueSelection("end") }
+ SettingsAction { objectName: "queueBatchSave"; visible: queueMenu.batch; text: "Add to saved queue…"; glyphName: "plus"; enabled: root.queueControlsReady; onTriggered: root.openSavedQueuePicker(root.queueSelection.map(i => root.ciderService.queue[i]), library) }
+ SettingsAction { objectName: "queueBatchRemove"; visible: queueMenu.batch; text: "Remove selected…"; glyphName: "close"; enabled: root.queueControlsReady; onTriggered: root.editQueueSelection("remove") }
+ SettingsAction { objectName: "queueMoveUp"; visible: !queueMenu.batch; text: "Move up"; glyphName: "up"; enabled: root.queueReorderAllowed && queueMenu.rowIndex > 0; onTriggered: root.moveQueueRow(queueMenu.rowIndex,queueMenu.rowIndex - 1,queueMenu.revision) }
+ SettingsAction { objectName: "queueMoveDown"; visible: !queueMenu.batch; text: "Move down"; glyphName: "down"; enabled: root.queueReorderAllowed && queueMenu.rowIndex < root.queueRows.length - 1; onTriggered: root.moveQueueRow(queueMenu.rowIndex,queueMenu.rowIndex + 1,queueMenu.revision) }
+ SettingsAction { objectName: "queueRemove"; visible: !queueMenu.batch; text: "Remove from queue"; glyphName: "close"; enabled: root.queueControlsReady; onTriggered: root.useCider ? root.ciderService.removeQueue(queueMenu.rowIndex,queueMenu.revision) : player.remove(queueMenu.rowIndex) }
+ SettingsAction {
+ objectName: "queueRadioAction"; visible: root.useCider && !queueMenu.batch
+ text: library.radioBusy ? "Finding station…" : library.radioAvailable ? "Start radio" : "Radio unavailable"
+ glyphName: "disc"; enabled: library.radioAvailable && !library.radioBusy && !root.ciderService.controlBusy
+ onTriggered: library.playRadio()
+ }
+ SettingsAction { objectName: "queueCopyLink"; visible: root.useCider && !queueMenu.batch; text: "Copy song link"; glyphName: "external"; enabled: queueMenu.rowIndex >= 0 && queueMenu.rowIndex < root.ciderService.queue.length; onTriggered: library.copyLink(root.ciderService.queue[queueMenu.rowIndex]) }
+
}
TrackMenu {
id: songMenu
@@ -1131,29 +1439,84 @@ ApplicationWindow {
onAboutToShow: root.actionService.observing = true
onClosed: root.actionService.observing = false
}
- function notifyAction(message, error) { actionNotice.text = message; actionNotice.failed = error; noticeTimer.interval = error ? 8000 : 2200; noticeTimer.restart() }
+ function showAudioQuality() { qualityPopup.open();root.ciderService.refreshAudioQuality() }
+ Popup {
+ id: qualityPopup; objectName: "audioQualityPopup"
+ popupType: Popup.Item; focus: true; width: 340; height: 176; padding: 20
+ x: (root.width - width) / 2; y: Math.min(root.height - height - 24, 330)
+ onVisibleChanged: Qt.callLater(root.updateMask)
+ background: Rectangle { color: SpunStyle.popup; radius: SpunStyle.popupRadius }
+ enter: SpunPopupEnter {}
+ exit: Transition { NumberAnimation { property: "opacity"; from: 1; to: 0; duration: SpunStyle.exit; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
+ contentItem: Loader { active: qualityPopup.visible; sourceComponent: Item {
+ SpunText { text: "Audio quality"; color: root.ink; font.pixelSize: SpunStyle.heading; font.weight: Font.Medium }
+ IconButton { x: parent.width - width; y: -8; glyphName: "close"; tip: "Close"; ink: root.mutedInk; onClicked: qualityPopup.close() }
+ SpunText { objectName: "audioQualityText"; y: 42; width: parent.width; text: root.ciderService.qualityBusy ? "Checking…" : root.ciderService.audioQuality; color: root.ink; font.pixelSize: SpunStyle.body; wrapMode: Text.WordWrap }
+ IconButton { x: parent.width - width; y: 96; glyphName: "refresh"; tip: "Refresh quality"; ink: root.accent; enabled: !root.ciderService.qualityBusy; onClicked: root.ciderService.refreshAudioQuality() }
+ } }
+ }
+ function showRecovery() { recoveryPopup.open(); root.listeningService.prepareRecovery() }
+ Popup {
+ id: recoveryPopup; objectName: "recoveryPopup"
+ parent: Overlay.overlay; x: (parent.width - width) / 2; y: (parent.height - height) / 2
+ width: Math.min(420, root.width - 24); height: Math.min(260, root.height - 24)
+ padding: 24; modal: true; dim: false; focus: true; popupType: Popup.Item
+ background: Rectangle { radius: SpunStyle.popupRadius; color: SpunStyle.popup }
+ enter: SpunPopupEnter {}
+ exit: Transition { NumberAnimation { property: "opacity"; to: 0; duration: SpunStyle.exit } }
+ onOpened: recoveryCancel.forceActiveFocus()
+ onClosed: root.listeningService.cancelRecovery()
+ contentItem: Item {
+ SpunText { text: "Recover session"; font.pixelSize: SpunStyle.heading; color: root.ink }
+ SpunText {
+ y: 38; width: parent.width; height: 112; wrapMode: Text.WordWrap; maximumLineCount: 5; elide: Text.ElideRight
+ font.pixelSize: SpunStyle.body; color: root.mutedInk
+ text: root.listeningService.error || (root.listeningService.busy ? "Restoring your session…" : root.ciderService.queueBusy ? "Checking Cider’s queue…" : !root.listeningService.session.trackCount ? "No saved session yet. Enable Remember Cider session in Preferences." : root.ciderService.queue.length ? "Cider already has a queue. Recovery keeps your existing queue safe. You can try again when it is empty." : "Resume “" + root.listeningService.session.title + "” at " + root.time(root.listeningService.session.position) + ", with " + root.listeningService.session.trackCount + " tracks? This starts playback.")
+ }
+ SpunButton { id: recoveryCancel; objectName: "recoveryCancel"; anchors.left: parent.left; anchors.bottom: parent.bottom; text: root.listeningService.busy ? "Close" : "Cancel"; onClicked: recoveryPopup.close() }
+ SpunButton { objectName: "recoveryConfirm"; anchors.right: parent.right; anchors.bottom: parent.bottom; text: "Restore"; tonal: true
+ enabled: !root.listeningService.busy && !!root.listeningService.session.trackCount && root.ciderService.queueReady && !root.ciderService.queueBusy && !root.ciderService.controlBusy && !root.ciderService.queueError.length && root.ciderService.queue.length === 0 && !root.actionService.busy
+ onClicked: root.listeningService.restoreSession()
+ }
+ }
+ Connections { target: root.listeningService; function onFeedback(message, error) { if (recoveryPopup.visible && !error && !root.listeningService.busy) recoveryPopup.close() } }
+ }
+ function notifyAction(message, error) { actionNotice.text = message; actionNotice.failed = error; actionNotice.savedUndo = false; actionNotice.undo = !error && message === "Removed from queue" && root.ciderService.canUndoQueue; noticeTimer.interval = error || actionNotice.undo ? 8000 : 2200; noticeTimer.restart() }
Connections {
- target: cider
+ target: root.ciderService
function onApiFeedback(message, error) { root.notifyAction(message,error) }
- function onLaunchChanged() { if (cider.launching) root.notifyAction("Starting Cider…",false) }
+ function onLaunchChanged() { if (root.ciderService.launching) root.notifyAction("Starting Cider…",false) }
}
Connections {
target: root.actionService
- function onCurrentChanged() { songMenu.close() }
+ function onCurrentChanged() { songMenu.close(); qualityPopup.close() }
function onFeedback(message, error) { root.notifyAction(message,error) }
}
+ Connections {
+ target: root.savedService
+ function onSavedEditCommitted() { actionNotice.savedUndo = true; noticeTimer.interval = 8000; noticeTimer.restart() }
+ }
Timer { id: noticeTimer }
Rectangle {
id: actionNotice
objectName: "actionNotice"
property string text: ""
property bool failed: false
- visible: noticeTimer.running && !root.miniMode
+ property bool undo: false
+ property bool savedUndo: false
+ readonly property bool canUndo: savedUndo ? root.savedService.canUndoSavedQueue : undo && root.ciderService.canUndoQueue
+ visible: noticeTimer.running && (!root.miniMode || failed)
onVisibleChanged: Qt.callLater(root.updateMask)
- z: 30; x: 65; y: 688; width: 400; height: 36; radius: 14 * theme.radius
+ 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
color: root.surface
- SpunText { x: 12; y: 2; width: 342; height: 32; text: actionNotice.text; color: actionNotice.failed ? theme.colors.error : root.ink; font.pixelSize: SpunStyle.caption; wrapMode: Text.WordWrap; verticalAlignment: Text.AlignVCenter }
- IconButton { x: 364; y: 0; width: 36; height: 36; glyphName: "close"; tip: "Dismiss"; ink: root.mutedInk; hoverFill: root.hoverFill; onClicked: noticeTimer.stop() }
+ 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 }
+ SpunButton {
+ objectName: "undoQueueButton"; visible: actionNotice.canUndo
+ x: noticeDismiss.x - width - 8; anchors.verticalCenter: parent.verticalCenter; width: 72; height: 40; enabled: actionNotice.savedUndo || root.queueControlsReady
+ text: "Undo"
+ onClicked: { noticeTimer.stop(); 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: noticeTimer.stop() }
}
component SettingsAction: MenuEntry { app: root }
component SettingsGap: MenuSeparator {
@@ -1171,13 +1534,14 @@ ApplicationWindow {
font.family: SpunStyle.family
background: Rectangle { color: SpunStyle.popup; radius: SpunStyle.popupRadius }
enter: SpunPopupEnter {}
- exit: Transition { NumberAnimation { property: "opacity"; from: 1; to: 0; duration: SpunStyle.exit } }
- onOpened: { if (root.useCider) cider.refreshModes() }
+ exit: Transition { NumberAnimation { property: "opacity"; from: 1; to: 0; duration: SpunStyle.exit; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
+ 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: "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() }
SettingsAction { objectName: "flipDiscAction"; text: root.discFlipped ? "Show artwork" : "Flip disc"; glyphName: "flip"; hint: "F"; enabled: root.deckPlayer.count > 0; onTriggered: root.flipDisc() }
SettingsAction { objectName: "miniToggle"; text: "Mini mode"; glyphName: "mini"; checkable: true; checked: player.miniMode; onTriggered: player.miniMode = !player.miniMode }
SettingsAction { objectName: "preferencesAction"; text: "Preferences"; glyphName: "settings"; onTriggered: Qt.callLater(function() { preferences.open() }) }
@@ -1197,13 +1561,13 @@ ApplicationWindow {
padding: 12
background: Rectangle { color: SpunStyle.popup; radius: SpunStyle.popupRadius }
enter: SpunPopupEnter {}
- exit: Transition { NumberAnimation { property: "opacity"; from: 1; to: 0; duration: SpunStyle.exit } }
+ exit: Transition { NumberAnimation { property: "opacity"; from: 1; to: 0; duration: SpunStyle.exit; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
onAboutToShow: fontPicker.prepare()
onAboutToHide: fontPicker.close()
- onOpened: { if (root.useCider) cider.refreshModes(); closePreferences.forceActiveFocus() }
+ onOpened: { if (root.useCider) root.ciderService.refreshModes(); closePreferences.forceActiveFocus() }
onClosed: { fontPicker.close(); menuButton.forceActiveFocus() }
contentItem: Item {
- SpunText { x: 12; y: 10; text: "Preferences"; color: root.ink; font.pixelSize: SpunStyle.heading }
+ SpunText { x: 12; y: 10; text: "Preferences"; color: root.ink; font.pixelSize: SpunStyle.heading; font.weight: Font.Medium }
IconButton { id: closePreferences; objectName: "closePreferences"; anchors.right: parent.right; glyphName: "close"; tip: "Close preferences"; ink: root.ink; onClicked: preferences.close() }
Flickable {
id: preferenceScroll
@@ -1214,6 +1578,37 @@ ApplicationWindow {
function reveal(item) { const p = item.mapToItem(preferenceItems, 0, 0); if (p.y < contentY) contentY = p.y; else if (p.y + item.height > contentY + height) contentY = p.y + item.height - height }
Column {
id: preferenceItems; width: parent.width; spacing: 4
+ Row {
+ width: parent.width; height: 48; spacing: 4
+ Repeater {
+ id: recordChoices
+ model: ["CD", "Vinyl"]
+ delegate: AbstractButton {
+ id: recordChoice
+ required property string modelData
+ objectName: modelData === "CD" ? "cdStyleButton" : "vinylStyleButton"
+ width: (preferenceItems.width - 4) / 2; height: SpunStyle.target
+ text: modelData; checkable: true; autoExclusive: true; checked: player.vinyl === (modelData === "Vinyl"); hoverEnabled: true
+ Accessible.name: modelData + " appearance"; Accessible.checked: checked
+ Keys.onLeftPressed: recordChoices.itemAt(0).forceActiveFocus(Qt.TabFocusReason)
+ Keys.onRightPressed: recordChoices.itemAt(1).forceActiveFocus(Qt.TabFocusReason)
+ Keys.onReturnPressed: clicked()
+ Keys.onEnterPressed: clicked()
+ onClicked: player.vinyl = modelData === "Vinyl"
+ onActiveFocusChanged: if(activeFocus) preferenceScroll.reveal(this)
+ background: Rectangle {
+ radius: 20 * theme.radius; color: "transparent"
+ border.width: recordChoice.visualFocus ? 2 : 0; border.color: root.accent
+ Rectangle { anchors.fill: parent; radius: parent.radius; color: SpunStyle.selected; opacity: recordChoice.checked ? 1 : 0
+ Behavior on opacity { NumberAnimation { duration: SpunStyle.feedback; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
+ }
+ SpunStateLayer { anchors.fill: parent; radius: parent.radius; color: root.ink; hovered: recordChoice.hovered; pressed: recordChoice.down; focused: recordChoice.visualFocus }
+ }
+ contentItem: SpunText { text: recordChoice.text; color: recordChoice.checked ? root.accent : root.mutedInk; font.pixelSize: SpunStyle.body; horizontalAlignment: Text.AlignHCenter; verticalAlignment: Text.AlignVCenter }
+ }
+ }
+ }
+
AbstractButton {
id: fontChoice
objectName: "fontChoice"
@@ -1224,6 +1619,7 @@ ApplicationWindow {
onActiveFocusChanged: if (activeFocus) preferenceScroll.reveal(this)
background: Rectangle {
radius: SpunStyle.rowRadius; color: "transparent"
+ border.width: fontChoice.visualFocus ? 2 : 0; border.color: root.accent
SpunStateLayer { anchors.fill: parent; radius: parent.radius; color: root.ink; hovered: fontChoice.hovered; pressed: fontChoice.down; focused: fontChoice.visualFocus }
}
contentItem: Item {
@@ -1236,9 +1632,10 @@ ApplicationWindow {
PreferenceSwitch { objectName: "blurToggle"; app: root; width: parent.width; visible: native.supportsBlur; height: visible ? implicitHeight : 0; text: "Blur background"; glyphName: "blur"; checked: player.backgroundBlur; onToggled: player.backgroundBlur = checked; onActiveFocusChanged: if (activeFocus) preferenceScroll.reveal(this) }
PreferenceSwitch { objectName: "motionToggle"; app: root; width: parent.width; text: "Animations"; glyphName: "motion"; checked: player.motion; onToggled: player.motion = checked; onActiveFocusChanged: if (activeFocus) preferenceScroll.reveal(this) }
Rectangle { x: 12; width: parent.width - 24; height: 1; color: root.hairline }
- PreferenceSwitch { objectName: "ciderAutoStartToggle"; app: root; width: parent.width; text: "Start Cider with Spun"; glyphName: "power"; checked: player.ciderAutoStart; onToggled: { player.ciderAutoStart = checked; if (checked && root.useCider) cider.ensureRunning() } onActiveFocusChanged: if (activeFocus) preferenceScroll.reveal(this) }
- PreferenceSwitch { objectName: "autoplayToggle"; app: root; width: parent.width; visible: root.useCider; height: visible ? implicitHeight : 0; text: "Autoplay"; glyphName: "autoplay"; checked: cider.autoplay; enabled: cider.modesReady && !cider.controlBusy; onToggled: cider.setAutoplay(checked); onActiveFocusChanged: if (activeFocus) preferenceScroll.reveal(this) }
- MenuEntry { objectName: "crossfadeAction"; app: root; width: parent.width; visible: root.useCider; text: "Crossfade"; glyphName: "crossfade"; onTriggered: { preferences.close(); Qt.callLater(function() { crossfadeMenu.open() }) } onActiveFocusChanged: if (activeFocus) preferenceScroll.reveal(this) }
+ PreferenceSwitch { objectName: "rememberSessionToggle"; app: root; width: parent.width; text: "Remember Cider session"; glyphName: "queue"; checked: root.listeningService.rememberSession; enabled: !root.listeningService.busy; onToggled: root.listeningService.rememberSession = checked; onActiveFocusChanged: if (activeFocus) preferenceScroll.reveal(this) }
+ PreferenceSwitch { objectName: "ciderAutoStartToggle"; app: root; width: parent.width; text: "Start Cider with Spun"; glyphName: "power"; checked: player.ciderAutoStart; onToggled: { player.ciderAutoStart = checked; if (checked && root.useCider) root.ciderService.ensureRunning() } onActiveFocusChanged: if (activeFocus) preferenceScroll.reveal(this) }
+ PreferenceSwitch { objectName: "autoplayToggle"; app: root; width: parent.width; visible: root.useCider; height: visible ? implicitHeight : 0; text: "Autoplay"; glyphName: "autoplay"; checked: root.ciderService.autoplay; enabled: root.ciderService.modesReady && !root.ciderService.controlBusy; onToggled: root.ciderService.setAutoplay(checked); onActiveFocusChanged: if (activeFocus) preferenceScroll.reveal(this) }
+ MenuEntry { objectName: "crossfadeAction"; app: root; width: parent.width; visible: root.useCider; text: "Audio settings"; glyphName: "crossfade"; onTriggered: { preferences.close(); Qt.callLater(function() { crossfadeMenu.open() }) } onActiveFocusChanged: if (activeFocus) preferenceScroll.reveal(this) }
}
}
}
@@ -1267,14 +1664,14 @@ ApplicationWindow {
id: crossfadeMenu
objectName: "crossfadeMenu"
focus: true
- property var service: cider
+ property var service: root.ciderService
popupType: Popup.Item
x: deck.x + deck.width - width; y: Math.max(12, deck.y - height - 10)
- width: 320; height: crossfadeServiceError.visible ? 246 : 170; padding: 12
+ width: 320; height: Math.max(170, audioExtras.y + audioExtras.implicitHeight + 24); padding: 12
background: Rectangle { color: SpunStyle.popup; radius: SpunStyle.popupRadius }
enter: SpunPopupEnter {}
- exit: Transition { NumberAnimation { property: "opacity"; from: 1; to: 0; duration: SpunStyle.exit } }
- onOpened: { service.refreshCrossfade() }
+ exit: Transition { NumberAnimation { property: "opacity"; from: 1; to: 0; duration: SpunStyle.exit; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
+ onOpened: { service.refreshCrossfade(); service.refreshAudioOptions() }
contentItem: Item {
PreferenceSwitch {
@@ -1293,35 +1690,52 @@ ApplicationWindow {
text: crossfadeMenu.service.crossfadeBusy ? "…" : crossfadeMenu.service.crossfadeReady ? (crossfadeDuration.pressed ? crossfadeDuration.value : crossfadeMenu.service.crossfadeSeconds) + " s" : "—"
font.pixelSize: 12; color: root.ink
}
- Slider {
+ SpunSlider {
id: crossfadeDuration; objectName: "crossfadeDuration"
x: 10; y: 78; width: parent.width - 20; height: 36
from: 1; to: 12; stepSize: 1; snapMode: Slider.SnapAlways
value: crossfadeMenu.service.crossfadeSeconds
enabled: crossfadeMenu.service.crossfadeReady && crossfadeMenu.service.crossfade && !crossfadeMenu.service.crossfadeBusy
- opacity: enabled ? 1 : .4
Accessible.name: "Crossfade duration in seconds"
onMoved: if (!pressed) crossfadeMenu.service.setCrossfadeSeconds(value)
onPressedChanged: if (!pressed && enabled) crossfadeMenu.service.setCrossfadeSeconds(value)
Connections { target: crossfadeMenu.service; function onCrossfadeChanged() { if (!crossfadeDuration.pressed) crossfadeDuration.value = crossfadeMenu.service.crossfadeSeconds } }
- background: Rectangle {
- x: crossfadeDuration.leftPadding; y: crossfadeDuration.topPadding + crossfadeDuration.availableHeight / 2 - 2
- width: crossfadeDuration.availableWidth; height: 3; radius: 2; color: root.hairline
- Rectangle { width: parent.width * crossfadeDuration.visualPosition; height: 3; radius: 2; color: root.accent }
- }
- handle: Rectangle {
- x: crossfadeDuration.leftPadding + crossfadeDuration.visualPosition * (crossfadeDuration.availableWidth - width)
- y: crossfadeDuration.topPadding + crossfadeDuration.availableHeight / 2 - height / 2
- width: 12; height: 12; radius: 6; color: root.accent
- scale: crossfadeDuration.pressed || crossfadeDuration.visualFocus ? 1.2 : 1
- Behavior on scale { NumberAnimation { duration: root.feedbackTime } }
- }
+ valueText: Math.round(value) + " s"
}
SpunText {
id: crossfadeServiceError; x: 10; y: 116; width: parent.width - 20; height: 42
visible: crossfadeMenu.service.crossfadeError.length > 0
text: crossfadeMenu.service.crossfadeError; font.pixelSize: SpunStyle.caption; color: theme.colors.error; wrapMode: Text.WordWrap
}
+ Column {
+ id: audioExtras; x: 0; y: crossfadeServiceError.visible ? 216 : 118; width: parent.width; spacing: 4
+ PreferenceSwitch {
+ objectName: "automixToggle"; app: root; width: parent.width
+ visible: crossfadeMenu.service.audioOptions.automix !== undefined
+ text: "Automix"; glyphName: "autoplay"; checked: !!crossfadeMenu.service.audioOptions.automix
+ enabled: !crossfadeMenu.service.audioBusy; onToggled: crossfadeMenu.service.setAudioOption("automix", checked)
+ }
+ SpunText { visible: crossfadeMenu.service.audioOptions.listeningMode !== undefined; x: 10; text: "Listening mode"; color: root.mutedInk; font.pixelSize: SpunStyle.caption; height: 24; verticalAlignment: Text.AlignVCenter }
+ Row {
+ visible: crossfadeMenu.service.audioOptions.listeningMode !== undefined; width: parent.width; spacing: 4
+ Repeater { model: crossfadeMenu.service.audioOptions.listeningMode !== undefined ? ["off", "gaming", "unwind"] : []
+ AbstractButton {
+ id: modeChoice; required property string modelData; objectName: "listeningMode_" + modelData
+ width: (audioExtras.width - 8) / 3; height: 40; hoverEnabled: true
+ enabled: !crossfadeMenu.service.audioBusy
+ readonly property bool selected: crossfadeMenu.service.audioOptions.listeningMode === modelData
+ text: modelData.charAt(0).toUpperCase() + modelData.slice(1)
+ onClicked: crossfadeMenu.service.setAudioOption("listeningMode", modelData)
+ background: Rectangle { radius: 20 * theme.radius; color: "transparent"
+ Rectangle { anchors.fill: parent; radius: parent.radius; color: SpunStyle.selected; opacity: modeChoice.selected ? 1 : 0; Behavior on opacity { NumberAnimation { duration: SpunStyle.feedback; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } } }
+ SpunStateLayer { anchors.fill: parent; radius: parent.radius; color: root.ink; hovered: modeChoice.hovered; pressed: modeChoice.down; focused: modeChoice.visualFocus }
+ }
+ contentItem: SpunText { text: modeChoice.text; color: modeChoice.selected ? root.accent : root.mutedInk; font.pixelSize: SpunStyle.caption; horizontalAlignment: Text.AlignHCenter; verticalAlignment: Text.AlignVCenter }
+ }
+ }
+ }
+ SettingsAction { width: parent.width; visible: crossfadeMenu.service.audioError.length > 0; text: "Refresh audio settings"; glyphName: "refresh"; enabled: !crossfadeMenu.service.audioBusy; onTriggered: crossfadeMenu.service.refreshAudioOptions(); SpunToolTip { visible: parent.hovered; text: crossfadeMenu.service.audioError } }
+ }
SettingsAction {
y: 165; width: parent.width; visible: crossfadeServiceError.visible
text: "Try again"; glyphName: "refresh"; enabled: !crossfadeMenu.service.crossfadeBusy
@@ -1338,12 +1752,12 @@ ApplicationWindow {
IconButton { x: 342; y: 7; glyphName: "close"; ink: root.mutedInk; tip: "Dismiss"; onClicked: root.deckPlayer.dismissError() }
}
Rectangle {
- x: 94; y: 146; width: 342; height: 450; radius: 22
+ x: 94; y: 110; width: 342; height: 514; radius: 22
visible: root.helpOpen; color: root.surface; border.width: 0
SpunText { x: 24; y: 23; text: "Shortcuts"; font.family: SpunStyle.family; font.pixelSize: 22; color: root.ink }
SpunText {
x: 24; y: 70; width: 294; color: root.mutedInk; font.pixelSize: 12; lineHeight: 1.55
- text: "Space Play / pause\n← / → Seek 5 seconds\nCtrl + ← / → Previous / next\n↑ / ↓ Volume\nM Mute\nCtrl + O Add music\nCtrl + L Show queue\nCtrl + F Search queue\nCtrl + M Mini / full player\nCtrl + B Browse Cider music\nCtrl + V Open music link\nF Flip disc\nY Lyrics / album tracks\n\nDouble-click to flip. Drag to move.\nScrub the outer rim to seek."
+ text: "Space Play / pause\n← / → Seek 5 seconds\nCtrl + ← / → Previous / next\n↑ / ↓ Volume\nM Mute\nCtrl + O Add music\nCtrl + L Show queue\nCtrl + F Search panel\nCtrl + K Quick jump\nCtrl + M Mini / full player\nCtrl + B Browse Cider music\nCtrl + V Open music link\nF Flip disc\nY Lyrics / album tracks\nCtrl / Shift + click Select tracks\nCtrl + A / Space Select all / toggle*\n*In a focused track list\n\nDouble-click to flip. Drag to move.\nScrub the outer rim to seek."
}
IconButton { x: 299; y: 8; glyphName: "close"; tip: "Close shortcuts"; ink: root.mutedInk; hoverFill: root.hoverFill; onClicked: root.helpOpen=false }
}
diff --git a/qml/MenuEntry.qml b/qml/MenuEntry.qml
index e1c498b..957d90f 100644
--- a/qml/MenuEntry.qml
+++ b/qml/MenuEntry.qml
@@ -12,11 +12,12 @@ MenuItem {
background: Rectangle {
radius: SpunStyle.rowRadius
color: "transparent"
+ border.width: entry.visualFocus ? 2 : 0; border.color: entry.app.accent
SpunStateLayer { anchors.fill: parent; radius: parent.radius; color: entry.app.ink; enabled: entry.enabled; pressed: entry.down; focused: entry.highlighted; hovered: entry.hovered }
}
contentItem: Item {
- opacity: entry.enabled ? 1 : .4
- Glyph { x: 12; anchors.verticalCenter: parent.verticalCenter; name: entry.glyphName; ink: entry.highlighted ? entry.app.accent : entry.app.mutedInk }
+ opacity: entry.enabled ? 1 : SpunStyle.disabledOpacity
+ Glyph { visible: entry.glyphName.length > 0; x: 12; anchors.verticalCenter: parent.verticalCenter; name: entry.glyphName; ink: entry.highlighted ? entry.app.accent : entry.app.mutedInk }
SpunText { x: 44; anchors.verticalCenter: parent.verticalCenter; width: parent.width - x - 12 - trailing.width - 8; text: entry.text; font: entry.font; color: entry.app.ink; elide: Text.ElideRight }
Item {
id: trailing
diff --git a/qml/NextTrackTip.qml b/qml/NextTrackTip.qml
new file mode 100644
index 0000000..fe7a324
--- /dev/null
+++ b/qml/NextTrackTip.qml
@@ -0,0 +1,36 @@
+import QtQuick
+import QtQuick.Controls
+
+SpunToolTip {
+ id: peek
+ required property var app
+ objectName: "nextTrackTip"
+ property bool requested: false
+ readonly property bool remote: app.useCider
+ readonly property var track: {
+ if (!visible || !requested) return ({})
+ if (remote && (!app.ciderService.queueReady || app.ciderService.queueBusy || app.ciderService.queueError.length)) return ({})
+ if (!remote && app.deckPlayer.shuffle && app.deckPlayer.count > 1) return ({})
+ const queue = app.deckPlayer.queue
+ const index = app.deckPlayer.currentIndex + 1
+ return queue[index] || (!remote && queue.length ? queue[0] : ({}))
+ }
+ readonly property string summary: track.title || (remote && app.ciderService.queueBusy ? "Checking next track…" : !remote && app.deckPlayer.shuffle && app.deckPlayer.count > 1 ? "Next track is shuffled" : remote && (!app.ciderService.queueReady || app.ciderService.queueError.length) ? "Next track unavailable" : "No upcoming track")
+ onAboutToShow: { requested = true; if (remote) app.ciderService.refreshQueue() }
+ onClosed: requested = false
+ Connections { target: peek.app.ciderService; function onTrackChanged() { if (peek.visible && peek.remote) peek.app.ciderService.refreshQueue() } }
+ implicitWidth: 264; implicitHeight: 80; padding: 12
+ contentItem: Loader {
+ active: peek.visible
+ sourceComponent: Item {
+ implicitWidth: 240; implicitHeight: 56
+ Rectangle { width: 52; height: 52; anchors.verticalCenter: parent.verticalCenter; radius: 8; color: peek.app.inset
+ Image { id: art; anchors.fill: parent; source: peek.track.artwork || ""; sourceSize: Qt.size(104,104); fillMode: Image.PreserveAspectCrop; asynchronous: true; cache: false }
+ Glyph { anchors.centerIn: parent; visible: art.status !== Image.Ready; name: "disc"; ink: peek.app.mutedInk }
+ }
+ SpunText { x: 64; y: 1; width: parent.width - 64; text: "Up next"; color: peek.app.accent; font.pixelSize: SpunStyle.caption }
+ SpunText { objectName: "nextTrackTitle"; x: 64; y: 19; width: parent.width - 64; text: peek.summary; color: peek.app.ink; font.pixelSize: SpunStyle.body; elide: Text.ElideRight }
+ SpunText { x: 64; y: 40; width: parent.width - 64; text: peek.track.artist || ""; color: peek.app.mutedInk; font.pixelSize: SpunStyle.caption; elide: Text.ElideRight }
+ }
+ }
+}
diff --git a/qml/PreferenceSwitch.qml b/qml/PreferenceSwitch.qml
index fe7321d..d04d937 100644
--- a/qml/PreferenceSwitch.qml
+++ b/qml/PreferenceSwitch.qml
@@ -16,23 +16,25 @@ Switch {
}
indicator: Rectangle {
x: control.width - width - 12; anchors.verticalCenter: parent.verticalCenter
- width: 40; height: 24; radius: 12
+ objectName: "switchTrack"
+ width: 52; height: 32; radius: 16
color: control.checked ? control.app.accent : control.app.inset
border.width: control.checked ? 0 : 2
border.color: control.app.mutedInk
- opacity: control.enabled ? 1 : .4
- Behavior on color { ColorAnimation { duration: SpunStyle.feedback } }
+ opacity: control.enabled ? 1 : SpunStyle.disabledOpacity
+ Behavior on color { ColorAnimation { duration: SpunStyle.feedback; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
Rectangle {
- SpunSpring { id: thumbPosition; targetValue: control.checked ? 19 : 5; epsilon: .1 }
- SpunSpring { id: thumbSize; targetValue: control.checked ? 18 : 14; epsilon: .1 }
- x: thumbPosition.value; anchors.verticalCenter: parent.verticalCenter
+ SpunSpring { id: thumbPosition; targetValue: control.checked ? 36 : 16; epsilon: .1 }
+ SpunSpring { id: thumbSize; targetValue: control.down ? 28 : control.checked ? 24 : 16; epsilon: .1 }
+ objectName: "switchThumb"
+ x: thumbPosition.value - width / 2; anchors.verticalCenter: parent.verticalCenter
width: thumbSize.value; height: width; radius: width / 2
color: control.checked ? theme.colors.onAccent : control.app.mutedInk
}
}
contentItem: Item {
- opacity: control.enabled ? 1 : .4
+ opacity: control.enabled ? 1 : SpunStyle.disabledOpacity
Glyph { x: 12; anchors.verticalCenter: parent.verticalCenter; name: control.glyphName; ink: control.app.mutedInk }
- SpunText { x: 44; width: control.width - x - 64; anchors.verticalCenter: parent.verticalCenter; text: control.text; font: control.font; color: control.app.ink; elide: Text.ElideRight }
+ SpunText { x: 44; width: control.width - x - 76; anchors.verticalCenter: parent.verticalCenter; text: control.text; font: control.font; color: control.app.ink; elide: Text.ElideRight }
}
}
diff --git a/qml/QuickJump.qml b/qml/QuickJump.qml
new file mode 100644
index 0000000..3e10682
--- /dev/null
+++ b/qml/QuickJump.qml
@@ -0,0 +1,133 @@
+import QtQuick
+import QtQuick.Controls
+
+Popup {
+ id: jump
+ required property var app
+ property var service: app.savedService
+ property var targets: []
+ property string query: ""
+ property string notice: ""
+ property int revision: -1
+ property bool waitingForQueue: false
+ readonly property var results: {
+ const words = query.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().trim().split(/\s+/).filter(Boolean)
+ return targets.filter(row => words.every(word => row.match.includes(word))).slice(0, 40)
+ }
+ objectName: "quickJump"
+ parent: Overlay.overlay
+ x: (parent.width - width) / 2
+ y: Math.max(12, (app.height - 430) / 2)
+ width: Math.min(440, app.width - 24)
+ height: Math.min(430, app.height - 24, Math.max(214, 126 + Math.max(1, results.length) * 66 + (notice.length ? 50 : 0)))
+ Behavior on height { NumberAnimation { duration: SpunStyle.feedback; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.standardCurve } }
+ padding: 16; focus: true; modal: true; dim: false; popupType: Popup.Item
+ background: Rectangle { radius: SpunStyle.popupRadius; color: SpunStyle.popup }
+ enter: SpunPopupEnter {}
+ exit: Transition { NumberAnimation { property: "opacity"; to: 0; duration: SpunStyle.exit; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
+ function show(preserveQuery) {
+ const saved = service.savedQueueChoices()
+ notice = saved.error || ""; if (!preserveQuery) query = ""
+ const rows = []
+ const add = (kind, key, title, subtitle, artwork, index, identity) => rows.push({kind: kind, key: key, title: title || "Untitled", subtitle: subtitle, artwork: artwork || "", index: index, identity: identity || "", match: ((title || "") + " " + subtitle).normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase()})
+ for (const row of service.pins) add("pin", row.path, row.title, row.type === "artists" ? "Pinned artist" : row.type === "stations" ? "Pinned station" : row.type.includes("albums") ? "Pinned album · " + (row.artist || "") : "Pinned playlist", row.artwork, -1)
+ for (const row of saved.rows || []) add("saved", row.id, row.title, "Saved queue · " + row.trackCount + (row.trackCount === 1 ? " track" : " tracks"), "", -1)
+ for (const row of app.listeningService.bookmarks) add("bookmark", row.key, row.title, "Bookmark · " + app.time(row.position) + " · " + (row.artist || ""), row.artwork, -1)
+ if (app.listeningService.session.trackCount) add("recovery", "", "Recover listening session", app.listeningService.session.title || "", "", -1)
+ targets = rows; open()
+ if (app.useCider) { waitingForQueue = true; app.ciderService.refreshQueue(); receiveQueue() }
+ else addQueue()
+ }
+ function addQueue() {
+ const rows = targets.filter(row => row.kind !== "queue")
+ const queue = app.deckPlayer.queue
+ revision = app.useCider ? app.ciderService.queueRevision : -1
+ for (let i = 0; i < queue.length; i++) {
+ const row = queue[i], title = row.title || "Untitled", subtitle = "Queue · " + (row.artist || "")
+ rows.push({kind: "queue", key: "", title: title, subtitle: subtitle, artwork: row.artwork || "", index: i, identity: app.useCider ? row.type + ":" + row.id : row.path, match: (title + " " + subtitle).normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase()})
+ }
+ targets = rows
+ }
+ function receiveQueue() {
+ if (!visible || !waitingForQueue || app.ciderService.queueBusy || app.ciderService.controlBusy) return
+ waitingForQueue = false
+ if (app.ciderService.queueReady && !app.ciderService.queueError.length) addQueue()
+ else notice = "Queue unavailable. Your pins and saved queues are still here."
+ }
+ Connections { target: jump.app.ciderService; function onQueueStatusChanged() { jump.receiveQueue() } }
+
+ function activate(row) {
+ if (!visible || !row) return
+ if (row.kind === "queue") {
+ if (app.useCider && (revision !== app.ciderService.queueRevision || !app.queueControlsReady)) { notice = "Queue changed. Refresh before choosing a song."; return }
+ const current = app.deckPlayer.queue[row.index]
+ if (!current || (app.useCider ? current.type + ":" + current.id : current.path) !== row.identity) { notice = "Queue changed. Refresh before choosing a song."; return }
+ close(); app.deckPlayer.select(row.index)
+ if (!app.miniMode) app.revealQueueTrack(row.index)
+ } else if (row.kind === "bookmark") {
+ if (app.actionService.busy || app.ciderService.controlBusy || app.listeningService.busy) { notice = "Cider is busy. Try again when it finishes."; return }
+ close(); app.useCider = true; app.listeningService.playBookmark(row.key)
+ } else if (row.kind === "recovery") {
+ close(); app.useCider = true; app.showRecovery()
+ } else {
+ const kind = row.kind, key = row.key
+ close(); app.useCider = true; app.libraryOpen = true; service.openQuickTarget(kind, key)
+ }
+ }
+ onClosed: { waitingForQueue = false; targets = []; query = ""; notice = "" }
+ contentItem: Loader {
+ active: jump.visible
+ sourceComponent: Item {
+ Component.onCompleted: Qt.callLater(function() { search.forceActiveFocus() })
+ SpunText { text: "Quick jump"; color: jump.app.ink; font.pixelSize: SpunStyle.heading; font.weight: Font.Medium }
+ IconButton { x: parent.width - 36; y: -8; width: 36; height: 36; glyphName: "close"; tip: "Close · Esc"; ink: jump.app.mutedInk; onClicked: jump.close() }
+ SpunSearchField {
+ id: search; objectName: "quickJumpSearch"; app: jump.app
+ y: 40; width: parent.width; placeholderText: "Find music…"; maximumLength: 160
+ text: jump.query; onTextEdited: { jump.query = text; choices.currentIndex = 0 }
+ onAccepted: jump.activate(jump.results[choices.currentIndex])
+ Keys.onDownPressed: { choices.currentIndex = Math.min(choices.count - 1, choices.currentIndex + 1); choices.positionViewAtIndex(choices.currentIndex, ListView.Contain) }
+ Keys.onUpPressed: { choices.currentIndex = Math.max(0, choices.currentIndex - 1); choices.positionViewAtIndex(choices.currentIndex, ListView.Contain) }
+ IconButton { anchors.right: parent.right; anchors.verticalCenter: parent.verticalCenter; width: 36; height: 36; visible: search.text.length > 0; glyphName: "close"; tip: "Clear search"; ink: jump.app.mutedInk; onClicked: { search.clear(); jump.query = ""; choices.currentIndex = 0; search.forceActiveFocus() } }
+ }
+ ListView {
+ id: choices; objectName: "quickJumpResults"
+ y: 94; width: parent.width; height: parent.height - y - (jump.notice.length ? 50 : 0)
+ model: jump.results; currentIndex: 0; clip: true; spacing: 4; boundsBehavior: Flickable.StopAtBounds
+ activeFocusOnTab: true
+ Keys.onReturnPressed: jump.activate(jump.results[currentIndex])
+ Keys.onEnterPressed: jump.activate(jump.results[currentIndex])
+ ScrollBar.vertical: ScrollBar {}
+ delegate: AbstractButton {
+ id: row
+ required property int index
+ required property var modelData
+ objectName: "quickJumpRow" + index
+ width: choices.width; height: 62; hoverEnabled: true
+ Accessible.name: modelData.title + ", " + modelData.subtitle
+ Accessible.selectable: true; Accessible.selected: row.index === choices.currentIndex
+ onClicked: jump.activate(modelData)
+ background: Rectangle {
+ radius: SpunStyle.rowRadius; color: row.index === choices.currentIndex ? SpunStyle.selected : "transparent"
+ border.width: row.visualFocus || (choices.activeFocus && row.index === choices.currentIndex) ? 2 : 0
+ border.color: jump.app.accent
+ Behavior on color { ColorAnimation { duration: SpunStyle.feedback; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
+ SpunStateLayer { anchors.fill: parent; radius: parent.radius; color: jump.app.ink; hovered: row.hovered; pressed: row.down; focused: row.visualFocus }
+ }
+ contentItem: Item {
+ Rectangle { x: 8; y: 9; width: 44; height: 44; radius: 8; color: jump.app.inset
+ Image { id: art; anchors.fill: parent; source: row.modelData.artwork; sourceSize: Qt.size(88,88); asynchronous: true; cache: false; fillMode: Image.PreserveAspectCrop }
+ Glyph { anchors.centerIn: parent; visible: art.status !== Image.Ready; name: row.modelData.kind === "queue" || row.modelData.kind === "saved" ? "queue" : "disc"; ink: jump.app.mutedInk }
+ }
+ IconButton { objectName: "removeBookmark" + row.index; anchors.right: parent.right; anchors.verticalCenter: parent.verticalCenter; width: 36; height: 36; visible: row.modelData.kind === "bookmark"; glyphName: "close"; ink: jump.app.mutedInk; tip: "Remove bookmark"; enabled: !jump.app.listeningService.busy; onClicked: { jump.app.listeningService.removeBookmark(row.modelData.key); jump.show(true) } }
+ SpunText { objectName: "quickJumpTitle" + row.index; height: 20; maximumLineCount: 1; x: 64; y: 9; width: parent.width - (row.modelData.kind === "bookmark" ? 112 : 76); text: row.modelData.title; color: jump.app.ink; font.pixelSize: SpunStyle.body; elide: Text.ElideRight }
+ SpunText { height: 16; maximumLineCount: 1; x: 64; y: 33; width: parent.width - (row.modelData.kind === "bookmark" ? 112 : 76); text: row.modelData.subtitle; color: jump.app.mutedInk; font.pixelSize: SpunStyle.caption; elide: Text.ElideRight }
+ }
+ }
+ SpunText { objectName: "quickJumpEmptyState"; anchors.centerIn: parent; width: parent.width - 24; visible: choices.count === 0; text: jump.waitingForQueue ? "Loading queue…" : jump.query.trim().length ? "No matches" : "Your pins, bookmarks, saved queues and loaded queue appear here."; wrapMode: Text.WordWrap; horizontalAlignment: Text.AlignHCenter; color: jump.app.mutedInk; font.pixelSize: SpunStyle.body }
+ }
+ SpunText { anchors.bottom: parent.bottom; height: 42; width: parent.width - 44; text: jump.notice; visible: text.length > 0; wrapMode: Text.WordWrap; font.pixelSize: SpunStyle.caption; color: jump.app.mutedInk }
+ IconButton { anchors.right: parent.right; anchors.bottom: parent.bottom; visible: jump.notice.length > 0; glyphName: "refresh"; tip: "Refresh Quick jump"; ink: jump.app.accent; objectName: "quickJumpRefresh"; onClicked: jump.show(true) }
+ }
+ }
+}
diff --git a/qml/SavedQueuePicker.qml b/qml/SavedQueuePicker.qml
new file mode 100644
index 0000000..c3841f3
--- /dev/null
+++ b/qml/SavedQueuePicker.qml
@@ -0,0 +1,101 @@
+import QtQuick
+import QtQuick.Controls
+
+Popup {
+ id: picker
+ required property var app
+ property var service: null
+ property var tracks: []
+ property var rows: []
+ property var selected: ({})
+ property string error: ""
+ property bool skipDuplicates: true
+ objectName: "savedQueuePicker"
+ popupType: Popup.Item; focus: true; modal: true; dim: true; padding: 24
+ parent: Overlay.overlay
+ anchors.centerIn: parent
+ width: Math.min(360, app.width - 32)
+ height: Math.min(438, Math.max(310, 252 + rows.length * 62), app.height - 48)
+ background: Rectangle { color: SpunStyle.popup; radius: SpunStyle.dialogRadius }
+ Overlay.modal: Rectangle { color: Qt.alpha("black", .32) }
+ enter: SpunPopupEnter {}
+ exit: Transition { NumberAnimation { property: "opacity"; from: 1; to: 0; duration: SpunStyle.exit; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
+ function refresh() {
+ const result = service.savedQueueChoices()
+ rows = result.rows || []; error = result.error || ""; selected = ({})
+ }
+ function show(songs, source) { tracks = songs.slice(); service = source; skipDuplicates = true; refresh(); open() }
+ function selectRow(index) {
+ if (index < 0 || index >= rows.length) return
+ selected = Object.assign({}, rows[index]); error = ""
+ }
+ function submit() {
+ if (!selected.id || !tracks.length) return
+ const result = service.appendSavedQueue(selected, tracks, skipDuplicates)
+ if (result.ok) close()
+ else error = result.error || "Couldn’t update this saved queue. Try again."
+ }
+ onOpened: if (contentItem.item) contentItem.item.focusFirst()
+ onClosed: { tracks = []; rows = []; selected = ({}); error = "" }
+ contentItem: Loader {
+ active: picker.visible
+ sourceComponent: Item {
+ function focusFirst() { closePicker.forceActiveFocus(Qt.TabFocusReason) }
+ IconButton { id: closePicker; objectName: "closeSavedQueuePicker"; x: parent.width - 40; y: -8; glyphName: "close"; tip: "Close"; ink: picker.app.mutedInk; onClicked: picker.close() }
+ SpunText { text: "Add to saved queue"; color: picker.app.ink; font.pixelSize: SpunStyle.heading; font.weight: Font.Medium }
+ SpunText { y: 30; text: picker.tracks.length + (picker.tracks.length === 1 ? " song selected" : " songs selected"); color: picker.app.mutedInk; font.pixelSize: SpunStyle.caption }
+ ListView {
+ id: choices; objectName: "savedQueueChoices"
+ y: 62; width: parent.width; height: Math.max(60, parent.height - 212)
+ clip: true; model: picker.rows; spacing: 4; boundsBehavior: Flickable.StopAtBounds
+ currentIndex: -1; activeFocusOnTab: true
+ Keys.onReturnPressed: picker.selectRow(currentIndex)
+ Keys.onEnterPressed: picker.selectRow(currentIndex)
+ Keys.onSpacePressed: picker.selectRow(currentIndex)
+ ScrollBar.vertical: ScrollBar {}
+ delegate: AbstractButton {
+ id: choice
+ required property int index
+ required property var modelData
+ objectName: "savedQueueChoice" + index
+ width: choices.width; height: 58; hoverEnabled: true
+ Accessible.name: modelData.title + ", " + modelData.trackCount + " tracks"
+ Accessible.checkable: true; Accessible.checked: picker.selected.id === modelData.id
+ onClicked: { choices.currentIndex = index; picker.selectRow(index) }
+ background: Rectangle {
+ border.width: choice.visualFocus || (choices.activeFocus && choices.currentIndex === choice.index) ? 2 : 0
+ border.color: picker.app.accent
+ radius: SpunStyle.rowRadius; color: picker.selected.id === choice.modelData.id ? SpunStyle.selected : "transparent"
+ Behavior on color { ColorAnimation { duration: SpunStyle.feedback; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
+ SpunStateLayer { anchors.fill: parent; radius: parent.radius; color: picker.app.ink; pressed: choice.down; hovered: choice.hovered; focused: choice.visualFocus || (choices.activeFocus && choices.currentIndex === choice.index) }
+ }
+ contentItem: Item {
+ SpunText { height: 20; maximumLineCount: 1; x: 12; y: 8; width: parent.width - 54; text: choice.modelData.title; color: picker.app.ink; font.pixelSize: SpunStyle.body; elide: Text.ElideRight }
+ SpunText { x: 12; y: 31; text: choice.modelData.trackCount + (choice.modelData.trackCount === 1 ? " track" : " tracks"); color: picker.app.mutedInk; font.pixelSize: SpunStyle.caption }
+ Glyph { visible: picker.selected.id === choice.modelData.id; anchors.right: parent.right; anchors.rightMargin: 12; anchors.verticalCenter: parent.verticalCenter; name: "check"; ink: picker.app.accent }
+ }
+ }
+ SpunText { anchors.centerIn: parent; width: parent.width - 24; visible: !choices.count; text: picker.error.length ? "" : "No saved queues yet. Save one from Queue → ⋯."; color: picker.app.mutedInk; font.pixelSize: SpunStyle.body; wrapMode: Text.WordWrap; horizontalAlignment: Text.AlignHCenter }
+ }
+ CheckBox {
+ id: skip; objectName: "skipSavedDuplicates"
+ y: choices.y + choices.height + 10; width: parent.width; height: 40
+ text: "Skip duplicates"; checked: picker.skipDuplicates; onToggled: picker.skipDuplicates = checked
+ spacing: 12; padding: 8; hoverEnabled: true
+ Accessible.name: text
+ indicator: Rectangle {
+ x: 8; anchors.verticalCenter: parent.verticalCenter; width: 20; height: 20; radius: 4
+ color: skip.checked ? picker.app.accent : "transparent"; border.width: skip.checked ? 0 : 2; border.color: picker.app.mutedInk
+ Behavior on color { ColorAnimation { duration: SpunStyle.feedback; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
+ Glyph { anchors.centerIn: parent; width: 16; height: 16; visible: skip.checked; name: "check"; ink: theme.colors.onAccent }
+ }
+ contentItem: SpunText { leftPadding: 32; text: skip.text; color: picker.app.ink; font.pixelSize: SpunStyle.body; verticalAlignment: Text.AlignVCenter }
+ background: SpunStateLayer { radius: SpunStyle.rowRadius; color: picker.app.ink; pressed: skip.down; hovered: skip.hovered; focused: skip.visualFocus }
+ }
+ SpunText { objectName: "savedQueueError"; y: skip.y + skip.height + 4; width: parent.width - 44; height: 42; text: picker.error; color: theme.colors.error; font.pixelSize: SpunStyle.caption; wrapMode: Text.WordWrap; elide: Text.ElideRight }
+ IconButton { objectName: "refreshSavedQueueChoices"; visible: picker.error.length > 0; x: parent.width - width; y: skip.y + skip.height + 4; glyphName: "refresh"; tip: "Refresh saved queues"; ink: picker.app.accent; onClicked: picker.refresh() }
+ SpunButton { objectName: "cancelSavedQueuePicker"; x: parent.width - 188; y: parent.height - 40; width: 80; text: "Cancel"; onClicked: picker.close() }
+ SpunButton { objectName: "appendSavedQueueConfirm"; x: parent.width - width; y: parent.height - 40; width: 100; tonal: true; text: "Add songs"; enabled: !!picker.selected.id && !picker.error.length; onClicked: picker.submit() }
+ }
+ }
+}
diff --git a/qml/SpunButton.qml b/qml/SpunButton.qml
new file mode 100644
index 0000000..d2dd60e
--- /dev/null
+++ b/qml/SpunButton.qml
@@ -0,0 +1,31 @@
+import QtQuick
+import QtQuick.Controls
+
+Button {
+ id: control
+ property bool tonal: false
+ implicitWidth: Math.max(64, contentItem.implicitWidth + 32)
+ implicitHeight: SpunStyle.target
+ horizontalPadding: 16
+ hoverEnabled: true
+ focusPolicy: Qt.StrongFocus
+ Accessible.name: text
+ contentItem: SpunText {
+ text: control.text
+ font.pixelSize: SpunStyle.body; font.weight: Font.Medium
+ color: theme.colors.accent
+ horizontalAlignment: Text.AlignHCenter; verticalAlignment: Text.AlignVCenter
+ opacity: control.enabled ? 1 : SpunStyle.disabledOpacity
+ }
+ background: Rectangle {
+ SpunSpring { id: corner; targetValue: control.down ? 12 * theme.radius : control.height / 2 * theme.radius }
+ radius: corner.value
+ color: control.tonal ? SpunStyle.selected : "transparent"
+ opacity: control.enabled ? 1 : SpunStyle.disabledOpacity
+ border.width: control.visualFocus ? 2 : 0; border.color: theme.colors.accent
+ SpunStateLayer {
+ anchors.fill: parent; radius: parent.radius; color: theme.colors.accent
+ enabled: control.enabled; hovered: control.hovered; pressed: control.down; focused: control.visualFocus
+ }
+ }
+}
diff --git a/qml/SpunPopupEnter.qml b/qml/SpunPopupEnter.qml
index 002bd3e..e86e74c 100644
--- a/qml/SpunPopupEnter.qml
+++ b/qml/SpunPopupEnter.qml
@@ -2,7 +2,7 @@ import QtQuick
Transition {
ParallelAnimation {
- NumberAnimation { property: "opacity"; from: 0; to: 1; duration: SpunStyle.feedback; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.standardCurve }
+ NumberAnimation { property: "opacity"; from: 0; to: 1; duration: SpunStyle.feedback; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve }
NumberAnimation { property: "scale"; from: SpunStyle.motion ? .97 : 1; to: 1; duration: SpunStyle.enter; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.enterCurve }
}
}
diff --git a/qml/SpunSearchField.qml b/qml/SpunSearchField.qml
index e7f859e..a7a5cad 100644
--- a/qml/SpunSearchField.qml
+++ b/qml/SpunSearchField.qml
@@ -3,16 +3,18 @@ import QtQuick.Controls
TextField {
id: field
required property var app
+ property bool searchIcon: true
+ Accessible.name: placeholderText
implicitHeight: SpunStyle.target
font.family: SpunStyle.family; font.pixelSize: SpunStyle.body
color: app.ink; placeholderTextColor: app.mutedInk
selectionColor: app.accent; selectedTextColor: theme.colors.onAccent
- leftPadding: 40; rightPadding: 40
+ leftPadding: searchIcon ? 40 : 16; rightPadding: 40
background: Rectangle {
color: field.app.inset
SpunStateLayer { anchors.fill: parent; radius: parent.radius; color: field.app.ink; focused: field.activeFocus; hovered: field.hovered }
radius: height / 2 * theme.radius
border.width: field.activeFocus ? 2 : 0; border.color: field.app.accent
}
- Glyph { x: SpunStyle.textGap; anchors.verticalCenter: parent.verticalCenter; width: SpunStyle.smallIcon; height: width; name: "search"; ink: field.app.mutedInk }
+ Glyph { visible: field.searchIcon; x: SpunStyle.textGap; anchors.verticalCenter: parent.verticalCenter; width: SpunStyle.smallIcon; height: width; name: "search"; ink: field.app.mutedInk }
}
diff --git a/qml/SpunSlider.qml b/qml/SpunSlider.qml
new file mode 100644
index 0000000..6073f40
--- /dev/null
+++ b/qml/SpunSlider.qml
@@ -0,0 +1,46 @@
+import QtQuick
+import QtQuick.Controls
+
+// Compact desktop slider: shared bar handle, separated tracks and keyboard focus.
+Slider {
+ id: control
+ implicitHeight: SpunStyle.target
+ padding: 4
+ hoverEnabled: true
+ focusPolicy: Qt.StrongFocus
+ property string valueText: Math.round(value * 100) + "%"
+ background: Item {
+ x: control.leftPadding; y: control.topPadding
+ width: control.availableWidth; height: control.availableHeight
+ readonly property real center: control.visualPosition * (width - 4) + 2
+ opacity: control.enabled ? 1 : SpunStyle.disabledOpacity
+ Rectangle {
+ anchors.verticalCenter: parent.verticalCenter
+ width: Math.max(0, parent.center - 5); height: 4; radius: 2
+ color: control.mirrored ? theme.colors.outline : theme.colors.accent
+ }
+ Rectangle {
+ anchors.verticalCenter: parent.verticalCenter
+ x: Math.min(parent.width, parent.center + 5); width: parent.width - x; height: 4; radius: 2
+ color: control.mirrored ? theme.colors.accent : theme.colors.outline
+ }
+ Rectangle {
+ anchors.verticalCenter: parent.verticalCenter
+ x: control.mirrored ? 0 : parent.width - width
+ width: 3; height: 3; radius: 1.5; color: theme.colors.accent
+ visible: control.position < .95
+ }
+ }
+ handle: Rectangle {
+ x: control.leftPadding + control.visualPosition * (control.availableWidth - 4)
+ y: control.topPadding + (control.availableHeight - height) / 2
+ width: 4; height: control.pressed ? 20 : 16; radius: 2
+ color: theme.colors.accent; opacity: control.enabled ? 1 : SpunStyle.disabledOpacity
+ Behavior on height { NumberAnimation { duration: SpunStyle.feedback; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
+ Rectangle {
+ anchors.centerIn: parent; width: 16; height: 28; radius: 8
+ color: "transparent"; border.width: control.visualFocus ? 2 : 0; border.color: theme.colors.accent
+ }
+ }
+ SpunToolTip { visible: control.enabled && (control.pressed || control.visualFocus); delay: 0; text: control.valueText }
+}
diff --git a/qml/SpunStateLayer.qml b/qml/SpunStateLayer.qml
index 69e09eb..4c56d1e 100644
--- a/qml/SpunStateLayer.qml
+++ b/qml/SpunStateLayer.qml
@@ -9,8 +9,8 @@ Rectangle {
color: theme.colors.text
// Keep RGB fixed. Interpolating transparent black into a light hover color
// creates a dark intermediate flash, especially on light surfaces.
- opacity: enabled ? (pressed || focused ? .12 : hovered ? .08 : 0) : 0
+ opacity: enabled ? (pressed ? SpunStyle.pressOpacity : focused ? SpunStyle.focusOpacity : hovered ? SpunStyle.hoverOpacity : 0) : 0
Behavior on opacity {
- NumberAnimation { duration: SpunStyle.feedback; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.standardCurve }
+ NumberAnimation { duration: SpunStyle.feedback; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve }
}
}
diff --git a/qml/SpunStyle.qml b/qml/SpunStyle.qml
index 4bbc635..058e5c9 100644
--- a/qml/SpunStyle.qml
+++ b/qml/SpunStyle.qml
@@ -4,7 +4,7 @@ QtObject {
readonly property string family: typography.family
readonly property int caption: 12
readonly property int body: 14
- readonly property int heading: 18
+ readonly property int heading: 16
readonly property int title: 22
readonly property int smallGap: 4
readonly property int gap: 8
@@ -12,20 +12,28 @@ QtObject {
readonly property int inset: 16
readonly property int outerInset: 24
readonly property int target: 40
- readonly property int icon: 22
+ readonly property int icon: 24
readonly property int smallIcon: 20
readonly property int trackHeight: 64
readonly property int artwork: 40
readonly property real rowRadius: 12 * theme.radius
readonly property real popupRadius: 16 * theme.radius
- readonly property real panelRadius: 24 * theme.radius
+ readonly property real panelRadius: 28 * theme.radius
+ readonly property real dialogRadius: 28 * theme.radius
+ readonly property real disabledOpacity: .38
+ readonly property real hoverOpacity: .08
+ readonly property real focusOpacity: .10
+ readonly property real pressOpacity: .10
readonly property bool motion: player.motion && theme.motionScale > 0
- readonly property int feedback: motion ? Math.round(100 * theme.motionScale) : 0
+ readonly property int feedback: motion ? Math.round(150 * theme.motionScale) : 0
readonly property int enter: motion ? Math.round(200 * theme.motionScale) : 0
readonly property int exit: motion ? Math.round(100 * theme.motionScale) : 0
readonly property int navigate: motion ? Math.round(250 * theme.motionScale) : 0
readonly property int hero: motion ? Math.round(350 * theme.motionScale) : 0
// Material's bounded effects and emphasized entrance/exit easing, in Qt's cubic format.
+ // M3 motion physics: effects stay bounded; spatial feedback uses springs.
+ // Official fast-effects curve approximation, used for color/opacity.
+ readonly property var effectsCurve: [0.31, 0.94, 0.34, 1, 1, 1]
readonly property var standardCurve: [0.2, 0, 0, 1, 1, 1]
readonly property var enterCurve: [0.05, 0.7, 0.1, 1, 1, 1]
readonly property var exitCurve: [0.3, 0, 0.8, 0.15, 1, 1]
diff --git a/qml/SpunText.qml b/qml/SpunText.qml
index 20083c6..153f5e4 100644
--- a/qml/SpunText.qml
+++ b/qml/SpunText.qml
@@ -1,5 +1,7 @@
import QtQuick
Text {
+ textFormat: Text.PlainText
font.family: SpunStyle.family
+ font.pixelSize: SpunStyle.body
}
diff --git a/qml/SpunToolTip.qml b/qml/SpunToolTip.qml
index 7feb464..b66c080 100644
--- a/qml/SpunToolTip.qml
+++ b/qml/SpunToolTip.qml
@@ -36,6 +36,6 @@ ToolTip {
radius: SpunStyle.rowRadius
border.width: 0
}
- enter: Transition { NumberAnimation { property: "opacity"; from: 0; to: 1; duration: SpunStyle.feedback; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.standardCurve } }
- exit: Transition { NumberAnimation { property: "opacity"; from: 1; to: 0; duration: SpunStyle.exit } }
+ enter: Transition { NumberAnimation { property: "opacity"; from: 0; to: 1; duration: SpunStyle.feedback; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
+ exit: Transition { NumberAnimation { property: "opacity"; from: 1; to: 0; duration: SpunStyle.exit; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
}
diff --git a/qml/Tonearm.qml b/qml/Tonearm.qml
new file mode 100644
index 0000000..1c1a315
--- /dev/null
+++ b/qml/Tonearm.qml
@@ -0,0 +1,73 @@
+import QtQuick
+
+// Decorative scene-graph geometry: no images, effects, timers or pointer handlers.
+Item {
+ id: arm
+ objectName: "vinylTonearm"
+ required property var app
+ readonly property bool motion: app.animate && visible && app.visible && native.exposed
+ readonly property bool engaged: visible && app.deckPlayer.count > 0 && app.deckPlayer.playing
+ property real lowered: engaged ? 1 : 0
+ property real groove: Math.max(0, Math.min(1, app.progress))
+ readonly property real armAngle: -4 + lowered * (10 + 20 * groove)
+ readonly property color gold: Qt.tint("#c6a25a", Qt.alpha(app.accent, .12))
+ readonly property color glint: Qt.lighter(gold, 1.5)
+ readonly property color shade: Qt.darker(gold, 1.6)
+ Behavior on lowered {
+ enabled: arm.motion
+ NumberAnimation { id: liftMotion; duration: SpunStyle.hero; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.standardCurve }
+ }
+ Behavior on groove {
+ enabled: arm.motion && arm.engaged
+ NumberAnimation { id: grooveMotion; duration: SpunStyle.navigate; easing.type: Easing.Linear }
+ }
+ onMotionChanged: if (!motion) {
+ liftMotion.complete(); grooveMotion.complete()
+ }
+ // The pivot rests at the record's edge; the stylus stays outside the label.
+ Item {
+ x: 378; y: 100
+ Rectangle { x: -15; y: -13; width: 30; height: 30; radius: 15; color: "#50000000" }
+ Rectangle {
+ x: -13; y: -13; width: 26; height: 26; radius: 13
+ color: arm.app.surface; border.width: 1; border.color: arm.shade
+ }
+ Item {
+ objectName: "tonearmShaft"
+ rotation: arm.armAngle
+ transformOrigin: Item.TopLeft
+ // A displaced hard shadow makes the lift legible without a blur pass.
+ Rectangle { x: 1 + (1 - arm.lowered) * 2; y: 5; width: 7; height: 187; radius: 3.5; color: "#48000000" }
+ Rectangle { x: (1 - arm.lowered) * 2; y: 188; width: 14; height: 24; radius: 4; color: "#48000000" }
+ Rectangle {
+ x: -7; y: -14; width: 14; height: 22; radius: 5
+ gradient: Gradient {
+ GradientStop { position: 0; color: arm.shade }
+ GradientStop { position: .4; color: arm.glint }
+ GradientStop { position: 1; color: arm.gold }
+ }
+ }
+ Rectangle {
+ x: -3; y: 0; width: 6; height: 187; radius: 3
+ gradient: Gradient {
+ orientation: Gradient.Horizontal
+ GradientStop { position: 0; color: arm.shade }
+ GradientStop { position: .36; color: arm.glint }
+ GradientStop { position: .65; color: arm.gold }
+ GradientStop { position: 1; color: arm.shade }
+ }
+ }
+ Rectangle { x: -4; y: 178; width: 8; height: 10; radius: 2; color: arm.gold }
+ Rectangle {
+ x: -7; y: 185; width: 14; height: 24; radius: 4
+ color: Qt.tint(arm.app.surface, Qt.alpha(arm.gold, .15))
+ border.width: 1; border.color: arm.gold
+ Rectangle { x: 4; y: 5; width: 6; height: 2; radius: 1; color: arm.gold }
+ Rectangle { x: 4; y: 10; width: 6; height: 2; radius: 1; color: arm.gold }
+ Rectangle { x: 6; y: 23; width: 2; height: 5; radius: 1; color: arm.glint }
+ }
+ }
+ Rectangle { x: -7; y: -7; width: 14; height: 14; radius: 7; color: arm.gold; border.width: 1; border.color: arm.glint }
+ Rectangle { x: -3; y: -1; width: 6; height: 2; radius: 1; rotation: -35; color: arm.shade }
+ }
+}
diff --git a/qml/TrackContent.qml b/qml/TrackContent.qml
index c5e7281..ba05bd6 100644
--- a/qml/TrackContent.qml
+++ b/qml/TrackContent.qml
@@ -1,14 +1,20 @@
import QtQuick
+import QtQuick.Controls
Item {
id: content
required property var app
+ property real leadingInset: SpunStyle.outerInset
+ property real trailingInset: SpunStyle.target + SpunStyle.gap
+ property bool artistLink: false
+ signal artistClicked()
+ signal selectionRequested(int modifiers)
property string title: ""
property string subtitle: ""
property url artwork: ""
property string artworkName: ""
property string fallback: "disc"
Rectangle {
- x: SpunStyle.outerInset; anchors.verticalCenter: parent.verticalCenter
+ x: content.leadingInset; anchors.verticalCenter: parent.verticalCenter
width: SpunStyle.artwork; height: width; radius: 8 * theme.radius; color: content.app.inset
Glyph { anchors.centerIn: parent; name: content.fallback; ink: content.app.mutedInk }
Image {
@@ -19,18 +25,39 @@ Item {
}
}
Column {
- x: SpunStyle.outerInset + SpunStyle.artwork + SpunStyle.textGap
- width: parent.width - x - SpunStyle.target - SpunStyle.gap
+ x: content.leadingInset + SpunStyle.artwork + SpunStyle.textGap
+ width: parent.width - x - content.trailingInset
anchors.verticalCenter: parent.verticalCenter; spacing: 2
+ // Grow the artist target downward, preserving text baselines and the
+ // primary row's center hit area above it.
+ anchors.verticalCenterOffset: 4
SpunText {
+ objectName: content.artworkName + "Title"
+ height: 20; maximumLineCount: 1
width: parent.width; text: content.title; color: content.app.ink
font.family: SpunStyle.family; font.pixelSize: SpunStyle.body
lineHeightMode: Text.FixedHeight; lineHeight: 20; elide: Text.ElideRight
}
- SpunText {
- width: parent.width; text: content.subtitle; color: content.app.mutedInk
- font.family: SpunStyle.family; font.pixelSize: SpunStyle.caption
- lineHeightMode: Text.FixedHeight; lineHeight: 16; elide: Text.ElideRight
+ AbstractButton {
+ id: artistButton
+ objectName: content.artworkName + "Artist"
+ width: parent.width; height: 24; enabled: content.artistLink; hoverEnabled: true
+ focusPolicy: Qt.StrongFocus
+ Accessible.name: content.artistLink ? "View artist " + content.subtitle : content.subtitle
+ background: null
+ onClicked: content.artistClicked()
+ MouseArea { anchors.fill: parent; onClicked: mouse => {
+ if (mouse.modifiers & (Qt.ControlModifier | Qt.ShiftModifier)) content.selectionRequested(mouse.modifiers)
+ else content.artistClicked()
+ } }
+ contentItem: SpunText {
+ maximumLineCount: 1
+ text: content.subtitle; color: content.artistLink && (artistButton.hovered || artistButton.visualFocus) ? content.app.accent : content.app.mutedInk
+ font.family: SpunStyle.family; font.pixelSize: SpunStyle.caption; font.underline: content.artistLink && (artistButton.hovered || artistButton.visualFocus)
+ lineHeightMode: Text.FixedHeight; lineHeight: 16; elide: Text.ElideRight
+ verticalAlignment: Text.AlignTop
+ Behavior on color { ColorAnimation { duration: SpunStyle.feedback; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
+ }
}
}
}
diff --git a/qml/TrackMenu.qml b/qml/TrackMenu.qml
index dc6542d..db832c0 100644
--- a/qml/TrackMenu.qml
+++ b/qml/TrackMenu.qml
@@ -5,6 +5,18 @@ Menu {
id: menu
required property var app
property var selection: ({})
+ property int savedTrackIndex: -1
+ signal selectRequested()
+ property var selectionBatch: []
+ property bool confirmDelete: false
+ readonly property var radioService: pinService || library
+ readonly property bool radioCandidate: !batch && (currentSong || (!!selection.type && selection.type.endsWith("songs")))
+ onOpened: { confirmDelete = false; if (radioCandidate) radioService.prepareRadio(selection, currentSong) }
+ readonly property bool session: selection.type === "saved-queues"
+ readonly property bool artist: selection.type === "artists"
+ readonly property bool station: selection.type === "stations"
+ readonly property bool batch: selectionBatch.length > 0
+ property var pinService: null
property bool currentSong: false
readonly property var service: app.actionService
popupType: Popup.Item
@@ -13,19 +25,124 @@ Menu {
font.family: SpunStyle.family
background: Rectangle { color: SpunStyle.popup; radius: SpunStyle.popupRadius }
enter: SpunPopupEnter {}
- exit: Transition { NumberAnimation { property: "opacity"; from: 1; to: 0; duration: SpunStyle.exit } }
+ exit: Transition { NumberAnimation { property: "opacity"; from: 1; to: 0; duration: SpunStyle.exit; easing.type: Easing.BezierSpline; easing.bezierCurve: SpunStyle.effectsCurve } }
component Entry: MenuEntry { app: menu.app }
Entry {
objectName: "playNextAction"
- visible: !menu.currentSong; text: "Play next"; glyphName: "next"
- enabled: !!menu.selection.playable && !menu.service.busy
- onTriggered: menu.service.enqueue(menu.selection, true)
+ visible: !menu.currentSong && !menu.station && !menu.artist; text: menu.batch ? "Play next · " + menu.selectionBatch.length : "Play next"; glyphName: "next"
+ enabled: (menu.batch || !!menu.selection.playable) && !menu.service.busy
+ onTriggered: menu.batch ? menu.service.enqueueMany(menu.selectionBatch, true) : menu.session ? menu.service.enqueueMany(menu.pinService.savedTracks(menu.selection.id), true) : menu.service.enqueue(menu.selection, true)
}
Entry {
objectName: "addQueueAction"
- visible: !menu.currentSong; text: "Add to queue"; glyphName: "queue"
- enabled: !!menu.selection.playable && !menu.service.busy
- onTriggered: menu.service.enqueue(menu.selection, false)
+ visible: !menu.currentSong && !menu.station && !menu.artist; text: menu.batch ? "Add to queue · " + menu.selectionBatch.length : "Add to queue"; glyphName: "queue"
+ enabled: (menu.batch || !!menu.selection.playable) && !menu.service.busy
+ onTriggered: menu.batch ? menu.service.enqueueMany(menu.selectionBatch, false) : menu.session ? menu.service.enqueueMany(menu.pinService.savedTracks(menu.selection.id), false) : menu.service.enqueue(menu.selection, false)
+ }
+ Entry {
+ objectName: "queueFromHereAction"
+ visible: !menu.currentSong && !menu.batch && !!menu.pinService && menu.pinService.tailCollection && menu.selection.collectionIndex !== undefined
+ text: menu.pinService && menu.pinService.preparingTail ? "Cancel loading tracks" : "Queue from here"; glyphName: "queue"
+ enabled: !!menu.selection.playable && !menu.service.busy && !menu.app.ciderService.controlBusy
+ onTriggered: menu.pinService.preparingTail ? menu.pinService.cancelQueueFromHere() : menu.pinService.queueFromHere(menu.selection)
+ }
+ Entry {
+ objectName: "appendSavedQueueAction"
+ visible: !menu.currentSong && !!menu.pinService && (menu.batch || (!!menu.selection.type && menu.selection.type.endsWith("songs")))
+ text: "Add to saved queue…"; glyphName: "plus"
+ enabled: menu.batch || !!menu.selection.playable
+ onTriggered: menu.app.openSavedQueuePicker(menu.batch ? menu.selectionBatch : [menu.selection], menu.pinService)
+ }
+ Entry {
+ objectName: "playStationAction"; visible: menu.station
+ text: "Play station"; glyphName: "play"; enabled: !!menu.selection.playable && !menu.pinService.starting
+ onTriggered: { const index = menu.pinService.items.findIndex(row => row.id === menu.selection.id && row.type === "stations"); if (index >= 0) menu.pinService.play(index); else if (menu.selection.pinIndex !== undefined) menu.pinService.playPin(menu.selection.pinIndex) }
+ }
+ Entry {
+ objectName: "shuffleCollectionAction"
+ visible: !menu.batch && !menu.currentSong && !!menu.pinService && !!menu.selection.type && (menu.selection.type.endsWith("albums") || menu.selection.type.endsWith("playlists"))
+ text: "Shuffle"; glyphName: "shuffle"
+ enabled: !!menu.selection.playable && !menu.pinService.starting && !menu.app.ciderService.controlBusy
+ onTriggered: menu.pinService.shuffleCollection(menu.selection)
+ }
+ Entry {
+ objectName: "songRadioAction"
+ visible: menu.radioCandidate
+ text: menu.radioService.radioBusy ? "Finding station…" : menu.radioService.radioAvailable ? "Start radio" : menu.radioService.radioError.length ? "Radio unavailable" : "No station for this song"
+ glyphName: "disc"
+ enabled: menu.radioService.radioAvailable && !menu.radioService.radioBusy && !menu.app.ciderService.controlBusy && !menu.service.busy
+ onTriggered: menu.radioService.playRadio()
+ SpunToolTip { visible: parent.hovered && menu.radioService.radioError.length > 0; text: menu.radioService.radioError }
+ }
+ Entry {
+ objectName: "bookmarkMomentAction"; visible: menu.currentSong
+ text: "Bookmark this moment"; glyphName: "pin"
+ enabled: !menu.app.listeningService.busy && !menu.service.busy && !menu.app.ciderService.controlBusy
+ onTriggered: menu.app.listeningService.addBookmark()
+ }
+ Entry {
+ objectName: "audioQualityAction"; visible: menu.currentSong
+ text: "Audio quality"; glyphName: "volume"
+ onTriggered: menu.app.showAudioQuality()
+ }
+ Entry {
+ objectName: "copySongLinkAction"
+ visible: !menu.batch && (menu.currentSong || (!!menu.selection.type && menu.selection.type.endsWith("songs")))
+ text: "Copy song link"; glyphName: "external"
+ enabled: menu.currentSong || !!menu.selection.url || !!menu.selection.catalogId || menu.selection.type === "songs"
+ onTriggered: menu.currentSong ? menu.app.ciderService.copySongLink() : menu.pinService.copyLink(menu.selection)
+ }
+ Entry {
+ objectName: "renameSavedQueueAction"; visible: menu.session; text: "Rename saved queue"; glyphName: "more"
+ onTriggered: menu.app.renameQueue(menu.selection, menu.pinService)
+ }
+ Entry {
+ objectName: "savedTrackUp"; visible: !menu.batch && menu.savedTrackIndex >= 0
+ text: "Move up"; glyphName: "up"; enabled: menu.savedTrackIndex > 0 && !menu.pinService.collectionQuery.trim().length
+ onTriggered: menu.pinService.editSavedTrack(menu.savedTrackIndex, menu.savedTrackIndex - 1, false)
+ }
+ Entry {
+ objectName: "savedTrackDown"; visible: !menu.batch && menu.savedTrackIndex >= 0
+ text: "Move down"; glyphName: "down"; enabled: menu.savedTrackIndex < (menu.pinService ? menu.pinService.collection.trackCount - 1 : -1) && !!menu.pinService && !menu.pinService.collectionQuery.trim().length
+ onTriggered: menu.pinService.editSavedTrack(menu.savedTrackIndex, menu.savedTrackIndex + 1, false)
+ }
+ Entry {
+ objectName: "savedTrackRemove"; visible: !menu.batch && menu.savedTrackIndex >= 0
+ text: "Remove from saved queue"; glyphName: "close"
+ onTriggered: menu.pinService.editSavedTrack(menu.savedTrackIndex, menu.savedTrackIndex, true)
+ }
+ Entry {
+ objectName: "deleteSavedQueueAction"; visible: menu.session; text: "Delete saved queue"; glyphName: "close"
+ onTriggered: menu.app.confirmDeleteQueue(menu.selection.id, menu.pinService)
+ }
+ Entry {
+ objectName: "pinCollectionAction"
+ visible: !menu.batch && !!menu.pinService && !menu.currentSong && !!menu.selection.type && (menu.selection.type.endsWith("albums") || menu.selection.type.endsWith("playlists") || menu.station || menu.artist)
+ text: menu.pinService && menu.pinService.pins && menu.pinService.isPinned(menu.selection) ? (menu.artist ? "Unpin artist" : menu.station ? "Unpin station" : "Unpin collection") : (menu.artist ? "Pin artist" : menu.station ? "Pin station" : "Pin collection")
+ glyphName: "pin"
+ onTriggered: menu.pinService.togglePin(menu.selection)
+ }
+ Entry {
+ objectName: "openPinnedCollectionAction"
+ visible: !menu.batch && !menu.station && menu.selection.pinIndex !== undefined && !!menu.pinService
+ text: menu.artist ? "Open artist" : "Open collection"; glyphName: "disc"
+ onTriggered: menu.pinService.openPin(menu.selection.pinIndex)
+ }
+ Entry {
+ objectName: "selectTrackAction"
+ visible: !menu.currentSong && !menu.batch && !!menu.pinService && !!menu.selection.type && menu.selection.type.endsWith("songs")
+ enabled: !!menu.selection.playable
+ text: "Select track"; glyphName: "check"
+ onTriggered: menu.selectRequested()
+ }
+ Entry {
+ objectName: "viewArtistAction"
+ visible: !menu.batch && (menu.currentSong ? !!menu.app.deckPlayer.artist : !!menu.selection.artist && !!menu.selection.type && (menu.selection.type.endsWith("songs") || menu.selection.type.endsWith("albums")))
+ text: "View artist"; glyphName: "search"
+ onTriggered: {
+ if (menu.pinService && !menu.currentSong) menu.pinService.showArtist(menu.selection.artist)
+ else menu.app.openArtistName(menu.app.deckPlayer.artist)
+ }
}
Entry {
objectName: "favoriteAction"
@@ -33,6 +150,12 @@ Menu {
enabled: menu.service.ready && !menu.service.busy
onTriggered: menu.service.toggleFavorite()
}
+ Entry {
+ objectName: "dislikeAction"; visible: menu.currentSong
+ text: menu.service.disliked ? "Clear dislike" : "Suggest less like this"; glyphName: "minus"
+ enabled: menu.service.ready && !menu.service.busy
+ onTriggered: menu.service.toggleDislike()
+ }
Entry {
objectName: "saveLibraryAction"
visible: menu.currentSong; text: menu.service.saved ? "Saved to library" : "Save to library"; glyphName: menu.service.saved ? "check" : "plus"
diff --git a/src/cider.cpp b/src/cider.cpp
index 180c949..edbba05 100644
--- a/src/cider.cpp
+++ b/src/cider.cpp
@@ -1,4 +1,7 @@
#include "cider.h"
+#include "library.h"
+#include <QClipboard>
+#include <QGuiApplication>
#include <QDBusArgument>
#include <QDBusConnection>
#include <QDBusMessage>
@@ -23,6 +26,7 @@
#include <QImageReader>
#include <QtConcurrent>
#include <utility>
+#include <algorithm>
static const QString service = QStringLiteral("org.mpris.MediaPlayer2.cider");
static const QString path = QStringLiteral("/org/mpris/MediaPlayer2");
@@ -42,8 +46,27 @@ Cider::Cider(bool enabled, const QString &connectionPath, const QUrl &rpcBase, Q
m_apiToken = QJsonDocument::fromJson(connection.readAll()).object().value("token").toString();
m_launchTimer.setSingleShot(true); m_launchTimer.setInterval(20000);
connect(&m_launchTimer,&QTimer::timeout,this,[this] { emit launchChanged(); emit apiFeedback("Cider is taking longer to connect. Check its window and local API.",true); });
+ m_recoveryTimer.setSingleShot(true);
+ connect(&m_recoveryTimer,&QTimer::timeout,this,&Cider::reconnect);
m_queuePoll.setInterval(10000);
connect(&m_queuePoll, &QTimer::timeout, this, &Cider::refreshQueue);
+ m_eventCoalesce.setSingleShot(true);m_eventCoalesce.setInterval(180);
+ connect(&m_events,&CiderEvents::connectedChanged,this,[this] {
+ m_queuePoll.setInterval(m_events.connected()?30000:10000);
+ if(m_events.connected() && (m_queueVisible || m_libraryVisible))refreshQueue();
+ emit liveChanged();
+ });
+ connect(&m_events,&CiderEvents::event,this,[this](const QString &type) {
+ if(type=="queueStatus.queueChanged" || type=="playbackStatus.nowPlayingItemDidChange")m_eventQueue=true;
+ else if(type.startsWith("audioStatus.") || type=="playbackStatus.nowPlayingStatusDidChange" || type=="queueStatus.smartQueueChanged")m_eventSettings=true;
+ else return;
+ if(!m_eventCoalesce.isActive())m_eventCoalesce.start();
+ });
+ connect(&m_eventCoalesce,&QTimer::timeout,this,[this] {
+ const bool queue=std::exchange(m_eventQueue,false),settings=std::exchange(m_eventSettings,false);
+ if(queue && (m_queueVisible || m_libraryVisible))refreshQueue();
+ if(settings)emit remoteSettingsChanged();
+ });
m_commandClock.start();
m_commands.setInterval(50);
connect(&m_commands, &QTimer::timeout, this, &Cider::flushCommands);
@@ -68,7 +91,7 @@ Cider::Cider(bool enabled, const QString &connectionPath, const QUrl &rpcBase, Q
m_poll.start();
refresh();
}
-Cider::~Cider() { if (m_artDecodeActive) m_artLoader.waitForFinished(); }
+Cider::~Cider() { m_events.configure(false,m_rpcBase,{}); if (m_artDecodeActive) m_artLoader.waitForFinished(); }
qint64 Cider::position() const {
return qBound<qint64>(0, m_position + (m_playing && m_clock.isValid() ? m_clock.elapsed() : 0), m_duration);
}
@@ -124,7 +147,7 @@ void Cider::apply(const QVariantMap &v) {
if (v.contains("CanSeek")) m_canSeek = unwrap(v.value("CanSeek")).toBool();
if (v.contains("CanGoNext")) m_canNext = unwrap(v.value("CanGoNext")).toBool();
if (v.contains("CanGoPrevious")) m_canPrevious = unwrap(v.value("CanGoPrevious")).toBool();
- if (metadataChanged) { emit trackChanged(); if (m_queueVisible) refreshQueue(); if (m_discVisible) refreshDisc(); }
+ if (metadataChanged) { emit trackChanged(); if (m_queueVisible || m_libraryVisible) refreshQueue(); if (m_discVisible) refreshDisc(); }
}
void Cider::propertiesChanged(const QString &interface, const QVariantMap &values, const QStringList &invalidated) {
if (interface == iface) { apply(values); if (!invalidated.isEmpty()) refresh(); }
@@ -252,18 +275,122 @@ void Cider::setQueueVisible(bool visible) {
if (m_queueVisible == visible) return;
m_queueVisible = visible;
if (visible) { refreshQueue(); m_queuePoll.start(); }
- else m_queuePoll.stop();
+ else if(!m_libraryVisible)m_queuePoll.stop();
+ scheduleRecovery();
emit queueStatusChanged();
}
+bool Cider::saveToken() {
+ if (m_connectionPath.isEmpty()) return true;
+ const auto bytes=QJsonDocument(QJsonObject{{"token",m_apiToken}}).toJson(QJsonDocument::Compact);
+ QFile previous(m_connectionPath);
+ if (previous.open(QIODevice::ReadOnly) && previous.readAll()==bytes) return true;
+ QDir().mkpath(QFileInfo(m_connectionPath).absolutePath());
+ QSaveFile file(m_connectionPath);
+ if (!file.open(QIODevice::WriteOnly) || !file.setPermissions(QFileDevice::ReadOwner|QFileDevice::WriteOwner) ||
+ file.write(bytes)!=bytes.size() || !file.commit()) {
+ emit apiFeedback("Connected for this session. Couldn’t save Cider access.",true); return false;
+ }
+ return true;
+}
void Cider::connectQueue(const QString &token) {
- if (m_queueBusy) return;
- m_apiToken = token.trimmed();
- m_needsToken = false; m_queueError.clear();
+ const auto value=token.trimmed();
+ if (value.isEmpty() || value.size()>8192 || value.contains('\n') || value.contains('\r')) return;
+ ++m_tokenGeneration; m_queueBusy=false;
+ if(!m_batchOps.isEmpty()) { m_afterQueue={};finishBatch(false); }
+ if(!m_cleanupIndices.isEmpty()) { m_afterQueue={};finishCleanup(false); }
+ m_apiToken=value; m_needsToken=false; m_queueError.clear();updateEvents();
+ m_recoveryTimer.stop(); m_connectionState.clear(); m_connectionMessage.clear(); emit connectionChanged();
+ if(m_queueVisible || m_libraryVisible)m_queuePoll.start();
refreshQueue();
}
+void Cider::authorize() {
+ if (m_authReply) return;
+ auto url=m_rpcBase; url.setPath("/api/v2/auth/request"); url.setQuery(QString());
+ QNetworkRequest req(url); req.setTransferTimeout(120000);
+ req.setAttribute(QNetworkRequest::RedirectPolicyAttribute,QNetworkRequest::ManualRedirectPolicy);
+ req.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
+ // Bootstrap is unauthenticated; an expired token must not block approval.
+ const QJsonObject body{{"app_name","Spun"},{"scopes",QJsonArray{"playback","queue","library","audio"}}};
+ auto *reply=m_rpcNetwork.post(req,QJsonDocument(body).toJson(QJsonDocument::Compact));
+ m_authReply=reply; m_connectionMessage="Approve Spun in Cider."; emit connectionChanged();
+ connect(reply,&QNetworkReply::readyRead,reply,[reply] { if(reply->bytesAvailable()>65536)reply->abort(); });
+ connect(reply,&QNetworkReply::finished,this,[this,reply] {
+ reply->deleteLater(); if (m_authReply!=reply) return; m_authReply=nullptr;
+ const int status=reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
+ const auto object=QJsonDocument::fromJson(reply->readAll()).object();
+ const auto data=object.value("data").isObject()?object.value("data").toObject():object;
+ const auto token=data.value("token").toString().trimmed();
+ if (reply->error()==QNetworkReply::NoError && status>=200 && status<300 && !token.isEmpty() && token.size()<=8192 && !token.contains('\n') && !token.contains('\r')) {
+ connectQueue(token); saveToken(); emit connectionRestored();
+ m_connectionMessage="Connected to Cider.";
+ } else {
+ if (status==404 || status==405) m_connectionMessage="This Cider version needs a manual app token.";
+ else if (status==401 || status==403) m_connectionMessage="Access wasn’t approved. Try again when you’re ready.";
+ else if (status==408) m_connectionMessage="Approval timed out. Try again when Cider is ready.";
+ else if (status==409) m_connectionMessage="Cider already has an approval prompt open. Finish or dismiss it first.";
+ else if (status==429) m_connectionMessage="Too many requests. Wait a moment, then try again.";
+ else if (!status) m_connectionMessage="Couldn’t connect. Open Cider and enable its local API, then try again.";
+ else m_connectionMessage="Cider didn’t return an access token. Try again or use a manual token.";
+ }
+ emit connectionChanged();
+ });
+}
+void Cider::cancelAuthorization() {
+ if (!m_authReply) return;
+ auto reply=m_authReply; m_authReply=nullptr; reply->abort();
+ m_connectionMessage="Request cancelled. Dismiss any open approval prompt in Cider."; emit connectionChanged();
+}
+void Cider::setLibraryVisible(bool visible) {
+ if(m_libraryVisible==visible)return;
+ m_libraryVisible=visible;
+ if(visible && !m_apiToken.isEmpty()) { refreshQueue();m_queuePoll.start(); }
+ else if(!m_queueVisible)m_queuePoll.stop();
+ scheduleRecovery(); emit connectionChanged();
+}
+void Cider::scheduleRecovery() {
+ if (!recovering() || (!m_libraryVisible && !m_queueVisible)) { m_recoveryTimer.stop(); return; }
+ if (!m_recoveryTimer.isActive() && !m_probeReply) m_recoveryTimer.start(m_recoveryDelay);
+}
+void Cider::observeConnection(int status, QNetworkReply::NetworkError error) {
+ if (status==401 || status==403) {
+ m_connectionState="access"; m_connectionMessage=m_apiToken.isEmpty()?"Connect Spun to Cider.":"Cider access expired or is missing permissions. Reconnect to approve Spun.";
+ m_needsToken=true; m_queueReady=false; m_recoveryTimer.stop();
+ } else if (!status && error!=QNetworkReply::NoError) {
+ m_connectionState=(error==QNetworkReply::TimeoutError || error==QNetworkReply::OperationCanceledError)?"timeout":"offline";
+ m_connectionMessage=launching()?"Cider is starting…":m_available?"Cider’s local API is unavailable. Check Connectivity in Cider.":"Cider isn’t reachable. Open it to reconnect.";
+ scheduleRecovery();
+ } else return;
+ emit connectionChanged(); emit queueStatusChanged();
+}
+void Cider::reconnect() {
+ if (m_probeReply || m_authReply) return;
+ m_recoveryTimer.stop();
+ auto url=m_rpcBase; url.setPath("/api/v2/client/info"); url.setQuery(QString());
+ QNetworkRequest req(url); req.setTransferTimeout(4000);
+ req.setAttribute(QNetworkRequest::RedirectPolicyAttribute,QNetworkRequest::ManualRedirectPolicy);
+ req.setRawHeader("apptoken",m_apiToken.toUtf8());
+ auto *reply=m_rpcNetwork.get(req); m_probeReply=reply;
+ const int generation=m_tokenGeneration;
+ connect(reply,&QNetworkReply::readyRead,reply,[reply] { if(reply->bytesAvailable()>65536)reply->abort(); });
+ connect(reply,&QNetworkReply::finished,this,[this,reply,generation] {
+ reply->deleteLater(); m_probeReply=nullptr;
+ if(generation!=m_tokenGeneration)return;
+ const int status=reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
+ const auto object=QJsonDocument::fromJson(reply->readAll()).object();
+ const auto data=object.value("data").isObject()?object.value("data").toObject():object;
+ if (status==200 && reply->error()==QNetworkReply::NoError && data.value("version").isString()) {
+ m_connectionState="connected"; m_connectionMessage.clear(); m_needsToken=false; m_queueError.clear(); m_recoveryDelay=3000;
+ emit connectionChanged(); emit queueStatusChanged(); emit connectionRestored();
+ if(m_queueVisible || m_libraryVisible)refreshQueue();
+ } else {
+ m_recoveryDelay=qMin(30000,m_recoveryDelay*2);
+ observeConnection(status,reply->error()); scheduleRecovery();
+ }
+ });
+}
void Cider::queueFailed(const QString &message, bool needsToken) {
m_queueBusy=false; m_needsToken=needsToken;
- if (m_afterQueue) { m_afterQueue={}; m_controlBusy=false; emit controlChanged(); emit apiFeedback("Couldn’t verify the queue. Refresh it and try again.",true); }
+ if (m_afterQueue) { m_afterQueue={}; if(!m_batchOps.isEmpty())finishBatch(false);else if(!m_cleanupIndices.isEmpty())finishCleanup(false);else if(!m_insertItems.isEmpty())finishInsert(false);else { m_controlBusy=false; emit controlChanged(); emit apiFeedback("Couldn’t verify the queue. Refresh it and try again.",true); } }
if (needsToken) m_queueReady=false;
m_pendingQueue.clear();
m_queueError=message;
@@ -275,7 +402,7 @@ void Cider::refreshQueue() {
fetchQueue();
}
void Cider::fetchQueue() {
- if (m_queueBusy || m_needsToken) return;
+ if (m_queueBusy || m_needsToken || recovering()) return;
m_queueBusy=true;
m_pendingQueue.clear(); m_pendingQueueTotal=-1; m_pendingQueuePosition=-1;
requestQueuePage(0);
@@ -294,12 +421,15 @@ void Cider::requestQueuePage(int offset) {
connect(reply,&QNetworkReply::downloadProgress,reply,[reply](qint64 received,qint64 total) {
if (received>16*1024*1024 || total>16*1024*1024) reply->abort();
});
- connect(reply,&QNetworkReply::finished,this,[this,reply,offset] {
+ const int generation=m_tokenGeneration;
+ connect(reply,&QNetworkReply::finished,this,[this,reply,offset,generation] {
+ if (generation!=m_tokenGeneration) { reply->deleteLater(); return; }
const int status=reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
const auto bytes=reply->readAll();
const auto error=reply->error(); reply->deleteLater();
const auto doc=QJsonDocument::fromJson(bytes);
const auto object=doc.object();
+ observeConnection(status,error);
if (status==401 || status==403) {
queueFailed(m_apiToken.isEmpty() ? "Connect Cider to see your queue." : "Check the Spun token and its queue access in Cider.",true); return;
}
@@ -333,7 +463,9 @@ void Cider::requestQueuePage(int offset) {
if (artUrl.scheme()!="https" && artUrl.scheme()!="http") art.clear();
m_pendingQueue.append(QVariantMap{{"title",attr.value("name").toString("Unknown track")},
{"artist",attr.value("artistName").toString("Unknown artist")}, {"duration",attr.value("durationInMillis").toDouble()},
- {"id",track.value("id").toString()}, {"rpcIndex",index++}, {"artwork",art}});
+ {"id",track.value("id").toString()}, {"type",track.value("type").toString()},
+ {"catalogId",attr.value("playParams").toObject().value("catalogId").toString()}, {"url",attr.value("url").toString()},
+ {"playable",!attr.value("playParams").toObject().isEmpty()}, {"rpcIndex",index++}, {"artwork",art}});
}
if (index<total) { requestQueuePage(index); return; }
const bool changed=m_queue!=m_pendingQueue;
@@ -343,19 +475,7 @@ void Cider::requestQueuePage(int offset) {
m_queue=m_pendingQueue; m_pendingQueue.clear();
m_queueIndex=nextIndex;
m_queueBusy=false; m_queueReady=true; m_needsToken=false; m_queueError.clear();
- if (!m_apiToken.isEmpty() && !m_connectionPath.isEmpty()) {
- QFile previous(m_connectionPath); QByteArray old;
- if (previous.open(QIODevice::ReadOnly)) old=previous.readAll();
- const auto next=QJsonDocument(QJsonObject{{"token",m_apiToken}}).toJson(QJsonDocument::Compact);
- if (old!=next) {
- QDir().mkpath(QFileInfo(m_connectionPath).absolutePath());
- QSaveFile file(m_connectionPath);
- if (file.open(QIODevice::WriteOnly)) {
- file.setPermissions(QFileDevice::ReadOwner|QFileDevice::WriteOwner);
- file.write(next); file.commit();
- }
- }
- }
+ if (!m_apiToken.isEmpty()) saveToken();
if (changed) emit queueChanged();
if (indexChanged) emit currentIndexChanged();
emit queueStatusChanged();
@@ -364,7 +484,8 @@ void Cider::requestQueuePage(int offset) {
});
}
void Cider::select(int index) {
- if (m_controlBusy || !m_queueReady || !m_queueError.isEmpty() || index < 0 || index >= m_queue.size()) return;
+ if (m_controlBusy || m_queueBusy || !m_queueReady || !m_queueError.isEmpty() || index < 0 || index >= m_queue.size()) return;
+ m_controlBusy=true; emit controlChanged();
auto url=m_rpcBase; url.setPath("/api/v2/queue/jump");
QNetworkRequest request(url);
request.setTransferTimeout(3000);
@@ -375,7 +496,9 @@ void Cider::select(int index) {
const auto data=QJsonDocument(QJsonObject{{"index",m_queue[index].toMap().value("rpcIndex").toInt()}}).toJson();
auto *reply=m_rpcNetwork.post(request,data);
connect(reply,&QNetworkReply::finished,this,[this,reply] {
- if (reply->error()!=QNetworkReply::NoError) { m_queueError="Could not play that queued track."; emit queueStatusChanged(); }
+ const bool failed=reply->error()!=QNetworkReply::NoError;
+ m_controlBusy=false; emit controlChanged();
+ if (failed) emit apiFeedback("Could not play that queued track. Try again.",true);
reply->deleteLater(); refresh(); refreshQueue();
});
}
@@ -473,20 +596,20 @@ void Cider::requestDiscTracks(const QString &path, int generation) {
}
// Cider v2 contracts are shared with ciderapp/CiderDeck's official client.
-void Cider::apiRequest(const QByteArray &method, const QString &endpoint, const QJsonObject &body, std::function<void(bool,QJsonObject)> done) {
- if (m_apiToken.isEmpty()) { emit apiFeedback("Connect Spun to Cider in Queue first.",true); done(false,{}); return; }
+void Cider::apiRequest(const QByteArray &method, const QString &endpoint, const QJsonObject &body, std::function<void(bool,QJsonObject)> done, bool reportError) {
+ if (m_apiToken.isEmpty()) { if(reportError)emit apiFeedback("Connect Spun to Cider in Queue first.",true); done(false,{}); return; }
auto url=m_rpcBase; url.setPath("/api/v2"+endpoint); url.setQuery(QString());
QNetworkRequest req(url); req.setTransferTimeout(6000);
req.setAttribute(QNetworkRequest::RedirectPolicyAttribute,QNetworkRequest::ManualRedirectPolicy);
req.setRawHeader("apptoken",m_apiToken.toUtf8()); req.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
auto *reply=m_rpcNetwork.sendCustomRequest(req,method,body.isEmpty()?QByteArray():QJsonDocument(body).toJson(QJsonDocument::Compact));
connect(reply,&QNetworkReply::readyRead,reply,[reply] { if (reply->bytesAvailable()>512*1024) reply->abort(); });
- connect(reply,&QNetworkReply::finished,this,[this,reply,done] {
+ connect(reply,&QNetworkReply::finished,this,[this,reply,done,reportError] {
reply->deleteLater(); const int status=reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
const auto bytes=reply->readAll(); const auto doc=QJsonDocument::fromJson(bytes); const auto json=doc.object();
const bool ok=reply->error()==QNetworkReply::NoError && status>=200 && status<300 &&
(bytes.trimmed().isEmpty() || doc.isObject()) && !json.contains("error") && !json.contains("errors");
- if (!ok) emit apiFeedback(status==401 || status==403 ? "Check Spun’s API permissions in Cider." :
+ if (!ok && reportError) emit apiFeedback(status==401 || status==403 ? "Check Spun’s API permissions in Cider." :
status==404 || status==405 ? "This control isn’t supported by your Cider version." : "Cider couldn’t confirm the change. Check its state before retrying.",true);
done(ok,json);
});
@@ -568,23 +691,158 @@ void Cider::changeMode(const QString &mode, bool value) {
}
void Cider::moveQueue(int from, int to, int revision) { editQueue(from,to,revision,false); }
void Cider::removeQueue(int index, int revision) { editQueue(index,index,revision,true); }
+// Queue identity excludes mutable artwork and rpcIndex, and preserves duplicates.
+static QString queueKey(const QVariantMap &row) {
+ const auto catalog=row.value("catalogId").toString();
+ return !catalog.isEmpty()?"songs:"+catalog:row.value("type").toString()+":"+row.value("id").toString();
+}
+static QStringList queueKeys(const QVariantList &rows) {
+ QStringList result; result.reserve(rows.size());
+ for(const auto &row:rows)result.append(queueKey(row.toMap()));
+ return result;
+}
+QVariantMap Cider::previewCleanup(const QString &mode) const {
+ if((mode!="duplicates" && mode!="upcoming") || !m_queueReady || !m_queueError.isEmpty() || m_queueBusy || controlBusy() || recovering())return {};
+ QSet<QString> seen; QVariantList rows,indices;
+ // Unknown identities must never be treated as duplicates by their title.
+ auto identity=[](const QVariantMap &row) {
+ if(!QStringList{"songs","library-songs"}.contains(row.value("type").toString()) || row.value("id").toString().isEmpty())return QString();
+ return queueKey(row);
+ };
+ if(m_queueIndex>=0 && m_queueIndex<m_queue.size())seen.insert(identity(m_queue[m_queueIndex].toMap()));
+ for(int i=qMax(0,m_queueIndex+1);i<m_queue.size();++i) {
+ const auto row=m_queue[i].toMap();const auto key=identity(row);
+ if(mode=="upcoming" || (!key.isEmpty() && seen.contains(key))) { rows.append(row);indices.append(i); }
+ if(!key.isEmpty())seen.insert(key);
+ }
+ return {{"rows",rows},{"indices",indices},{"revision",m_queueRevision},{"mode",mode}};
+}
+void Cider::cleanQueue(const QString &mode, int revision) {
+ const auto preview=previewCleanup(mode);
+ if(preview.isEmpty())return;
+ if(revision!=m_queueRevision) { emit apiFeedback("The queue changed. Preview cleanup again.",true);return; }
+ const auto indices=preview.value("indices").toList();if(indices.isEmpty())return;
+ m_cleanupIndices.clear();for(const auto &index:indices)m_cleanupIndices.append(index.toInt());
+ m_cleanupExpected=queueKeys(m_queue);m_cleanupDone=0;m_cleanupPosition=m_queueIndex;m_cleanupGeneration=m_tokenGeneration;
+ m_undoTrack.clear();m_controlBusy=true;emit controlChanged();emit queueStatusChanged();
+ emit apiFeedback("Cleaning upcoming queue…",false);
+ m_afterQueue=[this,revision] { if(revision!=m_queueRevision)finishCleanup(false);else cleanupNext(); };fetchQueue();
+}
+void Cider::finishCleanup(bool success) {
+ const int done=m_cleanupDone,total=m_cleanupIndices.size();
+ m_cleanupIndices.clear();m_cleanupExpected.clear();m_controlBusy=false;
+ emit controlChanged();emit queueStatusChanged();
+ emit apiFeedback(success ? QString("Removed %1 upcoming %2").arg(done).arg(done==1?"song":"songs") :
+ QString("%1 of %2 removals confirmed. Cleanup stopped; check the queue before retrying.").arg(done).arg(total),!success);
+}
+void Cider::cleanupNext() {
+ if(m_cleanupGeneration!=m_tokenGeneration || queueKeys(m_queue)!=m_cleanupExpected || m_queueIndex!=m_cleanupPosition) { finishCleanup(false);return; }
+ if(m_cleanupDone==m_cleanupIndices.size()) { finishCleanup(true);return; }
+ const int index=m_cleanupIndices[m_cleanupIndices.size()-1-m_cleanupDone];
+ if(index<=m_queueIndex || index<0 || index>=m_queue.size()) { finishCleanup(false);return; }
+ apiRequest("DELETE","/queue/items/"+QString::number(index),{},[this,index,generation=m_cleanupGeneration](bool ok,QJsonObject) {
+ if(generation!=m_tokenGeneration)return;
+ if(!ok) { finishCleanup(false);refreshQueue();return; }
+ m_cleanupExpected.removeAt(index);
+ m_afterQueue=[this] {
+ if(queueKeys(m_queue)!=m_cleanupExpected || m_queueIndex!=m_cleanupPosition) { finishCleanup(false);return; }
+ ++m_cleanupDone;cleanupNext();
+ };fetchQueue();
+ });
+}
void Cider::editQueue(int from, int to, int revision, bool remove) {
if (controlBusy() || m_queueBusy || !m_queueReady || !m_queueError.isEmpty()) return;
if (revision!=m_queueRevision) { emit apiFeedback("The queue changed. Try again.",true); return; }
if (from<0 || to<0 || from>=m_queue.size() || to>=m_queue.size() || (!remove && from==to)) return;
- m_controlBusy=true; emit controlChanged();
- // Index-based endpoints require a fresh queue before writing. Do not guess after a change.
+ m_undoTrack.clear(); m_controlBusy=true; emit queueStatusChanged(); emit controlChanged();
m_afterQueue=[this,from,to,revision,remove] {
if (revision!=m_queueRevision) { m_controlBusy=false; emit controlChanged(); emit apiFeedback("The queue changed. Try again.",true); return; }
+ const auto removed=m_queue[from].toMap(); auto expected=queueKeys(m_queue);
+ const int current=m_queueIndex;
+ if(remove)expected.removeAt(from);else expected.move(from,to);
apiRequest(remove?"DELETE":"POST",remove?"/queue/items/"+QString::number(from):"/queue/move",
- remove?QJsonObject{}:QJsonObject{{"from",from},{"to",to}},[this,remove](bool ok,QJsonObject) {
+ remove?QJsonObject{}:QJsonObject{{"from",from},{"to",to}},[this,remove,removed,expected,from,current](bool ok,QJsonObject) {
if (!ok) { m_controlBusy=false; emit controlChanged(); refreshQueue(); return; }
- m_afterQueue=[this,remove] { m_controlBusy=false; emit controlChanged(); emit apiFeedback(remove?"Removed from queue":"Queue reordered",false); };
+ m_afterQueue=[this,remove,removed,expected,from,current] {
+ m_controlBusy=false; emit controlChanged();
+ if(queueKeys(m_queue)!=expected) { emit apiFeedback("The queue changed. Check it before retrying.",true);return; }
+ // Restoring a removed current song would also need to rewind playback.
+ if(remove && from!=current && m_queueIndex==(from<current?current-1:current) && removed.value("playable").toBool()) {
+ m_undoTrack=removed;m_undoIndex=from;m_undoRevision=m_queueRevision;m_undoClock.start();
+ const int revision=m_undoRevision;
+ QTimer::singleShot(8000,this,[this,revision] { if(revision==m_undoRevision) { m_undoTrack.clear();emit queueStatusChanged(); } });
+ }
+ emit queueStatusChanged();emit apiFeedback(remove?"Removed from queue":"Queue reordered",false);
+ };
fetchQueue();
});
+ }; fetchQueue();
+}
+void Cider::undoQueueRemoval() {
+ if(!canUndoQueue() || controlBusy() || m_queueBusy)return;
+ const auto track=m_undoTrack;const int index=m_undoIndex,revision=m_undoRevision;
+ m_restoringQueue=true;insertQueue({track},index,revision);
+ if(!m_controlBusy)m_restoringQueue=false;
+}
+void Cider::insertQueue(const QVariantList &items, int index, int revision) {
+ if(controlBusy() || m_queueBusy || !m_queueReady || !m_queueError.isEmpty() || items.isEmpty())return;
+ if(revision!=m_queueRevision || index<0 || index>m_queue.size() || (!m_restoringQueue && index<=m_queueIndex)) {
+ emit apiFeedback("Drop into the upcoming queue and try again.",true);return;
+ }
+ if(items.size()>5000 || m_queue.size()+items.size()>10000) { emit apiFeedback("This queue is too large to insert more songs.",true);return; }
+ static const QRegularExpression identifier("^[A-Za-z0-9._-]{1,200}$");
+ for(const auto &value:items) { const auto row=value.toMap();
+ if(!row.value("playable").toBool() || !QStringList{"songs","library-songs"}.contains(row.value("type").toString()) || !identifier.match(row.value("id").toString()).hasMatch()) {
+ emit apiFeedback("Only available songs can be inserted.",true);return;
+ }
+ }
+ m_undoTrack.clear();m_insertItems=items;m_insertAt=index;m_insertDone=0;
+ m_insertExpected=queueKeys(m_queue);m_insertPosition=m_queueIndex;m_controlBusy=true;
+ emit controlChanged();emit queueStatusChanged();
+ m_afterQueue=[this,revision] { if(revision!=m_queueRevision)finishInsert(false);else insertNext(); };fetchQueue();
+}
+void Cider::finishInsert(bool success) {
+ const int done=m_insertDone,total=m_insertItems.size();const bool undo=m_restoringQueue;
+ m_insertItems.clear();m_insertExpected.clear();m_controlBusy=false;m_restoringQueue=false;
+ emit controlChanged();emit queueStatusChanged();
+ emit apiFeedback(success?(undo?"Restored to its original position":(total==1?QString("Song inserted"):QString("%1 tracks inserted").arg(total))):
+ QString("%1 of %2 tracks placed. Check the queue before retrying; a song may remain at the end.").arg(done).arg(total),!success);
+}
+void Cider::verifyInsert(const QStringList &before,int beforePosition,std::function<void()> done,int attempts) {
+ m_afterQueue=[this,before,beforePosition,done,attempts] {
+ const auto actual=queueKeys(m_queue);
+ if(actual==m_insertExpected && m_queueIndex==m_insertPosition) {done();return;}
+ // Cider can acknowledge a command before its catalog lookup finishes.
+ // Re-read the unchanged pre-action state; never repeat the mutation.
+ if(attempts>0 && actual==before && m_queueIndex==beforePosition) {
+ QTimer::singleShot(250,this,[this,before,beforePosition,done,attempts] {
+ if(!m_insertItems.isEmpty())verifyInsert(before,beforePosition,done,attempts-1);
+ });
+ } else finishInsert(false);
};
fetchQueue();
}
+void Cider::insertNext() {
+ if(queueKeys(m_queue)!=m_insertExpected || m_queueIndex!=m_insertPosition) { finishInsert(false);return; }
+ if(m_insertDone>=m_insertItems.size()) { finishInsert(true);return; }
+ const auto row=m_insertItems[m_insertDone].toMap();
+ apiRequest("POST","/queue/add-later",{{"type",row.value("type").toString()},{"id",row.value("id").toString()}},[this,row](bool ok,QJsonObject) {
+ if(!ok) { finishInsert(false);refreshQueue();return; }
+ const auto before=m_insertExpected;const int position=m_insertPosition;
+ m_insertExpected.append(queueKey(row));
+ verifyInsert(before,position,[this] {
+ const int from=m_queue.size()-1,to=m_insertAt+m_insertDone;
+ if(from==to) { ++m_insertDone;insertNext();return; }
+ apiRequest("POST","/queue/move",{{"from",from},{"to",to}},[this,from,to](bool ok,QJsonObject) {
+ if(!ok) { finishInsert(false);refreshQueue();return; }
+ const auto beforeMove=m_insertExpected;const int beforePosition=m_insertPosition;
+ m_insertExpected.move(from,to);
+ if(to<=m_insertPosition)++m_insertPosition;
+ verifyInsert(beforeMove,beforePosition,[this] {++m_insertDone;insertNext();});
+ });
+ });
+ });
+}
QStringList Cider::launchCommand() {
const auto native=QStandardPaths::findExecutable("cider");
if (!native.isEmpty()) return {native};
@@ -612,3 +870,128 @@ void Cider::ensureRunning() {
}
});
}
+
+void Cider::refreshAudioOptions() {
+ if(m_audioBusy)return;
+ m_audioBusy=true;m_audioError.clear();emit audioOptionsChanged();
+ apiRequest("GET","/audio/automix",{},[this](bool ok,QJsonObject json) {
+ const auto data=json.value("data").toObject();
+ if(ok && data.value("enabled").isBool())m_audioOptions["automix"]=data.value("enabled").toBool();else m_audioOptions.remove("automix");
+ apiRequest("GET","/audio/listening-mode",{},[this](bool ok,QJsonObject json) {
+ const auto data=json.value("data").toObject();const auto mode=data.value("mode").toString();
+ if(ok && data.value("available").toBool(true) && QStringList{"off","gaming","unwind"}.contains(mode))m_audioOptions["listeningMode"]=mode;else m_audioOptions.remove("listeningMode");
+ if(m_audioOptions.isEmpty())m_audioError="Extra audio controls aren’t available with this Cider connection.";
+ m_audioBusy=false;emit audioOptionsChanged();
+ });
+ });
+}
+void Cider::setAudioOption(const QString &key,const QVariant &value) {
+ if(m_audioBusy || !m_audioOptions.contains(key) || m_audioOptions.value(key)==value)return;
+ if((key=="automix" && value.metaType().id()!=QMetaType::Bool) || (key=="listeningMode" && !QStringList{"off","gaming","unwind"}.contains(value.toString())))return;
+ if(key!="automix" && key!="listeningMode")return;
+ const auto endpoint=key=="automix"?"/audio/automix":"/audio/listening-mode";
+ const auto field=key=="automix"?"enabled":"mode";
+ m_audioBusy=true;m_audioError.clear();emit audioOptionsChanged();
+ apiRequest("PATCH",endpoint,{{field,QJsonValue::fromVariant(value)}},[this,key,value,endpoint,field](bool ok,QJsonObject) {
+ if(!ok) { m_audioOptions.remove(key);m_audioBusy=false;m_audioError="Refresh audio settings before trying again.";emit audioOptionsChanged();return; }
+ apiRequest("GET",endpoint,{},[this,key,value,field](bool read,QJsonObject json) {
+ const auto actual=json.value("data").toObject().value(field).toVariant();
+ if(read && actual==value)m_audioOptions[key]=actual;
+ else { m_audioOptions.remove(key);m_audioError="Cider hasn’t confirmed this setting. Refresh to check."; }
+ m_audioBusy=false;emit audioOptionsChanged();
+ });
+ });
+}
+void Cider::copySongLink() {
+ if(m_linkBusy)return;
+ const auto track=m_track;m_linkBusy=true;
+ apiRequest("GET","/playback/now-playing",{},[this,track](bool ok,QJsonObject json) {
+ m_linkBusy=false;
+ if(track!=m_track) { emit apiFeedback("The song changed. Copy its link again.",true);return; }
+ const auto link=Library::songLink(json.value("data").toObject().value("url").toString());
+ if(!ok || link.isEmpty()) { emit apiFeedback("No shareable Apple Music link for this song.",true);return; }
+ QGuiApplication::clipboard()->setText(link);emit apiFeedback("Song link copied",false);
+ });
+}
+
+void Cider::refreshAudioQuality() {
+ if(m_qualityBusy)return;
+ const auto track=m_track; m_qualityBusy=true;m_audioQuality.clear();emit audioQualityChanged();
+ apiRequest("GET","/playback/audio-quality",{},[this,track](bool ok,QJsonObject json) {
+ m_qualityBusy=false;
+ if(track!=m_track) { m_audioQuality="Song changed. Refresh to see its quality.";emit audioQualityChanged();return; }
+ const auto data=json.value("data").toObject();
+ QStringList lines;const auto label=data.value("flavorLabel").toString().trimmed().left(120);
+ if(ok && !label.isEmpty())lines.append(label);
+ const auto output=data.value("deviceAudioConfig").toObject();
+ const auto rate=output.value("sampleRate").toDouble();const auto channels=output.value("channelCount").toInt();
+ // Device output is not the source file's sample rate or quality.
+ if(ok && rate>=8000 && rate<=768000) lines.append(QString("Output: %1 kHz").arg(rate/1000.,0,'g',5)+(channels>0 && channels<=32?QString(" · %1 channels").arg(channels):QString()));
+ m_audioQuality=lines.isEmpty()?"Quality unavailable from Cider.":lines.join("\n");emit audioQualityChanged();
+ });
+}
+
+void Cider::setLiveVisible(bool visible) {
+ if(m_liveVisible==visible)return;
+ m_liveVisible=visible;updateEvents();emit liveChanged();
+}
+void Cider::updateEvents() {
+ m_events.configure(m_liveVisible,m_rpcBase,m_apiToken.toUtf8());
+ if(!m_liveVisible) { m_eventCoalesce.stop();m_eventQueue=m_eventSettings=false; }
+}
+
+void Cider::editQueueSelection(const QVariantList &indices, const QString &operation, int revision) {
+ if(controlBusy() || m_queueBusy || !m_queueReady || !m_queueError.isEmpty() || recovering())return;
+ if(revision!=m_queueRevision) { emit apiFeedback("The queue changed. Select the songs again.",true);return; }
+ if(indices.size()>5000) { emit apiFeedback("Select up to 5,000 songs at a time.",true);return; }
+ if(indices.isEmpty() || !QStringList{"up","down","next","end","remove"}.contains(operation))return;
+ QList<int> positions;QSet<int> selected;
+ for(const auto &value:indices) {
+ bool ok=false;const int index=value.toInt(&ok);
+ if(!ok || value.toDouble()!=index || index<=m_queueIndex || index<0 || index>=m_queue.size() || selected.contains(index))return;
+ positions.append(index);selected.insert(index);
+ }
+ std::sort(positions.begin(),positions.end());m_batchOps.clear();
+ const int first=qMax(0,m_queueIndex+1),last=m_queue.size()-1;
+ if(operation=="up" || operation=="next") {
+ int destination=first;
+ for(int index:positions) {
+ const int to=operation=="next"?destination++:index-1;
+ if(to>=first && to!=index && (operation=="next" || !selected.contains(to))) { m_batchOps.append({index,to});selected.remove(index);selected.insert(to); }
+ }
+ } else {
+ int destination=last;
+ for(auto it=positions.crbegin();it!=positions.crend();++it) {
+ const int index=*it,to=operation=="remove"?-1:operation=="end"?destination--:index+1;
+ if(operation=="remove" || (to<=last && to!=index && (operation=="end" || !selected.contains(to)))) { m_batchOps.append({index,to});selected.remove(index);selected.insert(to); }
+ }
+ }
+ if(m_batchOps.isEmpty()) { emit apiFeedback("Selected songs are already there",false);return; }
+ m_batchExpected=queueKeys(m_queue);m_batchPosition=m_queueIndex;m_batchGeneration=m_tokenGeneration;m_batchDone=0;
+ m_undoTrack.clear();m_controlBusy=true;emit controlChanged();emit queueStatusChanged();
+ emit apiFeedback(operation=="remove"?"Removing selected songs…":"Moving selected songs…",false);
+ m_afterQueue=[this,revision] { if(revision!=m_queueRevision)finishBatch(false);else batchNext(); };fetchQueue();
+}
+void Cider::finishBatch(bool success) {
+ const int done=m_batchDone,total=m_batchOps.size();
+ m_batchOps.clear();m_batchExpected.clear();m_controlBusy=false;
+ emit controlChanged();emit queueStatusChanged();
+ emit apiFeedback(success?QString("Updated %1 selected %2").arg(done).arg(done==1?"song":"songs"):
+ QString("%1 of %2 changes confirmed. Stopped; check the queue before retrying.").arg(done).arg(total),!success);
+}
+void Cider::batchNext() {
+ if(m_batchGeneration!=m_tokenGeneration || queueKeys(m_queue)!=m_batchExpected || m_queueIndex!=m_batchPosition) { finishBatch(false);return; }
+ if(m_batchDone==m_batchOps.size()) { finishBatch(true);return; }
+ const auto [from,to]=m_batchOps[m_batchDone];
+ if(from<=m_queueIndex || from>=m_queue.size() || (to>=0 && (to<=m_queueIndex || to>=m_queue.size()))) { finishBatch(false);return; }
+ const bool remove=to<0;
+ apiRequest(remove?"DELETE":"POST",remove?"/queue/items/"+QString::number(from):"/queue/move",remove?QJsonObject{}:QJsonObject{{"from",from},{"to",to}},[this,from,to,generation=m_batchGeneration](bool ok,QJsonObject) {
+ if(generation!=m_tokenGeneration)return;
+ if(!ok) { finishBatch(false);refreshQueue();return; }
+ if(to<0)m_batchExpected.removeAt(from);else m_batchExpected.move(from,to);
+ m_afterQueue=[this] {
+ if(queueKeys(m_queue)!=m_batchExpected || m_queueIndex!=m_batchPosition) { finishBatch(false);return; }
+ ++m_batchDone;batchNext();
+ };fetchQueue();
+ });
+}
diff --git a/src/cider.h b/src/cider.h
index d911996..e6111b0 100644
--- a/src/cider.h
+++ b/src/cider.h
@@ -1,4 +1,5 @@
#pragma once
+#include "ciderevents.h"
#include <QObject>
#include <QVariantMap>
#include <QImage>
@@ -14,10 +15,21 @@
#include <QFutureWatcher>
class Cider : public QObject {
+ friend class Listening;
friend class Lyrics;
friend class Library;
friend class MusicActions;
Q_OBJECT
+ Q_PROPERTY(QString audioQuality READ audioQuality NOTIFY audioQualityChanged)
+ Q_PROPERTY(bool qualityBusy READ qualityBusy NOTIFY audioQualityChanged)
+ Q_PROPERTY(bool canUndoQueue READ canUndoQueue NOTIFY queueStatusChanged)
+ Q_PROPERTY(bool authorizing READ authorizing NOTIFY connectionChanged)
+ Q_PROPERTY(QString connectionMessage READ connectionMessage NOTIFY connectionChanged)
+ Q_PROPERTY(QString connectionState READ connectionState NOTIFY connectionChanged)
+ Q_PROPERTY(bool recovering READ recovering NOTIFY connectionChanged)
+ Q_PROPERTY(bool liveVisible READ liveVisible WRITE setLiveVisible NOTIFY liveChanged)
+ Q_PROPERTY(bool liveConnected READ liveConnected NOTIFY liveChanged)
+ Q_PROPERTY(bool libraryVisible READ libraryVisible WRITE setLibraryVisible NOTIFY connectionChanged)
Q_PROPERTY(bool available READ available NOTIFY trackChanged)
Q_PROPERTY(QString title READ title NOTIFY trackChanged)
Q_PROPERTY(QString artist READ artist NOTIFY trackChanged)
@@ -41,6 +53,9 @@ class Cider : public QObject {
Q_PROPERTY(qint64 position READ position NOTIFY positionChanged)
Q_PROPERTY(qint64 duration READ duration NOTIFY trackChanged)
Q_PROPERTY(double volume READ volume WRITE setVolume NOTIFY volumeChanged)
+ Q_PROPERTY(QVariantMap audioOptions READ audioOptions NOTIFY audioOptionsChanged)
+ Q_PROPERTY(bool audioBusy READ audioBusy NOTIFY audioOptionsChanged)
+ Q_PROPERTY(QString audioError READ audioError NOTIFY audioOptionsChanged)
Q_PROPERTY(bool crossfade READ crossfade NOTIFY crossfadeChanged)
Q_PROPERTY(double crossfadeSeconds READ crossfadeSeconds NOTIFY crossfadeChanged)
Q_PROPERTY(bool crossfadeReady READ crossfadeReady NOTIFY crossfadeChanged)
@@ -59,6 +74,24 @@ class Cider : public QObject {
Q_PROPERTY(bool canPrevious READ canPrevious NOTIFY trackChanged)
public:
explicit Cider(bool enabled = true, const QString &connectionPath = {}, const QUrl &rpcBase = QUrl("http://localhost:10767"), QObject *parent = nullptr);
+ QString audioQuality() const { return m_audioQuality; }
+ bool qualityBusy() const { return m_qualityBusy; }
+ Q_INVOKABLE void refreshAudioQuality();
+ bool canUndoQueue() const { return !m_undoTrack.isEmpty() && m_undoRevision==m_queueRevision && m_undoClock.isValid() && m_undoClock.elapsed()<8000; }
+ Q_INVOKABLE void undoQueueRemoval();
+ Q_INVOKABLE void insertQueue(const QVariantList &items, int index, int revision);
+ bool authorizing() const { return !m_authReply.isNull(); }
+ QString connectionMessage() const { return m_connectionMessage; }
+ QString connectionState() const { return m_connectionState; }
+ bool recovering() const { return m_connectionState=="offline" || m_connectionState=="timeout"; }
+ bool libraryVisible() const { return m_libraryVisible; }
+ bool liveVisible() const { return m_liveVisible; }
+ bool liveConnected() const { return m_events.connected(); }
+ void setLiveVisible(bool visible);
+ void setLibraryVisible(bool visible);
+ Q_INVOKABLE void authorize();
+ Q_INVOKABLE void cancelAuthorization();
+ Q_INVOKABLE void reconnect();
bool available() const { return m_available; }
~Cider() override;
QString title() const { return m_title.isEmpty() ? "Cider" : m_title; }
@@ -89,6 +122,12 @@ public:
qint64 position() const;
qint64 duration() const { return m_duration; }
double volume() const { return m_volume; }
+ QVariantMap audioOptions() const { return m_audioOptions; }
+ bool audioBusy() const { return m_audioBusy; }
+ QString audioError() const { return m_audioError; }
+ Q_INVOKABLE void refreshAudioOptions();
+ Q_INVOKABLE void setAudioOption(const QString &key, const QVariant &value);
+ Q_INVOKABLE void copySongLink();
bool crossfade() const { return m_crossfade; }
double crossfadeSeconds() const { return m_crossfadeSeconds; }
bool crossfadeReady() const { return m_crossfadeReady; }
@@ -99,13 +138,16 @@ public:
Q_INVOKABLE void setCrossfadeSeconds(double value);
bool autoplay() const { return m_autoplay; }
bool modesReady() const { return m_modesReady; }
- bool controlBusy() const { return m_controlBusy || m_modesReading; }
+ bool controlBusy() const { return m_controlBusy || m_modesReading || m_listeningBusy; }
int queueRevision() const { return m_queueRevision; }
bool launching() const { return m_launchTimer.isActive(); }
Q_INVOKABLE void refreshModes();
Q_INVOKABLE void setAutoplay(bool value);
Q_INVOKABLE void moveQueue(int from, int to, int revision);
Q_INVOKABLE void removeQueue(int index, int revision);
+ Q_INVOKABLE QVariantMap previewCleanup(const QString &mode) const;
+ Q_INVOKABLE void editQueueSelection(const QVariantList &indices, const QString &operation, int revision);
+ Q_INVOKABLE void cleanQueue(const QString &mode, int revision);
Q_INVOKABLE void ensureRunning();
static QStringList launchCommand();
bool shuffle() const { return m_shuffle; }
@@ -127,7 +169,13 @@ public:
Q_INVOKABLE void refresh();
Q_INVOKABLE void dismissError();
signals:
+ void liveChanged();
+ void remoteSettingsChanged();
+ void audioQualityChanged();
+ void connectionChanged();
+ void connectionRestored();
void crossfadeChanged();
+ void audioOptionsChanged();
void apiFeedback(const QString &message, bool error);
void controlChanged();
void launchChanged();
@@ -146,12 +194,40 @@ private slots:
void propertiesChanged(const QString &interface, const QVariantMap &values, const QStringList &invalidated);
void seeked(qlonglong microseconds);
private:
+ void updateEvents();
+ bool m_listeningBusy=false;
+ bool m_liveVisible=false, m_eventQueue=false, m_eventSettings=false;
+ CiderEvents m_events;
+ QTimer m_eventCoalesce;
+ QString m_audioQuality;
+ bool m_qualityBusy=false;
+ QVariantMap m_undoTrack;
+ int m_undoIndex=-1, m_undoRevision=-1;
+ QElapsedTimer m_undoClock;
+ QVariantList m_insertItems;
+ QStringList m_insertExpected;
+ int m_insertAt=0, m_insertDone=0, m_insertPosition=-1;
+ bool m_restoringQueue=false;
+ void insertNext();
+ void verifyInsert(const QStringList &before,int beforePosition,std::function<void()> done,int attempts=24);
+ void finishInsert(bool success);
+ void observeConnection(int status, QNetworkReply::NetworkError error);
+ void scheduleRecovery();
+ bool saveToken();
+ bool m_libraryVisible=false;
+ int m_recoveryDelay=3000, m_tokenGeneration=0;
+ QString m_connectionState, m_connectionMessage;
+ QTimer m_recoveryTimer;
+ QPointer<QNetworkReply> m_authReply, m_probeReply;
void requestDiscJson(const QString &path, const QJsonObject &body, int generation, std::function<void(QJsonObject)> done);
void requestDiscTracks(const QString &path, int generation);
void failDisc(const QString &message);
- void apiRequest(const QByteArray &method, const QString &endpoint, const QJsonObject &body, std::function<void(bool,QJsonObject)> done);
+ void apiRequest(const QByteArray &method, const QString &endpoint, const QJsonObject &body, std::function<void(bool,QJsonObject)> done, bool reportError=true);
bool applyCrossfade(const QJsonObject &json);
void changeCrossfade(const QJsonObject &patch);
+ QVariantMap m_audioOptions;
+ QString m_audioError;
+ bool m_audioBusy=false, m_linkBusy=false;
bool m_crossfade=false, m_crossfadeReady=false, m_crossfadeBusy=false;
double m_crossfadeSeconds=5;
QString m_crossfadeError;
@@ -159,6 +235,16 @@ private:
bool applyModes(const QJsonObject &json);
void fetchQueue();
void editQueue(int from, int to, int revision, bool remove);
+ void batchNext();
+ void finishBatch(bool success);
+ QList<QPair<int,int>> m_batchOps;
+ QStringList m_batchExpected;
+ int m_batchDone=0, m_batchPosition=-1, m_batchGeneration=0;
+ void cleanupNext();
+ void finishCleanup(bool success);
+ QList<int> m_cleanupIndices;
+ QStringList m_cleanupExpected;
+ int m_cleanupDone=0, m_cleanupPosition=-1, m_cleanupGeneration=0;
void requestQueuePage(int offset);
void queueFailed(const QString &message, bool needsToken = false);
void apply(const QVariantMap &values);
diff --git a/src/ciderevents.cpp b/src/ciderevents.cpp
new file mode 100644
index 0000000..748c09c
--- /dev/null
+++ b/src/ciderevents.cpp
@@ -0,0 +1,89 @@
+#include "ciderevents.h"
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QJsonArray>
+#include <QUrlQuery>
+#include <QNetworkProxy>
+#include <QRegularExpression>
+#include <utility>
+
+CiderEvents::CiderEvents(QObject *parent):QObject(parent) {
+ m_network.setProxy(QNetworkProxy::NoProxy);
+ m_retry.setSingleShot(true);
+ connect(&m_retry,&QTimer::timeout,this,&CiderEvents::open);
+}
+CiderEvents::~CiderEvents() { m_enabled=false;stop(); }
+void CiderEvents::configure(bool enabled,const QUrl &base,const QByteArray &token) {
+ enabled=enabled && !token.isEmpty();
+ if(enabled==m_enabled && base==m_base && token==m_token)return;
+ stop();m_enabled=enabled;m_base=base;m_token=token;m_retryDelay=1000;
+ if(m_enabled)open();
+}
+void CiderEvents::stop() {
+ ++m_generation;m_retry.stop();
+ for(auto reply:{m_poll,m_post})if(reply) { reply->disconnect(this);reply->abort();reply->deleteLater(); }
+ m_poll=nullptr;m_post=nullptr;m_sid.clear();m_pending.clear();
+ if(m_connected) { m_connected=false;emit connectedChanged(); }
+}
+void CiderEvents::failed() {
+ stop();if(!m_enabled)return;
+ m_retry.start(m_retryDelay);m_retryDelay=qMin(60000,m_retryDelay*2);
+}
+QNetworkRequest CiderEvents::request() const {
+ auto url=m_base;url.setPath("/socket.io/");
+ QUrlQuery query;query.addQueryItem("EIO","4");query.addQueryItem("transport","polling");
+ if(!m_sid.isEmpty())query.addQueryItem("sid",QString::fromLatin1(m_sid));
+ url.setQuery(query);
+ QNetworkRequest req(url);req.setRawHeader("apptoken",m_token);req.setHeader(QNetworkRequest::ContentTypeHeader,"text/plain;charset=UTF-8");
+ req.setAttribute(QNetworkRequest::RedirectPolicyAttribute,QNetworkRequest::ManualRedirectPolicy);
+ req.setTransferTimeout(m_sid.isEmpty()?8000:m_timeout);return req;
+}
+void CiderEvents::open() { if(m_enabled)poll(); }
+void CiderEvents::poll() {
+ if(!m_enabled || m_poll)return;
+ auto *reply=m_network.get(request());m_poll=reply;const int generation=m_generation;
+ connect(reply,&QNetworkReply::readyRead,reply,[reply] { if(reply->bytesAvailable()>1024*1024)reply->abort(); });
+ connect(reply,&QNetworkReply::finished,this,[this,reply,generation] {
+ reply->deleteLater();if(generation!=m_generation)return;m_poll=nullptr;
+ if(reply->error()!=QNetworkReply::NoError || reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt()!=200) { failed();return; }
+ const auto bytes=reply->readAll();if(bytes.isEmpty() || bytes.size()>1024*1024) { failed();return; }
+ receive(bytes);
+ if(generation==m_generation && m_enabled)QTimer::singleShot(0,this,&CiderEvents::poll);
+ });
+}
+void CiderEvents::receive(const QByteArray &bytes) {
+ const int generation=m_generation;
+ for(const auto &packet:bytes.split('\x1e')) {
+ if(generation!=m_generation)return;
+ if(packet.startsWith('0') && m_sid.isEmpty()) {
+ const auto data=QJsonDocument::fromJson(packet.mid(1)).object();const auto sid=data.value("sid").toString();
+ if(!QRegularExpression("^[A-Za-z0-9_-]{1,200}$").match(sid).hasMatch()) { failed();return; }
+ m_sid=sid.toLatin1();m_timeout=qBound(10000,data.value("pingInterval").toInt(25000)+data.value("pingTimeout").toInt(20000)+5000,120000);send("40");
+ } else if(packet=="2")send("3");
+ else if(packet.startsWith("40") && !m_sid.isEmpty()) {
+ if(!m_connected) { m_connected=true;m_retryDelay=1000;emit connectedChanged(); }
+ } else if(packet.startsWith("42") && m_connected) {
+ const auto args=QJsonDocument::fromJson(packet.mid(2)).array();
+ if(args.size()==2 && args[0].toString()=="API:Playback") {
+ const auto type=args[1].toObject().value("type").toString();
+ // Events are invalidation hints, never authoritative queue data.
+ if(type.size()<128)emit event(type);
+ }
+ } else if(packet=="1" || packet.startsWith("41") || packet.startsWith("44")) { failed();return; }
+ }
+}
+void CiderEvents::send(const QByteArray &packet) {
+ if(!m_pending.isEmpty())m_pending+='\x1e';
+ m_pending+=packet;
+ if(m_pending.size()>4096) { failed();return; }flush();
+}
+void CiderEvents::flush() {
+ if(m_post || m_pending.isEmpty() || !m_enabled)return;
+ auto req=request();req.setTransferTimeout(8000);
+ auto *reply=m_network.post(req,std::exchange(m_pending,{}));m_post=reply;const int generation=m_generation;
+ connect(reply,&QNetworkReply::readyRead,reply,[reply] { if(reply->bytesAvailable()>4096)reply->abort(); });
+ connect(reply,&QNetworkReply::finished,this,[this,reply,generation] {
+ reply->deleteLater();if(generation!=m_generation)return;m_post=nullptr;
+ if(reply->error()!=QNetworkReply::NoError || reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt()!=200) { failed();return; }flush();
+ });
+}
diff --git a/src/ciderevents.h b/src/ciderevents.h
new file mode 100644
index 0000000..fce352b
--- /dev/null
+++ b/src/ciderevents.h
@@ -0,0 +1,36 @@
+#pragma once
+#include <QObject>
+#include <QNetworkAccessManager>
+#include <QPointer>
+#include <QNetworkReply>
+#include <QTimer>
+
+// Socket.IO's HTTP transport uses the existing Qt network stack. One pending
+// long-poll sleeps on Cider; no WebSocket or JavaScript runtime is bundled.
+class CiderEvents : public QObject {
+ Q_OBJECT
+public:
+ explicit CiderEvents(QObject *parent=nullptr);
+ ~CiderEvents() override;
+ void configure(bool enabled, const QUrl &base, const QByteArray &token);
+ bool connected() const { return m_connected; }
+signals:
+ void connectedChanged();
+ void event(const QString &type);
+private:
+ void open();
+ void stop();
+ void failed();
+ void poll();
+ void receive(const QByteArray &bytes);
+ void send(const QByteArray &packet);
+ void flush();
+ QNetworkRequest request() const;
+ QNetworkAccessManager m_network;
+ QPointer<QNetworkReply> m_poll, m_post;
+ QTimer m_retry;
+ QUrl m_base;
+ QByteArray m_token, m_sid, m_pending;
+ bool m_enabled=false, m_connected=false;
+ int m_generation=0, m_retryDelay=1000, m_timeout=35000;
+};
diff --git a/src/disc.cpp b/src/disc.cpp
index be78b39..971a2cb 100644
--- a/src/disc.cpp
+++ b/src/disc.cpp
@@ -55,6 +55,7 @@ void Disc::paint(QPainter *p) {
const double side = qMin(width(), height());
p->translate((width() - side) / 2, (height() - side) / 2);
p->scale(side / 1000, side / 1000);
+ if (m_vinyl) { paintVinyl(p); return; }
const QPointF center(500, 500);
QPainterPath annulus;
annulus.setFillRule(Qt::OddEvenFill);
@@ -110,6 +111,48 @@ void Disc::paint(QPainter *p) {
p->setPen(QPen(QColor(255, 255, 255, 150), 1.3)); p->drawEllipse(center, 59, 59);
}
+void Disc::paintVinyl(QPainter *p) {
+ const QPointF center(500,500);
+ QPainterPath record; record.setFillRule(Qt::OddEvenFill);
+ record.addEllipse(center,497,497); record.addEllipse(center,16,16);
+ p->setClipPath(record);
+ if (m_overlay) {
+ // Fixed light over a rotating, cached record texture; no per-frame painting.
+ QConicalGradient sheen(center,24);
+ sheen.setColorAt(0,Qt::transparent); sheen.setColorAt(.12,QColor(190,202,218,18));
+ sheen.setColorAt(.22,Qt::transparent); sheen.setColorAt(.5,Qt::transparent);
+ sheen.setColorAt(.63,QColor(255,235,205,14)); sheen.setColorAt(.73,Qt::transparent); sheen.setColorAt(1,Qt::transparent);
+ p->fillPath(record,sheen); return;
+ }
+ QRadialGradient body(center,500);
+ body.setColorAt(0,QColor("#141519")); body.setColorAt(.46,QColor("#17181c"));
+ body.setColorAt(.94,QColor("#101114")); body.setColorAt(1,QColor("#24252a"));
+ p->fillPath(record,body);
+ p->setBrush(Qt::NoBrush);
+ const int inner=m_labelColor.isValid()?475:213;
+ for (int r=inner;r<488;r+=4) {
+ p->setPen(QPen(QColor(180,185,195,(r%12==1)?26:12),.85));p->drawEllipse(center,r,r);
+ p->setPen(QPen(QColor(0,0,0,75),1));p->drawEllipse(center,r+1.5,r+1.5);
+ }
+ if(!m_labelColor.isValid()) {
+ for(int r:{242,310,381,452}) { p->setPen(QPen(QColor(2,3,5,115),3));p->drawEllipse(center,r,r); }
+ }
+ const double radius=m_labelColor.isValid()?470:198;
+ QPainterPath label; label.addEllipse(center,radius,radius);
+ p->save();p->setClipPath(label,Qt::IntersectClip);
+ if(m_labelColor.isValid())p->fillPath(label,m_labelColor);
+ else {
+ if(m_art.isNull()&&m_fallback.isNull()) { static const QImage shared=fallbackArt();m_fallback=shared; }
+ const auto &art=m_art.isNull()?m_fallback:m_art;const double crop=qMin(art.width(),art.height());
+ p->drawImage(QRectF(500-radius,500-radius,radius*2,radius*2),art,QRectF((art.width()-crop)/2,(art.height()-crop)/2,crop,crop));
+ }
+ p->restore();
+ p->setBrush(Qt::NoBrush);p->setPen(QPen(QColor(0,0,0,120),3));p->drawEllipse(center,radius+1,radius+1);
+ if(!m_labelColor.isValid()) {p->setPen(QPen(QColor(255,255,255,32),1));p->drawEllipse(center,178,178);}
+ p->setPen(QPen(QColor(0,0,0,170),3));p->drawEllipse(center,18,18);
+ p->setPen(QPen(QColor(255,255,255,40),1));p->drawEllipse(center,21,21);
+}
+
class RingNode final : public QSGGeometryNode {
public:
int capacity = 0, indexCapacity = 0, indexedSteps = -1;
diff --git a/src/disc.h b/src/disc.h
index 4eead43..ac5719d 100644
--- a/src/disc.h
+++ b/src/disc.h
@@ -5,12 +5,15 @@
class Disc : public QQuickPaintedItem {
Q_OBJECT
+ Q_PROPERTY(bool vinyl READ vinyl WRITE setVinyl NOTIFY vinylChanged)
Q_PROPERTY(QImage artwork READ artwork WRITE setArtwork NOTIFY artworkChanged)
Q_PROPERTY(QColor labelColor READ labelColor WRITE setLabelColor NOTIFY labelColorChanged)
Q_PROPERTY(bool overlay READ overlay WRITE setOverlay NOTIFY overlayChanged)
public:
explicit Disc(QQuickItem *parent = nullptr);
void paint(QPainter *painter) override;
+ bool vinyl() const { return m_vinyl; }
+ void setVinyl(bool value) { if(m_vinyl==value)return; m_vinyl=value; update(); emit vinylChanged(); }
QImage artwork() const { return m_art; }
void setArtwork(const QImage &image);
bool overlay() const { return m_overlay; }
@@ -19,13 +22,15 @@ public:
void setLabelColor(const QColor &value) { if (m_labelColor==value) return; m_labelColor=value; update(); emit labelColorChanged(); }
static QImage fallbackArt(int size = 1000);
signals:
+ void vinylChanged();
void artworkChanged();
void overlayChanged();
void labelColorChanged();
private:
QImage m_art, m_fallback;
QColor m_labelColor;
- bool m_overlay = false;
+ bool m_overlay = false, m_vinyl = false;
+ void paintVinyl(QPainter *painter);
};
class ProgressRing : public QQuickItem {
diff --git a/src/eventstest.cpp b/src/eventstest.cpp
new file mode 100644
index 0000000..ab7264f
--- /dev/null
+++ b/src/eventstest.cpp
@@ -0,0 +1,62 @@
+#include "cider.h"
+#include <QTcpServer>
+#include <QTcpSocket>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QJsonArray>
+#include <QTest>
+#include <QElapsedTimer>
+#include <QFile>
+#include <iostream>
+#include <utility>
+
+int exerciseCiderEvents(const QString &temp) {
+ int failures=0,requests=0,queueReads=0,pongs=0;bool reject=false;
+ QByteArray pending;
+ const QByteArray queueEvent="42[\"API:Playback\",{\"type\":\"queueStatus.queueChanged\",\"data\":{}}]";
+ auto check=[&](bool ok,const char *label) { std::cout<<(ok?"PASS ":"FAIL ")<<label<<std::endl;if(!ok)++failures; };
+ auto wait=[&](auto condition) { QElapsedTimer clock;clock.start();while(!condition()&&clock.elapsed()<5000)QTest::qWait(20);return condition(); };
+ QTcpServer server;check(server.listen(QHostAddress::LocalHost),"event fixture starts");
+ QObject::connect(&server,&QTcpServer::newConnection,&server,[&] {
+ auto *socket=server.nextPendingConnection();QObject::connect(socket,&QTcpSocket::disconnected,socket,&QObject::deleteLater);
+ QObject::connect(socket,&QTcpSocket::readyRead,socket,[&,socket] {
+ auto bytes=socket->property("buffer").toByteArray()+socket->readAll();socket->setProperty("buffer",bytes);
+ const int split=bytes.indexOf("\r\n\r\n");if(split<0)return;
+ int size=0;for(const auto &line:bytes.left(split).toLower().split('\n'))if(line.startsWith("content-length:"))size=line.mid(15).trimmed().toInt();
+ if(bytes.size()<split+4+size)return;
+ ++requests;const auto path=bytes.split(' ').value(1),body=bytes.mid(split+4,size);QByteArray result;int status=200,delay=15;
+ if(!bytes.left(split).contains("event-test-token"))status=403;
+ else if(path.startsWith("/socket.io/")) {
+ if(reject)status=503;
+ else if(bytes.startsWith("POST")) {
+ if(body.contains("40"))pending="40{}";
+ if(body.contains('3'))++pongs;
+ result="ok";
+ } else if(!path.contains("sid="))result="0{\"sid\":\"test-session\",\"pingInterval\":1000,\"pingTimeout\":1000}";
+ else { result=pending.isEmpty()?QByteArray("2"):std::exchange(pending,{});delay=60; }
+ } else if(path.startsWith("/api/v2/queue?")) {
+ ++queueReads;result="{\"data\":{\"position\":-1,\"items\":[]},\"meta\":{\"total\":0}}";
+ } else { status=404;result="{}"; }
+ QTimer::singleShot(delay,socket,[socket,result,status] {
+ socket->write("HTTP/1.1 "+QByteArray::number(status)+" Result\r\nContent-Length: "+QByteArray::number(result.size())+"\r\nConnection: close\r\n\r\n"+result);socket->disconnectFromHost();
+ });
+ });
+ });
+ const QString config=temp+"/events-connection.json";QFile file(config);check(file.open(QIODevice::WriteOnly),"event fixture token file opens");file.write("{\"token\":\"event-test-token\"}");file.close();
+ Cider cider(false,config,QUrl("http://127.0.0.1:"+QString::number(server.serverPort())));
+ cider.setQueueVisible(true);cider.setLiveVisible(true);
+ check(wait([&]{return cider.liveConnected()&&!cider.queueBusy();}),"event stream authenticates and reconciles queue on connect");
+ check(wait([&]{return pongs>0;}),"event stream answers Engine.IO heartbeat");
+ QTest::qWait(200);const int before=queueReads;
+ for(int i=0;i<20;++i) { if(!pending.isEmpty())pending+='\x1e';pending+=queueEvent; }
+ check(wait([&]{return queueReads>before;}),"external queue event refreshes the visible queue");QTest::qWait(350);
+ check(queueReads==before+1,"burst of queue events produces one readback");
+ const int beforeUnknown=queueReads;pending="42[\"API:Playback\",{\"type\":\"playbackStatus.playbackTimeDidChange\"}]";QTest::qWait(350);
+ check(queueReads==beforeUnknown,"playback ticks do not trigger queue requests");
+ reject=true;check(wait([&]{return !cider.liveConnected();}),"failed event transport falls back without clearing queue");
+ check(cider.queueReady(),"event outage retains the confirmed queue");reject=false;
+ check(wait([&]{return cider.liveConnected();}),"event connection recovers with backoff");
+ cider.setLiveVisible(false);cider.setQueueVisible(false);QTest::qWait(100);const int stopped=requests;QTest::qWait(300);
+ check(!cider.liveConnected()&&requests==stopped,"hidden player stops event requests and reconnect timers");
+ server.close();return failures;
+}
diff --git a/src/library.cpp b/src/library.cpp
index be7d977..027d0e8 100644
--- a/src/library.cpp
+++ b/src/library.cpp
@@ -8,27 +8,56 @@
#include <QNetworkProxy>
#include <QRegularExpression>
#include <QUrlQuery>
+#include <QFile>
+#include <QFileInfo>
+#include <QDir>
+#include <QSaveFile>
+#include <QUuid>
+#include <QSettings>
+#include <algorithm>
Library::Library(Cider *cider, QObject *parent) : QObject(parent), m_cider(cider) {
+ if (!cider->m_connectionPath.isEmpty()) {
+ m_sortSettings=QFileInfo(cider->m_connectionPath).dir().filePath("settings.ini");
+ for (const auto &term:QSettings(m_sortSettings,QSettings::IniFormat).value("recentSearches").toStringList().mid(0,8))
+ if (!term.trimmed().isEmpty() && term.size()<=200 && !m_recentSearches.contains(term)) m_recentSearches.append(term);
+ m_newestFirst=QSettings(m_sortSettings,QSettings::IniFormat).value("libraryNewestFirst",false).toBool();
+ m_sessionsDir=QFileInfo(cider->m_connectionPath).dir().filePath("saved-queues");
+ m_pinsPath=QFileInfo(cider->m_connectionPath).dir().filePath("cider-pins.json");
+ QFile file(m_pinsPath);
+ if (file.open(QIODevice::ReadOnly) && file.size()<=1024*1024) {
+ for (const auto &entry:QJsonDocument::fromJson(file.readAll()).array()) {
+ const auto pin=validatedPin(entry.toObject().toVariantMap());
+ if (!pin.isEmpty() && !isPinned(pin) && m_pins.size()<200) m_pins.append(pin);
+ }
+ }
+ }
+ connect(cider,&Cider::connectionRestored,this,[this] { if(m_active && (m_needsConnection || !m_error.isEmpty())) reload(); });
+ m_savedUndoTimer.setSingleShot(true);m_savedUndoTimer.setInterval(8000);
+ connect(&m_savedUndoTimer,&QTimer::timeout,this,&Library::clearSavedUndo);
+ connect(this,&Library::changed,this,[this] { if(preparingTail()) QTimer::singleShot(0,this,&Library::continueTail); });
m_network.setProxy(QNetworkProxy::NoProxy);
m_debounce.setSingleShot(true); m_debounce.setInterval(350);
connect(&m_debounce, &QTimer::timeout, this, &Library::reload);
}
Library::~Library() {
- for (auto reply : {m_reply, m_actionReply}) if (reply) { reply->disconnect(this); reply->abort(); }
+ clearSavedUndo();
+ for (auto reply : {m_reply, m_actionReply, m_radioReply}) if (reply) { reply->disconnect(this); reply->abort(); }
}
void Library::setItems(const QVariantList &items, bool append) {
- emit itemsChanging(append); m_items=items; emit itemsChanged();
+ emit itemsChanging(append || m_preservePosition); m_items=items; emit itemsChanged();
}
void Library::invalidate() {
- ++m_generation; m_debounce.stop();
+ cancelQueueFromHere();
+ ++m_generation; m_debounce.stop(); m_preservePosition=false;
if (m_reply) m_reply->abort();
m_busy=false; m_loaded=false; m_error.clear(); m_playError.clear(); m_needsConnection=false;
}
void Library::setActive(bool value) {
if (m_active==value) return;
- m_active=value;
+ m_active=value; m_cider->setLibraryVisible(value);
if (!value) {
+ cancelQueueFromHere();
++m_generation; m_debounce.stop();
if (m_busy) m_loaded=false;
if (m_reply) m_reply->abort();
@@ -37,21 +66,25 @@ void Library::setActive(bool value) {
emit changed();
}
void Library::setSection(const QString &value) {
- if (value==m_section || !QStringList{"search","songs","albums","playlists","recent"}.contains(value)) return;
- invalidate(); m_section=value; m_query.clear(); m_collectionQuery.clear(); m_allItems.clear(); m_filterText.clear(); m_collection.clear(); setItems({}); m_next.clear();
- m_savedItems.clear(); m_savedPages.clear();
- emit changed(); if (m_active) reload();
+ if (value==m_section || !QStringList{"search","songs","albums","playlists","recent","sessions","releases","for-you"}.contains(value)) return;
+ invalidate(); m_findArtist=false; m_section=value; m_query.clear(); m_collectionQuery.clear(); m_allItems.clear(); m_filterText.clear(); m_collection.clear(); setItems({}); m_next.clear();
+ m_history.clear(); emit navigationReset();
+ emit changed(); if (m_active) {
+ if(value=="releases" && m_releaseClock.isValid() && m_releaseClock.elapsed()<3600000 && m_releaseTokenGeneration==m_cider->m_tokenGeneration) {
+ m_allItems=m_releaseCache; m_filterText.clear(); filterItems(); m_loaded=true; m_releaseNotice.clear(); emit changed();
+ } else reload();
+ }
}
void Library::setQuery(const QString &value) {
const auto query=value.left(2048);
if (query==m_query || !m_collection.isEmpty()) return;
- if (m_section=="recent") {
+ if (m_section=="recent" || m_section=="sessions" || m_section=="releases" || m_section=="for-you") {
m_query=query; filterItems(); emit changed(); continueSearch(); return;
}
- invalidate(); m_query=query; setItems({}); m_next.clear(); emit changed();
+ invalidate(); m_findArtist=false; m_query=query; setItems({}); m_next.clear(); emit changed();
if (m_active) { m_busy=true; m_debounce.start(); emit changed(); }
}
-bool Library::filteringLocally() const { return !m_collection.isEmpty() || m_section=="recent"; }
+bool Library::filteringLocally() const { return !m_collection.isEmpty() || m_section=="recent" || m_section=="sessions" || m_section=="releases" || m_section=="for-you"; }
void Library::setCollectionQuery(const QString &value) {
const auto query=value.left(200);
if (m_collection.isEmpty() || m_collectionQuery==query) return;
@@ -71,7 +104,7 @@ void Library::filterItems(bool append) {
m_filterText.reserve(m_allItems.size());
while (m_filterText.size()<m_allItems.size()) {
const auto row=m_allItems[m_filterText.size()].toMap();
- m_filterText.append(fold(row["title"].toString()+" "+row["artist"].toString()));
+ m_filterText.append(fold(row["title"].toString()+" "+row["artist"].toString()+" "+row["recommendation"].toString()));
}
QVariantList rows;
for (qsizetype i=0;i<m_allItems.size();++i) {
@@ -92,8 +125,8 @@ void Library::continueSearch() {
});
}
void Library::setKind(const QString &value) {
- if (value==m_kind || !QStringList{"songs","albums","playlists"}.contains(value)) return;
- invalidate(); m_kind=value; setItems({}); m_next.clear(); emit changed(); if (m_active) reload();
+ if (value==m_kind || !QStringList{"songs","albums","playlists","artists","stations"}.contains(value)) return;
+ invalidate(); m_findArtist=false; m_kind=value; m_history.clear(); emit navigationReset(); setItems({}); m_next.clear(); emit changed(); if (m_active) reload();
}
// Resolve only explicit Apple Music catalog URLs. Never follow a pasted URL or
// forward it (or the Cider token) to an arbitrary origin.
@@ -105,10 +138,10 @@ QString Library::linkPath(const QString &text) {
const auto parts=url.path().split('/',Qt::SkipEmptyParts);
if (parts.contains(".") || parts.contains("..") || parts.size()<3 || parts.size()>4 || !QRegularExpression("^[a-z]{2}$").match(parts[0]).hasMatch()) return {};
QString type=parts[1], id=parts.last();
- if (!QStringList{"song","album","playlist"}.contains(type)) return {};
+ if (!QStringList{"song","album","playlist","station"}.contains(type)) return {};
const QUrlQuery query(url);
if (type=="album" && query.hasQueryItem("i")) { type="song"; id=query.queryItemValue("i"); }
- const auto pattern=type=="playlist" ? "^pl\\.[A-Za-z0-9.-]+$" : "^[0-9]+$";
+ const auto pattern=type=="station" ? "^ra\\.[A-Za-z0-9.-]+$" : type=="playlist" ? "^pl\\.[A-Za-z0-9.-]+$" : "^[0-9]+$";
if (!QRegularExpression(pattern).match(id).hasMatch()) return {};
return "/v1/catalog/"+parts[0]+"/"+type+"s/"+id;
}
@@ -122,15 +155,16 @@ bool Library::openLink(const QString &text) {
}
bool Library::openClipboardLink() { return openLink(QGuiApplication::clipboard()->text()); }
QString Library::resultType() const {
+ if (m_collection.value("type")=="artists") return m_artistView=="similar" ? "artists" : m_artistView;
if (!m_collection.isEmpty()) return m_collection["type"].toString().startsWith("library-") ? "library-songs" : "songs";
if (m_section=="recent") return "songs";
return m_section=="search" ? m_kind : "library-"+m_section;
}
QString Library::listPath() const {
- if (!m_collection.isEmpty()) return m_collection["path"].toString()+"/tracks?limit=50";
+ if (!m_collection.isEmpty()) return collectionPath()+(m_collection.value("type")=="artists" && m_artistView=="songs"?"?limit=25":"?limit=50");
if (m_section=="recent") return "/v1/me/recent/played/tracks?types=songs,library-songs&limit=30";
if (m_section=="search" && !linkPath(m_query).isEmpty()) return linkPath(m_query);
- if (m_query.trimmed().isEmpty()) return m_section=="search" ? QString() : "/v1/me/library/"+m_section+"?limit=50";
+ if (m_query.trimmed().isEmpty()) return m_section=="search" ? QString() : "/v1/me/library/"+m_section+"?limit=50"+(m_newestFirst && (m_section=="songs" || m_section=="albums")?"&sort=-dateAdded":"");
QUrl url(m_section=="search" ? "/v1/catalog/"+m_storefront+"/search" : "/v1/me/library/search");
QUrlQuery query; query.addQueryItem("term",m_query.trimmed().left(200)); query.addQueryItem("types",resultType()); query.addQueryItem("limit","25");
url.setQuery(query); return url.toString(QUrl::FullyEncoded);
@@ -149,15 +183,20 @@ void Library::request(const QString &path, const QJsonObject &body, bool action,
reply->deleteLater();
if (!action && generation!=m_generation) return;
const int status=reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
+ // A denied library capability does not invalidate working playback/queue access.
+ // Unauthorized tokens and transport outages still update the shared connection.
+ if(status!=403 || action)m_cider->observeConnection(status,reply->error());
const auto json=QJsonDocument::fromJson(reply->readAll());
auto object=json.object();
const bool upstreamError=object.contains("errors") || object.value("data").toObject().contains("errors");
if (reply->error()!=QNetworkReply::NoError || status<200 || status>=300 || !json.isObject() || upstreamError) {
QString message;
- if (status==401 || status==403) { message="Check Spun’s access token in Cider."; m_needsConnection=true; }
+ if (status==401 || status==403) { message="Reconnect to approve Spun’s access in Cider."; m_needsConnection=true; }
+ else if(status==404 && m_section=="for-you" && m_collection.isEmpty()) message="For You isn’t available through this Cider connection.";
else if (status==422) message="No playable tracks in this collection.";
- else if (status==404) message="This item is no longer available.";
- else if (reply->error()==QNetworkReply::ConnectionRefusedError) message="Open Cider to browse your music.";
+ else if(status==404 && m_collection.value("type")=="artists" && m_artistView=="albums" && m_discography!="all") message="This release category isn’t available through Cider.";
+ else if (status==404) message=m_collection.value("type")=="artists" && m_artistView=="songs" ? "Top songs aren’t available through this Cider connection." : "This item is no longer available.";
+ else if (!status) message=m_cider->connectionMessage();
else message=action ? "Cider couldn’t start playback. Try again." : "Couldn’t load music. Try again.";
if (action) { m_starting=false; m_playError=message; }
else { m_busy=false; m_error=message; }
@@ -168,7 +207,25 @@ void Library::request(const QString &path, const QJsonObject &body, bool action,
}
void Library::reload() {
if (!m_active) return;
- invalidate(); m_allItems.clear(); m_filterText.clear(); setItems({}); m_next.clear(); m_pages.clear();
+ invalidate(); m_preservePosition=!m_items.isEmpty(); m_pages.clear();
+ if(m_section=="releases" && m_collection.isEmpty()) { fetchReleases(); return; }
+ if(m_section=="for-you" && m_collection.isEmpty()) { m_recommendationPages.clear();m_next.clear();fetchRecommendations("/v1/me/recommendations?limit=10",false);return; }
+ if(m_section=="sessions") {
+ bool valid=true;
+ const auto sessions=readSessions(&valid);
+ if(m_collection.isEmpty())m_allItems=sessions;
+ else {
+ const auto id=m_collection.value("id").toString();QVariantMap current;
+ for(const auto &entry:sessions)if(entry.toMap().value("id")==id)current=entry.toMap();
+ m_allItems.clear();
+ if(current.isEmpty())m_error="This saved queue is no longer available.";
+ else { m_collection=current;m_allItems=savedTracks(id);
+ for(int i=0;i<m_allItems.size();++i) { auto row=m_allItems[i].toMap();row["savedIndex"]=i;row["collectionIndex"]=i;m_allItems[i]=row; }
+ }
+ }
+ if(!valid)m_error="Couldn’t read the saved queue list.";
+ m_filterText.clear();filterItems();m_next.clear();m_loaded=true;m_preservePosition=false;emit changed();return;
+ }
if (m_cider->m_apiToken.isEmpty()) {
m_needsConnection=true; m_error="Connect Spun to Cider to browse music."; emit changed(); return;
}
@@ -192,24 +249,25 @@ QVariantMap Library::item(const QJsonObject &value, const QString &fallbackType)
const auto attrs=value.value("attributes").toObject();
const auto type=value.value("type").toString(fallbackType), id=value.value("id").toString();
if (!validId.match(id).hasMatch() ||
- !QStringList{"songs","albums","playlists","library-songs","library-albums","library-playlists"}.contains(type)) return {};
+ !QStringList{"songs","albums","playlists","library-songs","library-albums","library-playlists","artists","stations"}.contains(type)) return {};
QString artwork=attrs.value("artwork").toObject().value("url").toString();
artwork.replace("{w}","160").replace("{h}","160").replace("{f}","jpg");
const QUrl artUrl(artwork);
if (artUrl.scheme()!="https") artwork.clear();
const auto playParams=attrs.value("playParams").toObject();
return {{"id",id},{"type",type},{"title",attrs.value("name").toString()},
- {"artist",attrs.value("artistName").toString(attrs.value("curatorName").toString())},
+ {"artist",type=="artists"?attrs.value("genreNames").toVariant().toStringList().join(" · "):attrs.value("artistName").toString(attrs.value("curatorName").toString())},
{"artwork",artwork},{"year",attrs.value("releaseDate").toString().left(4)},
- {"duration",attrs.value("durationInMillis").toInteger()},
+ {"duration",attrs.value("durationInMillis").toInteger()},{"releaseDate",attrs.value("releaseDate").toString()},
{"trackCount",attrs.value("trackCount").toInt(-1)},
+ {"catalogId",playParams.value("catalogId").toString()},{"url",attrs.value("url").toString()},
{"playable",!playParams.isEmpty()}, {"path",value.value("href").toString()}};
}
void Library::fetch(const QString &path, bool append) {
- if (path.isEmpty()) { m_busy=false; m_loaded=true; emit changed(); return; }
+ if (path.isEmpty()) { m_busy=false; m_loaded=true; m_next.clear(); setItems({}); m_preservePosition=false; emit changed(); return; }
const QUrl target(path);
const QString linked=m_section=="search" && m_collection.isEmpty() ? linkPath(m_query) : QString();
- const QString base=m_section=="recent" && m_collection.isEmpty() ? "/v1/me/recent/played/tracks" : !linked.isEmpty() ? linked : m_collection.isEmpty() ? (m_section=="search" ? "/v1/catalog/"+m_storefront+"/search" : "/v1/me/library/"+(m_query.trimmed().isEmpty() ? m_section : "search")) : m_collection["path"].toString()+"/tracks";
+ const QString base=m_section=="recent" && m_collection.isEmpty() ? "/v1/me/recent/played/tracks" : !linked.isEmpty() ? linked : m_collection.isEmpty() ? (m_section=="search" ? "/v1/catalog/"+m_storefront+"/search" : "/v1/me/library/"+(m_query.trimmed().isEmpty() ? m_section : "search")) : collectionPath();
if (!target.isRelative() || target.hasFragment() || target.path()!=base || m_pages.contains(path)) {
m_busy=false; m_error="Couldn’t load the next page."; m_next.clear(); emit changed(); return;
}
@@ -236,36 +294,635 @@ void Library::fetch(const QString &path, bool append) {
row["path"]=type=="library-songs" ? expected :
catalogSong.match(href).hasMatch() ? href : QString();
}
+ if(tailCollection())row["collectionIndex"]=rows.size();
rows.append(row);
}
if (filteringLocally()) { if (!append) m_filterText.clear(); m_allItems=rows; filterItems(append); }
else setItems(rows,append);
m_next=linked.isEmpty() ? data.value("next").toString() : QString(); m_pages.insert(path);
- m_busy=false; m_loaded=true; emit changed(); continueSearch();
+ m_preservePosition=false; m_busy=false; m_loaded=true; emit changed(); continueSearch();
+ if(m_findArtist && m_collection.isEmpty()) {
+ m_findArtist=false; int match=-1, count=0;
+ for(int i=0;i<m_items.size();++i) if(m_items[i].toMap().value("title").toString().compare(m_query.trimmed(),Qt::CaseInsensitive)==0) { match=i; ++count; }
+ if(count==1)open(match);
+ }
});
}
-void Library::more() { if (m_active && !m_busy && !m_next.isEmpty()) fetch(m_next,true); }
+void Library::more() {
+ if(!m_active || m_busy || m_next.isEmpty())return;
+ if(m_section=="for-you" && m_collection.isEmpty()) {
+ if(!m_recommendationPages.isEmpty()) {const auto page=m_recommendationPages.first().toMap();fetchRecommendations(page.value("path").toString(),true,page.value("reason").toString());}
+ return;
+ }
+ QUrl next(m_next);
+ if(m_newestFirst && m_collection.isEmpty() && m_query.trimmed().isEmpty() && (m_section=="songs" || m_section=="albums")) {
+ QUrlQuery query(next);query.removeAllQueryItems("sort");query.addQueryItem("sort","-dateAdded");next.setQuery(query);
+ }
+ fetch(next.toString(QUrl::FullyEncoded),true);
+}
+void Library::pushPage() {
+ if(m_history.size()>=16)m_history.removeFirst();
+ m_history.append({m_collection,m_items,m_allItems,m_next,m_collectionQuery,m_artistView,m_discography,m_recommendationPages,m_pages}); emit navigating();
+}
void Library::open(int index) {
- if (index<0 || index>=m_items.size() || m_busy || !m_collection.isEmpty()) return;
+ if(index<0 || index>=m_items.size() || m_busy)return;
const auto selected=m_items[index].toMap();
- if (selected["type"].toString().endsWith("songs")) { play(index); return; }
- m_savedItems=m_items; m_savedNext=m_next; m_savedPages=m_pages;
- m_collectionQuery.clear(); m_collection=selected; reload();
+ if(selected.value("type").toString().endsWith("songs") || selected.value("type")=="stations") {play(index);return;}
+ if(!m_collection.isEmpty() && m_collection.value("type")!="artists")return;
+ rememberSearch();
+ pushPage(); m_collectionQuery.clear(); m_collection=selected; if(selected.value("type")=="artists") {m_artistView="albums";m_discography="all";} setItems({}); reload();
}
void Library::back() {
- if (m_collection.isEmpty()) return;
- invalidate(); m_collectionQuery.clear(); m_allItems.clear(); m_filterText.clear(); m_collection.clear(); setItems(m_savedItems); m_next=m_savedNext; m_pages=m_savedPages;
- m_loaded=true; emit changed(); emit returned();
+ if(m_history.isEmpty())return;
+ invalidate(); const auto page=m_history.takeLast();
+ m_collection=page.collection; m_artistView=page.artistView; m_discography=page.discography;m_recommendationPages=page.recommendationPages; m_collectionQuery=page.collectionQuery; m_allItems=page.allItems; m_filterText.clear();
+ setItems(page.items); m_next=page.next; m_pages=page.pages; m_loaded=true;
+ if(m_section=="sessions" && m_collection.isEmpty())reload();
+ emit changed(); emit returned();
+}
+void Library::showArtist(const QString &name) {
+ if(name.trimmed().isEmpty())return;
+ invalidate(); m_history.clear();emit navigationReset();
+ m_collection.clear();m_collectionQuery.clear();m_allItems.clear();m_filterText.clear();m_next.clear();setItems({});
+ m_section="search";m_kind="artists";m_query=name.trimmed().left(200);m_findArtist=true;emit changed();reload();
}
+bool Library::tailCollection() const {
+ const auto type=m_collection.value("type").toString();
+ return type.endsWith("albums") || type.endsWith("playlists") || type=="saved-queues";
+}
+void Library::cancelQueueFromHere() {
+ if(!preparingTail())return;
+ m_tailIndex=-1;m_tailAnchor.clear();emit changed();
+}
+void Library::queueFromHere(const QVariantMap &selected) {
+ if(!m_active || preparingTail() || m_starting || m_cider->controlBusy() || !tailCollection() || !selected.contains("collectionIndex"))return;
+ const int index=selected.value("collectionIndex").toInt();
+ if(index<0 || index>=m_allItems.size() || m_allItems[index].toMap()!=selected)return;
+ m_tailIndex=index;m_tailAnchor=selected;emit feedback("Loading remaining tracks…",false);emit changed();continueTail();
+}
+void Library::continueTail() {
+ if(!preparingTail() || m_busy)return;
+ if(!m_error.isEmpty() || m_tailIndex>=m_allItems.size() || m_allItems[m_tailIndex].toMap()!=m_tailAnchor) {
+ cancelQueueFromHere();emit feedback("Couldn’t read the remaining tracks. Nothing was queued.",true);return;
+ }
+ if(m_allItems.size()-m_tailIndex>5000) { cancelQueueFromHere();emit feedback("Select a smaller range; the limit is 5,000 tracks.",true);return; }
+ if(!m_next.isEmpty()) { more();return; }
+ const auto tracks=m_allItems.mid(m_tailIndex);cancelQueueFromHere();
+ for(const auto &value:tracks)if(!value.toMap().value("playable").toBool()) {
+ emit feedback("This range includes unavailable songs. Select available tracks instead.",true);return;
+ }
+ emit tailReady(tracks);
+}
+
void Library::play(int index) { if (m_active && index>=0 && index<m_items.size()) start(m_items[index].toMap()); }
void Library::playCollection() { if (m_active && !m_collection.isEmpty()) start(m_collection); }
-void Library::start(const QVariantMap &selected) {
- if (m_starting || !selected["playable"].toBool()) return;
+void Library::shuffleCollection(const QVariantMap &selected) {
+ if (!m_active || validatedPin(selected).isEmpty() || selected.value("type")=="stations") return;
+ start(selected,true);
+}
+void Library::start(const QVariantMap &selected, bool shuffle) {
+ if (m_starting || m_cider->controlBusy() || selected.value("type")=="artists" || !selected["playable"].toBool()) return;
const bool song=selected["type"].toString().endsWith("songs");
+ rememberSearch();
m_starting=true; m_playError.clear(); emit changed();
- request(song ? "/api/v2/playback/play-item" : "/api/v2/playback/play-collection",
- {{"type",selected["type"].toString()},{"id",selected["id"].toString()}},true,[this](QJsonObject) {
+ QJsonObject body{{"type",selected["type"].toString()},{"id",selected["id"].toString()}};
+ if(!song)body["shuffle"]=shuffle;
+ request(song ? "/api/v2/playback/play-item" : "/api/v2/playback/play-collection",body,true,[this](QJsonObject) {
m_starting=false; emit changed();
QTimer::singleShot(600,m_cider,[cider=m_cider] { cider->refresh(); if (cider->queueVisible()) cider->refreshQueue(); });
});
}
+
+QVariantMap Library::validatedPin(const QVariantMap &row) {
+ const auto type=row.value("type").toString(), id=row.value("id").toString(), path=row.value("path").toString();
+ static const QRegularExpression identifier("^[A-Za-z0-9._-]{1,200}$");
+ if (!QStringList{"albums","playlists","library-albums","library-playlists","stations","artists"}.contains(type) || !identifier.match(id).hasMatch()) return {};
+ const QString prefix=type.startsWith("library-")?"/v1/me/library/"+type.mid(8):"/v1/catalog/"+path.split('/').value(3)+"/"+type;
+ if (path!=prefix+"/"+id || (!type.startsWith("library-") && !QRegularExpression("^[a-z]{2}$").match(path.split('/').value(3)).hasMatch())) return {};
+ QVariantMap result;
+ for (const auto &key:QStringList{"id","type","path","title","artist","year","trackCount","playable"}) result[key]=row.value(key);
+ result["title"]=row.value("title").toString().left(300); result["artist"]=row.value("artist").toString().left(300);
+ const QUrl art(row.value("artwork").toString());
+ result["artwork"]=art.scheme()=="https" && art.userInfo().isEmpty()?art.toString().left(4096):QString();
+ return result;
+}
+bool Library::isPinned(const QVariantMap &row) const {
+ for (const auto &entry:m_pins) if(entry.toMap().value("path")==row.value("path")) return true;
+ return false;
+}
+void Library::togglePin(const QVariantMap &row) {
+ const auto pin=validatedPin(row); if(pin.isEmpty())return;
+ auto next=m_pins; bool removed=false;
+ for (qsizetype i=0;i<next.size();++i) if(next[i].toMap().value("path")==pin.value("path")) { next.removeAt(i); removed=true; break; }
+ if (!removed) {
+ if(next.size()>=200) { m_playError="Your pins are full. Unpin an item first."; emit changed(); return; }
+ next.append(pin);
+ }
+ if (!m_pinsPath.isEmpty()) {
+ QDir().mkpath(QFileInfo(m_pinsPath).absolutePath()); QSaveFile file(m_pinsPath);
+ const auto bytes=QJsonDocument(QJsonArray::fromVariantList(next)).toJson(QJsonDocument::Compact);
+ if (!file.open(QIODevice::WriteOnly) || !file.setPermissions(QFileDevice::ReadOwner|QFileDevice::WriteOwner) || file.write(bytes)!=bytes.size() || !file.commit()) {
+ m_playError="Couldn’t save your pins. Try again."; emit changed(); return;
+ }
+ }
+ m_pins=next; m_releaseClock.invalidate(); emit pinsChanged();
+}
+void Library::playPin(int index) {
+ if(!m_active || index<0 || index>=m_pins.size())return;
+ if(m_pins[index].toMap().value("type")=="artists")openPin(index);else start(m_pins[index].toMap());
+}
+void Library::openPin(int index) {
+ if (!m_active || m_busy || !m_collection.isEmpty() || index<0 || index>=m_pins.size())return;
+ if(m_pins[index].toMap().value("type")=="stations") { playPin(index); return; }
+ pushPage();
+ m_collectionQuery.clear(); m_collection=m_pins[index].toMap();
+ if(m_collection.value("type")=="artists")m_artistView="songs";
+ setItems({}); reload();
+}
+
+void Library::setNewestFirst(bool value) {
+ if(m_newestFirst==value)return;
+ m_newestFirst=value;
+ if(!m_sortSettings.isEmpty()) { QSettings settings(m_sortSettings,QSettings::IniFormat);settings.setValue("libraryNewestFirst",value); }
+ if(m_collection.isEmpty() && (m_section=="songs" || m_section=="albums")) { invalidate();setItems({});m_next.clear();emit changed();reload(); }
+ else emit changed();
+}
+QString Library::songLink(const QString &url) {
+ const auto path=linkPath(url);
+ if(!path.contains("/songs/"))return {};
+ return "https://music.apple.com/"+path.split('/').value(3)+"/song/"+path.section('/',-1);
+}
+void Library::copyLink(const QVariantMap &row) {
+ QString link=songLink(row.value("url").toString());
+ const auto type=row.value("type").toString();
+ const auto id=type=="songs"?row.value("id").toString():row.value("catalogId").toString();
+ if(link.isEmpty() && type.endsWith("songs") && QRegularExpression("^[0-9]+$").match(id).hasMatch()) {
+ const auto path=row.value("path").toString();
+ const auto store=path.startsWith("/v1/catalog/")?path.split('/').value(3):m_storefront;
+ if(QRegularExpression("^[a-z]{2}$").match(store).hasMatch())link="https://music.apple.com/"+store+"/song/"+id;
+ else if(!m_busy) {
+ m_busy=true;emit changed();
+ request("/api/v1/amapi/run-v3",{{"path","/v1/me/storefront"}},false,[this,row](QJsonObject response) {
+ m_busy=false;const auto rows=response.value("data").toObject().value("data").toArray();
+ const auto store=rows.isEmpty()?QString():rows.first().toObject().value("id").toString();
+ if(!QRegularExpression("^[a-z]{2}$").match(store).hasMatch()) { emit m_cider->apiFeedback("No shareable Apple Music link for this song.",true);emit changed();return; }
+ m_storefront=store;copyLink(row);emit changed();
+ });return;
+ } else { emit m_cider->apiFeedback("Wait for the music list to finish loading, then copy again.",true);return; }
+ }
+ if(link.isEmpty()) { emit m_cider->apiFeedback("No shareable Apple Music link for this song.",true);return; }
+ QGuiApplication::clipboard()->setText(link);emit m_cider->apiFeedback("Song link copied",false);
+}
+
+static bool sessionId(const QString &id) {
+ static const QRegularExpression valid("^[a-f0-9]{32}$");return valid.match(id).hasMatch();
+}
+static QVariantMap savedSong(const QVariantMap &row) {
+ const auto type=row.value("type").toString(),id=row.value("id").toString();
+ static const QRegularExpression valid("^[A-Za-z0-9._-]{1,200}$");
+ if(!QStringList{"songs","library-songs"}.contains(type) || !valid.match(id).hasMatch() || !row.value("playable").toBool())return {};
+ QVariantMap song{{"id",id},{"type",type},{"playable",true}};
+ for(const auto &key:QStringList{"title","artist","catalogId"})song[key]=row.value(key).toString().left(300);
+ song["duration"]=qBound<qint64>(qint64(0),row.value("duration").toLongLong(),qint64(86400000));
+ const QUrl art(row.value("artwork").toString());song["artwork"]=art.scheme()=="https"&&art.userInfo().isEmpty()?art.toString().left(4096):QString();
+ song["url"]=Library::songLink(row.value("url").toString());return song;
+}
+QVariantList Library::readSessions(bool *valid) const {
+ if(valid)*valid=true;
+ QVariantList rows;QFile file(m_sessionsDir+"/index.json");
+ if(m_sessionsDir.isEmpty() || !file.exists())return rows;
+ const auto fail=[valid] { if(valid)*valid=false;return QVariantList{}; };
+ if(!file.open(QIODevice::ReadOnly) || file.size()>128*1024)return fail();
+ const auto doc=QJsonDocument::fromJson(file.readAll());
+ if(!doc.isArray() || doc.array().size()>30)return fail();
+ QSet<QString> ids,dataIds;
+ for(const auto &value:doc.array()) {
+ const auto row=value.toObject();const auto id=row.value("id").toString();
+ const int count=row.value("trackCount").toInt();
+ const auto dataId=row.value("dataId").toString(id);
+ if(!sessionId(id) || !sessionId(dataId) || ids.contains(id) || dataIds.contains(dataId) || !row.value("trackCount").isDouble() || row.value("trackCount").toDouble()!=count || count<0 || count>5000)return fail();
+ ids.insert(id);dataIds.insert(dataId);
+ rows.append(QVariantMap{{"id",id},{"type","saved-queues"},{"title",row.value("title").toString().left(80)},
+ {"artist",QString()},{"dataId",dataId},{"trackCount",count},{"playable",count>0},{"artwork",QString()}});
+ }return rows;
+}
+bool Library::writeSessions(const QVariantList &rows) {
+ if(m_sessionsDir.isEmpty() || !QDir().mkpath(m_sessionsDir))return false;
+ QSaveFile file(m_sessionsDir+"/index.json");const auto bytes=QJsonDocument(QJsonArray::fromVariantList(rows)).toJson(QJsonDocument::Compact);
+ return file.open(QIODevice::WriteOnly)&&file.setPermissions(QFileDevice::ReadOwner|QFileDevice::WriteOwner)&&file.write(bytes)==bytes.size()&&file.commit();
+}
+bool Library::saveQueue(const QString &name) {
+ if(m_sessionsDir.isEmpty() || name.trimmed().isEmpty() || !m_cider->queueReady() || m_cider->queueBusy() || !m_cider->queueError().isEmpty())return false;
+ bool valid=true;auto sessions=readSessions(&valid);
+ if(!valid) { emit m_cider->apiFeedback("Couldn’t read saved queues. Your existing files were left intact.",true);return false; }
+ if(sessions.size()>=30) { emit m_cider->apiFeedback("Saved queues are full. Delete one first.",true);return false; }
+ QVariantList tracks;const auto queue=m_cider->queue();
+ for(int i=qMax(0,m_cider->currentIndex());i<queue.size();++i) {
+ const auto song=savedSong(queue[i].toMap());
+ if(song.isEmpty() || tracks.size()>=5000) { emit m_cider->apiFeedback("This queue is too large or includes tracks Cider can’t replay.",true);return false; }tracks.append(song);
+ }
+ if(tracks.isEmpty()) { emit m_cider->apiFeedback("There are no tracks to save.",true);return false; }
+ const auto id=QUuid::createUuid().toString(QUuid::Id128);
+ QDir().mkpath(m_sessionsDir);QSaveFile file(m_sessionsDir+"/"+id+".json");
+ const auto bytes=QJsonDocument(QJsonArray::fromVariantList(tracks)).toJson(QJsonDocument::Compact);
+ bool ok=file.open(QIODevice::WriteOnly)&&file.setPermissions(QFileDevice::ReadOwner|QFileDevice::WriteOwner)&&file.write(bytes)==bytes.size()&&file.commit();
+ if(ok) {
+ sessions.prepend(QVariantMap{{"id",id},{"title",name.trimmed().left(80)},{"trackCount",tracks.size()}});ok=writeSessions(sessions);
+ if(!ok)QFile::remove(m_sessionsDir+"/"+id+".json");
+ }
+ emit m_cider->apiFeedback(ok?"Queue saved":"Couldn’t save the queue. Try again.",!ok);
+ if(ok && m_section=="sessions" && m_collection.isEmpty())reload();
+ return ok;
+}
+QVariantList Library::savedTracks(const QString &id) {
+ if(!sessionId(id) || m_sessionsDir.isEmpty())return {};
+ bool valid=true;const auto sessions=readSessions(&valid);QVariantMap info;
+ for(const auto &entry:sessions)if(entry.toMap().value("id")==id)info=entry.toMap();
+ if(!valid || info.isEmpty()) { m_error="Couldn’t read this saved queue.";emit changed();return {}; }
+ QFile file(m_sessionsDir+"/"+info.value("dataId").toString()+".json");
+ if(!file.open(QIODevice::ReadOnly) || file.size()>24*1024*1024) { m_error="Couldn’t read this saved queue.";emit changed();return {}; }
+ const auto doc=QJsonDocument::fromJson(file.readAll());
+ if(!doc.isArray() || doc.array().size()!=info.value("trackCount").toInt() || doc.array().size()>5000) { m_error="This saved queue is unreadable.";emit changed();return {}; }
+ QVariantList result;result.reserve(doc.array().size());
+ for(const auto &value:doc.array()) {
+ const auto song=savedSong(value.toObject().toVariantMap());
+ if(song.isEmpty()) { m_error="This saved queue contains an unavailable track.";emit changed();return {}; }result.append(song);
+ }return result;
+}
+QVariantMap Library::savedQueueChoices() const {
+ bool valid=true;const auto rows=readSessions(&valid);
+ return {{"rows",rows},{"error",valid?QString():QString("Couldn’t read saved queues. Try again.")}};
+}
+QVariantMap Library::appendSavedQueue(const QVariantMap &expected, const QVariantList &selection, bool skipDuplicates) {
+ auto fail=[](const QString &message) { return QVariantMap{{"ok",false},{"error",message}}; };
+ if(selection.isEmpty() || selection.size()>5000)return fail("Choose between 1 and 5,000 songs.");
+ bool valid=true;const auto sessions=readSessions(&valid);QVariantMap current;
+ for(const auto &entry:sessions)if(entry.toMap().value("id")==expected.value("id"))current=entry.toMap();
+ if(!valid || current.isEmpty())return fail("This saved queue is unavailable. Refresh the list.");
+ if(current.value("dataId")!=expected.value("dataId",expected.value("id")) || current.value("title")!=expected.value("title") || current.value("trackCount")!=expected.value("trackCount"))return fail("This saved queue changed. Refresh the list and choose it again.");
+ // Read every selected item before writing anything; never silently drop an
+ // unavailable song from a requested append.
+ QVariantList incoming;
+ for(const auto &value:selection) { const auto row=savedSong(value.toMap());if(row.isEmpty())return fail("This selection includes a song that can’t be saved.");incoming.append(row); }
+ const auto priorError=m_error;
+ auto tracks=savedTracks(current.value("id").toString());
+ if(tracks.size()!=current.value("trackCount").toInt() || (tracks.isEmpty() && m_error!=priorError))return fail("Couldn’t read this saved queue. Your files were left intact.");
+ // A valid empty queue still has a readable track file. savedTracks reports
+ // errors through m_error, so check its storage explicitly for that case.
+ if(tracks.isEmpty()) {
+ QFile file(m_sessionsDir+"/"+current.value("dataId").toString()+".json");
+ if(!file.open(QIODevice::ReadOnly) || file.size()>24*1024*1024)return fail("Couldn’t read this saved queue. Your files were left intact.");
+ const auto doc=QJsonDocument::fromJson(file.readAll());
+ if(!doc.isArray() || !doc.array().isEmpty())return fail("Couldn’t read this saved queue. Your files were left intact.");
+ }
+ auto key=[](const QVariantMap &row) { const auto id=row.value("catalogId").toString();return id.isEmpty()?row.value("type").toString()+":"+row.value("id").toString():"songs:"+id; };
+ QSet<QString> seen;
+ if(skipDuplicates)for(const auto &row:tracks)seen.insert(key(row.toMap()));
+ int added=0,skipped=0;
+ for(const auto &row:incoming) {
+ const auto identity=key(row.toMap());
+ if(skipDuplicates && seen.contains(identity)) { ++skipped;continue; }
+ seen.insert(identity);tracks.append(row);++added;
+ }
+ if(tracks.size()>5000)return fail("A saved queue can hold up to 5,000 songs.");
+ if(added && !updateSavedQueue(current,current.value("title").toString(),&tracks))return fail("Couldn’t save the changes. Refresh the list before trying again.");
+ emit m_cider->apiFeedback(added?QString("Added %1 %2%3").arg(added).arg(added==1?"song":"songs").arg(skipped?QString(" · %1 duplicates skipped").arg(skipped):QString()):QString("All selected songs are already saved"),false);
+ if(added)emit savedEditCommitted();
+ return {{"ok",true},{"added",added},{"skipped",skipped}};
+}
+bool Library::renameSavedQueue(const QVariantMap &queue, const QString &name) {
+ const bool ok=updateSavedQueue(queue,name,nullptr);if(ok)emit savedEditCommitted();return ok;
+}
+bool Library::editSavedTrack(int from, int to, bool remove) {
+ if(m_section!="sessions" || m_collection.value("type")!="saved-queues")return false;
+ const auto expected=m_collection;auto tracks=savedTracks(expected.value("id").toString());
+ if(from<0 || from>=tracks.size() || (!remove && (to<0 || to>=tracks.size() || to==from || !m_collectionQuery.trimmed().isEmpty())))return false;
+ if(remove)tracks.removeAt(from);else tracks.move(from,to);
+ const bool ok=updateSavedQueue(expected,expected.value("title").toString(),&tracks);if(ok)emit savedEditCommitted();return ok;
+}
+bool Library::updateSavedQueue(const QVariantMap &expected, const QString &name, const QVariantList *tracks) {
+ const auto id=expected.value("id").toString();const auto title=name.trimmed().left(80);
+ if(!sessionId(id) || title.isEmpty())return false;
+ bool valid=true;auto sessions=readSessions(&valid);int at=-1;
+ for(int i=0;i<sessions.size();++i)if(sessions[i].toMap().value("id")==id)at=i;
+ if(!valid || at<0) { emit m_cider->apiFeedback("Couldn’t read this saved queue. Your files were left intact.",true);return false; }
+ auto row=sessions[at].toMap();const auto oldData=row.value("dataId").toString();
+ if(oldData!=expected.value("dataId",id).toString() || row.value("title")!=expected.value("title") || row.value("trackCount")!=expected.value("trackCount")) {
+ emit m_cider->apiFeedback("This saved queue changed. Reopen it before editing.",true);return false;
+ }
+ QString newData;
+ if(tracks) {
+ // Publish a new immutable track file, then atomically switch the index.
+ // Failed writes leave the previous queue and its metadata together.
+ newData=QUuid::createUuid().toString(QUuid::Id128);
+ QSaveFile file(m_sessionsDir+"/"+newData+".json");
+ const auto bytes=QJsonDocument(QJsonArray::fromVariantList(*tracks)).toJson(QJsonDocument::Compact);
+ if(!file.open(QIODevice::WriteOnly) || !file.setPermissions(QFileDevice::ReadOwner|QFileDevice::WriteOwner) || file.write(bytes)!=bytes.size() || !file.commit()) {
+ emit m_cider->apiFeedback("Couldn’t save the edit. Your saved queue is unchanged.",true);return false;
+ }
+ row["dataId"]=newData;row["trackCount"]=tracks->size();row["playable"]=!tracks->isEmpty();
+ }
+ const auto before=sessions[at].toMap();
+ row["title"]=title;sessions[at]=row;
+ if(!writeSessions(sessions)) {
+ if(!newData.isEmpty())QFile::remove(m_sessionsDir+"/"+newData+".json");
+ emit m_cider->apiFeedback("Couldn’t save the edit. Your saved queue is unchanged.",true);return false;
+ }
+ clearSavedUndo();m_savedUndoBefore=before;m_savedUndoAfter=row;
+ m_savedUndoTimer.start();emit savedUndoChanged();
+ if(m_section=="sessions")reload();
+ emit m_cider->apiFeedback(tracks?"Saved queue updated":"Saved queue renamed",false);return true;
+}
+void Library::clearSavedUndo() {
+ const auto oldData=m_savedUndoBefore.value("dataId").toString();
+ if(!oldData.isEmpty() && oldData!=m_savedUndoAfter.value("dataId").toString()) {
+ bool valid=true;const auto rows=readSessions(&valid);bool referenced=false;
+ for(const auto &row:rows)if(row.toMap().value("dataId")==oldData)referenced=true;
+ if(valid&&!referenced)QFile::remove(m_sessionsDir+"/"+oldData+".json");
+ }
+ m_savedUndoTimer.stop();m_savedUndoBefore.clear();m_savedUndoAfter.clear();emit savedUndoChanged();
+}
+bool Library::undoSavedQueue() {
+ if(!canUndoSavedQueue())return false;
+ bool valid=true;auto rows=readSessions(&valid);int at=-1;
+ for(int i=0;i<rows.size();++i)if(rows[i].toMap().value("id")==m_savedUndoAfter.value("id"))at=i;
+ if(!valid || at<0 || rows[at].toMap()!=m_savedUndoAfter) {
+ clearSavedUndo();emit m_cider->apiFeedback("This saved queue changed. Undo is no longer available.",true);return false;
+ }
+ // Restore the previous immutable file by switching the index. No second
+ // track list is held in RAM and no Cider playback action is issued.
+ QFile file(m_sessionsDir+"/"+m_savedUndoBefore.value("dataId").toString()+".json");
+ if(!file.open(QIODevice::ReadOnly)||file.size()>24*1024*1024) {
+ clearSavedUndo();emit m_cider->apiFeedback("The previous saved queue is unavailable.",true);return false;
+ }
+ const auto doc=QJsonDocument::fromJson(file.readAll());
+ bool readable=doc.isArray()&&doc.array().size()==m_savedUndoBefore.value("trackCount").toInt();
+ if(readable)for(const auto &v:doc.array())if(savedSong(v.toObject().toVariantMap()).isEmpty()){readable=false;break;}
+ if(!readable){clearSavedUndo();emit m_cider->apiFeedback("The previous saved queue is unreadable.",true);return false;}
+ rows[at]=m_savedUndoBefore;
+ if(!writeSessions(rows)) { emit m_cider->apiFeedback("Couldn’t undo the edit. Try again.",true);return false; }
+ const auto replaced=m_savedUndoAfter.value("dataId").toString();const auto restored=m_savedUndoBefore.value("dataId").toString();
+ clearSavedUndo();if(replaced!=restored)QFile::remove(m_sessionsDir+"/"+replaced+".json");
+ if(m_section=="sessions")reload();
+ emit m_cider->apiFeedback("Saved queue edit undone",false);return true;
+}
+bool Library::openQuickTarget(const QString &kind, const QString &key) {
+ QVariantMap selected;
+ if(kind=="saved") { for(const auto &v:readSessions())if(v.toMap().value("id")==key)selected=v.toMap(); }
+ else if(kind=="pin") { for(const auto &v:m_pins)if(v.toMap().value("path")==key)selected=v.toMap(); }
+ if(selected.isEmpty()) { emit m_cider->apiFeedback("This item is no longer available. Open Quick jump again.",true);return false; }
+ invalidate();m_history.clear();m_collection.clear();m_collectionQuery.clear();m_query.clear();m_allItems.clear();m_filterText.clear();m_next.clear();m_findArtist=false;
+ m_section=kind=="saved"?"sessions":"search";m_kind="songs";
+ if(kind=="saved")m_allItems=readSessions();
+ setItems(m_allItems);m_loaded=true;emit navigationReset();pushPage();
+ if(selected.value("type")=="stations") { m_kind="stations";m_query=selected.value("title").toString(); }
+ else { m_collection=selected;if(selected.value("type")=="artists")m_artistView="songs"; }
+ setItems({});m_loaded=false;emit changed();reload();return true;
+}
+void Library::deleteSavedQueue(const QString &id) {
+ if(!sessionId(id))return;
+ bool valid=true;auto sessions=readSessions(&valid);
+ if(!valid) { emit m_cider->apiFeedback("Couldn’t read saved queues. Your existing files were left intact.",true);return; }
+ bool found=false;QString dataId;
+ for(int i=0;i<sessions.size();++i)if(sessions[i].toMap().value("id")==id) { dataId=sessions[i].toMap().value("dataId").toString();sessions.removeAt(i);found=true;break; }
+ if(!found)return;
+ if(!writeSessions(sessions)) { emit m_cider->apiFeedback("Couldn’t delete this saved queue.",true);return; }
+ if(m_savedUndoAfter.value("id")==id)clearSavedUndo();
+ QFile::remove(m_sessionsDir+"/"+dataId+".json");
+ if(m_collection.value("id")==id)back();
+ if(m_section=="sessions")reload();
+ emit m_cider->apiFeedback("Saved queue deleted",false);
+}
+
+void Library::persistSearches() {
+ if (!m_sortSettings.isEmpty()) { QSettings settings(m_sortSettings,QSettings::IniFormat); settings.setValue("recentSearches",m_recentSearches); }
+ emit recentSearchesChanged();
+}
+void Library::rememberSearch() {
+ // Store intentional searches (Enter or a result action), never every keystroke.
+ const auto term=m_query.trimmed().left(200);
+ if (m_section!="search" || !m_collection.isEmpty() || term.isEmpty() || term.contains("://") || m_findArtist) return;
+ auto next=m_recentSearches;
+ for (qsizetype i=next.size();i>0;--i) if(next[i-1].compare(term,Qt::CaseInsensitive)==0) next.removeAt(i-1);
+ next.prepend(term); next=next.mid(0,8);
+ if(next==m_recentSearches)return;
+ m_recentSearches=next;persistSearches();
+}
+void Library::removeRecentSearch(const QString &query) {
+ if(m_recentSearches.removeAll(query))persistSearches();
+}
+
+QString Library::collectionPath() const {
+ return m_collection.value("path").toString()+(m_collection.value("type")=="artists"?
+ (m_artistView=="songs"?"/view/top-songs":m_artistView=="similar"?"/view/similar-artists":m_discography=="all"?"/albums":"/view/"+m_discography):"/tracks");
+}
+void Library::setDiscography(const QString &value) {
+ if(m_collection.value("type")!="artists" || m_artistView!="albums" || m_discography==value || !QStringList{"all","full-albums","singles","live-albums"}.contains(value))return;
+ invalidate();m_discography=value;m_allItems.clear();m_filterText.clear();m_next.clear();setItems({});
+ emit changed();if(m_active)reload();
+}
+void Library::setArtistView(const QString &value) {
+ if(m_collection.value("type")!="artists" || m_artistView==value || (value!="albums" && value!="songs" && value!="similar"))return;
+ invalidate();m_artistView=value;m_collectionQuery.clear();m_allItems.clear();m_filterText.clear();m_next.clear();setItems({});
+ emit changed();if(m_active)reload();
+}
+
+
+bool Library::hasArtistPins() const {
+ for(const auto &pin:m_pins) if(pin.toMap().value("type")=="artists") return true;
+ return false;
+}
+void Library::fetchRecommendations(const QString &path,bool append,const QString &reason) {
+ const QUrl url(path);
+ static const QRegularExpression safePath("^/v1/me/recommendations(?:/[A-Za-z0-9._~-]+(?:/contents)?)?$");
+ if(!url.isRelative() || !url.host().isEmpty() || url.hasFragment() || !safePath.match(url.path()).hasMatch() || path.size()>2048 || m_pages.contains(path)) {
+ m_busy=false;m_error="Couldn’t load more recommendations.";emit changed();return;
+ }
+ if(m_cider->m_apiToken.isEmpty()) {m_needsConnection=true;m_busy=false;m_error="Connect Spun to Cider to see For You.";emit changed();return;}
+ m_busy=true;m_error.clear();emit changed();
+ request("/api/v1/amapi/run-v3",{{"path",path}},false,[this,path,append,reason](QJsonObject response) {
+ const auto data=response.value("data").toObject();
+ if(!data.value("data").isArray()) {m_busy=false;m_error="Cider returned unreadable recommendations.";emit changed();return;}
+ auto pending=append?m_recommendationPages:QVariantList{};
+ if(append && !pending.isEmpty() && pending.first().toMap().value("path")==path)pending.removeFirst();
+ QVariantList rows=append?m_allItems:QVariantList{};QSet<QString> identities;
+ for(const auto &row:rows)identities.insert(row.toMap().value("type").toString()+":"+row.toMap().value("id").toString());
+ bool truncated=false;
+ const auto enqueue=[&](const QString &next,const QString &label) {
+ if(next.isEmpty())return;
+ if(pending.size()+m_pages.size()>=100) {truncated=true;return;}
+ // URL validation runs again before any request; credentials stay on localhost.
+ if(next==path || m_pages.contains(next))return;
+ for(const auto &value:pending)if(value.toMap().value("path")==next)return;
+ pending.append(QVariantMap{{"path",next},{"reason",label.left(200)}});
+ };
+ std::function<void(const QJsonArray &,const QString &,int)> collect;
+ collect=[&](const QJsonArray &items,const QString &label,int depth) {
+ if(depth>4) {truncated=true;return;}
+ for(const auto &value:items) {
+ const auto resource=value.toObject();
+ if(resource.value("type")=="personal-recommendation") {
+ const auto attributes=resource.value("attributes").toObject();
+ const auto title=attributes.value("title").toObject().value("stringForDisplay").toString(label).left(200);
+ const auto contents=resource.value("relationships").toObject().value("contents").toObject();
+ collect(contents.value("data").toArray(),title,depth+1);enqueue(contents.value("next").toString(),title);continue;
+ }
+ const auto type=resource.value("type").toString();
+ if(!QStringList{"albums","playlists","stations"}.contains(type))continue;
+ auto row=item(resource);if(row.isEmpty())continue;
+ const auto href=resource.value("href").toString();
+ static const QRegularExpression catalog("^/v1/catalog/[a-z]{2}/(?:albums|playlists|stations)/[A-Za-z0-9._-]+$");
+ if(!catalog.match(href).hasMatch() || !href.endsWith("/"+type+"/"+row.value("id").toString()))continue;
+ row["path"]=href;row["recommendation"]=label;
+ const auto key=type+":"+row.value("id").toString();if(identities.contains(key))continue;
+ if(rows.size()>=1000) {truncated=true;return;}
+ identities.insert(key);rows.append(row);
+ }
+ };
+ collect(data.value("data").toArray(),reason,0);enqueue(data.value("next").toString(),reason);
+ m_pages.insert(path);m_recommendationPages=pending;
+ if(truncated) {m_recommendationPages.clear();m_releaseNotice="Showing the first available recommendations.";}else m_releaseNotice.clear();
+ m_next=m_recommendationPages.isEmpty()?QString():m_recommendationPages.first().toMap().value("path").toString();
+ m_allItems=rows;if(!append)m_filterText.clear();filterItems(append);
+ m_busy=false;m_loaded=true;m_preservePosition=false;emit changed();continueSearch();
+ if(rows.isEmpty() && !m_next.isEmpty())QTimer::singleShot(0,this,[this] {if(m_active && m_section=="for-you" && m_collection.isEmpty() && !m_busy && m_error.isEmpty())more();});
+ });
+}
+
+void Library::fetchReleases() {
+ m_releaseRequests.clear(); m_releaseRows.clear(); m_releaseNotice.clear(); m_releaseFailed=false; m_next.clear();
+ if(!hasArtistPins()) { m_allItems.clear();m_filterText.clear();filterItems();m_loaded=true;emit changed();return; }
+ if(m_cider->m_apiToken.isEmpty()) { m_needsConnection=true;m_error="Connect Spun to Cider to see releases.";emit changed();return; }
+ // Group by storefront; batch 25 artists rather than issuing a request per pin.
+ QMap<QString,QStringList> groups;
+ for(const auto &entry:m_pins) {
+ const auto pin=validatedPin(entry.toMap());
+ if(pin.value("type")=="artists")groups[pin.value("path").toString().split('/').value(3)].append(pin.value("id").toString());
+ }
+ for(auto it=groups.cbegin();it!=groups.cend();++it) for(int i=0;i<it.value().size();i+=25)
+ m_releaseRequests.append("/v1/catalog/"+it.key()+"/artists?ids="+it.value().mid(i,25).join(',')+"&views=latest-release");
+ m_busy=true;emit changed();fetchReleaseBatch();
+}
+void Library::fetchReleaseBatch() {
+ if(m_releaseRequests.isEmpty()) { finishReleases();return; }
+ const auto path=m_releaseRequests.takeFirst();
+ auto url=m_cider->m_rpcBase;url.setPath("/api/v1/amapi/run-v3");url.setQuery(QString());
+ QNetworkRequest req(url);req.setTransferTimeout(10000);req.setRawHeader("apptoken",m_cider->m_apiToken.toUtf8());
+ req.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");req.setAttribute(QNetworkRequest::RedirectPolicyAttribute,QNetworkRequest::ManualRedirectPolicy);
+ auto *reply=m_network.post(req,QJsonDocument(QJsonObject{{"path",path}}).toJson(QJsonDocument::Compact));m_reply=reply;
+ const int generation=m_generation,token=m_cider->m_tokenGeneration;
+ connect(reply,&QNetworkReply::readyRead,reply,[reply] { if(reply->bytesAvailable()>4*1024*1024)reply->abort(); });
+ connect(reply,&QNetworkReply::finished,this,[this,reply,path,generation,token] {
+ reply->deleteLater();if(generation!=m_generation)return;
+ if(token!=m_cider->m_tokenGeneration) { m_busy=false;m_error="Cider access changed. Refresh releases.";emit changed();return; }
+ const int status=reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
+ m_cider->observeConnection(status,reply->error());
+ const auto data=QJsonDocument::fromJson(reply->readAll()).object().value("data").toObject();
+ if(status!=200 || reply->error()!=QNetworkReply::NoError || !data.value("data").isArray()) {
+ m_releaseFailed=true;
+ if(status==401 || status==403) { m_needsConnection=true;m_releaseRequests.clear(); }
+ } else for(const auto &artist:data.value("data").toArray()) {
+ const auto releases=artist.toObject().value("views").toObject().value("latest-release").toObject().value("data");
+ if(!releases.isArray()) { m_releaseFailed=true;continue; }
+ for(const auto &release:releases.toArray()) {
+ auto row=item(release.toObject());if(row.value("type")!="albums" || !row.value("playable").toBool())continue;
+ row["path"]="/v1/catalog/"+path.split('/').value(3)+"/albums/"+row.value("id").toString();
+ bool duplicate=false;for(const auto &existing:m_releaseRows)if(existing.toMap().value("id")==row.value("id")) { duplicate=true;break; }
+ if(!duplicate && m_releaseRows.size()<200)m_releaseRows.append(row);
+ }
+ }
+ fetchReleaseBatch();
+ });
+}
+void Library::finishReleases() {
+ std::stable_sort(m_releaseRows.begin(),m_releaseRows.end(),[](const QVariant &a,const QVariant &b) {
+ return a.toMap().value("releaseDate").toString()>b.toMap().value("releaseDate").toString();
+ });
+ m_busy=false;m_loaded=true;
+ if(m_releaseFailed) {
+ m_error=m_needsConnection?"Reconnect to load releases.":"Some releases couldn’t load. Try again.";
+ // Preserve the last good list on a complete outage; don't cache partial reads.
+ if(m_releaseRows.isEmpty() && !m_allItems.isEmpty())m_releaseNotice="Showing previous results";
+ else m_allItems=m_releaseRows;
+ } else { m_allItems=m_releaseRows;m_releaseCache=m_releaseRows;m_releaseClock.restart();m_releaseTokenGeneration=m_cider->m_tokenGeneration; }
+ m_filterText.clear();filterItems();m_preservePosition=false;emit changed();
+}
+
+void Library::prepareRadio(const QVariantMap &song, bool current) {
+ ++m_radioGeneration;if(m_radioReply)m_radioReply->abort();
+ m_radioResolvedToken=m_cider->m_tokenGeneration;
+ if(m_radioCacheToken!=m_cider->m_tokenGeneration) { m_radioCache.clear();m_radioCacheToken=m_cider->m_tokenGeneration; }
+ m_radioCurrent=current;m_radioTrack=m_cider->m_track;m_radioStation.clear();m_radioError.clear();m_radioBusy=false;
+ if(m_radioCacheClock.isValid() && m_radioCacheClock.elapsed()>1800000)m_radioCache.clear();
+ if(!m_radioCacheClock.isValid() || m_radioCacheClock.elapsed()>1800000)m_radioCacheClock.restart();
+ if(m_cider->m_apiToken.isEmpty()) { m_radioError="Connect to Cider to find a station.";emit radioChanged();return; }
+ m_radioBusy=true;emit radioChanged();
+ if(current)radioRequest("/api/v2/playback/now-playing",{},[this](QJsonObject json) {
+ const auto data=json.value("data").toObject();const auto attrs=data.value("attributes").isObject()?data.value("attributes").toObject():data;
+ resolveRadio({{"id",data.value("id").toString()},{"type","songs"},{"url",attrs.value("url").toString()},{"catalogId",attrs.value("playParams").toObject().value("catalogId").toString()}});
+ });
+ else resolveRadio(song);
+}
+void Library::radioRequest(const QString &endpoint,const QJsonObject &body,std::function<void(QJsonObject)> done) {
+ auto url=m_cider->m_rpcBase;url.setPath(endpoint);url.setQuery(QString());
+ QNetworkRequest req(url);req.setTransferTimeout(8000);req.setRawHeader("apptoken",m_cider->m_apiToken.toUtf8());
+ req.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");req.setAttribute(QNetworkRequest::RedirectPolicyAttribute,QNetworkRequest::ManualRedirectPolicy);
+ auto *reply=body.isEmpty()?m_network.get(req):m_network.post(req,QJsonDocument(body).toJson(QJsonDocument::Compact));m_radioReply=reply;
+ const int generation=m_radioGeneration,token=m_cider->m_tokenGeneration;
+ connect(reply,&QNetworkReply::readyRead,reply,[reply] { if(reply->bytesAvailable()>1024*1024)reply->abort(); });
+ connect(reply,&QNetworkReply::finished,this,[this,reply,generation,token,done] {
+ reply->deleteLater();if(generation!=m_radioGeneration)return;
+ const int status=reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
+ const auto json=QJsonDocument::fromJson(reply->readAll());
+ if(token!=m_cider->m_tokenGeneration || (m_radioCurrent && m_radioTrack!=m_cider->m_track)) { m_radioBusy=false;m_radioError="Song or connection changed. Reopen the menu.";emit radioChanged();return; }
+ m_cider->observeConnection(status,reply->error());
+ if(reply->error()!=QNetworkReply::NoError || status!=200 || !json.isObject()) {
+ m_radioBusy=false;m_radioError="Couldn’t check radio. Reopen the menu to retry.";emit radioChanged();return;
+ }
+ done(json.object());
+ });
+}
+void Library::resolveRadio(const QVariantMap &song) {
+ auto path=linkPath(song.value("url").toString());
+ const auto id=song.value("catalogId").toString().isEmpty()?(song.value("type")=="songs"?song.value("id").toString():QString()):song.value("catalogId").toString();
+ if(!path.contains("/songs/"))path.clear();
+ if(path.isEmpty() && QRegularExpression("^[0-9]+$").match(id).hasMatch()) {
+ const auto candidate=song.value("path").toString().split('/').value(3);
+ const auto store=QRegularExpression("^[a-z]{2}$").match(candidate).hasMatch()?candidate:m_storefront;
+ if(store.isEmpty()) {
+ radioRequest("/api/v1/amapi/run-v3",{{"path","/v1/me/storefront"}},[this,song](QJsonObject json) {
+ const auto rows=json.value("data").toObject().value("data").toArray();
+ const auto store=rows.isEmpty()?QString():rows.first().toObject().value("id").toString();
+ if(!QRegularExpression("^[a-z]{2}$").match(store).hasMatch()) { m_radioBusy=false;m_radioError="Cider couldn’t identify your music region.";emit radioChanged();return; }
+ m_storefront=store;resolveRadio(song);
+ });return;
+ }
+ path="/v1/catalog/"+store+"/songs/"+id;
+ }
+ if(path.isEmpty()) { m_radioBusy=false;emit radioChanged();return; }
+ if(m_radioCache.contains(path)) { m_radioStation=m_radioCache.value(path);m_radioBusy=false;emit radioChanged();return; }
+ radioRequest("/api/v1/amapi/run-v3",{{"path",path+"/station"}},[this,path](QJsonObject json) {
+ const auto data=json.value("data").toObject();const auto errors=data.value("errors").toArray();
+ bool absent=!errors.isEmpty();for(const auto &error:errors)if(error.toObject().value("code").toString()!="40403")absent=false;
+ if(!data.value("data").isArray() && !absent) m_radioError="Couldn’t check radio. Reopen the menu to retry.";
+ else {
+ for(const auto &value:data.value("data").toArray()) { auto row=item(value.toObject());if(row.value("type")=="stations" && row.value("playable").toBool()) { m_radioStation=row;break; } }
+ if(m_radioCache.size()>=64)m_radioCache.clear();
+ m_radioCache.insert(path,m_radioStation);
+ }
+ m_radioBusy=false;emit radioChanged();
+ });
+}
+void Library::playRadio() {
+ if(radioBusy() || m_radioStation.isEmpty() || m_cider->controlBusy())return;
+ if(m_radioResolvedToken!=m_cider->m_tokenGeneration) { m_radioStation.clear();emit radioChanged();emit m_cider->apiFeedback("Cider access changed. Choose radio again.",true);return; }
+ if(m_radioCurrent && m_radioTrack!=m_cider->m_track) { m_radioStation.clear();emit radioChanged();emit m_cider->apiFeedback("Song changed. Choose radio again.",true);return; }
+ m_radioStarting=true;emit radioChanged();
+ const QPointer<Library> guard(this);
+ m_cider->apiRequest("POST","/playback/play-collection",{{"type","stations"},{"id",m_radioStation.value("id").toString()}},[this,guard](bool ok,QJsonObject) {
+ if(!guard)return;
+ m_radioStarting=false;emit radioChanged();
+ emit m_cider->apiFeedback(ok?"Radio started":"Cider couldn’t start radio. Try again.",!ok);
+ if(ok) { m_cider->refresh();if(m_cider->queueVisible() || m_cider->libraryVisible())m_cider->refreshQueue(); }
+ });
+}
diff --git a/src/library.h b/src/library.h
index a8160aa..6afb34c 100644
--- a/src/library.h
+++ b/src/library.h
@@ -7,12 +7,26 @@
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QSet>
+#include <QElapsedTimer>
#include <functional>
class Cider;
// Browsing is read-only. Playback is sent only by an explicit play action.
class Library : public QObject {
Q_OBJECT
+ Q_PROPERTY(bool preparingTail READ preparingTail NOTIFY changed)
+ Q_PROPERTY(bool tailCollection READ tailCollection NOTIFY changed)
+ Q_PROPERTY(bool canUndoSavedQueue READ canUndoSavedQueue NOTIFY savedUndoChanged)
+ Q_PROPERTY(bool radioBusy READ radioBusy NOTIFY radioChanged)
+ Q_PROPERTY(bool radioAvailable READ radioAvailable NOTIFY radioChanged)
+ Q_PROPERTY(QString radioError READ radioError NOTIFY radioChanged)
+ Q_PROPERTY(QString releaseNotice READ releaseNotice NOTIFY changed)
+ Q_PROPERTY(bool hasArtistPins READ hasArtistPins NOTIFY pinsChanged)
+ Q_PROPERTY(QString discography READ discography WRITE setDiscography NOTIFY changed)
+ Q_PROPERTY(QString artistView READ artistView WRITE setArtistView NOTIFY changed)
+ Q_PROPERTY(QStringList recentSearches READ recentSearches NOTIFY recentSearchesChanged)
+ Q_PROPERTY(bool newestFirst READ newestFirst WRITE setNewestFirst NOTIFY changed)
+ Q_PROPERTY(QVariantList pins READ pins NOTIFY pinsChanged)
Q_PROPERTY(bool active READ active WRITE setActive NOTIFY changed)
Q_PROPERTY(QString section READ section WRITE setSection NOTIFY changed)
Q_PROPERTY(QString query READ query WRITE setQuery NOTIFY changed)
@@ -29,6 +43,40 @@ class Library : public QObject {
public:
explicit Library(Cider *cider, QObject *parent=nullptr);
~Library() override;
+ bool radioBusy() const { return m_radioBusy || m_radioStarting; }
+ bool radioAvailable() const { return !m_radioStation.isEmpty(); }
+ QString radioError() const { return m_radioError; }
+ QString releaseNotice() const { return m_releaseNotice; }
+ bool hasArtistPins() const;
+ Q_INVOKABLE void prepareRadio(const QVariantMap &song, bool current=false);
+ Q_INVOKABLE void playRadio();
+ QString discography() const { return m_discography; }
+ void setDiscography(const QString &value);
+ QString artistView() const { return m_artistView; }
+ void setArtistView(const QString &value);
+ QStringList recentSearches() const { return m_recentSearches; }
+ Q_INVOKABLE void rememberSearch();
+ Q_INVOKABLE void removeRecentSearch(const QString &query);
+ Q_INVOKABLE void shuffleCollection(const QVariantMap &item);
+ bool newestFirst() const { return m_newestFirst; }
+ void setNewestFirst(bool value);
+ Q_INVOKABLE bool saveQueue(const QString &name);
+ Q_INVOKABLE void deleteSavedQueue(const QString &id);
+ Q_INVOKABLE bool renameSavedQueue(const QVariantMap &queue, const QString &name);
+ Q_INVOKABLE bool editSavedTrack(int from, int to, bool remove);
+ Q_INVOKABLE QVariantMap savedQueueChoices() const;
+ Q_INVOKABLE bool openQuickTarget(const QString &kind, const QString &key);
+ bool canUndoSavedQueue() const { return m_savedUndoTimer.isActive() && !m_savedUndoBefore.isEmpty(); }
+ Q_INVOKABLE bool undoSavedQueue();
+ Q_INVOKABLE QVariantMap appendSavedQueue(const QVariantMap &queue, const QVariantList &tracks, bool skipDuplicates);
+ Q_INVOKABLE QVariantList savedTracks(const QString &id);
+ Q_INVOKABLE void copyLink(const QVariantMap &item);
+ static QString songLink(const QString &url);
+ QVariantList pins() const { return m_pins; }
+ Q_INVOKABLE bool isPinned(const QVariantMap &item) const;
+ Q_INVOKABLE void togglePin(const QVariantMap &item);
+ Q_INVOKABLE void playPin(int index);
+ Q_INVOKABLE void openPin(int index);
bool active() const { return m_active; }
QString section() const { return m_section; }
QString query() const { return m_query; }
@@ -53,16 +101,65 @@ public:
Q_INVOKABLE void reload();
Q_INVOKABLE void more();
Q_INVOKABLE void open(int index);
+ Q_INVOKABLE void showArtist(const QString &name);
Q_INVOKABLE void back();
+ bool preparingTail() const { return m_tailIndex>=0; }
+ bool tailCollection() const;
+ Q_INVOKABLE void queueFromHere(const QVariantMap &selected);
+ Q_INVOKABLE void cancelQueueFromHere();
Q_INVOKABLE void play(int index);
Q_INVOKABLE void playCollection();
static QVariantMap item(const QJsonObject &value, const QString &fallbackType = {});
signals:
+ void tailReady(const QVariantList &tracks);
+ void feedback(const QString &message, bool error);
+ void savedUndoChanged();
+ void savedEditCommitted();
+ void radioChanged();
+ void recentSearchesChanged();
+ void pinsChanged();
void changed();
void returned();
+ void navigating();
+ void navigationReset();
void itemsChanging(bool append);
void itemsChanged();
private:
+ int m_tailIndex=-1;
+ QVariantMap m_tailAnchor;
+ void continueTail();
+ void radioRequest(const QString &endpoint, const QJsonObject &body, std::function<void(QJsonObject)> done);
+ void resolveRadio(const QVariantMap &song);
+ QPointer<QNetworkReply> m_radioReply;
+ int m_radioGeneration=0;
+ bool m_radioBusy=false, m_radioCurrent=false, m_radioStarting=false;
+ int m_radioCacheToken=-1, m_radioResolvedToken=-1;
+ QString m_radioError, m_radioTrack;
+ QVariantMap m_radioStation;
+ QHash<QString,QVariantMap> m_radioCache;
+ QElapsedTimer m_radioCacheClock;
+ void fetchRecommendations(const QString &path,bool append,const QString &reason={});
+ QVariantList m_recommendationPages;
+ void fetchReleases();
+ void fetchReleaseBatch();
+ void finishReleases();
+ QStringList m_releaseRequests;
+ QVariantList m_releaseRows, m_releaseCache;
+ QElapsedTimer m_releaseClock;
+ QString m_releaseNotice;
+ bool m_releaseFailed=false;
+ int m_releaseTokenGeneration=-1;
+ static QVariantMap validatedPin(const QVariantMap &item);
+ QString m_sessionsDir, m_sortSettings;
+ QVariantMap m_savedUndoBefore, m_savedUndoAfter;
+ QTimer m_savedUndoTimer;
+ void clearSavedUndo();
+ QVariantList readSessions(bool *valid=nullptr) const;
+ bool writeSessions(const QVariantList &rows);
+ bool updateSavedQueue(const QVariantMap &expected, const QString &name, const QVariantList *tracks);
+ QString m_pinsPath;
+ QVariantList m_pins;
+ bool m_preservePosition=false;
void filterItems(bool append=false);
void continueSearch();
bool filteringLocally() const;
@@ -71,7 +168,11 @@ private:
void fetch(const QString &path, bool append=false);
void request(const QString &path, const QJsonObject &body, bool action,
std::function<void(QJsonObject)> done);
- void start(const QVariantMap &item);
+ void start(const QVariantMap &item, bool shuffle=false);
+ void persistSearches();
+ QStringList m_recentSearches;
+ QString collectionPath() const;
+ QString m_artistView="albums",m_discography="all";
QString listPath() const;
QString resultType() const;
Cider *m_cider;
@@ -82,9 +183,18 @@ private:
bool m_active=false, m_busy=false, m_loaded=false, m_starting=false, m_needsConnection=false;
QString m_section="search", m_kind="songs", m_query, m_storefront, m_next, m_error, m_playError;
QString m_collectionQuery;
- QVariantList m_allItems, m_items, m_savedItems;
+ struct Page {
+ QVariantMap collection;
+ QVariantList items, allItems;
+ QString next, collectionQuery, artistView, discography;
+ QVariantList recommendationPages;
+ QSet<QString> pages;
+ };
+ QList<Page> m_history;
+ void pushPage();
+ bool m_findArtist=false, m_newestFirst=false;
+ QVariantList m_allItems, m_items;
QStringList m_filterText;
QVariantMap m_collection;
- QString m_savedNext;
- QSet<QString> m_pages, m_savedPages;
+ QSet<QString> m_pages;
};
diff --git a/src/librarytest.cpp b/src/librarytest.cpp
index e1874f7..0ecf574 100644
--- a/src/librarytest.cpp
+++ b/src/librarytest.cpp
@@ -1,10 +1,12 @@
#include "librarytest.h"
#include "testinput.h"
#include "library.h"
+#include "listening.h"
#include "musicactions.h"
#include "cider.h"
#include "player.h"
#include <QQmlContext>
+#include <QQmlProperty>
#include <QQmlEngine>
#include <QDir>
#include <QQuickWindow>
@@ -26,17 +28,34 @@
#include <QElapsedTimer>
#include <iostream>
+int exerciseCiderEvents(const QString &temp);
+
int exerciseLibrary(QQuickWindow *window, const QString &temp, const QString &captures) {
if(!captures.isEmpty())QDir().mkpath(captures);
+ int recommendationReads=0,discoveryDelay=0,discoveryStatus=200,discographyDelay=0;bool emptyRecommendations=false,malformedRecommendations=false,hostileRecommendations=false,failRecommendationPage=false,rejectDiscography=false,emptyDiscography=false;
+ bool tailFixture=false,listeningFixture=false,snapshotFailure=false,ignoreSeek=false,wrongSong=false;
+ QString snapshotId="b",snapshotType="songs";double snapshotPosition=12.345;int snapshotReads=0,seekWrites=0,delayedAppendMs=0;
int failures=0, plays=0, reads=0; bool failPage=false, hostilePage=false, rejectPlay=false, rejectRead=false, manyRows=false;
bool pagedTracks=false, failTracks=false, slowTracks=false, hostileTracks=false, renamedTracks=false; int historyReads=0;
- QString playedType, playedId, playedPath, lastTerm;
+ bool failReleases=false, slowReleases=false; int releaseReads=0, radioReads=0;
+ bool slowTop=false, rejectTop=false, emptyTop=false, hostileTop=false;
+ bool playedShuffle=false, transactionQueue=false, changeQueueOnRead=false, changeAfterAppend=false; int queueWrites=0,qualityReads=0;
+ QJsonObject quality{{"flavorLabel","AAC 256kbps"},{"deviceAudioConfig",QJsonObject{{"sampleRate",48000},{"channelCount",2}}}};
+ QString playedType, playedId, playedPath, lastTerm, lastBrowsePath;
+ QJsonArray fixtureQueue; int fixturePosition=-1;
+ int jumps=0,jumpedIndex=-1,jumpDelay=0; bool rejectJump=false;
+ int queueReads=0,queueDelay=0;int deleteWrites=0,rejectDeleteAt=-1; QList<int> deletedIndices;
+ bool changeAfterDelete=false,advanceAfterDelete=false,failAfterDelete=false,failQueueRead=false;
+ bool automix=false, audioUnavailable=false, rejectAudio=false; QString listeningMode="off"; int audioReads=0,audioWrites=0; QJsonObject audioPatch;
+ QString shareUrl="https://music.apple.com/ca/album/example/100?i=123&ls=1"; int shareDelay=0;
+ const auto originalClipboard=QGuiApplication::clipboard()->text();
int edits=0, statusReads=0, rating=0, editDelay=0;
bool crossfade=false, rejectCrossfade=false, malformedCrossfade=false; double fadeSeconds=5; int fadeReads=0, fadeWrites=0; QJsonObject fadePatch;
bool saved=false, rejectEdit=false, malformedStatus=false;
- QString editPath, editMethod; QJsonObject editBody;
+ int authCode=200, authDelay=0, authRequests=0, probes=0; bool malformedAuth=false, rejectProbe=false; QJsonObject authBody;
+ QString editPath, editMethod; QJsonObject editBody; QStringList queueIds; int rejectQueueAt=-1;
auto check=[&](bool ok,const char *name) { std::cout<<(ok?"PASS ":"FAIL ")<<name<<std::endl; if(!ok)++failures; };
- auto wait=[&](const std::function<bool()> &condition) { QElapsedTimer t;t.start();while(!condition()&&t.elapsed()<5000)QTest::qWait(25);return condition(); };
+ auto wait=[&](const std::function<bool()> &condition) { QElapsedTimer t;t.start();while(!condition()&&t.elapsed()<10000)QTest::qWait(25);return condition(); };
auto resource=[](QString id,QString type,QString title,bool playable=true) {
QJsonObject attrs{{"name",title},{"artistName","Spun Sound Lab"},{"trackCount",2},{"durationInMillis",32000}};
if(playable)attrs["playParams"]=QJsonObject{{"id",id}};
@@ -54,14 +73,66 @@ int exerciseLibrary(QQuickWindow *window, const QString &temp, const QString &ca
auto body=QJsonDocument::fromJson(request.mid(split+4,length)).object();
const QString endpoint=QString::fromUtf8(request.split(' ').value(1));
QJsonObject response{{"data",QJsonObject{}}}; int code=200, delay=0;
- if(!request.left(split).contains("test-library-token"))code=403;
+ if(endpoint=="/api/v2/auth/request") {
+ ++authRequests; authBody=body; code=authCode; delay=authDelay;
+ response["data"]=malformedAuth?QJsonObject{}:QJsonObject{{"token","test-library-token"},{"scopes",QJsonArray{"playback","queue","library","audio"}}};
+ } else if(!request.left(split).contains("test-library-token"))code=403;
+ else if(endpoint=="/api/v2/client/info") { ++probes; if(rejectProbe)code=401; response["data"]=QJsonObject{{"version","4.0.9"}}; }
+ else if(endpoint.startsWith("/api/v2/queue?")) { ++queueReads;delay=queueDelay;if(failQueueRead)code=500; if(changeQueueOnRead) { changeQueueOnRead=false;fixtureQueue.append(QJsonObject{{"track",resource("external","songs","External")}}); } response["data"]=QJsonObject{{"items",fixtureQueue},{"position",fixturePosition}}; response["meta"]=QJsonObject{{"total",fixtureQueue.size()}}; }
+ else if(endpoint=="/api/v2/queue/jump") {
+ ++jumps; jumpedIndex=body["index"].toInt(-1); delay=jumpDelay;
+ if(rejectJump)code=503;
+ else if(jumpedIndex<0 || jumpedIndex>=fixtureQueue.size())code=400;
+ else {fixturePosition=jumpedIndex;if(listeningFixture) {const auto track=fixtureQueue[jumpedIndex].toObject()["track"].toObject();snapshotId=track["id"].toString();snapshotType=track["type"].toString();snapshotPosition=0;}}
+ }
+ else if(listeningFixture && endpoint=="/api/v2/playback") {
+ ++snapshotReads;if(snapshotFailure)code=503;
+ auto attrs=resource(wrongSong?"wrong":snapshotId,snapshotType,"Bookmarked <song>")["attributes"].toObject();
+ attrs["playParams"]=QJsonObject{{"id",wrongSong?"wrong":snapshotId},{"kind","song"},{"isLibrary",snapshotType=="library-songs"}};
+ response["data"]=QJsonObject{{"state","playing"},{"nowPlaying",attrs},{"time",QJsonObject{{"currentTime",snapshotPosition},{"duration",32.0}}}};
+ }
+ else if(listeningFixture && endpoint=="/api/v2/playback/seek") {++seekWrites;if(!ignoreSeek)snapshotPosition=body["position"].toDouble();}
+ else if(endpoint=="/api/v2/playback/audio-quality") { ++qualityReads;response["data"]=quality; }
+ else if(transactionQueue && (endpoint.startsWith("/api/v2/queue/items/") || endpoint=="/api/v2/queue/move")) {
+ ++queueWrites;
+ if(rejectEdit)code=403;
+ else if(endpoint.startsWith("/api/v2/queue/items/")) {
+ const int index=endpoint.section('/',-1).toInt();
+ ++deleteWrites;deletedIndices.append(index);
+ if(deleteWrites==rejectDeleteAt)code=500;
+ else if(index<0 || index>=fixtureQueue.size())code=400;
+ else { fixtureQueue.removeAt(index);if(index<fixturePosition)--fixturePosition;else if(index==fixturePosition)fixturePosition=qMin(fixturePosition,int(fixtureQueue.size())-1);
+ if(changeAfterDelete) { changeAfterDelete=false;changeQueueOnRead=true; }
+ if(advanceAfterDelete) { advanceAfterDelete=false;++fixturePosition; }
+ if(failAfterDelete) { failAfterDelete=false;failQueueRead=true; }
+ }
+ } else {
+ const int from=body["from"].toInt(),to=body["to"].toInt();
+ if(from<0 || to<0 || from>=fixtureQueue.size() || to>=fixtureQueue.size())code=400;
+ else { const auto row=fixtureQueue.takeAt(from);fixtureQueue.insert(to,row);
+ if(fixturePosition==from)fixturePosition=to;else if(from<fixturePosition && to>=fixturePosition)--fixturePosition;else if(from>fixturePosition && to<=fixturePosition)++fixturePosition;
+ }
+ }
+ }
+ else if(endpoint=="/api/v2/playback/now-playing") { response["data"]=QJsonObject{{"url",shareUrl}};delay=shareDelay; }
+ else if(endpoint=="/api/v2/audio/automix" || endpoint=="/api/v2/audio/listening-mode") {
+ if(request.startsWith("PATCH")) { ++audioWrites;audioPatch=body;
+ if(rejectAudio)code=403;else if(endpoint.endsWith("automix"))automix=body["enabled"].toBool();else listeningMode=body["mode"].toString();
+ } else ++audioReads;
+ if(audioUnavailable)code=404;
+ response["data"]=endpoint.endsWith("automix")?QJsonObject{{"enabled",automix},{"vocalGuard",true}}:QJsonObject{{"mode",listeningMode},{"available",true}};
+ }
else if(endpoint=="/api/v2/library/now-playing/status") {
++statusReads;
response["data"]=malformedStatus ? QJsonObject{} : QJsonObject{{"inLibrary",saved},{"rating",rating}};
delay=editDelay;
} else if(endpoint.startsWith("/api/v2/library/now-playing/") || endpoint.startsWith("/api/v2/queue/add-")) {
++edits; editPath=endpoint; editBody=body; editMethod=QString::fromUtf8(request.split(' ').first()); delay=editDelay;
- if(rejectEdit) code=403;
+ if(endpoint.startsWith("/api/v2/queue/add-")) queueIds.append(body["id"].toString());
+ if(rejectEdit || (rejectQueueAt>=0 && queueIds.size()==rejectQueueAt)) code=403;
+ else if(transactionQueue && endpoint.endsWith("/add-later")) { if(changeAfterAppend) { changeQueueOnRead=true;changeAfterAppend=false; } ++queueWrites;const auto row=QJsonObject{{"track",resource(body["id"].toString(),body["type"].toString(),body["id"].toString())}};
+ if(delayedAppendMs)QTimer::singleShot(delayedAppendMs,&server,[&,row]{fixtureQueue.append(row);});else fixtureQueue.append(row); }
+ else if(endpoint.endsWith("/dislike")) rating=-1;
else if(endpoint.endsWith("/love")) rating=1;
else if(endpoint.endsWith("/rating")) rating=body["rating"].toInt();
else if(endpoint.endsWith("/add")) saved=true;
@@ -78,22 +149,67 @@ int exerciseLibrary(QQuickWindow *window, const QString &temp, const QString &ca
response["data"]=malformedCrossfade?QJsonObject{}:QJsonObject{{"enabled",crossfade},{"durationSec",fadeSeconds},{"exclusions",QJsonObject{{"albums",true}}}};
}
else if(endpoint=="/api/v1/amapi/run-v3") {
- ++reads; const QUrl path(body["path"].toString()); const QUrlQuery query(path); const int offset=query.queryItemValue("offset").toInt();
+ ++reads;lastBrowsePath=body["path"].toString(); const QUrl path(lastBrowsePath); const QUrlQuery query(path); const int offset=query.queryItemValue("offset").toInt();
QJsonObject data; QJsonArray rows;
- if(path.path()=="/v1/me/storefront") rows.append(QJsonObject{{"id","ca"}});
+ if(path.path().startsWith("/v1/me/recommendations")) {
+ ++recommendationReads;delay=discoveryDelay;code=discoveryStatus;
+ const auto catalog=[&](const QString &id,const QString &type,const QString &name) {auto row=resource(id,type,name);row["href"]="/v1/catalog/ca/"+type+"/"+id;return row;};
+ if(!emptyRecommendations) {
+ if(offset) {
+ if(failRecommendationPage)code=503;
+ rows={catalog(path.path().endsWith("contents")?"late":"pl.later",path.path().endsWith("contents")?"albums":"playlists","Later recommendation")};
+ } else {
+ const auto album=catalog("recommended","albums","Recommended <album>");
+ QJsonObject nested{{"type","personal-recommendation"},{"relationships",QJsonObject{{"contents",QJsonObject{{"data",QJsonArray{catalog("ra.mix","stations","Your station")}}}}}}};
+ auto bad=catalog("bad","albums","Bad route");bad["href"]="https://example.invalid/credentials";
+ QJsonObject group{{"id","group1"},{"type","personal-recommendation"},{"attributes",QJsonObject{{"title",QJsonObject{{"stringForDisplay","Made for you"}}}}},
+ {"relationships",QJsonObject{{"contents",QJsonObject{{"data",QJsonArray{album,catalog("pl.mix","playlists","Weekly mix"),album,nested,bad}},{"next",hostileRecommendations?"https://example.invalid/steal":"/v1/me/recommendations/group1/contents?offset=1"}}}}}};
+ rows={group};data["next"]="/v1/me/recommendations?offset=1";
+ }
+ }
+ if(malformedRecommendations)data["data"]="invalid";
+ }
+ else if(path.path()=="/v1/me/storefront") rows.append(QJsonObject{{"id","ca"}});
else if(path.path().endsWith("/search")) {
const QString type=query.queryItemValue("types");lastTerm=query.queryItemValue("term",QUrl::FullyDecoded);
if(lastTerm=="slow")delay=600;
- if(lastTerm!="empty")rows.append(resource("123",type,lastTerm));
+ if(lastTerm!="empty")rows.append(resource(type=="stations"?"ra.station":"123",type,lastTerm));
+ if(type=="artists" && lastTerm=="Shared name")rows.append(resource("456",type,lastTerm));
data={{"results",QJsonObject{{type,QJsonObject{{"data",rows}}}}}};
} else if(path.path()=="/v1/me/recent/played/tracks") {
++historyReads;
rows={resource(offset?"i.older":"recent-new","songs",offset?"Older memory":"Latest song")};
if(offset)rows[0]=resource("i.older","library-songs","Older memory");
if(!offset)data["next"]="/v1/me/recent/played/tracks?types=songs,library-songs&offset=1";
+ } else if(path.path().endsWith("/songs/999/station")) {
+ ++radioReads; data["errors"]=QJsonArray{QJsonObject{{"code","40403"}}};
+ } else if(path.path().endsWith("/station")) {
+ ++radioReads;if(path.path().contains("/777/"))delay=500;
+ rows={resource("ra.seed","stations","Song radio")};
+ } else if(path.path().endsWith("/artists") && query.hasQueryItem("views")) {
+ ++releaseReads;if(failReleases)code=503;if(slowReleases)delay=500;
+ for(const auto &id:query.queryItemValue("ids").split(',')) {
+ auto release=resource("album"+id,"albums","Release "+id);auto attrs=release["attributes"].toObject();attrs["releaseDate"]=id=="123"?"2026-01-01":"2026-08-01";release["attributes"]=attrs;
+ QJsonObject views;views["latest-release"]=QJsonObject{{"data",QJsonArray{release}}};
+ rows.append(QJsonObject{{"id",id},{"type","artists"},{"views",views}});
+ }
+ } else if(path.path().endsWith("/view/similar-artists")) {
+ rows={resource("456","artists","Related artist",false)};
+ } else if(path.path().contains("/artists/") && path.path().endsWith("/view/top-songs")) {
+ if(slowTop)delay=450;
+ if(rejectTop)code=404;
+ if(!emptyTop)rows={resource(offset?"top2":"top1","songs",offset?"Second hit":"First hit")};
+ if(!offset&&!emptyTop)data["next"]=hostileTop?"https://example.invalid/steal":path.path()+"?offset=1";
+ } else if(path.path().contains("/artists/") && path.path().endsWith("/albums")) {
+ rows={resource(offset?"456":"234","albums",offset?"Evening sketches":"First Light")};
+ if(!offset)data["next"]=path.path()+"?offset=1";
+ } else if(path.path().endsWith("/view/full-albums") || path.path().endsWith("/view/singles") || path.path().endsWith("/view/live-albums")) {
+ delay=discographyDelay;if(rejectDiscography)code=404;
+ if(!emptyDiscography) {rows={resource(offset?"filter2":"filter1","albums",path.path().section('/',-1)+(offset?" second":" first"))};if(!offset)data["next"]=path.path()+"?offset=1";}
} else if(path.path().endsWith("/tracks")) {
const auto type=path.path().contains("/me/")?"library-songs":"songs";
rows={resource("i.first",type,renamedTracks?"Renamed café":"First Light"),resource("i.second",type,"Second Light"),resource("i.unavailable",type,"Unavailable",false)};
+ if(tailFixture)rows={resource("repeat",type,"Repeat"),resource("repeat",type,"Repeat"),resource("middle",type,"Middle")};
if(pagedTracks) {
if(!offset)data["next"]=hostileTracks?"https://example.invalid/tracks":path.path()+"?offset=1";
else { rows={resource("i.hidden",type,"Café Afterglow")}; if(failTracks)code=503; if(slowTracks)delay=400; }
@@ -112,10 +228,11 @@ int exerciseLibrary(QQuickWindow *window, const QString &temp, const QString &ca
if(albums&&!offset)data["next"]=hostilePage?"https://example.invalid/steal":"/v1/me/library/albums?offset=1";
if(offset&&failPage)code=503;
}
- if(!data.contains("results"))data["data"]=rows;
+ if(!data.contains("results"))data["data"]=path.path().startsWith("/v1/me/recommendations")&&malformedRecommendations?QJsonValue("invalid"):QJsonValue(rows);
response["data"]=data;if(rejectRead)code=403;
} else if(endpoint.startsWith("/api/v2/playback/")) {
- ++plays;playedId=body["id"].toString();playedType=body["type"].toString();playedPath=endpoint;if(rejectPlay)code=422;
+ ++plays;playedShuffle=body["shuffle"].toBool();playedId=body["id"].toString();playedType=body["type"].toString();playedPath=endpoint;if(rejectPlay)code=422;
+ if(listeningFixture && !rejectPlay && endpoint.endsWith("play-item")) {snapshotId=playedId;snapshotType=playedType;snapshotPosition=0;}
}
QByteArray bytes=QJsonDocument(response).toJson(QJsonDocument::Compact);
auto send=[s,bytes,code] { s->write("HTTP/1.1 "+QByteArray::number(code)+" Result\r\nContent-Type: application/json\r\nConnection: close\r\nContent-Length: "+QByteArray::number(bytes.size())+"\r\n\r\n"+bytes);s->disconnectFromHost(); };
@@ -145,6 +262,47 @@ int exerciseLibrary(QQuickWindow *window, const QString &temp, const QString &ca
check(wait([&]{return !browser.starting();})&&playedType=="albums","catalog album playback uses catalog collection type");browser.back();
browser.setKind("playlists");wait([&]{return !browser.busy();});browser.open(0);wait([&]{return !browser.busy();});browser.playCollection();
check(wait([&]{return !browser.starting();})&&playedType=="playlists","catalog playlist playback uses catalog collection type");browser.back();
+ browser.setKind("stations");browser.setQuery("Chill");
+ check(wait([&]{return !browser.busy();})&&browser.items().first().toMap()["type"]=="stations","station search uses the catalog through the existing token");
+ const auto station=browser.items().first().toMap();browser.open(0);
+ check(wait([&]{return !browser.starting();})&&playedType=="stations"&&playedId=="ra.station"&&browser.collection().isEmpty(),"station row starts station playback without requesting a track list");
+ browser.togglePin(station);Library stationReload(&cider);
+ check(stationReload.pins().size()==1&&stationReload.pins().first().toMap()["type"]=="stations","station pins survive relaunch");
+ browser.playPin(0);check(wait([&]{return !browser.starting();})&&playedType=="stations","station pin starts its original station identity");browser.togglePin(station);
+ check(Library::linkPath("https://music.apple.com/ca/station/chill/ra.123")=="/v1/catalog/ca/stations/ra.123","Apple Music station links resolve safely");
+ browser.setKind("playlists");wait([&]{return !browser.busy();});
+ const int artistPlays=plays;
+ browser.showArtist("Spun Sound Lab");
+ check(wait([&]{return !browser.busy();})&&browser.collection()["type"]=="artists"&&browser.items().first().toMap()["type"]=="albums","unique artist lookup opens its catalog albums");
+ const auto artistPin=browser.collection();browser.togglePin(artistPin);
+ Library restoredArtistPins(&cider);
+ check(browser.isPinned(artistPin)&&restoredArtistPins.pins().size()==1&&restoredArtistPins.pins().first().toMap()["type"]=="artists","artist pins persist without changing playback");
+ auto invalidArtist=artistPin;invalidArtist["path"]="https://example.com/artists/123";browser.togglePin(invalidArtist);
+ check(browser.pins().size()==1,"artist pins reject external resource paths");
+ browser.playCollection();browser.shuffleCollection(artistPin);QTest::qWait(30);
+ check(plays==artistPlays,"artist resources never dispatch collection playback");
+ browser.togglePin(artistPin);check(browser.pins().isEmpty(),"artist pins can be removed independently");
+ browser.setArtistView("songs");
+ check(wait([&]{return !browser.busy();})&&browser.items().size()==1&&browser.items().first().toMap()["id"]=="top1"&&lastBrowsePath.endsWith("/view/top-songs?limit=25"),"artist Top songs uses the existing Cider proxy");
+ browser.more();check(wait([&]{return !browser.busy();})&&browser.items().size()==2,"artist top songs paginate in server order");
+ browser.setCollectionQuery("Second");check(browser.items().size()==1&&browser.items().first().toMap()["id"]=="top2","top songs support inline filtering");
+ browser.setArtistView("albums");check(wait([&]{return !browser.busy();})&&browser.collectionQuery().isEmpty()&&browser.items().first().toMap()["type"]=="albums","switching artist view clears the filter and restores albums");
+ slowTop=true;browser.setArtistView("songs");QTest::qWait(40);browser.setArtistView("albums");wait([&]{return !browser.busy();});QTest::qWait(500);
+ check(browser.artistView()=="albums"&&browser.items().first().toMap()["type"]=="albums","late top-song replies cannot overwrite artist albums");slowTop=false;
+ rejectTop=true;browser.setArtistView("songs");check(wait([&]{return !browser.busy();})&&!browser.error().isEmpty()&&browser.collection()["type"]=="artists","unavailable top songs preserve the artist and Albums option");rejectTop=false;
+ emptyTop=true;browser.reload();check(wait([&]{return !browser.busy();})&&browser.items().isEmpty()&&browser.error().isEmpty(),"artists with no top songs show a normal empty list");emptyTop=false;
+ hostileTop=true;browser.reload();wait([&]{return !browser.busy();});const int beforeTopMore=reads;browser.more();
+ check(reads==beforeTopMore&&!browser.error().isEmpty(),"top-song pagination never forwards credentials outside Cider");hostileTop=false;
+ browser.setArtistView("albums");wait([&]{return !browser.busy();});
+ browser.more();check(wait([&]{return !browser.busy();})&&browser.items().size()==2,"artist discography paginates");
+ browser.setCollectionQuery("evening");check(browser.items().size()==1,"artist albums support inline filtering");
+ browser.open(0);check(wait([&]{return !browser.busy();})&&browser.collection()["id"]=="456"&&browser.items().first().toMap()["type"]=="songs","artist album opens its catalog tracks");
+ browser.back();check(browser.collection()["type"]=="artists"&&browser.collectionQuery()=="evening"&&browser.items().size()==1,"Back restores the artist and album filter");
+ browser.back();check(browser.collection().isEmpty()&&browser.kind()=="artists"&&plays==artistPlays,"artist browsing never changes playback");
+ browser.showArtist("Shared name");check(wait([&]{return !browser.busy();})&&browser.collection().isEmpty()&&browser.items().size()==2,"ambiguous artist names stay in the chooser");
+ browser.showArtist("slow");QTest::qWait(50);browser.setQuery("fresh artist");
+ check(wait([&]{return !browser.busy();})&&browser.collection().isEmpty()&&browser.items().first().toMap()["title"]=="fresh artist","editing an artist lookup cancels automatic navigation");
+ browser.setKind("playlists");wait([&]{return !browser.busy();});
browser.setQuery("empty");check(wait([&]{return !browser.busy();})&&browser.items().isEmpty()&&browser.error().isEmpty(),"empty search is a normal state");
browser.setQuery("slow");QTest::qWait(400);browser.setActive(false);QTest::qWait(650);
check(browser.items().isEmpty()&&!browser.busy(),"closing browser discards pending searches");
@@ -186,6 +344,47 @@ int exerciseLibrary(QQuickWindow *window, const QString &temp, const QString &ca
int oldFadeReads=fadeReads;QTest::qWait(100);check(fadeReads==oldFadeReads,"crossfade does not poll in the background");
browser.setSection("albums");wait([&]{return !browser.busy();});
+ // Connection approval uses only the fixture, never the user's Cider session.
+ {
+ const QString authConfig=temp+"/auth/connection.json";
+ Cider approval(false,authConfig,QUrl(QString("http://127.0.0.1:%1").arg(server.serverPort())));
+ authCode=403; approval.authorize();
+ check(wait([&]{return !approval.authorizing();})&&!QFile::exists(authConfig)&&approval.connectionMessage().contains("approved"),"denied authorization never replaces stored access");
+ authCode=200; malformedAuth=true; approval.authorize();
+ check(wait([&]{return !approval.authorizing();})&&!QFile::exists(authConfig),"malformed approval cannot save an empty token");
+ malformedAuth=false; authDelay=500; approval.authorize(); approval.authorize(); QTest::qWait(50);
+ const int requests=authRequests; approval.cancelAuthorization(); QTest::qWait(600);
+ check(!approval.authorizing()&&!QFile::exists(authConfig)&&authRequests==requests,"cancel and duplicate clicks cannot accept a late approval");
+ authDelay=0; approval.authorize();
+ check(wait([&]{return !approval.authorizing()&&approval.queueReady();})&&QFile::exists(authConfig),"approved connection persists and loads the queue");
+ check(authBody["app_name"]=="Spun"&&authBody["scopes"].toArray().size()==4,"approval identifies Spun and requests only its four feature scopes");
+ check(!(QFile::permissions(authConfig)&(QFileDevice::ReadGroup|QFileDevice::ReadOther|QFileDevice::WriteGroup|QFileDevice::WriteOther)),"saved Cider token is owner-only");
+ Cider restored(false,authConfig,QUrl(QString("http://127.0.0.1:%1").arg(server.serverPort()))); restored.reconnect();
+ check(wait([&]{return restored.connectionState()=="connected";}),"saved approval reconnects on a new app instance");
+ }
+ {
+ const auto row=browser.items().first().toMap(); const int beforePins=plays;
+ browser.togglePin(row);
+ check(browser.pins().size()==1&&browser.isPinned(row)&&plays==beforePins,"pinning a collection does not change playback");
+ Library restored(&cider); check(restored.pins().size()==1,"pins survive a new browser instance");
+ auto hostile=row; hostile["path"]="https://example.invalid/album"; browser.togglePin(hostile);
+ check(browser.pins().size()==1,"pin validation rejects external collection paths");
+ browser.playPin(0); check(wait([&]{return !browser.starting();})&&playedId==row["id"]&&playedType==row["type"],"pin playback preserves library ID and resource type");
+ browser.openPin(0); check(wait([&]{return !browser.busy();})&&browser.collection()["path"]==row["path"],"pinned collection opens its own track list");browser.back();
+ const auto rows=browser.items(); rejectRead=true;browser.reload();
+ check(wait([&]{return !browser.busy();})&&browser.items()==rows&&browser.needsConnection(),"access failure preserves the visible browsing results");
+ const int beforeRecovery=plays; rejectRead=false;cider.reconnect();
+ check(wait([&]{return !browser.busy()&&browser.error().isEmpty();})&&plays==beforeRecovery,"reconnection reloads failed reads without replaying a music command");
+ const auto port=server.serverPort(); server.close(); cider.reconnect();
+ check(wait([&]{return cider.recovering();}),"lost local API is distinguished from expired permission");
+ const int offlinePlays=plays;check(server.listen(QHostAddress::LocalHost,port),"fixture API returns on the same port");
+ check(wait([&]{return cider.connectionState()=="connected";})&&plays==offlinePlays,"visible browser recovers automatically without resuming music");
+ const int settledProbes=probes; QTest::qWait(150);
+ check(probes==settledProbes,"successful recovery stops connection probing");
+ browser.togglePin(row); Library unpinned(&cider);
+ check(browser.pins().isEmpty()&&unpinned.pins().isEmpty(),"unpin persists without leaving a stale saved collection");
+ }
+
browser.setSection("recent");
check(wait([&]{return !browser.busy();})&&browser.items().value(0).toMap()["id"]=="recent-new"&&browser.hasMore(),"recent history loads lazily in API order");
browser.setQuery("older");
@@ -234,6 +433,15 @@ int exerciseLibrary(QQuickWindow *window, const QString &temp, const QString &ca
editBefore=edits;chosen["playable"]=false;actions.enqueue(chosen,true);QTest::qWait(50);check(edits==editBefore,"unavailable items cannot be queued");
chosen["playable"]=true;rejectEdit=true;actions.enqueue(chosen,false);
check(wait([&]{return !actions.busy();})&&!actions.error().isEmpty()&&notices.last().at(1).toBool(),"denied edits give visible feedback without reporting success");rejectEdit=false;
+ const QVariantList batch{QVariantMap{{"id","one"},{"type","songs"},{"playable",true}},QVariantMap{{"id","i.two"},{"type","library-songs"},{"playable",true}},QVariantMap{{"id","three"},{"type","songs"},{"playable",true}}};
+ queueIds.clear();actions.enqueueMany(batch,true);actions.enqueueMany(batch,true);
+ check(wait([&]{return !actions.busy();})&&queueIds==QStringList{"three","i.two","one"},"batch Play Next reverses requests to preserve selected order and rejects duplicate submission");
+ queueIds.clear();actions.enqueueMany(batch,false);
+ check(wait([&]{return !actions.busy();})&&queueIds==QStringList{"one","i.two","three"},"batch Add to Queue preserves visual order and mixed resource identity");
+ queueIds.clear();rejectQueueAt=2;actions.enqueueMany(batch,false);
+ check(wait([&]{return !actions.busy();})&&queueIds.size()==2&&actions.error().contains("1 of 3"),"partial batch failure stops without replay and reports confirmed count");rejectQueueAt=-1;
+ auto invalidBatch=batch;invalidBatch.append(QVariantMap{{"id","bad"},{"type","albums"},{"playable",true}});queueIds.clear();actions.enqueueMany(invalidBatch,false);QTest::qWait(50);
+ check(queueIds.isEmpty()&&!actions.busy(),"batch validates every song before issuing any queue writes");
actions.setObserving(false);const int readsBefore=statusReads;QTest::qWait(2100);check(statusReads==readsBefore,"closed song menu does not poll Cider");
malformedStatus=true;actions.setObserving(true);QTest::qWait(100);
check(!actions.ready()&&!actions.error().isEmpty(),"unreadable status never appears as an unfavorited song");
@@ -241,8 +449,157 @@ int exerciseLibrary(QQuickWindow *window, const QString &temp, const QString &ca
actions.setObserving(false);QMetaObject::invokeMethod(&cider,"trackChanged");QTest::qWait(350);
check(!actions.ready()&&!actions.saved(),"late status cannot restore the previous track state");editDelay=0;
+ browser.setSection("songs");wait([&]{return !browser.busy();});browser.setNewestFirst(true);
+ check(wait([&]{return !browser.busy();})&&lastBrowsePath.contains("sort=-dateAdded"),"recently added songs request server-side newest-first order");
+ browser.more();check(wait([&]{return !browser.busy();})&&lastBrowsePath.contains("sort=-dateAdded"),"recently added pagination preserves the requested order");
+ { Library restoredSort(&cider);check(restoredSort.newestFirst(),"library sort preference survives relaunch"); }
+ browser.setSection("albums");check(wait([&]{return !browser.busy();})&&lastBrowsePath.contains("sort=-dateAdded"),"recently added albums use the same bounded server sort");browser.setNewestFirst(false);wait([&]{return !browser.busy();});
+ check(Library::songLink("https://music.apple.com/ca/album/test/100?i=123&ls=1")=="https://music.apple.com/ca/song/123","share links keep the song identity and remove tracking parameters");
+ check(Library::songLink("https://music.apple.com.evil.test/ca/song/123").isEmpty(),"share links reject lookalike domains");
+ browser.copyLink({{"id","123"},{"type","songs"},{"path","/v1/catalog/ca/songs/123"}});
+ check(QGuiApplication::clipboard()->text()=="https://music.apple.com/ca/song/123","catalog song link is copied without a network request");
+ browser.copyLink({{"id","i.example"},{"type","library-songs"},{"catalogId","456"}});
+ check(wait([&]{return !browser.busy();})&&QGuiApplication::clipboard()->text()=="https://music.apple.com/ca/song/456","library song sharing uses the catalog ID instead of the private library ID");
+ cider.copySongLink();check(wait([&]{return QGuiApplication::clipboard()->text()=="https://music.apple.com/ca/song/123";}),"current song sharing uses Cider's song URL");
+ shareUrl="https://example.invalid/private";cider.copySongLink();QTest::qWait(100);
+ check(QGuiApplication::clipboard()->text()=="https://music.apple.com/ca/song/123","unshareable current tracks preserve the clipboard");shareUrl="https://music.apple.com/ca/album/example/100?i=123";
+ cider.refreshAudioOptions();check(wait([&]{return !cider.audioBusy();})&&cider.audioOptions().contains("automix")&&cider.audioOptions()["listeningMode"]=="off","extra audio settings discover supported controls");
+ cider.setAudioOption("automix",true);cider.setAudioOption("automix",true);
+ check(wait([&]{return !cider.audioBusy();})&&automix&&audioWrites==1&&audioPatch.size()==1&&audioPatch.contains("enabled"),"Automix writes only its toggle and confirms state without duplicate writes");
+ cider.setAudioOption("listeningMode","unwind");check(wait([&]{return !cider.audioBusy();})&&listeningMode=="unwind"&&cider.audioOptions()["listeningMode"]=="unwind","listening mode reads back its confirmed state");
+ const int writtenAudio=audioWrites;cider.setAudioOption("listeningMode","unknown");check(audioWrites==writtenAudio,"unknown listening modes cannot be written");
+ rejectAudio=true;cider.setAudioOption("automix",false);check(wait([&]{return !cider.audioBusy();})&&!cider.audioOptions().contains("automix")&&automix&&!cider.audioError().isEmpty(),"denied audio writes never show an unconfirmed toggle");rejectAudio=false;
+ audioUnavailable=true;cider.refreshAudioOptions();check(wait([&]{return !cider.audioBusy();})&&cider.audioOptions().isEmpty(),"unsupported audio endpoints hide their controls");audioUnavailable=false;
+ cider.refreshAudioOptions();wait([&]{return !cider.audioBusy();});const int quietAudio=audioReads;QTest::qWait(150);check(audioReads==quietAudio,"extra audio settings never poll in the background");
+ fixtureQueue={QJsonObject{{"track",resource("history","songs","Already heard")}},QJsonObject{{"track",resource("123","songs","First Light")}},QJsonObject{{"track",resource("i.two","library-songs","Second Light")}}};fixturePosition=1;
+ cider.refreshQueue();check(wait([&]{return !cider.queueBusy();})&&cider.queueReady(),"saved queue fixture loads with current position");
+ const int savePlays=plays;check(browser.saveQueue("Evening drive")&&plays==savePlays,"saving a queue never changes playback");
+ browser.setSection("sessions");wait([&]{return !browser.busy();});check(browser.items().size()==1&&browser.items().first().toMap()["trackCount"].toInt()==2,"saved queues exclude already played history");
+ const auto session=browser.items().first().toMap();const auto snapshot=browser.savedTracks(session["id"].toString());
+ check(snapshot.size()==2&&snapshot[0].toMap()["id"]=="123"&&snapshot[1].toMap()["type"]=="library-songs","saved queues preserve order and library identities");
+ const QString snapshotPath=temp+"/saved-queues/"+session["id"].toString()+".json";
+ check(!(QFile::permissions(snapshotPath)&(QFileDevice::ReadGroup|QFileDevice::ReadOther)),"saved queue references are owner-only");
+ QFile snapshotFile(snapshotPath);check(snapshotFile.open(QIODevice::ReadOnly),"saved queue file opens for inspection");const auto snapshotBytes=snapshotFile.readAll();snapshotFile.close();
+ check(!snapshotBytes.contains("test-library-token"),"saved queues never include connection credentials");
+ check(snapshotFile.open(QIODevice::WriteOnly),"saved queue fixture opens for corruption test");snapshotFile.write("broken");snapshotFile.close();check(browser.savedTracks(session["id"].toString()).isEmpty(),"corrupt saved queues never produce partial playback lists");
+ check(snapshotFile.open(QIODevice::WriteOnly),"saved queue fixture opens for corruption test");snapshotFile.write(snapshotBytes);snapshotFile.close();
+ QFile manifest(temp+"/saved-queues/index.json");check(manifest.open(QIODevice::ReadOnly),"saved queue index opens");const auto manifestBytes=manifest.readAll();manifest.close();
+ check(manifest.open(QIODevice::WriteOnly),"saved queue index fixture opens");manifest.write("broken");manifest.close();
+ check(!browser.saveQueue("Do not overwrite"),"a corrupt index cannot be overwritten by saving another queue");
+ check(manifest.open(QIODevice::ReadOnly),"saved queue index can be checked after failed save");check(manifest.readAll()=="broken","failed save preserves the existing index");manifest.close();
+ check(manifest.open(QIODevice::WriteOnly),"saved queue index fixture restores");manifest.write(manifestBytes);manifest.close();
+ check(browser.savedTracks("../cider-connection").isEmpty(),"saved queue IDs cannot escape the storage directory");
+ Library restoredSessions(&cider);restoredSessions.setSection("sessions");restoredSessions.setActive(true);
+ check(restoredSessions.items().size()==1,"saved queue metadata survives a new browser instance");restoredSessions.setActive(false);
+ browser.open(0);check(browser.items().size()==2&&browser.collection()["type"]=="saved-queues","saved queue opens its tracks without autoplay or API reads");
+ const auto renameBefore=browser.collection();
+ const int editsBeforeSaved=edits,playsBeforeSaved=plays;
+ check(browser.renameSavedQueue(renameBefore," Night drive ")&&browser.collection()["title"]=="Night drive","saved queue rename trims and persists the new title");
+ check(!browser.renameSavedQueue(renameBefore,"Stale")&&!browser.renameSavedQueue(browser.collection()," "),"stale and empty saved-queue names cannot overwrite the current title");
+ check(browser.editSavedTrack(1,0,false)&&browser.items().first().toMap()["id"]=="i.two","saved track move preserves library identity and duplicate-safe order");
+ const auto versioned=browser.collection();const QString versionPath=temp+"/saved-queues/"+versioned["dataId"].toString()+".json";
+ check(versioned["dataId"]!=session["dataId"]&&QFile::exists(versionPath)&&QFile::exists(snapshotPath)&&browser.canUndoSavedQueue(),"saved track edit publishes a new version and briefly retains its predecessor for Undo");
+ check(!(QFile::permissions(versionPath)&(QFileDevice::ReadGroup|QFileDevice::ReadOther)),"edited saved queues remain owner-only");
+ const auto beforeFailedEdit=browser.savedTracks(session["id"].toString());
+ const auto filesBeforeFailed=QDir(temp+"/saved-queues").entryList(QDir::Files);
+ QFile::setPermissions(temp+"/saved-queues/index.json",QFileDevice::ReadOwner);
+ check(!browser.editSavedTrack(0,1,false)&&browser.savedTracks(session["id"].toString())==beforeFailedEdit&&QDir(temp+"/saved-queues").entryList(QDir::Files)==filesBeforeFailed,"failed index commit preserves the old snapshot and leaves no orphan edit");
+ QFile::setPermissions(temp+"/saved-queues/index.json",QFileDevice::ReadOwner|QFileDevice::WriteOwner);
+ browser.setCollectionQuery("First Light");
+ check(browser.items().size()==1&&browser.items().first().toMap()["savedIndex"]==1&&!browser.editSavedTrack(1,0,false),"filtered saved rows retain original positions and disable ambiguous reordering");
+ check(browser.editSavedTrack(browser.items().first().toMap()["savedIndex"].toInt(),0,true)&&browser.collection()["trackCount"]==1&&browser.items().isEmpty(),"filtered removal edits the matching source track only");
+ browser.setCollectionQuery("");
+ check(browser.items().first().toMap()["id"]=="i.two"&&browser.editSavedTrack(0,0,true)&&browser.collection()["trackCount"]==0&&!browser.collection()["playable"].toBool(),"removing the last saved song leaves an editable empty queue");
+ check(browser.renameSavedQueue(browser.collection(),"Empty queue"),"empty saved queues can still be renamed");
+ browser.back();check(browser.items().first().toMap()["title"]=="Empty queue"&&browser.items().first().toMap()["trackCount"]==0,"Back refreshes saved queue names and counts");
+ Library editedReload(&cider);editedReload.setSection("sessions");editedReload.setActive(true);
+ check(editedReload.items().first().toMap()["trackCount"]==0&&editedReload.savedTracks(session["id"].toString()).isEmpty(),"edited empty queue survives a new browser instance");editedReload.setActive(false);
+ check(edits==editsBeforeSaved&&plays==playsBeforeSaved,"saved queue edits never issue Cider playback or queue writes");
+ // Append to local snapshots without touching the live Cider queue.
+ auto savedChoice=[&]{return browser.savedQueueChoices()["rows"].toList().first().toMap();};
+ auto appendSong=Library::item(resource("fresh","songs","Fresh song"));
+ const auto emptyChoice=savedChoice();const int appendWrites=queueWrites+edits+plays;
+ auto appended=browser.appendSavedQueue(emptyChoice,{appendSong,appendSong},true);
+ check(appended["ok"].toBool()&&appended["added"]==1&&appended["skipped"]==1&&browser.savedTracks(session["id"].toString()).size()==1,"append fills an empty saved queue and skips repeated incoming identities");
+ check(!browser.appendSavedQueue(emptyChoice,{appendSong},false)["ok"].toBool(),"a stale saved-queue picker cannot overwrite a newer version");
+ const auto duplicateChoice=savedChoice();const auto duplicateFiles=QDir(temp+"/saved-queues").entryList(QDir::Files);
+ appended=browser.appendSavedQueue(duplicateChoice,{appendSong},true);
+ check(appended["ok"].toBool()&&appended["added"]==0&&appended["skipped"]==1&&savedChoice()==duplicateChoice&&duplicateFiles==QDir(temp+"/saved-queues").entryList(QDir::Files),"an all-duplicate append succeeds without rewriting files");
+ auto alias=appendSong;alias["id"]="i.alias";alias["type"]="library-songs";alias["catalogId"]="fresh";
+ check(browser.appendSavedQueue(savedChoice(),{alias},true)["skipped"]==1,"saved appends match catalog and library identities");
+ appended=browser.appendSavedQueue(savedChoice(),{alias,appendSong},false);
+ const auto repeatedSaved=browser.savedTracks(session["id"].toString());
+ check(appended["added"]==2&&repeatedSaved.size()==3&&repeatedSaved[1].toMap()["id"]=="i.alias"&&repeatedSaved[2].toMap()["id"]=="fresh","turning off duplicate skipping preserves deliberate repeats in order");
+ const auto beforeInvalidAppend=savedChoice();auto invalidAppend=appendSong;invalidAppend["id"]="../unsafe";
+ check(!browser.appendSavedQueue(beforeInvalidAppend,{appendSong,invalidAppend},false)["ok"].toBool()&&savedChoice()==beforeInvalidAppend,"one invalid song rejects the entire saved append without partial changes");
+ QFile::setPermissions(temp+"/saved-queues/index.json",QFileDevice::ReadOwner);
+ check(!browser.appendSavedQueue(beforeInvalidAppend,{appendSong},false)["ok"].toBool()&&browser.savedTracks(session["id"].toString())==repeatedSaved,"a failed append commit preserves the previous saved tracks");
+ QFile::setPermissions(temp+"/saved-queues/index.json",QFileDevice::ReadOwner|QFileDevice::WriteOwner);
+ check(queueWrites+edits+plays==appendWrites,"saved appends never issue Cider queue or playback writes");
+ const auto undoName=savedChoice()["title"].toString();
+ check(browser.renameSavedQueue(savedChoice(),"Temporary name")&&browser.canUndoSavedQueue()&&browser.undoSavedQueue()&&savedChoice()["title"]==undoName&&!browser.canUndoSavedQueue(),"Undo restores a saved queue name once");
+ check(browser.openQuickTarget("saved",session["id"].toString())&&browser.collection()["id"]==session["id"],"Quick jump opens a saved queue by its stable ID");
+ const auto undoTracks=browser.savedTracks(session["id"].toString());
+ check(browser.editSavedTrack(0,2,false)&&browser.undoSavedQueue()&&browser.savedTracks(session["id"].toString())==undoTracks,"Undo restores the exact saved order including duplicates");
+ const auto undoFile=browser.collection()["dataId"].toString();
+ check(browser.editSavedTrack(1,0,true)&&browser.undoSavedQueue()&&browser.savedTracks(session["id"].toString())==undoTracks&&browser.collection()["dataId"]==undoFile,"Undo restores a removed occurrence by switching back to its previous file");
+ check(browser.renameSavedQueue(browser.collection(),"Retry undo"),"Undo failure fixture renames locally");
+ QFile::setPermissions(temp+"/saved-queues/index.json",QFileDevice::ReadOwner);
+ check(!browser.undoSavedQueue()&&browser.canUndoSavedQueue()&&savedChoice()["title"]=="Retry undo","failed Undo keeps the current queue and allows a retry");
+ QFile::setPermissions(temp+"/saved-queues/index.json",QFileDevice::ReadOwner|QFileDevice::WriteOwner);
+ check(browser.undoSavedQueue()&&savedChoice()["title"]==undoName,"Undo can be retried after a failed index commit");
+ browser.renameSavedQueue(browser.collection(),"First editor");
+ { Library otherEditor(&cider);otherEditor.renameSavedQueue(savedChoice(),"Second editor");
+ check(!browser.undoSavedQueue()&&savedChoice()["title"]=="Second editor","stale Undo never overwrites another editor's changes"); }
+ browser.reload();const auto expiresFile=browser.collection()["dataId"].toString();
+ browser.editSavedTrack(0,1,false);QTest::qWait(8200);
+ check(!browser.canUndoSavedQueue()&&!QFile::exists(temp+"/saved-queues/"+expiresFile+".json")&&!browser.undoSavedQueue(),"Undo expires and retires the old track file without retaining a track list in RAM");
+ { Library inactiveJump(&cider);check(inactiveJump.openQuickTarget("saved",session["id"].toString()),"Quick jump can prepare a saved target while its browser is inactive");inactiveJump.setActive(true);
+ check(inactiveJump.items().size()==browser.savedTracks(session["id"].toString()).size(),"activating a prepared Quick jump target loads its tracks");inactiveJump.setActive(false); }
+ auto jumpArtist=Library::item(resource("123","artists","Quick artist"));jumpArtist["path"]="/v1/catalog/ca/artists/123";const bool jumpPinned=browser.isPinned(jumpArtist);if(!jumpPinned)browser.togglePin(jumpArtist);
+ check(browser.openQuickTarget("pin",jumpArtist["path"].toString())&&wait([&]{return !browser.busy();})&&browser.collection()["id"]=="123"&&browser.artistView()=="songs","Quick jump opens a pinned artist's Top songs");
+ browser.back();check(browser.collection().isEmpty(),"Back from a Quick jump artist returns to browsing");if(!jumpPinned)browser.togglePin(jumpArtist);
+ browser.openQuickTarget("saved",session["id"].toString());
+ const auto quickBefore=browser.collection();check(!browser.openQuickTarget("saved","missing")&&browser.collection()==quickBefore,"missing Quick jump targets leave browsing unchanged");
+ browser.back();check(browser.collection().isEmpty()&&browser.section()=="sessions","Back from a jumped saved queue returns to its saved-queue list");
+ check(queueWrites+edits+plays==appendWrites,"Undo and saved-queue navigation never write to Cider or start playback");
+ // Restore the fixture expected by the subsequent UI tests through normal Save.
+ browser.deleteSavedQueue(session["id"].toString());wait([&]{return !cider.queueBusy();});
+ check(!QFile::exists(versionPath)&&browser.saveQueue("Evening drive"),"deleting an edited queue cleans its current data and a new queue can be saved");
+ browser.open(0);
+ queueIds.clear();actions.enqueueMany(snapshot,false);check(wait([&]{return !actions.busy();})&&queueIds==QStringList{"123","i.two"},"saved queue appends its original track sequence");browser.back();
+ fixtureQueue={};fixturePosition=-1;cider.refreshQueue();wait([&]{return !cider.queueBusy();});
+ browser.setSection("albums");wait([&]{return !browser.busy();});
+ const int discoveryWrites=plays+edits;
+ browser.setSection("search");browser.setKind("artists");browser.setQuery("Seed artist");wait([&]{return !browser.busy();});browser.open(0);wait([&]{return !browser.busy();});
+ const auto seedArtist=browser.collection();browser.setArtistView("similar");
+ check(wait([&]{return !browser.busy();})&&browser.items().first().toMap()["type"]=="artists","similar artists use Cider catalog views");
+ browser.open(0);wait([&]{return !browser.busy();});check(browser.collection()["id"]=="456","similar artist opens a real artist page");
+ browser.back();check(browser.artistView()=="similar"&&browser.collection()["id"]=="123","Back restores similar artist results and view");
+ browser.togglePin(seedArtist);auto secondArtist=seedArtist;secondArtist["id"]="456";secondArtist["path"]="/v1/catalog/ca/artists/456";browser.togglePin(secondArtist);
+ browser.setSection("releases");check(wait([&]{return !browser.busy();})&&browser.items().size()==2&&releaseReads==1,"latest releases batch artist pins into one request");
+ check(browser.items().first().toMap()["id"]=="album456","latest releases sort newest first");
+ browser.open(0);wait([&]{return !browser.busy();});check(browser.collection()["type"]=="albums","release opens its album track list");browser.back();
+ check(browser.items().size()==2&&browser.collection().isEmpty(),"Back restores releases without refetching");
+ browser.setQuery("123");check(browser.items().size()==1,"release search filters the loaded list");browser.setQuery("");
+ browser.setSection("search");browser.setSection("releases");check(releaseReads==1&&browser.items().size()==2,"reopening releases uses bounded session cache");
+ failReleases=true;browser.reload();check(wait([&]{return !browser.busy();})&&browser.items().size()==2&&!browser.releaseNotice().isEmpty()&&!browser.error().isEmpty(),"release outage preserves previous results with explicit retry state");
+ failReleases=false;browser.reload();check(wait([&]{return !browser.busy();})&&browser.error().isEmpty()&&browser.releaseNotice().isEmpty(),"release retry clears stale status");
+ slowReleases=true;browser.reload();QTest::qWait(50);browser.setSection("songs");wait([&]{return !browser.busy();});QTest::qWait(550);
+ check(browser.section()=="songs"&&browser.items().first().toMap()["type"]=="library-songs","late releases cannot replace a different page");slowReleases=false;
+ browser.togglePin(seedArtist);browser.togglePin(secondArtist);browser.setSection("releases");check(browser.items().isEmpty()&&!browser.busy(),"unpinning all artists invalidates the release cache");
+ check(plays+edits==discoveryWrites,"artist discovery never changes playback or library");
+ const QVariantMap radioSong{{"id","123"},{"type","songs"},{"path","/v1/catalog/ca/songs/123"}};
+ browser.prepareRadio(radioSong);check(wait([&]{return !browser.radioBusy();})&&browser.radioAvailable(),"song radio resolves through existing Cider access");
+ const int beforeCachedRadio=radioReads;browser.prepareRadio(radioSong);check(!browser.radioBusy()&&radioReads==beforeCachedRadio,"radio lookup reuses cached station metadata");
+ browser.playRadio();check(wait([&]{return !browser.radioBusy();})&&playedType=="stations"&&playedId=="ra.seed","explicit radio action plays the resolved station");
+ auto noRadio=radioSong;noRadio["id"]="999";browser.prepareRadio(noRadio);check(wait([&]{return !browser.radioBusy();})&&!browser.radioAvailable()&&browser.radioError().isEmpty(),"song without radio has a normal unavailable state");
+ auto slowRadio=radioSong;slowRadio["id"]="777";browser.prepareRadio(slowRadio);QTest::qWait(50);browser.prepareRadio(noRadio);QTest::qWait(600);
+ check(!browser.radioAvailable()&&!browser.radioBusy(),"late radio lookup cannot overwrite another song menu");
+ browser.prepareRadio({{"id","i.upload"},{"type","library-songs"}});check(!browser.radioBusy()&&!browser.radioAvailable(),"uploaded songs without catalog identity do not guess a station");
+ browser.setSection("albums");wait([&]{return !browser.busy();});
std::function<QQuickItem*(QQuickItem*,QString)> find=[&](QQuickItem *parent,QString name)->QQuickItem* {if(parent->objectName()==name)return parent;for(auto *child:parent->childItems())if(auto *hit=find(child,name))return hit;return nullptr;};
- auto click=[&](QString name) {focusTestWindow(window);auto *hit=find(window->contentItem(),name);check(hit!=nullptr,"browser control exists");if(hit)QTest::mouseClick(window,Qt::LeftButton,Qt::NoModifier,hit->mapToScene(QPointF(hit->width()/2,hit->height()/2)).toPoint());QTest::qWait(100);};
+ auto click=[&](QString name) {focusTestWindow(window);auto *hit=find(window->contentItem(),name);check(hit!=nullptr,"browser control exists");if(hit)QTest::mouseClick(window,Qt::LeftButton,Qt::NoModifier,hit->mapToScene(QPointF(hit->width()/2,hit->height()/2)).toPoint());QTest::qWait(180);};
manyRows=true;browser.reload();wait([&]{return !browser.busy();});
check(!find(window->contentItem(),"libraryPanel"),"unopened browser does not allocate its controls at startup");
auto *openingPlayer=qobject_cast<Player *>(QQmlEngine::contextForObject(window)->contextProperty("player").value<QObject *>());
@@ -254,7 +611,9 @@ int exerciseLibrary(QQuickWindow *window, const QString &temp, const QString &ca
QTest::qWait(30);
check(panel->opacity()<1,"first browser opening preserves the entrance animation");
const auto original=panel->property("browser");
- window->requestActivate(); QTest::qWait(100);
+ if(!qEnvironmentVariableIsSet("SPUN_TEST_NO_COMPOSITOR_FOCUS"))window->requestActivate();
+ QTest::qWait(100);
+ const auto originalSavedService=window->property("savedService");window->setProperty("savedService",QVariant::fromValue(&browser));
const auto originalActions=window->property("actionService");window->setProperty("actionService",QVariant::fromValue(&actions));
panel->setProperty("browser",QVariant::fromValue(&browser));window->setProperty("useCider",true);window->setProperty("libraryOpen",true);QTest::qWait(250);
openingPlayer->setMotion(openingMotion);
@@ -301,6 +660,21 @@ int exerciseLibrary(QQuickWindow *window, const QString &temp, const QString &ca
click("libraryTab_search");click("librarySearchInput");
auto *search=find(window->contentItem(),"librarySearchInput");
check(search && search->hasActiveFocus(),"browser search receives keyboard focus");
+ auto *searchTab=find(window->contentItem(),"libraryTab_search");
+ auto *songsTab=find(window->contentItem(),"libraryTab_songs");
+ searchTab->forceActiveFocus(Qt::TabFocusReason);testKeyClick(window,Qt::Key_Right);
+ check(songsTab->hasActiveFocus()&&browser.section()=="search","library arrows move focus without fetching a different section");
+ testKeyClick(window,Qt::Key_Return);wait([&]{return !browser.busy();});
+ check(browser.section()=="songs"&&search->hasActiveFocus(),"Enter activates the focused library destination and focuses its search");
+ songsTab->forceActiveFocus(Qt::TabFocusReason);testKeyClick(window,Qt::Key_End);
+ check(find(window->contentItem(),"libraryTab_playlists")->hasActiveFocus()&&browser.section()=="songs","End focuses the last library tab without activating it");
+ testKeyClick(window,Qt::Key_Tab);
+ check(search->hasActiveFocus(),"Tab exits the library tab group into search");
+ songsTab->forceActiveFocus(Qt::TabFocusReason);testKeyClick(window,Qt::Key_Home);
+ check(searchTab->hasActiveFocus(),"Home focuses the first library destination");
+ if(!captures.isEmpty())window->grabWindow().save(captures+"/20-library-keyboard-focus.png");
+ testKeyClick(window,Qt::Key_Space);wait([&]{return !browser.busy();});
+ check(browser.section()=="search"&&search->hasActiveFocus(),"Space activates the focused library destination");
for(char c:QByteArray("music"))testKeyClick(window,c);
check(wait([&]{return !browser.busy();})&&browser.query()=="music","search field updates the debounced catalog request");
@@ -332,6 +706,10 @@ int exerciseLibrary(QQuickWindow *window, const QString &temp, const QString &ca
check(wait([&]{return fadeMenu->property("opened").toBool() && cider.crossfadeReady() && !cider.crossfadeBusy();}),
"crossfade popup finishes entering and loads its state before interaction");
if(!captures.isEmpty())window->grabWindow().save(captures+"/08-crossfade.png");
+ check(wait([&]{return !cider.audioBusy();}),"audio popup finishes discovering extras");
+ if(!captures.isEmpty())window->grabWindow().save(captures+"/12-audio-settings.png");
+ click("automixToggle");check(wait([&]{return !cider.audioBusy();})&&!automix,"Automix toggles from the themed audio popup");
+ click("listeningMode_gaming");check(wait([&]{return !cider.audioBusy();})&&listeningMode=="gaming","listening mode switches from its segmented control");
click("crossfadeToggle");check(wait([&]{return !cider.crossfadeBusy();})&&!crossfade,"crossfade toggle operates from the themed popup");
auto *duration=find(window->contentItem(),"crossfadeDuration");check(duration&&!duration->isEnabled(),"duration is disabled when crossfade is off");
click("crossfadeToggle");wait([&]{return !cider.crossfadeBusy();});
@@ -354,12 +732,641 @@ int exerciseLibrary(QQuickWindow *window, const QString &temp, const QString &ca
click("libraryActions0");click("playNextAction");check(wait([&]{return !actions.busy();})&&editBody["id"]=="i.hidden","filtered playlist row queues the matching song");
testKeyClick(window,Qt::Key_Escape);QTest::qWait(100);check(browser.collectionQuery().isEmpty()&&!browser.collection().isEmpty()&&browser.items().size()==4,"first Escape clears the playlist filter");
testKeyClick(window,Qt::Key_Escape);QTest::qWait(100);check(browser.collection().isEmpty(),"second Escape returns to playlists");pagedTracks=false;
+ click("libraryRow0");wait([&]{return !browser.busy();});QTest::qWait(200);
+ const int selectionPlays=plays;
+ auto selectRow=[&](int index,Qt::KeyboardModifiers mods) {
+ auto *row=find(window->contentItem(),"libraryRow"+QString::number(index));
+ if(row)QTest::mouseClick(window,Qt::LeftButton,mods,row->mapToScene(QPointF(35,row->height()/2)).toPoint());
+ QTest::qWait(100);
+ };
+ selectRow(0,Qt::ControlModifier);selectRow(1,Qt::ShiftModifier);
+ check(panel->property("selectionCount").toInt()==2&&plays==selectionPlays,"Ctrl-click and Shift-click select a range without playback");
+ if(!captures.isEmpty())window->grabWindow().save(captures+"/11-multi-selection.png");
+ queueIds.clear();click("selectedTrackActions");click("playNextAction");
+ check(wait([&]{return !actions.busy();})&&queueIds==QStringList{"i.second","i.first"},"selection toolbar queues all selected tracks in displayed order");
+ testKeyClick(window,Qt::Key_Escape);QTest::qWait(100);
+ check(panel->property("selectionCount").toInt()==0&&!browser.collection().isEmpty(),"Escape clears selection before leaving the album");
+ click("libraryActions0");click("selectTrackAction");
+ check(panel->property("selectionCount").toInt()==1,"song menu offers a discoverable selection entry");
+ list->forceActiveFocus();testKeyClick(window,Qt::Key_A,Qt::ControlModifier);QTest::qWait(100);
+ check(panel->property("selectionCount").toInt()==2,"Ctrl+A selects loaded playable songs and skips unavailable tracks");
+ list->setProperty("currentIndex",0);testKeyClick(window,Qt::Key_Space);QTest::qWait(100);
+ check(panel->property("selectionCount").toInt()==1&&plays==selectionPlays,"Space toggles the focused selection instead of playback");
+ selectRow(0,Qt::ControlModifier);pagedTracks=true;browser.reload();wait([&]{return !browser.busy();});QTest::qWait(200);
+ selectRow(0,Qt::ControlModifier);browser.more();wait([&]{return !browser.busy();});QTest::qWait(200);
+ check(panel->property("selectionCount").toInt()==1,"loading more tracks preserves the selected row identity");pagedTracks=false;
+ browser.setCollectionQuery("Second");QTest::qWait(100);
+ check(panel->property("selectionCount").toInt()==0,"filtering clears selection so hidden tracks cannot be queued by accident");
+ browser.setCollectionQuery("");QTest::qWait(200);
+ auto *artistLink=find(window->contentItem(),"libraryArtwork0Artist");
+ check(artistLink&&artistLink->height()>=24,"artist links provide a usable hit area without overlapping the song action");
+ if(artistLink) {
+ const auto edge=artistLink->mapToScene(QPointF(artistLink->width()/2,artistLink->height()-2)).toPoint();
+ QTest::mouseClick(window,Qt::LeftButton,Qt::NoModifier,edge);QTest::qWait(150);
+ }
+
+ check(wait([&]{return !browser.busy();})&&browser.collection()["type"]=="artists"&&plays==selectionPlays,"clicking a track artist opens its page without playing the track");
+ QTest::qWait(250);if(!captures.isEmpty())window->grabWindow().save(captures+"/11-artist-page.png");
+ click("pinArtistButton");check(browser.isPinned(browser.collection()),"artist page pin button saves the artist");
+ browser.back();browser.setQuery("");wait([&]{return !browser.busy();});QTest::qWait(220);
+ if(!captures.isEmpty())window->grabWindow().save(captures+"/16-pinned-artist.png");
+ const int beforeArtistPin=plays;click("pinnedCollection0");
+ check(wait([&]{return !browser.busy();})&&browser.collection()["type"]=="artists"&&browser.artistView()=="songs"&&plays==beforeArtistPin,"artist pin opens Top songs without starting playback");
+ click("pinArtistButton");check(browser.pins().isEmpty(),"artist page pin button also unpins");
+ click("artistSimilarTab");check(wait([&]{return !browser.busy();})&&panel->property("artistSimilar").toBool(),"similar artist tab opens without adding another panel");
+ if(!captures.isEmpty())window->grabWindow().save(captures+"/18-similar-artists.png");
+ click("libraryRow0");wait([&]{return !browser.busy();});click("libraryBack");check(browser.artistView()=="similar","similar artist navigation restores the selected tab");
+ click("artistAlbumsTab");wait([&]{return !browser.busy();});
+ click("artistTopSongsTab");check(wait([&]{return !browser.busy();})&&panel->property("artistSongs").toBool()&&browser.items().first().toMap()["type"]=="songs","artist Top songs tab displays playable song rows");
+ QTest::qWait(200);if(!captures.isEmpty())window->grabWindow().save(captures+"/15-artist-top-songs.png");
+ const int beforeTopPlay=plays;click("libraryRow0");check(wait([&]{return !browser.starting();})&&plays==beforeTopPlay+1&&playedId=="top1"&&playedPath.endsWith("play-item"),"artist top song starts through Cider without leaving the artist page");
+ click("libraryActions0");click("playNextAction");check(wait([&]{return !actions.busy();})&&editBody["id"]=="top1","artist top songs retain Play next actions");
+ click("artistAlbumsTab");wait([&]{return !browser.busy();});
+ click("libraryRow0");check(wait([&]{return !browser.busy();})&&browser.collection()["type"]=="albums","artist album row opens its songs");
+ click("libraryBack");check(browser.collection()["type"]=="artists"&&browser.artistView()=="albums","UI Back restores artist and its Albums view");
+ click("libraryBack");click("libraryTab_playlists");wait([&]{return !browser.busy();});QTest::qWait(200);
+ click("libraryActions0");click("pinCollectionAction");
+ check(browser.pins().size()==1,"collection menu pins without another panel");
+ click("libraryTab_search");wait([&]{return !browser.busy();});QTest::qWait(250);
+ auto *pins=find(window->contentItem(),"pinnedCollections");
+ check(pins&&pins->isVisible(),"empty search page displays pinned collections");
+ if(!captures.isEmpty())window->grabWindow().save(captures+"/10-pinned-collections.png");
+ const int pinPlays=plays; click("pinnedCollection0");
+ check(wait([&]{return !browser.starting();})&&plays==pinPlays+1,"pinned cover starts its collection with one click");
+ browser.togglePin(browser.pins().first().toMap());QTest::qWait(100);
+ check(!pins->isVisible(),"unpinning the final collection restores the empty search view");
+
+ window->setProperty("libraryOpen",false);window->setProperty("queueOpen",true);QTest::qWait(150);
+ auto *form=find(window->contentItem(),"ciderConnectionForm");
+ check(form!=nullptr,"connection controls exist inside the queue");
+ if(form) {
+ const auto originalService=form->property("service"); form->setProperty("service",QVariant::fromValue(&cider));
+ rejectProbe=true;cider.reconnect();wait([&]{return cider.needsToken();});QTest::qWait(150);
+ check(form->isVisible(),"expired permission presents the connection controls");
+ auto *manual=find(window->contentItem(),"ciderTokenInput");
+ check(manual&&!manual->isVisible(),"manual token entry stays tucked away by default");
+ if(!captures.isEmpty())window->grabWindow().save(captures+"/10-cider-connection.png");
+ authDelay=500; click("authorizeCiderButton");check(cider.authorizing(),"Connect to Cider opens only the fixture approval request");
+ click("authorizeCiderButton");check(!cider.authorizing(),"Cancel remains usable during approval");QTest::qWait(600);
+ click("manualCiderTokenButton");check(manual->isVisible(),"manual token fallback can be expanded");
+ authDelay=0;rejectProbe=false;click("authorizeCiderButton");
+ check(wait([&]{return cider.queueReady();})&&!form->isVisible(),"successful approval replaces the form with the queue");
+ form->setProperty("service",originalService);
+ }
+ window->setProperty("queueOpen",false);window->setProperty("libraryOpen",true);QTest::qWait(200);
auto *player=qobject_cast<Player *>(QQmlEngine::contextForObject(window)->contextProperty("player").value<QObject *>());
const bool motion=player->motion();player->setMotion(true);
window->setProperty("libraryOpen",false);window->setProperty("libraryOpen",true);QTest::qWait(30);
check(find(window->contentItem(),"libraryPanel")==panel,"reopening retains the browser and its navigation state");
check(panel->opacity()<1,"browser entrance uses a short opacity transition");QTest::qWait(200);
check(panel->opacity()==1,"browser entrance settles without lingering animation");
+ window->setProperty("libraryOpen",true);browser.setSection("search");browser.setKind("stations");browser.setQuery("Chill");wait([&]{return !browser.busy();});QTest::qWait(300);
+ if(!captures.isEmpty())window->grabWindow().save(captures+"/12-stations.png");
+ click("libraryActions0");click("pinCollectionAction");check(browser.isPinned(browser.items().first().toMap()),"station row menu exposes pinning");browser.togglePin(browser.items().first().toMap());
+ browser.setSection("songs");wait([&]{return !browser.busy();});click("recentlyAddedTab");wait([&]{return !browser.busy();});
+ check(browser.newestFirst(),"Recently added chip switches the songs sort");QTest::qWait(250);if(!captures.isEmpty())window->grabWindow().save(captures+"/12-recently-added.png");
+ browser.setSection("sessions");QTest::qWait(250);click("libraryRow0");
+ check(browser.collection()["type"]=="saved-queues"&&browser.items().size()==2,"saved queue opens inside the existing sidebar");
+ if(!captures.isEmpty())window->grabWindow().save(captures+"/12-saved-queue.png");
+ click("libraryActions0");click("copySongLinkAction");check(QGuiApplication::clipboard()->text()=="https://music.apple.com/ca/song/123","row menu copies the selected song link");
+ check(wait([&]{return !panel->property("actionsOpen").toBool();}),"copy action closes before reopening collection menu");
+ const int beforeSavedUiWrites=edits,beforeSavedUiPlays=plays;
+ click("collectionActions");click("renameSavedQueueAction");
+ auto *renameField=find(window->contentItem(),"savedQueueName");
+ check(renameField&&renameField->property("text").toString()==browser.collection()["title"],"Rename opens the shared name dialog with the current title");
+ auto *saveAction=find(window->contentItem(),"confirmSaveQueue");
+ auto *cancelSave=find(window->contentItem(),"cancelSaveQueue");
+ auto *saveDialog=window->findChild<QObject *>("saveQueuePopup");
+ check(saveAction&&cancelSave&&saveDialog&&saveDialog->property("modal").toBool()&&saveAction->y()==cancelSave->y()&&cancelSave->x()+cancelSave->width()<saveAction->x(),"Save dialog is modal with aligned, separated Cancel and Save actions");
+ const auto dialogSize=window->size();
+ const bool dialogLibraryOpen=window->property("libraryOpen").toBool(),dialogQueueOpen=window->property("queueOpen").toBool();
+ testKeyClick(window,Qt::Key_M,Qt::ControlModifier);
+ testKeyClick(window,Qt::Key_L,Qt::ControlModifier);
+ testKeyClick(window,Qt::Key_B,Qt::ControlModifier);QTest::qWait(200);
+ check(saveDialog->property("visible").toBool()&&window->size()==dialogSize&&!window->property("miniMode").toBool(),"dialog blocks Mini shortcut so its content cannot be clipped by a window resize");
+ check(window->property("libraryOpen").toBool()==dialogLibraryOpen&&window->property("queueOpen").toBool()==dialogQueueOpen,"dialog shortcuts cannot switch background library or queue panels");
+ if(renameField) {
+ renameField->setProperty("text"," ");
+ check(!saveAction->isEnabled()&&cancelSave->isEnabled(),"blank queue names disable Save while Cancel remains available");
+ renameField->setProperty("text","Late night mix");
+ renameField->forceActiveFocus(Qt::TabFocusReason);
+ testKeyClick(window,Qt::Key_Tab);
+ check(cancelSave->hasActiveFocus(),"Save dialog keyboard order reaches Cancel after the name field");
+ testKeyClick(window,Qt::Key_Tab);
+ check(saveAction->hasActiveFocus(),"Save dialog keyboard order follows the visible Cancel then Save actions");
+ }
+ if(!captures.isEmpty())window->grabWindow().save(captures+"/17-rename-queue.png");
+ click("confirmSaveQueue");check(browser.collection()["title"]=="Late night mix","Rename saves and updates the collection header");
+ const auto firstSavedId=browser.items().first().toMap()["id"];
+ click("libraryActions0");click("savedTrackDown");check(browser.items().last().toMap()["id"]==firstSavedId,"saved song menu moves the selected occurrence down");
+ if(!captures.isEmpty())window->grabWindow().save(captures+"/17-edited-queue.png");
+ click("libraryActions0");click("savedTrackRemove");check(browser.items().size()==1&&browser.collection()["trackCount"]==1,"saved song menu removes the song and updates its count");
+ check(edits==beforeSavedUiWrites&&plays==beforeSavedUiPlays,"saved queue UI editing leaves Cider playback and queue untouched");
+ click("collectionActions");if(!captures.isEmpty())window->grabWindow().save(captures+"/12-saved-queue-menu.png");click("deleteSavedQueueAction");QTest::qWait(150);click("confirmDeleteQueue");
+ check(browser.items().isEmpty()&&browser.collection().isEmpty(),"saved queue deletion requires confirmation and returns to the list");
+ fixtureQueue={QJsonObject{{"track",resource("123","songs","First Light")}}};fixturePosition=0;cider.refreshQueue();wait([&]{return !cider.queueBusy();});
+ auto *savePopup=window->findChild<QObject *>("saveQueuePopup");check(savePopup!=nullptr,"save queue dialog exists");
+ if(savePopup) {
+ const auto originalService=savePopup->property("service");savePopup->setProperty("service",QVariant::fromValue(&browser));QMetaObject::invokeMethod(savePopup,"open");QTest::qWait(250);
+ auto *name=find(window->contentItem(),"savedQueueName");if(name)name->setProperty("text","Night drive");
+ if(!captures.isEmpty())window->grabWindow().save(captures+"/12-save-queue.png");
+ click("confirmSaveQueue");QTest::qWait(200);
+ check(!savePopup->property("visible").toBool()&&browser.items().size()==1,"named queue saves through the dialog without changing playback");
+ if(!browser.items().isEmpty())browser.deleteSavedQueue(browser.items().first().toMap()["id"].toString());
+ savePopup->setProperty("service",originalService);
+ }
+ // New workflows use only the isolated server, including queue mutations.
+ browser.setSection("albums");wait([&]{return !browser.busy();});browser.open(0);wait([&]{return !browser.busy();});
+ browser.shuffleCollection(browser.collection());check(wait([&]{return !browser.starting();})&&playedShuffle&&playedPath.endsWith("play-collection"),"Shuffle collection sends explicit shuffle without changing the global mode first");
+ browser.playCollection();check(wait([&]{return !browser.starting();})&&!playedShuffle,"normal collection Play explicitly disables shuffle");browser.back();
+ browser.setSection("search");browser.setQuery("unsubmitted");wait([&]{return !browser.busy();});
+ check(!browser.recentSearches().contains("unsubmitted"),"typing alone does not persist search history");
+ browser.rememberSearch();Library searchesReload(&cider);
+ check(searchesReload.recentSearches().first()=="unsubmitted","intentional search persists locally");
+ browser.setQuery("UNSUBMITTED");browser.rememberSearch();
+ check(browser.recentSearches().count("unsubmitted")==0 && browser.recentSearches().first()=="UNSUBMITTED","recent searches deduplicate case-insensitively");
+ for(int i=0;i<12;++i){browser.setQuery(QString("term %1").arg(i));browser.rememberSearch();}
+ check(browser.recentSearches().size()==8 && browser.recentSearches().first()=="term 11","history is bounded to eight most recent searches");
+ browser.removeRecentSearch("term 11");Library removedSearch(&cider);
+ check(!removedSearch.recentSearches().contains("term 11"),"removing a recent search survives relaunch");
+ const auto recentBefore=browser.recentSearches();browser.setQuery("https://music.apple.com/ca/song/123");browser.rememberSearch();
+ check(browser.recentSearches()==recentBefore,"pasted links are not stored as search terms");
+ browser.setQuery("");wait([&]{return !browser.busy();});
+ actions.setObserving(true);wait([&]{return actions.ready();});actions.toggleDislike();
+ check(wait([&]{return !actions.busy()&&actions.ready();})&&rating==-1&&actions.disliked()&&!actions.favorite(),"Suggest less writes dislike and reads back the rating");
+ actions.toggleDislike();check(wait([&]{return !actions.busy()&&actions.ready();})&&rating==0&&!actions.disliked()&&editMethod=="DELETE","Clear dislike uses the rating delete endpoint");
+ rejectEdit=true;actions.toggleDislike();check(wait([&]{return !actions.busy();})&&rating==0&&!actions.disliked(),"rejected dislike never changes the confirmed rating");rejectEdit=false;actions.setObserving(false);
+ cider.refreshAudioQuality();check(wait([&]{return !cider.qualityBusy();})&&cider.audioQuality()=="AAC 256kbps\nOutput: 48 kHz · 2 channels","audio quality separates stream encoding from device output");
+ quality={};cider.refreshAudioQuality();check(wait([&]{return !cider.qualityBusy();})&&cider.audioQuality().contains("unavailable"),"missing quality fields never imply lossless or Atmos");
+ const int quietQuality=qualityReads;QTest::qWait(150);check(qualityReads==quietQuality,"quality details never poll while closed");
+ quality={{"flavorLabel","AAC 256kbps"},{"deviceAudioConfig",QJsonObject{{"sampleRate",48000},{"channelCount",2}}}};
+ transactionQueue=true;rejectQueueAt=-1;queueIds.clear();
+ auto queueTrack=[&](QString id){return QJsonObject{{"track",resource(id,"songs",id)}};};
+ auto ids=[&]{QStringList values;for(const auto &v:fixtureQueue)values.append(v.toObject()["track"].toObject()["id"].toString());return values;};
+ auto syncQueue=[&]{cider.refreshQueue();return wait([&]{return !cider.queueBusy()&&!cider.controlBusy();});};
+ auto track=[&](QString id){return Library::item(resource(id,"songs",id));};
+ auto resetBatch=[&]{fixtureQueue={queueTrack("h"),queueTrack("now"),queueTrack("a"),queueTrack("b"),queueTrack("c"),queueTrack("d"),queueTrack("e")};fixturePosition=1;return syncQueue();};
+ auto batchIdle=[&]{return wait([&]{return !cider.controlBusy()&&!cider.queueBusy();});};
+ resetBatch();cider.editQueueSelection({3,4},"up",cider.queueRevision());
+ check(batchIdle()&&ids()==QStringList{"h","now","b","c","a","d","e"}&&fixturePosition==1,"moving a selected block up preserves its order, history and current playback");
+ resetBatch();cider.editQueueSelection({2,4},"down",cider.queueRevision());
+ check(batchIdle()&&ids()==QStringList{"h","now","b","a","d","c","e"},"moving disjoint selections down moves each occurrence exactly once");
+ resetBatch();cider.editQueueSelection({4,6},"next",cider.queueRevision());
+ check(batchIdle()&&ids()==QStringList{"h","now","c","e","a","b","d"},"Play next gathers selected upcoming songs in their original order");
+ resetBatch();cider.editQueueSelection({2,4},"end",cider.queueRevision());
+ check(batchIdle()&&ids()==QStringList{"h","now","b","d","e","a","c"},"Move to end preserves both selected and unselected relative order");
+ resetBatch();const int batchBoundaryWrites=queueWrites+deleteWrites;
+ cider.editQueueSelection({2,3},"up",cider.queueRevision());cider.editQueueSelection({0,2},"remove",cider.queueRevision());cider.editQueueSelection({1},"remove",cider.queueRevision());cider.editQueueSelection({3,3},"remove",cider.queueRevision());cider.editQueueSelection({2.5},"remove",cider.queueRevision());
+ check(!cider.controlBusy()&&queueWrites+deleteWrites==batchBoundaryWrites,"batch boundaries, duplicate indices and history/current selection cannot issue writes");
+ fixtureQueue={queueTrack("now"),queueTrack("same"),queueTrack("other"),queueTrack("same")};fixturePosition=0;syncQueue();deletedIndices.clear();
+ cider.editQueueSelection({1,3},"remove",cider.queueRevision());
+ check(batchIdle()&&ids()==QStringList{"now","other"}&&deletedIndices==QList<int>{3,1},"batch removal handles repeated songs as distinct occurrences and deletes backwards");
+ resetBatch();const int preflightBatchWrites=deleteWrites;const int oldBatchRevision=cider.queueRevision();fixtureQueue.append(queueTrack("extra"));syncQueue();
+ cider.editQueueSelection({2,3},"remove",oldBatchRevision);changeQueueOnRead=true;cider.editQueueSelection({2,3},"remove",cider.queueRevision());
+ check(batchIdle()&&deleteWrites==preflightBatchWrites,"stale selection and a changed fresh preflight prevent every batch write");
+ resetBatch();const int partialBatchWrites=deleteWrites;rejectDeleteAt=deleteWrites+2;cider.editQueueSelection({2,3,4},"remove",cider.queueRevision());
+ check(batchIdle()&&deleteWrites==partialBatchWrites+2&&ids()==QStringList{"h","now","a","b","d","e"},"a rejected batch write stops remaining operations without replaying confirmed removals");rejectDeleteAt=-1;
+ resetBatch();const int raceBatchWrites=deleteWrites;changeAfterDelete=true;cider.editQueueSelection({2,3},"remove",cider.queueRevision());
+ check(batchIdle()&&deleteWrites==raceBatchWrites+1,"an external edit during a batch stops the next removal");
+ resetBatch();const int advanceBatchWrites=deleteWrites;advanceAfterDelete=true;cider.editQueueSelection({2,3},"remove",cider.queueRevision());
+ check(batchIdle()&&deleteWrites==advanceBatchWrites+1,"playback advancing during a batch stops subsequent writes");
+ resetBatch();const int failedBatchReads=deleteWrites;failAfterDelete=true;cider.editQueueSelection({2,3},"remove",cider.queueRevision());
+ check(batchIdle()&&deleteWrites==failedBatchReads+1,"failed batch verification releases controls without sending further writes");failQueueRead=false;syncQueue();
+ resetBatch();const int reauthBatchWrites=deleteWrites;cider.editQueueSelection({2,3},"remove",cider.queueRevision());cider.connectQueue("test-library-token");
+ check(batchIdle()&&deleteWrites==reauthBatchWrites,"reconnecting Cider cancels pending batch edits before further writes");
+ fixtureQueue={queueTrack("a"),queueTrack("b"),queueTrack("c")};fixturePosition=0;syncQueue();
+ cider.insertQueue({track("x"),track("x"),track("y")},1,cider.queueRevision());
+ check(wait([&]{return !cider.controlBusy()&&!cider.queueBusy();})&&ids()==QStringList{"a","x","x","y","b","c"}&&fixturePosition==0,"queue insertion preserves batch order and duplicates without changing playback");
+ const int beforeStale=queueWrites;const int stale=cider.queueRevision();fixtureQueue.append(queueTrack("external"));syncQueue();cider.insertQueue({track("z")},1,stale);
+ check(!cider.controlBusy()&&queueWrites==beforeStale,"stale drop cannot mutate the queue");
+ changeQueueOnRead=true;cider.insertQueue({track("z")},1,cider.queueRevision());
+ check(wait([&]{return !cider.controlBusy()&&!cider.queueBusy();})&&queueWrites==beforeStale,"fresh preflight catches external edits before insertion");
+ const int writesBeforeRace=queueWrites;changeAfterAppend=true;cider.insertQueue({track("z")},1,cider.queueRevision());
+ check(wait([&]{return !cider.controlBusy()&&!cider.queueBusy();})&&queueWrites==writesBeforeRace+1&&ids().contains("z"),"external edit after append prevents moving the wrong row and never replays the append");
+ fixtureQueue={queueTrack("a"),queueTrack("b"),queueTrack("c")};fixturePosition=0;syncQueue();
+ cider.removeQueue(1,cider.queueRevision());check(wait([&]{return !cider.controlBusy()&&!cider.queueBusy();})&&cider.canUndoQueue()&&ids()==QStringList{"a","c"},"confirmed upcoming removal offers Undo");
+ cider.undoQueueRemoval();check(wait([&]{return !cider.controlBusy()&&!cider.queueBusy();})&&ids()==QStringList{"a","b","c"}&&fixturePosition==0&&!cider.canUndoQueue(),"Undo restores original queue position exactly once");
+ const int afterUndo=queueWrites;cider.undoQueueRemoval();QTest::qWait(50);check(queueWrites==afterUndo,"repeating Undo does not duplicate a track");
+ fixturePosition=2;syncQueue();cider.removeQueue(0,cider.queueRevision());wait([&]{return !cider.controlBusy()&&!cider.queueBusy();});cider.undoQueueRemoval();
+ check(wait([&]{return !cider.controlBusy()&&!cider.queueBusy();})&&ids()==QStringList{"a","b","c"}&&fixturePosition==2,"Undo of history removal preserves the currently playing track");
+ cider.removeQueue(2,cider.queueRevision());check(wait([&]{return !cider.controlBusy()&&!cider.queueBusy();})&&!cider.canUndoQueue(),"removing the current song does not offer a misleading playback Undo");
+ fixturePosition=0;syncQueue();cider.removeQueue(1,cider.queueRevision());wait([&]{return !cider.controlBusy()&&!cider.queueBusy();});fixtureQueue.append(queueTrack("external"));syncQueue();
+ check(!cider.canUndoQueue(),"external queue edits invalidate Undo");
+ fixtureQueue={queueTrack("history"),queueTrack("a"),queueTrack("b"),queueTrack("a"),queueTrack("b"),queueTrack("c")};fixturePosition=1;syncQueue();
+ const int beforeCleanup=queueWrites;const auto cleanup=cider.previewCleanup("duplicates");
+ check(cleanup["indices"].toList()==QVariantList{3,4}&&queueWrites==beforeCleanup,"duplicate preview lists upcoming repeats without writing or touching history");
+ deletedIndices.clear();cider.cleanQueue("duplicates",cleanup["revision"].toInt());
+ check(wait([&]{return !cider.controlBusy()&&!cider.queueBusy();})&&ids()==QStringList{"history","a","b","c"}&&fixturePosition==1&&deletedIndices==QList<int>{4,3},"cleanup removes duplicates from the end and preserves current playback and history");
+ check(!cider.canUndoQueue(),"batch cleanup does not expose an unrelated single-track Undo");
+ const int afterCleanup=queueWrites;cider.cleanQueue("duplicates",cider.queueRevision());
+ check(queueWrites==afterCleanup&&cider.previewCleanup("duplicates")["rows"].toList().isEmpty(),"clean queues require no mutation requests");
+ const int cleanRevision=cider.queueRevision();fixtureQueue.append(queueTrack("c"));syncQueue();cider.cleanQueue("upcoming",cleanRevision);
+ check(queueWrites==afterCleanup,"stale cleanup previews cannot mutate the queue");
+ changeQueueOnRead=true;cider.cleanQueue("upcoming",cider.queueRevision());
+ check(wait([&]{return !cider.controlBusy()&&!cider.queueBusy();})&&queueWrites==afterCleanup,"cleanup revalidates the preview against Cider before its first removal");
+ const int beforeReauthCleanup=deleteWrites;cider.cleanQueue("upcoming",cider.queueRevision());cider.connectQueue("test-library-token");
+ check(wait([&]{return !cider.controlBusy()&&!cider.queueBusy();})&&deleteWrites==beforeReauthCleanup,"replacing Cider credentials cancels cleanup before further writes");
+ // The same catalog song may appear under a library identifier.
+ auto catalogDuplicate=resource("i.a","library-songs","Different title");auto duplicateAttrs=catalogDuplicate["attributes"].toObject();duplicateAttrs["playParams"]=QJsonObject{{"id","i.a"},{"catalogId","a"}};catalogDuplicate["attributes"]=duplicateAttrs;
+ fixtureQueue={queueTrack("a"),QJsonObject{{"track",catalogDuplicate}},queueTrack(""),queueTrack(""),queueTrack("b")};fixturePosition=0;syncQueue();
+ check(cider.previewCleanup("duplicates")["indices"].toList()==QVariantList{1},"cleanup matches catalog identities and never merges unknown IDs by title");
+ fixtureQueue={queueTrack("h"),queueTrack("a"),queueTrack("b"),queueTrack("c"),queueTrack("d")};fixturePosition=1;syncQueue();
+ const int beforePartial=deleteWrites;rejectDeleteAt=deleteWrites+2;cider.cleanQueue("upcoming",cider.queueRevision());
+ check(wait([&]{return !cider.controlBusy()&&!cider.queueBusy();})&&deleteWrites==beforePartial+2&&ids()==QStringList{"h","a","b","c"},"cleanup stops after a rejected removal and does not replay confirmed writes");rejectDeleteAt=-1;
+ fixtureQueue={queueTrack("a"),queueTrack("b"),queueTrack("c")};fixturePosition=0;syncQueue();
+ const int beforeChangedCleanup=deleteWrites;changeAfterDelete=true;cider.cleanQueue("upcoming",cider.queueRevision());
+ check(wait([&]{return !cider.controlBusy()&&!cider.queueBusy();})&&deleteWrites==beforeChangedCleanup+1&&ids()==QStringList{"a","b","external"},"an external queue edit stops cleanup before the next deletion");
+ fixtureQueue={queueTrack("a"),queueTrack("b"),queueTrack("c")};fixturePosition=0;syncQueue();
+ const int beforeAdvance=deleteWrites;advanceAfterDelete=true;cider.cleanQueue("upcoming",cider.queueRevision());
+ check(wait([&]{return !cider.controlBusy()&&!cider.queueBusy();})&&deleteWrites==beforeAdvance+1&&ids()==QStringList{"a","b"}&&fixturePosition==1,"cleanup stops when playback advances to an upcoming song");
+ fixtureQueue={queueTrack("a"),queueTrack("b"),queueTrack("c")};fixturePosition=0;syncQueue();
+ const int beforeReadFailure=deleteWrites;failAfterDelete=true;cider.cleanQueue("upcoming",cider.queueRevision());
+ check(wait([&]{return !cider.controlBusy()&&!cider.queueBusy();})&&deleteWrites==beforeReadFailure+1,"failed cleanup verification releases busy state and stops further writes");failQueueRead=false;syncQueue();
+ fixtureQueue={queueTrack("h"),queueTrack("a"),queueTrack("b"),queueTrack("c")};fixturePosition=1;syncQueue();cider.cleanQueue("upcoming",cider.queueRevision());
+ check(wait([&]{return !cider.controlBusy()&&!cider.queueBusy();})&&ids()==QStringList{"h","a"}&&fixturePosition==1,"clear upcoming keeps history and the playing song");
+ fixtureQueue={queueTrack("a"),queueTrack("a"),queueTrack("b")};fixturePosition=-1;syncQueue();cider.cleanQueue("duplicates",cider.queueRevision());
+ check(wait([&]{return !cider.controlBusy()&&!cider.queueBusy();})&&ids()==QStringList{"a","b"},"with no current song cleanup keeps the first occurrence");
+ fixtureQueue={};fixturePosition=-1;syncQueue();
+ check(cider.previewCleanup("upcoming")["rows"].toList().isEmpty()&&cider.previewCleanup("invalid").isEmpty(),"empty queues and unsupported cleanup modes are harmless");
+
+ const int beforeReject=queueWrites;rejectEdit=true;cider.insertQueue({track("z")},1,cider.queueRevision());
+ check(wait([&]{return !cider.controlBusy()&&!cider.queueBusy();})&&queueWrites==beforeReject,"rejected append is not retried or followed by a move");rejectEdit=false;
+ // Exercise actual pointer and popup wiring against the same mock service.
+ const auto originalCider=window->property("ciderService");window->setProperty("ciderService",QVariant::fromValue(&cider));
+ window->setProperty("useCider",true);window->setProperty("libraryOpen",true);
+ browser.setSection("songs");wait([&]{return !browser.busy();});QTest::qWait(250);
+ auto *dragArea=find(window->contentItem(),"libraryDragArea");check(dragArea!=nullptr,"library artwork has a drag target");
+ if(dragArea){
+ fixtureQueue={queueTrack("a"),queueTrack("b"),queueTrack("c")};fixturePosition=0;syncQueue();
+ const auto origin=dragArea->mapToScene(QPointF(dragArea->width()/2,32)).toPoint();
+ QTest::mousePress(window,Qt::LeftButton,Qt::NoModifier,origin);QTest::mouseMove(window,origin+QPoint(18,0),50);QTest::qWait(250);
+ check(window->property("libraryDragging").toBool()&&window->property("queueOpen").toBool(),"dragging artwork reveals Queue without losing the pointer grab");
+ auto *queueList=find(window->contentItem(),"trackList");const auto drop=queueList->mapToScene(QPointF(120,76)).toPoint();
+ QTest::mouseMove(window,drop,50);QTest::qWait(100);
+ check(window->property("libraryDropIndex").toInt()==1,"drag shows an insertion slot in the upcoming queue");
+ if(!captures.isEmpty())window->grabWindow().save(captures+"/13-drag-queue.png");
+ QTest::mouseRelease(window,Qt::LeftButton,Qt::NoModifier,drop);check(wait([&]{return !cider.controlBusy()&&!cider.queueBusy();})&&!window->property("libraryDragging").toBool()&&fixtureQueue.size()==4,"dropping artwork inserts the selected song");
+ }
+ window->setProperty("libraryOpen",true);QTest::qWait(200);
+ if(dragArea) {
+ const int beforeCancel=queueWrites;
+ const auto origin=dragArea->mapToScene(QPointF(dragArea->width()/2,32)).toPoint();
+ QTest::mousePress(window,Qt::LeftButton,Qt::NoModifier,origin);QTest::mouseMove(window,origin+QPoint(18,0),50);QTest::qWait(150);
+ testKeyClick(window,Qt::Key_Escape);QTest::mouseRelease(window,Qt::LeftButton,Qt::NoModifier,origin+QPoint(18,0));QTest::qWait(100);
+ check(!window->property("libraryDragging").toBool()&&window->property("libraryOpen").toBool()&&queueWrites==beforeCancel,"Escape cancels a drag and restores the browser without queue writes");
+ }
+ browser.more();wait([&]{return !browser.busy();});QTest::qWait(150);QMetaObject::invokeMethod(panel,"clearSelection");
+ selectRow(0,Qt::ControlModifier);selectRow(1,Qt::ShiftModifier);
+ check(panel->property("selectionCount").toInt()==2,"two browser songs can be selected for dragging");
+ if(dragArea) {
+ fixtureQueue={queueTrack("a"),queueTrack("b"),queueTrack("c")};fixturePosition=0;syncQueue();
+ const auto origin=dragArea->mapToScene(QPointF(dragArea->width()/2,32)).toPoint();
+ QTest::mousePress(window,Qt::LeftButton,Qt::NoModifier,origin);QTest::mouseMove(window,origin+QPoint(18,0),50);QTest::qWait(200);
+ auto *queueList=find(window->contentItem(),"trackList");const auto drop=queueList->mapToScene(QPointF(120,76)).toPoint();
+ QTest::mouseMove(window,drop,50);QTest::qWait(100);QTest::mouseRelease(window,Qt::LeftButton,Qt::NoModifier,drop);
+ check(wait([&]{return !cider.controlBusy()&&!cider.queueBusy();})&&ids()==QStringList{"a","i.saved1","i.saved2","b","c"},"dragging a selected artwork inserts the entire selection in display order");
+ }
+ window->setProperty("libraryOpen",true);browser.setSection("search");browser.setQuery("");wait([&]{return !browser.busy();});QTest::qWait(200);
+ if(!captures.isEmpty())window->grabWindow().save(captures+"/13-recent-searches.png");
+ auto *recentItem=find(window->contentItem(),"recentSearch0");check(recentItem&&recentItem->isVisible(),"empty Search exposes recent searches");
+ if(recentItem){click("recentSearch0");check(!browser.query().isEmpty(),"recent search restores its query");}
+ QMetaObject::invokeMethod(window,"showAudioQuality");wait([&]{return !cider.qualityBusy();});QTest::qWait(250);
+ if(!captures.isEmpty())window->grabWindow().save(captures+"/13-audio-quality.png");
+ auto *qualityPopup=window->findChild<QObject *>("audioQualityPopup");check(qualityPopup&&qualityPopup->property("visible").toBool(),"audio quality opens in a themed popup");if(qualityPopup)QMetaObject::invokeMethod(qualityPopup,"close");
+ window->setProperty("queueOpen",true);syncQueue();cider.removeQueue(1,cider.queueRevision());wait([&]{return !cider.controlBusy()&&!cider.queueBusy();});QTest::qWait(200);
+ auto *undoButton=find(window->contentItem(),"undoQueueButton");check(undoButton&&undoButton->isVisible(),"confirmed removal exposes the Undo action");
+ if(!captures.isEmpty())window->grabWindow().save(captures+"/13-undo.png");
+ if(undoButton&&undoButton->isVisible()){click("undoQueueButton");check(wait([&]{return !cider.controlBusy()&&!cider.queueBusy();})&&!cider.canUndoQueue(),"Undo button restores the removed item");}
+ fixtureQueue={queueTrack("History"),queueTrack("Current"),queueTrack("Upcoming"),queueTrack("Current"),queueTrack("Upcoming")};fixturePosition=1;syncQueue();QTest::qWait(100);
+ const int beforePreviewUi=queueWrites;
+ click("savedQueueMenuButton");click("deduplicateQueueAction");
+ auto *cleanupPopup=window->findChild<QObject *>("cleanupPopup");
+ check(cleanupPopup&&cleanupPopup->property("visible").toBool()&&cleanupPopup->property("preview").toMap()["rows"].toList().size()==2&&queueWrites==beforePreviewUi,"queue menu opens a read-only duplicate preview");
+ if(!captures.isEmpty())window->grabWindow().save(captures+"/16-cleanup-preview.png");
+ click("cancelCleanup");check(!cleanupPopup->property("visible").toBool()&&queueWrites==beforePreviewUi,"Cancel leaves the Cider queue untouched");
+ click("savedQueueMenuButton");click("deduplicateQueueAction");
+ fixtureQueue.append(queueTrack("External"));syncQueue();QTest::qWait(100);
+ check(cleanupPopup->property("stale").toBool()&&!find(window->contentItem(),"confirmCleanup")->isEnabled(),"changing the queue invalidates the visible cleanup preview");
+ testKeyClick(window,Qt::Key_Escape);check(wait([&]{return !cleanupPopup->property("visible").toBool();}),"Escape dismisses the cleanup preview");
+ click("savedQueueMenuButton");click("deduplicateQueueAction");click("confirmCleanup");
+ check(wait([&]{return !cider.controlBusy()&&!cider.queueBusy();})&&ids()==QStringList{"History","Current","Upcoming","External"},"confirming the preview removes only its duplicate songs");
+ click("savedQueueMenuButton");click("clearUpcomingAction");click("confirmCleanup");
+ check(wait([&]{return !cider.controlBusy()&&!cider.queueBusy();})&&ids()==QStringList{"History","Current"},"clear upcoming works through its preview and confirmation");
+ click("savedQueueMenuButton");click("deduplicateQueueAction");
+ check(!find(window->contentItem(),"confirmCleanup")->isEnabled(),"empty cleanup preview disables Remove");click("cancelCleanup");
+ auto durationTrack=[&](QString id,int ms){auto row=queueTrack(id);auto data=row["track"].toObject();auto attr=data["attributes"].toObject();attr["durationInMillis"]=ms;data["attributes"]=attr;row["track"]=data;return row;};
+ fixtureQueue={durationTrack("history",600000),durationTrack("current",120000),durationTrack("next",180000)};fixturePosition=1;syncQueue();QTest::qWait(80);
+ check(window->property("queueTimeSummary").toString()=="2 songs · 5 min left","queue time excludes playback history and includes the current song");
+ window->setProperty("queueQuery","no-match");QTest::qWait(30);check(window->property("queueTimeSummary").toString()=="2 songs · 5 min left","queue filtering does not change listening time");window->setProperty("queueQuery","");
+ fixtureQueue.append(durationTrack("unknown",0));syncQueue();
+ check(window->property("queueTimeSummary").toString()=="3 songs · ≥ 5 min left","unknown durations are shown as a lower bound");
+ resetBatch();window->setProperty("queueOpen",true);QTest::qWait(200);
+ auto selectQueue=[&](int index,Qt::KeyboardModifiers modifiers){auto *row=find(window->contentItem(),"queueRow"+QString::number(index));if(row)QTest::mouseClick(window,Qt::LeftButton,modifiers,row->mapToScene(QPointF(130,row->height()/2)).toPoint());QTest::qWait(80);};
+ const int queueSelectionPlays=plays;
+ selectQueue(2,Qt::ControlModifier);selectQueue(4,Qt::ShiftModifier);
+ check(window->property("queueSelectionCount").toInt()==3&&plays==queueSelectionPlays,"Ctrl and Shift clicks select upcoming queue ranges without playback");
+ auto *selectionBar=find(window->contentItem(),"queueSelectionBar");
+ check(selectionBar&&selectionBar->isVisible(),"queue selection exposes its compact action bar");
+ if(!captures.isEmpty())window->grabWindow().save(captures+"/18-queue-selection.png");
+ selectQueue(1,Qt::ControlModifier);check(window->property("queueSelectionCount").toInt()==3,"current queue song cannot join the selection");
+ QTest::keyClick(window,Qt::Key_A,Qt::ControlModifier);QTest::qWait(100);
+ check(window->property("queueSelectionCount").toInt()==5,"Ctrl+A selects upcoming queue songs only");
+ QTest::keyClick(window,Qt::Key_Space);QTest::qWait(100);
+ check(window->property("queueSelectionCount").toInt()==5&&plays==queueSelectionPlays,"Space on the current queue song neither selects it nor starts playback");
+ click("queueSelectionActions");click("queueBatchRemove");
+ const int previewBatchWrites=deleteWrites;
+ check(cleanupPopup->property("visible").toBool()&&cleanupPopup->property("preview").toMap()["indices"].toList().size()==5,"batch removal shows a preview of precisely the selected tracks");
+ click("cancelCleanup");check(deleteWrites==previewBatchWrites,"cancelling selected removal sends no deletion");
+ QTest::keyClick(window,Qt::Key_Escape);QTest::qWait(100);check(window->property("queueSelectionCount").toInt()==0&&window->property("queueOpen").toBool(),"Escape clears queue selection before closing the panel");
+ selectQueue(3,Qt::ControlModifier);QTest::keyClick(window,Qt::Key_Space);QTest::qWait(100);
+ check(window->property("queueSelectionCount").toInt()==0&&plays==queueSelectionPlays,"Space toggles the focused upcoming track without triggering global playback");
+ selectQueue(3,Qt::ControlModifier);fixtureQueue.append(queueTrack("external"));syncQueue();QTest::qWait(100);
+ check(window->property("queueSelectionCount").toInt()==0,"an external queue revision clears stale UI selection");
+ window->setProperty("queueQuery","external");QMetaObject::invokeMethod(window,"selectUpcomingQueue");QTest::qWait(80);
+ check(window->property("queueSelectionCount").toInt()==1,"filtered Select all includes only visible upcoming songs");
+ window->setProperty("queueQuery","");resetBatch();QTest::qWait(150);selectQueue(3,Qt::ControlModifier);selectQueue(4,Qt::ControlModifier);
+ click("queueSelectionActions");
+ auto *batchCopy=find(window->contentItem(),"queueCopyLink");check(!batchCopy||!batchCopy->isVisible(),"batch actions do not offer an ambiguous single-song Copy link");
+ click("queueBatchNext");check(batchIdle()&&ids()==QStringList{"h","now","b","c","a","d","e"}&&window->property("queueSelectionCount").toInt()==0,"selection menu moves the chosen songs next and clears the completed selection");
+ selectQueue(2,Qt::ControlModifier);click("queueActions4");
+ check(window->property("queueSelectionCount").toInt()==0,"opening an unselected row menu clears the previous selection");
+ auto *queueEditPopup=window->findChild<QObject *>("queueEditMenu");if(queueEditPopup)QMetaObject::invokeMethod(queueEditPopup,"close");QTest::qWait(150);
+ check(browser.saveQueue("Late night"),"picker fixture saves an isolated queue");
+ // Open the picker using isolated local storage, with no live library writes.
+ QVariant pickerSongs=QVariantList{track("picker-new")};QVariant pickerService=QVariant::fromValue(&browser);
+ QMetaObject::invokeMethod(window,"openSavedQueuePicker",Q_ARG(QVariant,pickerSongs),Q_ARG(QVariant,pickerService));QTest::qWait(200);
+ auto *appendPicker=window->findChild<QObject *>("savedQueuePicker");
+ check(appendPicker&&appendPicker->property("visible").toBool()&&find(window->contentItem(),"savedQueueChoice0"),"saved queue picker lazily displays existing snapshots");
+ const auto pickerTarget=browser.savedQueueChoices()["rows"].toList().first().toMap();const int pickerBefore=browser.savedTracks(pickerTarget["id"].toString()).size();
+ auto *pickerClose=find(window->contentItem(),"closeSavedQueuePicker");
+ check(pickerClose&&wait([&]{return pickerClose->hasActiveFocus();}),"saved queue picker initially focuses its first interactive control");
+ auto *pickerCancel=find(window->contentItem(),"cancelSavedQueuePicker");
+ auto cancelPixels=[&] {
+ const auto image=window->grabWindow();const auto dpr=image.devicePixelRatio();
+ const auto point=pickerCancel->mapToScene(QPointF());
+ return image.copy(QRect(qRound(point.x()*dpr),qRound(point.y()*dpr),qRound(pickerCancel->width()*dpr),qRound(pickerCancel->height()*dpr)));
+ };
+ click("savedQueueChoice0");const auto normalCancelPixels=cancelPixels();
+ check(browser.renameSavedQueue(pickerTarget,"Refreshed queue"),"picker fixture changes the saved queue after selection");
+ click("appendSavedQueueConfirm");
+ auto *pickerRefresh=find(window->contentItem(),"refreshSavedQueueChoices");
+ auto *pickerConfirm=find(window->contentItem(),"appendSavedQueueConfirm");
+ check(appendPicker->property("visible").toBool()&&!appendPicker->property("error").toString().isEmpty()&&!pickerConfirm->isEnabled(),"stale picker selection shows a recoverable error without appending songs");
+ check(pickerCancel&&pickerCancel->isVisible()&&pickerCancel->isEnabled()&&pickerRefresh&&pickerRefresh->isVisible(),"saved queue errors preserve Cancel alongside the inline Refresh action");
+ check(pickerRefresh&&pickerCancel&&pickerRefresh->y()+pickerRefresh->height()<=pickerCancel->y(),"inline recovery stays separate from the dialog footer");
+ if(!captures.isEmpty())window->grabWindow().save(captures+"/21-saved-queue-recovery.png");
+ bool cancelHasInk=false;
+ if(!normalCancelPixels.isNull())for(int y=0;y<normalCancelPixels.height();++y)for(int x=0;x<normalCancelPixels.width();++x)
+ cancelHasInk|=normalCancelPixels.pixel(x,y)!=normalCancelPixels.pixel(0,0);
+ check(cancelHasInk&&cancelPixels()==normalCancelPixels,"Cancel remains visibly rendered when an inline error appears");
+ auto *pickerList=find(window->contentItem(),"savedQueueChoices");
+ pickerList->forceActiveFocus(Qt::TabFocusReason);testKeyClick(window,Qt::Key_Enter);
+ check(appendPicker->property("error").toString().isEmpty()&&pickerConfirm->isEnabled(),"keypad Enter selects a saved queue and clears the previous error like a click");
+ click("appendSavedQueueConfirm");
+ check(!appendPicker->property("error").toString().isEmpty()&&browser.savedTracks(pickerTarget["id"].toString()).size()==pickerBefore,"keyboard reselection still revalidates stale data before writing");
+ click("refreshSavedQueueChoices");
+ check(appendPicker->property("error").toString().isEmpty()&&!pickerConfirm->isEnabled()&&appendPicker->property("rows").toList().first().toMap()["title"]=="Refreshed queue","Refresh reads current snapshots and requires a fresh selection");
+ pickerList->setProperty("currentIndex",0);pickerList->forceActiveFocus(Qt::TabFocusReason);testKeyClick(window,Qt::Key_Space);
+ check(pickerConfirm->isEnabled(),"Space selects the refreshed saved queue with the keyboard");
+ if(!captures.isEmpty())window->grabWindow().save(captures+"/21-saved-queue-focus.png");
+ click("cancelSavedQueuePicker");
+ check(!appendPicker->property("visible").toBool()&&browser.savedTracks(pickerTarget["id"].toString()).size()==pickerBefore,"Cancel closes the recovered picker without saving changes");
+ const auto refreshedTarget=browser.savedQueueChoices()["rows"].toList().first().toMap();
+ check(browser.renameSavedQueue(refreshedTarget,pickerTarget["title"].toString()),"picker fixture restores its original title");
+ QMetaObject::invokeMethod(window,"openSavedQueuePicker",Q_ARG(QVariant,pickerSongs),Q_ARG(QVariant,pickerService));QTest::qWait(200);
+ click("savedQueueChoice0");
+ if(!captures.isEmpty())window->grabWindow().save(captures+"/18-saved-queue-picker.png");
+ click("skipSavedDuplicates");check(!appendPicker->property("skipDuplicates").toBool(),"saved picker exposes an optional duplicate filter");
+ click("appendSavedQueueConfirm");check(!appendPicker->property("visible").toBool()&&browser.savedTracks(pickerTarget["id"].toString()).size()==pickerBefore+1,"picker confirmation appends to the selected local snapshot");
+ auto *savedUndoButton=find(window->contentItem(),"undoQueueButton");
+ check(savedUndoButton&&savedUndoButton->isVisible()&&browser.canUndoSavedQueue(),"saved edits expose Undo in the existing notice");
+ click("undoQueueButton");check(browser.savedTracks(pickerTarget["id"].toString()).size()==pickerBefore&&!browser.canUndoSavedQueue(),"notice Undo restores the saved snapshot without changing Cider");
+ fixtureQueue={queueTrack("history"),queueTrack("current"),queueTrack("jump-target"),queueTrack("last")};fixturePosition=1;syncQueue();window->setProperty("queueOpen",false);window->setProperty("libraryOpen",false);QTest::qWait(150);
+ const int jumpPlays=plays,jumpWrites=queueWrites+deleteWrites,jumpStart=jumps;
+ window->contentItem()->forceActiveFocus();testKeyClick(window,Qt::Key_K,Qt::ControlModifier);QTest::qWait(250);
+ auto *jump=window->findChild<QObject *>("quickJump");
+ check(jump&&jump->property("visible").toBool()&&wait([&]{return !jump->property("waitingForQueue").toBool();}),"Ctrl+K opens Quick jump and refreshes the queue once");
+ auto *jumpSearch=find(window->contentItem(),"quickJumpSearch");
+ check(jumpSearch&&jumpSearch->hasActiveFocus(),"Quick jump focuses its search field");
+ if(jumpSearch)for(char c:QByteArray("jump-target"))QTest::keyClick(window,c);
+ QTest::qWait(100);auto *jumpList=find(window->contentItem(),"quickJumpResults");
+ check(jumpList&&jumpList->property("count").toInt()==1,"Quick jump filters the current queue through typed text");
+ if(!captures.isEmpty())window->grabWindow().save(captures+"/19-quick-jump.png");
+ QTest::keyClick(window,Qt::Key_Return);QTest::qWait(250);
+ check(wait([&]{return jumps==jumpStart+1&&!cider.controlBusy()&&!cider.queueBusy();})&&!jump->property("visible").toBool()&&window->property("queueOpen").toBool()&&find(window->contentItem(),"trackList")->property("keyboardIndex").toInt()==2&&jumpedIndex==2&&fixturePosition==2&&cider.currentIndex()==2,"Quick jump Enter plays the matching provider index and confirms the queue highlight");
+ QMetaObject::invokeMethod(window,"openQuickJump");wait([&]{return !jump->property("waitingForQueue").toBool();});jump->setProperty("query","jump-target");QTest::qWait(100);
+ fixtureQueue.append(queueTrack("external"));syncQueue();QTest::keyClick(window,Qt::Key_Return);QTest::qWait(100);
+ check(jump->property("visible").toBool()&&!jump->property("notice").toString().isEmpty()&&plays==jumpPlays&&jumps==jumpStart+1,"stale Quick jump queue results require a refresh instead of activating a different row");
+ click("quickJumpRefresh");wait([&]{return !jump->property("waitingForQueue").toBool();});
+ check(jump->property("query").toString()=="jump-target"&&jump->property("notice").toString().isEmpty(),"refreshing a stale Quick jump preserves the search and reloads confirmed results");
+ QMetaObject::invokeMethod(jump,"close");QTest::qWait(200);
+ QMetaObject::invokeMethod(window,"openQuickJump");wait([&]{return !jump->property("waitingForQueue").toBool();});jump->setProperty("query","Late night");QTest::qWait(100);QTest::keyClick(window,Qt::Key_Return);QTest::qWait(250);
+ check(!jump->property("visible").toBool()&&browser.collection()["id"]==pickerTarget["id"]&&window->property("libraryOpen").toBool(),"Quick jump opens a saved queue without replacing playback");
+ check(queueWrites+deleteWrites==jumpWrites&&plays==jumpPlays&&jumps==jumpStart+1,"opening a saved Quick jump result never replaces the queue or starts another song");
+ window->setProperty("libraryOpen",false);browser.setActive(false);
+ auto showJump=[&](const QString &term){QMetaObject::invokeMethod(window,"openQuickJump");wait([&]{return !jump->property("waitingForQueue").toBool();});jump->setProperty("query",term);QTest::qWait(180);};
+ showJump("last");click("quickJumpRow0");
+ check(wait([&]{return jumps==jumpStart+2&&!cider.controlBusy()&&!cider.queueBusy();})&&fixturePosition==3&&cider.currentIndex()==3,"clicking a Quick jump result plays its exact queue index");
+ showJump("no-match-at-all");QTest::keyClick(window,Qt::Key_Return);QTest::qWait(100);
+ check(jump->property("visible").toBool()&&jumps==jumpStart+2,"Enter with no Quick jump matches does not change playback");
+ QTest::keyClick(window,Qt::Key_Escape);QTest::qWait(200);
+ check(!jump->property("visible").toBool()&&jumps==jumpStart+2,"Escape dismisses Quick jump without playing");
+ showJump("current");QSignalSpy jumpFeedback(&cider,&Cider::apiFeedback);rejectJump=true;jumpDelay=500;click("quickJumpRow0");cider.select(0);
+ check(wait([&]{return !cider.controlBusy()&&!cider.queueBusy();})&&jumps==jumpStart+3&&fixturePosition==3&&!jumpFeedback.isEmpty()&&jumpFeedback.last()[1].toBool(),"a rejected jump reports an error, preserves playback and blocks overlapping requests");
+ rejectJump=false;jumpDelay=0;showJump("current");click("quickJumpRow0");
+ check(wait([&]{return jumps==jumpStart+4&&!cider.controlBusy()&&!cider.queueBusy();})&&fixturePosition==1,"Quick jump can retry successfully after a rejected playback request");
+ player->setMiniMode(true);QTest::qWait(250);showJump("jump-target");click("quickJumpRow0");
+ check(wait([&]{return jumps==jumpStart+5&&!cider.controlBusy()&&!cider.queueBusy();})&&fixturePosition==2&&player->miniMode()&&!jump->property("visible").toBool(),"Mini Quick jump plays the selected track while preserving Mini mode");
+ rejectJump=true;showJump("last");click("quickJumpRow0");
+ auto *jumpNotice=find(window->contentItem(),"actionNotice");
+ check(wait([&]{return !cider.controlBusy()&&!cider.queueBusy();})&&fixturePosition==2&&jumpNotice&&jumpNotice->isVisible()&&jumpNotice->property("failed").toBool()&&jumpNotice->x()>=0&&jumpNotice->x()+jumpNotice->width()<=window->width(),"Mini jump failures remain visible inside the compact player without changing playback");
+ if(!captures.isEmpty())window->grabWindow().save(captures+"/19-mini-jump-error.png");
+ auto *dismissNotice=find(window->contentItem(),"dismissActionNotice");
+ check(dismissNotice&&jumpNotice&&jumpNotice->contains(dismissNotice->mapToItem(jumpNotice,QPointF(0,0)))&&jumpNotice->contains(dismissNotice->mapToItem(jumpNotice,QPointF(dismissNotice->width()-1,dismissNotice->height()-1))),"Mini feedback dismiss target stays entirely inside its visible surface");
+ click("dismissActionNotice");
+ check(!jumpNotice->isVisible()&&player->miniMode()&&fixturePosition==2,"Mini feedback can be dismissed without changing playback or leaving Mini mode");
+
+ rejectJump=false;fixturePosition=1;syncQueue();
+ window->setProperty("libraryOpen",false);browser.setActive(false);player->setMiniMode(true);QTest::qWait(250);
+ auto *miniNext=find(window->contentItem(),"miniNext");const bool nextEnabled=miniNext->isEnabled();QQmlProperty::write(miniNext,"enabled",true);
+ const auto miniPoint=miniNext->mapToScene(QPointF(20,20)).toPoint();QTest::mouseMove(window,QPoint(2,2));QTest::qWait(80);const int peekReads=queueReads;
+ QTest::mouseMove(window,miniPoint);QTest::qWait(800);auto *peek=miniNext->findChild<QObject *>("nextTrackTip");
+ check(peek&&wait([&]{return peek->property("visible").toBool()&&!cider.queueBusy();})&&peek->property("summary").toString()=="jump-target","Mini hover previews the confirmed next song");
+ check(queueReads==peekReads+1,"Mini preview makes a single on-demand queue request");
+ if(!captures.isEmpty())window->grabWindow().save(captures+"/19-mini-up-next.png");
+ const int quietPeek=queueReads;QTest::qWait(1100);check(queueReads==quietPeek,"holding the Mini preview open does not poll the queue");
+ fixturePosition=2;QMetaObject::invokeMethod(&cider,"trackChanged");
+ check(wait([&]{return !cider.queueBusy();})&&peek->property("summary").toString()=="last"&&queueReads==quietPeek+1,"Mini preview refreshes once when the current song changes while hovered");
+ QTest::mouseMove(window,QPoint(2,2));window->contentItem()->forceActiveFocus();QTest::qWait(250);
+ check(!peek->property("visible").toBool(),"Mini preview dismisses when the pointer leaves");
+ failQueueRead=true;QTest::mouseMove(window,miniPoint);QTest::qWait(800);wait([&]{return !cider.queueBusy();});
+ check(peek->property("summary").toString()=="Next track unavailable","Mini preview never presents stale artwork as a confirmed next song after a failed read");
+ QTest::mouseMove(window,QPoint(2,2));QTest::qWait(200);failQueueRead=false;syncQueue();
+ QMetaObject::invokeMethod(window,"openQuickJump");QTest::qWait(200);
+ check(jump->property("visible").toBool()&&jump->property("width").toDouble()<=window->width()&&jump->property("height").toDouble()<=window->height(),"Quick jump fits inside Mini mode");
+ QMetaObject::invokeMethod(jump,"close");QTest::qWait(200);check(player->miniMode(),"dismissing Quick jump preserves Mini mode");
+ queueDelay=900;QMetaObject::invokeMethod(window,"openQuickJump");jump->setProperty("query","no-matching-title");QTest::qWait(100);
+ auto *jumpEmpty=find(window->contentItem(),"quickJumpEmptyState");
+ check(jumpEmpty&&jumpEmpty->isVisible()&&jump->property("waitingForQueue").toBool()&&jumpEmpty->property("text").toString()=="Loading queue…","Quick jump distinguishes a pending queue read from an empty result");
+ if(!captures.isEmpty())window->grabWindow().save(captures+"/22-mini-jump-loading.png");
+ check(wait([&]{return !jump->property("waitingForQueue").toBool();})&&jumpEmpty->property("text").toString()=="No matches","Quick jump reports no matches only after the queue read completes");
+ QMetaObject::invokeMethod(jump,"close");QTest::qWait(200);queueDelay=0;
+ QQmlProperty::write(miniNext,"enabled",nextEnabled);player->setMiniMode(false);browser.setActive(true);window->setProperty("queueOpen",true);QTest::qWait(200);
+ const QString literalTitle="<b>Night & Day</b> — a very long live recording\nSecond line";
+ const QString literalArtist="<i>Spun Sound Lab</i>\nGuest artist";
+ auto unusualTrack=resource("literal-title","songs",literalTitle);auto unusualAttributes=unusualTrack["attributes"].toObject();unusualAttributes["artistName"]=literalArtist;unusualTrack["attributes"]=unusualAttributes;
+ fixtureQueue={QJsonObject{{"track",unusualTrack}}};fixturePosition=0;syncQueue();QTest::qWait(200);
+ auto *literalLabel=find(window->contentItem(),"queueArtwork0Title");
+ auto *literalArtistButton=find(window->contentItem(),"queueArtwork0Artist");
+ auto *literalArtistLabel=literalArtistButton?literalArtistButton->property("contentItem").value<QQuickItem *>():nullptr;
+ check(literalLabel&&literalLabel->property("text").toString()==literalTitle&&literalLabel->property("textFormat").toInt()==0,"queue titles retain literal markup characters instead of changing typography");
+ check(literalLabel&&literalArtistLabel&&literalLabel->property("lineCount").toInt()==1&&literalArtistLabel->property("lineCount").toInt()==1&&literalLabel->height()==20,"multiline metadata stays within the title and artist lines of a fixed-height queue row");
+ if(!captures.isEmpty())window->grabWindow().save(captures+"/22-literal-queue-title.png");
+ player->setMiniMode(true);QTest::qWait(250);showJump("recording");
+ auto *miniLiteralTitle=find(window->contentItem(),"quickJumpTitle0");
+ check(miniLiteralTitle&&miniLiteralTitle->property("text").toString()==literalTitle&&miniLiteralTitle->property("textFormat").toInt()==0&&miniLiteralTitle->property("lineCount").toInt()==1&&miniLiteralTitle->property("truncated").toBool(),"Mini Quick jump truncates long literal titles without overlapping their subtitles");
+ if(!captures.isEmpty())window->grabWindow().save(captures+"/22-mini-long-title.png");
+ auto *spaceJumpList=find(window->contentItem(),"quickJumpResults");focusTestWindow(window);spaceJumpList->setProperty("currentIndex",0);spaceJumpList->forceActiveFocus(Qt::TabFocusReason);
+ const int beforeSpaceJump=jumps;testKeyClick(window,Qt::Key_Space);
+ const bool spaceIdle=wait([&]{return !cider.controlBusy()&&!cider.queueBusy()&&!jump->property("visible").toBool();});
+ check(spaceIdle&&jumps==beforeSpaceJump+1&&fixturePosition==0&&!jump->property("visible").toBool()&&player->miniMode(),"Space activates the focused Quick jump result without leaving Mini mode");
+ player->setMiniMode(false);window->setProperty("queueOpen",true);QTest::qWait(200);
+
+ fixtureQueue={durationTrack("unknown",0)};fixturePosition=-1;syncQueue();
+ check(window->property("queueTimeSummary").toString()=="1 song · Duration incomplete","an entirely unknown duration is never shown as zero listening time");
+ fixtureQueue={durationTrack("long",3720000)};fixturePosition=-1;syncQueue();
+ check(window->property("queueTimeSummary").toString()=="1 song · 1 h 2 min left","long queue durations format as hours and minutes");
+ if(!captures.isEmpty())window->grabWindow().save(captures+"/15-queue-time.png");
+ fixtureQueue={};fixturePosition=-1;syncQueue();check(window->property("queueTimeSummary").toString()=="0 songs","empty queue does not invent a remaining duration");
+ // Current/upcoming identities are indexed once for all rendered browse rows.
+ window->setProperty("libraryOpen",true);browser.setSection("search");browser.setKind("songs");browser.setQuery("queued match");wait([&]{return !browser.busy();});QTest::qWait(200);
+ fixtureQueue={queueTrack("history"),queueTrack("123"),queueTrack("next")};fixturePosition=1;syncQueue();QTest::qWait(120);
+ auto *queuedMark=find(window->contentItem(),"alreadyQueued0");
+ check(queuedMark&&queuedMark->isVisible(),"current song is marked Already queued in search results");
+ if(!captures.isEmpty())window->grabWindow().save(captures+"/17-already-queued.png");
+ fixturePosition=2;syncQueue();QTest::qWait(100);check(!queuedMark->isVisible(),"history-only matches lose the Already queued marker");
+ auto queuedLibrary=resource("i.same","library-songs","Different display name");auto queuedAttrs=queuedLibrary["attributes"].toObject();queuedAttrs["playParams"]=QJsonObject{{"id","i.same"},{"catalogId","123"}};queuedLibrary["attributes"]=queuedAttrs;
+ fixtureQueue={queueTrack("current"),QJsonObject{{"track",queuedLibrary}}};fixturePosition=0;syncQueue();QTest::qWait(100);
+ check(queuedMark->isVisible(),"library and catalog IDs share the queued marker without title matching");
+ click("libraryActions0");const int beforeRepeatEnqueue=edits;click("addQueueAction");wait([&]{return !actions.busy();});
+ check(edits==beforeRepeatEnqueue+1,"Already queued does not block intentional repeated additions");
+ failQueueRead=true;syncQueue();QTest::qWait(100);check(!queuedMark->isVisible(),"unavailable queue status hides stale queued markers");failQueueRead=false;syncQueue();
+ window->setProperty("libraryOpen",false);browser.setActive(false);cider.setQueueVisible(false);
+ const int beforeObserverRead=queueReads;cider.setLibraryVisible(true);wait([&]{return !cider.queueBusy();});
+ check(queueReads==beforeObserverRead+1,"opening browsing refreshes queue membership without opening Queue");
+ cider.setLibraryVisible(false);const int hiddenReads=queueReads;QTest::qWait(150);
+ check(queueReads==hiddenReads,"closing both panels makes no new membership request");browser.setActive(true);
+ const int discoveryPlays=plays;browser.setSection("for-you");wait([&]{return !browser.busy();});
+ check(browser.error().isEmpty()&&browser.items().size()==3&&browser.hasMore(),"For You flattens curated album, playlist and station recommendations");
+ check(plays==discoveryPlays&&browser.items().first().toMap()["recommendation"]=="Made for you","recommendations preserve their context without starting playback");
+ check(browser.items().first().toMap()["path"]=="/v1/catalog/ca/albums/recommended","recommendation links retain the returned storefront and safe catalog route");
+ browser.open(0);wait([&]{return !browser.busy();});check(browser.collection()["type"]=="albums","recommended albums open inside the existing browser");browser.back();
+ check(browser.items().size()==3&&browser.hasMore(),"Back restores the recommendation feed and pending content pages");
+ failRecommendationPage=true;browser.more();wait([&]{return !browser.busy();});check(browser.items().size()==3&&!browser.error().isEmpty()&&browser.hasMore(),"failed recommendation pagination preserves prior results and retry state");
+ failRecommendationPage=false;browser.more();wait([&]{return !browser.busy();});check(browser.items().size()==4&&browser.error().isEmpty(),"retry reads the failed recommendation contents page without duplicating cards");
+ browser.more();wait([&]{return !browser.busy();});check(browser.items().size()==5&&!browser.hasMore(),"For You loads both group contents and top-level recommendation pages");
+ const int cachedRecommendations=recommendationReads;browser.setActive(false);browser.setActive(true);QTest::qWait(50);check(recommendationReads==cachedRecommendations,"reopening a loaded recommendation feed performs no extra fetch");
+ browser.setQuery("later");check(browser.items().size()==2,"recommendations can be searched locally");browser.setQuery("");
+ hostileRecommendations=true;browser.reload();wait([&]{return !browser.busy();});const int beforeHostile=recommendationReads;browser.more();QTest::qWait(100);
+ check(recommendationReads==beforeHostile&&!browser.error().isEmpty()&&browser.items().size()==3,"hostile recommendation pagination is rejected before sending credentials");hostileRecommendations=false;
+ emptyRecommendations=true;browser.reload();wait([&]{return !browser.busy();});check(browser.error().isEmpty()&&browser.items().isEmpty()&&!browser.hasMore(),"an empty For You feed is a normal empty state");emptyRecommendations=false;
+ malformedRecommendations=true;browser.reload();wait([&]{return !browser.busy();});check(!browser.error().isEmpty(),"malformed recommendation responses are reported explicitly");malformedRecommendations=false;
+ discoveryStatus=403;browser.reload();wait([&]{return !browser.busy();});check(browser.needsConnection(),"For You permission failures offer connection recovery");check(cider.queueReady()&&!cider.needsToken(),"a denied recommendation capability leaves working queue access intact");discoveryStatus=200;browser.reload();wait([&]{return !browser.busy();});
+ discoveryDelay=450;browser.reload();QTest::qWait(25);browser.setSection("songs");wait([&]{return !browser.busy();});QTest::qWait(500);check(browser.section()=="songs"&&browser.items().first().toMap()["type"]=="library-songs","leaving For You discards late personalized responses");discoveryDelay=0;
+ browser.setSection("search");browser.setKind("artists");browser.setQuery("Neon Atlas");wait([&]{return !browser.busy();});browser.open(0);wait([&]{return !browser.busy();});
+ for(const auto &filter:QStringList{"full-albums","singles","live-albums"}) {
+ browser.setDiscography(filter);wait([&]{return !browser.busy();});check(browser.error().isEmpty()&&lastBrowsePath.contains("/view/"+filter)&&browser.items().size()==1,"discography filter fetches its explicit artist catalog view");
+ browser.more();wait([&]{return !browser.busy();});check(browser.items().size()==2,"discography filters preserve pagination");
+ }
+ browser.open(0);wait([&]{return !browser.busy();});browser.back();check(browser.discography()=="live-albums"&&browser.items().size()==2,"Back from an album restores the selected discography filter and rows");
+ const auto beforeInvalidFilter=lastBrowsePath;browser.setDiscography("../bad");check(lastBrowsePath==beforeInvalidFilter&&browser.discography()=="live-albums","unsupported discography filters do not issue requests");
+ emptyDiscography=true;browser.setDiscography("singles");wait([&]{return !browser.busy();});check(browser.error().isEmpty()&&browser.items().isEmpty(),"artists with no releases in a category show an empty list");emptyDiscography=false;
+ rejectDiscography=true;browser.setDiscography("full-albums");wait([&]{return !browser.busy();});check(!browser.error().isEmpty(),"unavailable discography views report failure rather than showing another category");rejectDiscography=false;
+ discographyDelay=450;browser.setDiscography("singles");QTest::qWait(25);browser.setArtistView("songs");wait([&]{return !browser.busy();});QTest::qWait(500);check(browser.artistView()=="songs"&&browser.items().first().toMap()["type"]=="songs","a late discography response cannot overwrite Top songs");discographyDelay=0;
+ window->setProperty("libraryOpen",true);browser.setSection("albums");browser.setSection("search");browser.setQuery("");QTest::qWait(250);click("forYouButton");wait([&]{return !browser.busy();});
+ check(browser.section()=="for-you"&&browser.items().size()==3,"For You landing-page button opens personalized browsing");
+ if(!captures.isEmpty())window->grabWindow().save(captures+"/20-for-you.png");
+ click("libraryArtwork0Artist");wait([&]{return !browser.busy();});
+ check(browser.collection().value("type")=="albums","clicking recommendation context opens its album rather than an artist search");
+ browser.back();
+ browser.setSection("search");browser.setKind("artists");browser.setQuery("Neon Atlas");wait([&]{return !browser.busy();});browser.open(0);wait([&]{return !browser.busy();});QTest::qWait(150);
+ click("discographyFilter");auto *filterMenu=panel->findChild<QObject *>("discographyMenu");check(filterMenu&&filterMenu->property("visible").toBool()&&window->property("menuOpen").toBool(),"discography menu participates in the shared modal shortcut guard");
+ if(!captures.isEmpty())window->grabWindow().save(captures+"/21-discography-menu.png");
+ click("discography_singles");wait([&]{return !browser.busy();});check(browser.discography()=="singles"&&!filterMenu->property("visible").toBool(),"choosing a discography filter updates the list and closes its menu");
+ click("discographyFilter");QTest::keyClick(window,Qt::Key_Escape);QTest::qWait(180);check(!filterMenu->property("visible").toBool()&&browser.collection()["type"]=="artists","Escape dismisses the filter without leaving the artist");
+ if(!captures.isEmpty())window->grabWindow().save(captures+"/22-discography-filtered.png");
+ browser.setSection("albums");wait([&]{return !browser.busy();});
+
+ // New collection action uses canonical occurrence indices, not filtered list positions.
+ fixtureQueue={queueTrack("a")};fixturePosition=0;syncQueue();
+ tailFixture=true;pagedTracks=true;browser.setSection("albums");wait([&]{return !browser.busy();});browser.open(0);wait([&]{return !browser.busy();});
+ QSignalSpy tails(&browser,&Library::tailReady);
+ const auto secondOccurrence=browser.items().value(1).toMap();
+ browser.queueFromHere(secondOccurrence);
+ check(wait([&]{return !browser.preparingTail()&&!browser.busy()&&!actions.busy()&&!cider.controlBusy()&&!cider.queueBusy();})&&tails.size()==1,"Queue from here fetches unloaded collection pages before enqueueing");
+ if(tails.size()) {const auto rows=tails.last().first().toList();check(rows.size()==3&&rows[0].toMap()["id"]=="repeat"&&rows[1].toMap()["id"]=="middle"&&rows[2].toMap()["id"]=="i.hidden","Queue from here keeps the chosen duplicate occurrence and album order");}
+ browser.setCollectionQuery("middle");wait([&]{return !browser.busy();});browser.queueFromHere(browser.items().first().toMap());
+ check(wait([&]{return !actions.busy()&&!cider.controlBusy()&&!cider.queueBusy()&&!browser.preparingTail();})&&tails.size()==2&&tails.last().first().toList().size()==2,"Queue from here includes following tracks hidden by the collection filter");
+ browser.back();wait([&]{return !browser.busy();});failTracks=true;browser.open(0);wait([&]{return !browser.busy();});browser.queueFromHere(browser.items().first().toMap());
+ check(wait([&]{return !browser.busy()&&!browser.preparingTail();})&&tails.size()==2,"a later collection page failure queues nothing");failTracks=false;
+ browser.back();browser.open(0);wait([&]{return !browser.busy();});slowTracks=true;browser.queueFromHere(browser.items().first().toMap());browser.back();QTest::qWait(500);
+ check(!browser.preparingTail()&&tails.size()==2,"leaving the collection cancels preparation without queue writes");slowTracks=false;
+ tailFixture=false;pagedTracks=false;browser.open(0);wait([&]{return !browser.busy();});browser.queueFromHere(browser.items().first().toMap());
+ check(!browser.preparingTail()&&tails.size()==2,"unavailable tracks reject the whole range rather than silently skipping songs");
+ browser.back();tailFixture=true;browser.open(0);wait([&]{return !browser.busy();});window->setProperty("libraryOpen",true);QTest::qWait(200);
+ click("libraryActions1");auto *tailMenu=panel->findChild<QObject *>("browserTrackMenu");auto *tailAction=tailMenu?tailMenu->findChild<QObject *>("queueFromHereAction"):nullptr;
+ check(tailAction&&tailAction->property("visible").toBool()&&tailAction->property("enabled").toBool(),"collection song menu exposes Queue from here");click("queueFromHereAction");
+ check(wait([&]{return !actions.busy()&&!cider.controlBusy()&&!cider.queueBusy()&&!browser.preparingTail();})&&tails.size()==3,"Queue from here menu activates the complete workflow");
+ tailFixture=false;browser.back();
+
+ listeningFixture=true;fixtureQueue={queueTrack("a"),queueTrack("b"),queueTrack("c")};fixturePosition=1;syncQueue();
+ Listening listeningState(&cider);QSignalSpy listeningNotices(&listeningState,&Listening::feedback);
+ const auto originalListening=window->property("listeningService");window->setProperty("listeningService",QVariant::fromValue(&listeningState));
+ const int disabledReads=snapshotReads;listeningState.checkpoint();QTest::qWait(30);
+ check(snapshotReads==disabledReads&&!listeningState.rememberSession(),"session recovery is opt-in and disabled checkpoints make no API requests");
+ if(songMenu) {songMenu->setProperty("x",230);songMenu->setProperty("y",160);QMetaObject::invokeMethod(songMenu,"open");QTest::qWait(200);}
+ click("bookmarkMomentAction");check(wait([&]{return !listeningState.busy();})&&listeningState.bookmarks().size()==1,"current-song menu bookmarks one atomic song and position snapshot");
+ const auto bookmark=listeningState.bookmarks().value(0).toMap();const auto bookmarkKey=bookmark["key"].toString();
+ check(bookmark["position"].toLongLong()==12345&&bookmark["title"]=="Bookmarked <song>","bookmark preserves millisecond position and literal title");
+ listeningState.addBookmark();wait([&]{return !listeningState.busy();});check(listeningState.bookmarks().size()==1,"repeated bookmark action deduplicates the same moment");
+ {Listening restored(&cider);check(restored.bookmarks()==listeningState.bookmarks(),"bookmarks survive a fresh backend instance");}
+ QFile listeningFile(temp+"/listening.json");check(listeningFile.exists()&&!(listeningFile.permissions()&(QFileDevice::ReadGroup|QFileDevice::ReadOther)),"listening references are stored with private permissions");
+ listeningState.playBookmark(bookmarkKey);check(wait([&]{return !listeningState.busy();})&&listeningState.error().isEmpty()&&snapshotPosition==12.345&&seekWrites==1,"bookmark playback verifies the song, seeks, and reads back its position");
+ wrongSong=true;const int beforeWrongSeek=seekWrites;listeningState.playBookmark(bookmarkKey);
+ check(wait([&]{return !listeningState.busy();})&&!listeningState.error().isEmpty()&&seekWrites==beforeWrongSeek,"bookmark never seeks when Cider reports a different song");wrongSong=false;
+ ignoreSeek=true;listeningState.playBookmark(bookmarkKey);check(wait([&]{return !listeningState.busy();})&&!listeningState.error().isEmpty(),"an acknowledged but ineffective seek is reported honestly");ignoreSeek=false;
+ snapshotFailure=true;listeningState.addBookmark();check(wait([&]{return !listeningState.busy();})&&listeningState.bookmarks().size()==1,"failed playback snapshot cannot create an invalid bookmark");snapshotFailure=false;
+ snapshotId="b";snapshotPosition=12.345;fixtureQueue={queueTrack("a"),queueTrack("b"),queueTrack("c")};fixturePosition=1;syncQueue();
+ listeningState.setRememberSession(true);check(wait([&]{return listeningState.session()["trackCount"].toInt()==2;}),"optional checkpoint saves the current and upcoming songs without history");
+ check(listeningState.session()["position"].toLongLong()==12345,"session checkpoint preserves exact playback position");
+ listeningState.prepareRecovery();wait([&]{return !cider.queueBusy();});const int beforeActiveRestore=queueWrites;
+ listeningState.restoreSession();check(wait([&]{return !listeningState.busy();})&&queueWrites==beforeActiveRestore&&!listeningState.error().isEmpty(),"session restore refuses an existing Cider queue without any mutations");
+ fixtureQueue={};fixturePosition=-1;syncQueue();listeningState.prepareRecovery();wait([&]{return !cider.queueBusy();});
+ changeQueueOnRead=true;listeningState.restoreSession();check(wait([&]{return !listeningState.busy();})&&queueWrites==beforeActiveRestore,"a queue created after confirmation is protected by a fresh read");
+ fixtureQueue={};fixturePosition=-1;syncQueue();listeningState.prepareRecovery();wait([&]{return !cider.queueBusy();});rejectEdit=true;
+ listeningState.restoreSession();check(wait([&]{return !listeningState.busy()&&!cider.queueBusy();})&&!listeningState.error().isEmpty()&&listeningState.session()["trackCount"].toInt()==2,"failed restoration retains the original checkpoint and does not retry writes");rejectEdit=false;
+ fixtureQueue={};fixturePosition=-1;syncQueue();listeningState.prepareRecovery();wait([&]{return !cider.queueBusy();});delayedAppendMs=350;const int writesBeforeDelayedRestore=queueWrites;listeningState.restoreSession();
+ check(wait([&]{return !listeningState.busy()&&!cider.queueBusy();})&&listeningState.error().isEmpty()&&ids()==QStringList{"b","c"}&&fixturePosition==0&&snapshotPosition==12.345,"recovery restores an empty queue in order and resumes the saved moment");
+ check(queueWrites==writesBeforeDelayedRestore+2,"delayed Cider queue writes are verified without repeating mutations");delayedAppendMs=0;
+ fixtureQueue={};fixturePosition=-1;syncQueue();window->setProperty("miniMode",true);QTest::qWait(250);
+ QMetaObject::invokeMethod(window,"openQuickJump");QTest::qWait(250);jump->setProperty("query","bookmark");QTest::qWait(150);
+ const auto bookmarkResults=jump->property("results").toList();bool foundBookmark=false;
+ for(const auto &value:bookmarkResults)if(value.toMap().value("kind")=="bookmark"&&value.toMap().value("key")==bookmarkKey)foundBookmark=true;
+ check(foundBookmark,"Quick jump finds listening bookmarks in Mini mode");
+ if(!captures.isEmpty())window->grabWindow().save(captures+"/18-mini-bookmarks.png");
+ click("quickJumpRow0");check(wait([&]{return !listeningState.busy();})&&window->property("miniMode").toBool(),"Quick jump bookmark playback preserves Mini mode");
+ QMetaObject::invokeMethod(window,"showRecovery");QTest::qWait(250);auto *recovery=window->findChild<QObject *>("recoveryPopup");
+ check(recovery&&recovery->property("visible").toBool(),"session recovery opens an explicit confirmation dialog");
+ if(!captures.isEmpty())window->grabWindow().save(captures+"/19-mini-recovery.png");
+ const int beforeCancel=queueWrites;click("recoveryCancel");QTest::qWait(200);check(queueWrites==beforeCancel&&!recovery->property("visible").toBool(),"canceling recovery makes no queue changes");
+ QMetaObject::invokeMethod(window,"openQuickJump");QTest::qWait(200);jump->setProperty("query","bookmark");QTest::qWait(120);click("removeBookmark0");QTest::qWait(150);
+ check(listeningState.bookmarks().isEmpty(),"Quick jump remove control deletes a bookmark without playing it");QMetaObject::invokeMethod(jump,"close");QTest::qWait(150);
+ listeningState.setRememberSession(false);check(!listeningState.rememberSession()&&listeningState.session().isEmpty(),"turning off recovery deletes its local checkpoint");
+ window->setProperty("listeningService",originalListening);window->setProperty("miniMode",false);listeningFixture=false;
+ window->setProperty("ciderService",originalCider);window->setProperty("libraryOpen",true);transactionQueue=false;
+ fixtureQueue={};fixturePosition=-1;
+ browser.setNewestFirst(false);browser.setSection("search");QTest::qWait(150);
+ QGuiApplication::clipboard()->setText(originalClipboard);
auto *browseButton=find(window->contentItem(),"addMusicButton");
const auto center=browseButton->mapToScene(QPointF(18,18)).toPoint();
auto *buttonContent=browseButton->property("contentItem").value<QQuickItem *>();
@@ -388,7 +1395,8 @@ int exerciseLibrary(QQuickWindow *window, const QString &temp, const QString &ca
if(!captures.isEmpty())window->grabWindow().save(captures+"/06-tooltip-light.png");
palette.resize(0);palette.seek(0);palette.write(old);palette.close();QTest::qWait(200);
}
- window->setProperty("libraryOpen",false);panel->setProperty("browser",original);window->setProperty("actionService",originalActions);window->setProperty("useCider",false);browser.setActive(false);
+ window->setProperty("libraryOpen",false);panel->setProperty("browser",original);window->setProperty("savedService",originalSavedService);window->setProperty("actionService",originalActions);window->setProperty("useCider",false);browser.setActive(false);
+ failures += exerciseCiderEvents(temp);
std::cout<<"LIBRARY RESULT "<<failures<<" failures"<<std::endl;
return failures;
}
diff --git a/src/listening.cpp b/src/listening.cpp
new file mode 100644
index 0000000..47a4eb2
--- /dev/null
+++ b/src/listening.cpp
@@ -0,0 +1,244 @@
+#include "listening.h"
+#include "cider.h"
+#include <QFile>
+#include <QFileInfo>
+#include <QDir>
+#include <QSaveFile>
+#include <QJsonDocument>
+#include <QJsonArray>
+#include <QRegularExpression>
+#include <QUuid>
+#include <QDateTime>
+#include <QPointer>
+#include <cmath>
+
+static qint64 snapshotPosition(const QJsonObject &data) {
+ const auto value=data.value("time").toObject().value("currentTime");const double seconds=value.toDouble(-1);
+ return value.isDouble() && std::isfinite(seconds) && seconds>=0 && seconds<=604800?qint64(seconds*1000):-1;
+}
+
+QString Listening::identity(const QVariantMap &row) {
+ const auto id=row.value("catalogId").toString();
+ return id.isEmpty()?row.value("type").toString()+":"+row.value("id").toString():"songs:"+id;
+}
+QVariantMap Listening::cleanTrack(const QVariantMap &row) {
+ static const QRegularExpression id("^[A-Za-z0-9._-]{1,200}$");
+ if(!QStringList{"songs","library-songs"}.contains(row.value("type").toString()) || !id.match(row.value("id").toString()).hasMatch() || !row.value("playable").toBool())return {};
+ QVariantMap result{{"id",row.value("id")},{"type",row.value("type")},{"playable",true}};
+ for(const auto &key:QStringList{"title","artist"})result[key]=row.value(key).toString().left(500);
+ if(id.match(row.value("catalogId").toString()).hasMatch())result["catalogId"]=row.value("catalogId");
+ const double duration=row.value("duration").toDouble();
+ if(std::isfinite(duration) && duration>0 && duration<=604800000)result["duration"]=duration;
+ // Keep only small, remote artwork references; never serialize local desktop paths.
+ const QUrl artwork(row.value("artwork").toString());
+ if(artwork.scheme()=="https" && artwork.userInfo().isEmpty() && artwork.toString().size()<2048)result["artwork"]=artwork.toString();
+ return result;
+}
+QVariantMap Listening::snapshotTrack(const QJsonObject &snapshot) {
+ const auto attrs=snapshot.value("nowPlaying").toObject(),params=attrs.value("playParams").toObject();
+ const auto kind=params.value("kind").toString("song");
+ if(kind!="song" && kind!="songs" && kind!="library-song" && kind!="library-songs")return {};
+ const bool library=params.value("isLibrary").toBool() || kind.startsWith("library-") || params.value("id").toString().startsWith("i.");
+ auto artwork=attrs.value("artwork").toObject().value("url").toString();
+ artwork.replace("{w}","96").replace("{h}","96").replace("{f}","jpg");
+ return cleanTrack({{"id",params.value("id").toString()},{"type",library?"library-songs":"songs"},
+ {"catalogId",params.value("catalogId").toString()},{"playable",!params.isEmpty()},
+ {"title",attrs.value("name").toString()},{"artist",attrs.value("artistName").toString()},
+ {"duration",attrs.value("durationInMillis").toDouble()},{"artwork",artwork}});
+}
+Listening::Listening(Cider *cider,QObject *parent):QObject(parent),m_cider(cider) {
+ if(!cider->m_connectionPath.isEmpty())m_path=QFileInfo(cider->m_connectionPath).dir().filePath("listening.json");
+ QFile file(m_path);
+ if(file.exists())m_storageValid=false;
+ if(file.open(QIODevice::ReadOnly) && file.size()<=4*1024*1024) {
+ const auto document=QJsonDocument::fromJson(file.readAll());
+ auto data=document.object();
+ m_storageValid=document.isObject() && data.value("version").toInt()==1;
+ if(!m_storageValid)data={};
+ m_remember=data.value("rememberSession").toBool();
+ QSet<QString> keys;
+ for(const auto &value:data.value("bookmarks").toArray()) {
+ const auto raw=value.toObject().toVariantMap();auto row=cleanTrack(raw);
+ const auto key=raw.value("key").toString();const auto position=raw.value("position").toLongLong();
+ if(row.isEmpty() || QUuid(key).isNull() || keys.contains(key) || position<0 || position>=row.value("duration").toLongLong() || m_bookmarks.size()>=100)continue;
+ keys.insert(key);row["key"]=key;row["position"]=position;m_bookmarks.append(row);
+ }
+ const auto saved=data.value("session").toObject();QVariantList tracks;bool valid=true;
+ for(const auto &value:saved.value("tracks").toArray()) {
+ const auto row=cleanTrack(value.toObject().toVariantMap());
+ if(row.isEmpty() || tracks.size()>=5000) {valid=false;break;}tracks.append(row);
+ }
+ const auto position=saved.value("position").toVariant().toLongLong();
+ if(m_remember && valid && !tracks.isEmpty() && position>=0 && position<tracks.first().toMap().value("duration").toLongLong())
+ m_session={{"tracks",tracks},{"position",position},{"savedAt",saved.value("savedAt").toString().left(40)}};
+ }
+ m_checkpoint.setInterval(15000);m_saveDelay.setInterval(700);m_saveDelay.setSingleShot(true);
+ connect(&m_checkpoint,&QTimer::timeout,this,&Listening::checkpoint);
+ connect(&m_saveDelay,&QTimer::timeout,this,&Listening::checkpoint);
+ connect(cider,&Cider::queueStatusChanged,this,&Listening::queueUpdated);
+ connect(cider,&Cider::controlChanged,this,&Listening::queueUpdated);
+ connect(cider,&Cider::playingChanged,this,[this] { if(m_remember && m_cider->playing())m_checkpoint.start();else m_checkpoint.stop();scheduleCheckpoint(); });
+ connect(cider,&Cider::trackChanged,this,[this] { if(m_remember && !m_busy) QTimer::singleShot(0,m_cider,&Cider::refreshQueue); });
+ connect(cider,&Cider::connectionRestored,this,[this] { if(m_remember)m_cider->refreshQueue(); });
+ if(m_remember) { if(cider->playing())m_checkpoint.start();QTimer::singleShot(0,cider,&Cider::refreshQueue); }
+}
+Listening::~Listening() { if(m_busy) {m_cider->m_listeningBusy=false;emit m_cider->controlChanged();} }
+QVariantMap Listening::session() const {
+ if(m_session.isEmpty())return {};
+ const auto tracks=m_session.value("tracks").toList();
+ return {{"title",tracks.first().toMap().value("title")},{"trackCount",tracks.size()},
+ {"position",m_session.value("position")},{"savedAt",m_session.value("savedAt")}};
+}
+bool Listening::persist() {
+ if(m_path.isEmpty() || !m_storageValid)return false;
+ QDir().mkpath(QFileInfo(m_path).absolutePath());QSaveFile file(m_path);
+ if(!file.open(QIODevice::WriteOnly))return false;
+ file.setPermissions(QFileDevice::ReadOwner|QFileDevice::WriteOwner);
+ const auto bytes=QJsonDocument(QJsonObject{{"version",1},{"rememberSession",m_remember},
+ {"bookmarks",QJsonArray::fromVariantList(m_bookmarks)},{"session",QJsonObject::fromVariantMap(m_session)}}).toJson(QJsonDocument::Compact);
+ return bytes.size()<=4*1024*1024 && file.write(bytes)==bytes.size() && file.commit();
+}
+void Listening::setRememberSession(bool enabled) {
+ if(m_remember==enabled || m_busy)return;
+ const auto old=m_session;m_remember=enabled;if(!enabled)m_session.clear();
+ if(!persist()) {m_remember=!enabled;m_session=old;emit feedback("Couldn’t save the session preference.",true);return;}
+ if(enabled) {if(m_cider->playing())m_checkpoint.start();m_cider->refreshQueue();scheduleCheckpoint();}
+ else {m_checkpoint.stop();m_saveDelay.stop();}
+ emit changed();
+}
+void Listening::request(const QByteArray &method,const QString &path,const QJsonObject &body,std::function<void(bool,QJsonObject)> done,bool quiet) {
+ const auto guard=QPointer<Listening>(this);const int generation=m_cider->m_tokenGeneration;
+ m_cider->apiRequest(method,path,body,[guard,generation,done](bool ok,QJsonObject data) {
+ if(!guard)return;
+ if(generation!=guard->m_cider->m_tokenGeneration || (guard->m_busy && guard->m_tokenGeneration!=generation))ok=false;
+ done(ok,data.value("data").toObject());
+ },!quiet);
+}
+bool Listening::begin() {
+ if(m_busy || m_cider->controlBusy() || m_cider->queueBusy() || m_cider->m_apiToken.isEmpty() || m_cider->recovering()) {
+ emit feedback("Wait for Cider to connect and finish its current action.",true);return false;
+ }
+ m_busy=true;m_error.clear();m_cider->m_listeningBusy=true;m_tokenGeneration=m_cider->m_tokenGeneration;
+ emit m_cider->controlChanged();emit changed();return true;
+}
+void Listening::finish(const QString &message,bool error) {
+ m_inserting=false;m_restoring=false;if(!error)m_preparing=false;m_busy=false;m_target.clear();m_error=error?message:QString();
+ m_cider->m_listeningBusy=false;emit m_cider->controlChanged();emit changed();emit feedback(message,error);
+}
+void Listening::addBookmark() {
+ if(m_bookmarks.size()>=100) {emit feedback("You have 100 bookmarks. Remove one before adding another.",true);return;}
+ if(!begin())return;
+ request("GET","/playback",{},[this](bool ok,QJsonObject data) {
+ auto row=snapshotTrack(data);const auto time=data.value("time").toObject().value("currentTime");
+ const auto position=snapshotPosition(data);
+ if(!ok || row.isEmpty() || !time.isDouble() || position<0 || position>=row.value("duration").toLongLong()) {finish("This song’s position is unavailable.",true);return;}
+ for(const auto &value:m_bookmarks)if(identity(value.toMap())==identity(row) && qAbs(value.toMap().value("position").toLongLong()-position)<1000) {finish("This moment is already bookmarked");return;}
+ row["key"]=QUuid::createUuid().toString(QUuid::WithoutBraces);row["position"]=position;m_bookmarks.prepend(row);
+ if(!persist()) {m_bookmarks.removeFirst();finish("Couldn’t save the bookmark.",true);return;}
+ finish("Bookmarked · Find it in Quick jump");
+ });
+}
+void Listening::removeBookmark(const QString &key) {
+ if(m_busy)return;
+ for(int i=0;i<m_bookmarks.size();++i)if(m_bookmarks[i].toMap().value("key")==key) {
+ const auto row=m_bookmarks.takeAt(i);
+ if(!persist()) {m_bookmarks.insert(i,row);emit feedback("Couldn’t remove the bookmark.",true);}else emit feedback("Bookmark removed",false);
+ emit changed();return;
+ }
+}
+void Listening::playBookmark(const QString &key) {
+ for(const auto &value:m_bookmarks)if(value.toMap().value("key")==key) {
+ const auto row=value.toMap();if(begin())playAt(row,row.value("position").toLongLong(),false);return;
+ }
+ emit feedback("This bookmark is no longer available.",true);
+}
+void Listening::playAt(const QVariantMap &track,qint64 position,bool fromQueue) {
+ m_target=track;m_targetPosition=position;
+ request("POST",fromQueue?"/queue/jump":"/playback/play-item",fromQueue?QJsonObject{{"index",0}}:QJsonObject{{"type",track.value("type").toString()},{"id",track.value("id").toString()}},[this](bool ok,QJsonObject) {
+ if(!ok) {finish("Playback wasn’t confirmed. Check Cider before retrying.",true);return;}
+ QTimer::singleShot(250,this,[this]{verifyPlaying(12);});
+ });
+}
+void Listening::verifyPlaying(int attempts) {
+ request("GET","/playback",{},[this,attempts](bool ok,QJsonObject data) {
+ if(!ok) {finish("Couldn’t verify the playing song; its position was left unchanged.",true);return;}
+ if(identity(snapshotTrack(data))!=identity(m_target)) {
+ if(attempts>0)QTimer::singleShot(250,this,[this,attempts]{verifyPlaying(attempts-1);});
+ else finish("Cider didn’t start the expected song; its position was left unchanged.",true);
+ return;
+ }
+ const double duration=data.value("time").toObject().value("duration").toDouble();
+ if(duration<=0 || m_targetPosition>=duration*1000) {finish("The saved position is outside this version of the song.",true);return;}
+ request("POST","/playback/seek",{{"position",m_targetPosition/1000.0}},[this](bool success,QJsonObject) {
+ if(!success) {finish("Song opened, but Cider couldn’t confirm the saved position.",true);return;}
+ QTimer::singleShot(350,this,&Listening::verifySeek);
+ });
+ });
+}
+void Listening::verifySeek() {
+ request("GET","/playback",{},[this](bool ok,QJsonObject data) {
+ const double position=data.value("time").toObject().value("currentTime").toDouble(-1)*1000;
+ const bool verified=ok && identity(snapshotTrack(data))==identity(m_target) && qAbs(position-m_targetPosition)<2000;
+ finish(verified?"Resumed from saved position":"Cider hasn’t confirmed the saved position. Check playback before retrying.",!verified);
+ m_cider->refresh();m_cider->refreshQueue();
+ });
+}
+void Listening::scheduleCheckpoint() { if(m_remember && !m_busy && !m_preparing && !m_saveDelay.isActive())m_saveDelay.start(); }
+void Listening::checkpoint() {
+ if(!m_remember || m_busy || m_reading || m_preparing || !m_cider->queueReady() || m_cider->queueBusy() || !m_cider->queueError().isEmpty() || m_cider->controlBusy() || m_cider->recovering())return;
+ const auto queue=m_cider->queue();const int index=m_cider->currentIndex(),revision=m_cider->queueRevision();
+ if(index<0 || index>=queue.size() || queue.size()-index>5000)return;
+ m_reading=true;
+ request("GET","/playback",{},[this,queue,index,revision](bool ok,QJsonObject data) {
+ m_reading=false;
+ if(!ok || !m_remember || m_busy || m_preparing || revision!=m_cider->queueRevision())return;
+ const auto current=snapshotTrack(data);const auto time=data.value("time").toObject().value("currentTime");const auto position=snapshotPosition(data);
+ if(current.isEmpty() || identity(current)!=identity(queue[index].toMap()) || !time.isDouble() || position<0 || position>=current.value("duration").toLongLong())return;
+ QVariantList tracks;for(const auto &value:queue.mid(index)) {auto row=cleanTrack(value.toMap());if(row.isEmpty())return;tracks.append(row);}
+ // Keep the full-duration current reference even if the queue omitted duration metadata.
+ tracks[0]=current;
+ if(m_session.value("tracks").toList()==tracks && m_session.value("position").toLongLong()==position)return;
+ const auto previous=m_session;
+ m_session={{"tracks",tracks},{"position",position},{"savedAt",QDateTime::currentDateTimeUtc().toString(Qt::ISODate)}};
+ if(!persist()) {m_session=previous;m_checkpoint.stop();m_error="Couldn’t save the listening session.";}else m_error.clear();
+ emit changed();
+ },true);
+}
+void Listening::prepareRecovery() {
+ if(m_busy)return;
+ m_preparing=true;m_error.clear();emit changed();m_cider->refreshQueue();
+}
+void Listening::cancelRecovery() { if(!m_busy) {m_preparing=false;scheduleCheckpoint();} }
+void Listening::forgetSession() {
+ if(m_busy)return;
+ const auto previous=m_session;m_session.clear();
+ if(!persist()) {m_session=previous;m_error="Couldn’t forget this session.";}else m_error.clear();
+ m_preparing=false;emit changed();
+}
+void Listening::restoreSession() {
+ if(m_session.isEmpty() || !begin())return;
+ m_restoring=true;m_preparing=true;
+ // Re-read after confirmation. Never clear or replace a nonempty remote queue.
+ m_cider->refreshQueue();
+}
+void Listening::queueUpdated() {
+ if(m_restoring && !m_cider->m_controlBusy && !m_cider->queueBusy()) {
+ if(m_tokenGeneration!=m_cider->m_tokenGeneration || !m_cider->queueReady() || !m_cider->queueError().isEmpty()) {finish("Couldn’t verify Cider’s queue. Nothing else was changed.",true);return;}
+ const auto tracks=m_session.value("tracks").toList();const auto queue=m_cider->queue();
+ if(m_inserting) {
+ bool same=tracks.size()==queue.size();for(int i=0;same && i<tracks.size();++i)same=identity(tracks[i].toMap())==identity(queue[i].toMap());
+ if(!same || m_cider->currentIndex()!=-1) {finish("Recovery stopped because the queue changed. Check Cider before retrying.",true);return;}
+ m_restoring=false;m_inserting=false;playAt(tracks.first().toMap(),m_session.value("position").toLongLong(),true);return;
+ }
+ if(!queue.isEmpty()) {finish("Cider already has a queue. Recovery won’t replace it.",true);return;}
+ m_inserting=true;m_cider->m_listeningBusy=false;
+ m_cider->insertQueue(tracks,0,m_cider->queueRevision());
+ m_cider->m_listeningBusy=m_busy;
+ if(!m_cider->m_controlBusy && m_restoring)finish("Couldn’t start session recovery.",true);
+ return;
+ }
+ if(!m_cider->queueBusy() && !m_cider->controlBusy()) {
+ if(m_observedRevision!=m_cider->queueRevision()) {m_observedRevision=m_cider->queueRevision();scheduleCheckpoint();}
+ emit changed();
+ }
+}
diff --git a/src/listening.h b/src/listening.h
new file mode 100644
index 0000000..2b6f8b2
--- /dev/null
+++ b/src/listening.h
@@ -0,0 +1,61 @@
+#pragma once
+#include <QObject>
+#include <QVariantList>
+#include <QVariantMap>
+#include <QTimer>
+#include <QJsonObject>
+#include <functional>
+class Cider;
+
+// Small local references only: no audio, credentials or artwork bytes are persisted.
+class Listening : public QObject {
+ Q_OBJECT
+ Q_PROPERTY(QVariantList bookmarks READ bookmarks NOTIFY changed)
+ Q_PROPERTY(bool busy READ busy NOTIFY changed)
+ Q_PROPERTY(bool rememberSession READ rememberSession WRITE setRememberSession NOTIFY changed)
+ Q_PROPERTY(QVariantMap session READ session NOTIFY changed)
+ Q_PROPERTY(QString error READ error NOTIFY changed)
+public:
+ explicit Listening(Cider *cider, QObject *parent=nullptr);
+ ~Listening() override;
+ QVariantList bookmarks() const { return m_bookmarks; }
+ bool busy() const { return m_busy; }
+ bool rememberSession() const { return m_remember; }
+ QVariantMap session() const;
+ QString error() const { return m_error; }
+ void setRememberSession(bool enabled);
+ Q_INVOKABLE void addBookmark();
+ Q_INVOKABLE void removeBookmark(const QString &key);
+ Q_INVOKABLE void playBookmark(const QString &key);
+ Q_INVOKABLE void prepareRecovery();
+ Q_INVOKABLE void cancelRecovery();
+ Q_INVOKABLE void restoreSession();
+ Q_INVOKABLE void forgetSession();
+ // Debounced, and only while the optional recovery setting is enabled.
+ void checkpoint();
+ static QVariantMap cleanTrack(const QVariantMap &row);
+ static QString identity(const QVariantMap &row);
+signals:
+ void changed();
+ void feedback(const QString &message, bool error);
+private:
+ void request(const QByteArray &method,const QString &path,const QJsonObject &body,std::function<void(bool,QJsonObject)> done,bool quiet=false);
+ bool begin();
+ void finish(const QString &message,bool error=false);
+ bool persist();
+ void scheduleCheckpoint();
+ void queueUpdated();
+ void playAt(const QVariantMap &track,qint64 position,bool fromQueue);
+ void verifyPlaying(int attempts);
+ void verifySeek();
+ static QVariantMap snapshotTrack(const QJsonObject &snapshot);
+ Cider *m_cider;
+ QString m_path, m_error;
+ QVariantList m_bookmarks;
+ QVariantMap m_session, m_target;
+ qint64 m_targetPosition=0;
+ int m_tokenGeneration=0,m_observedRevision=-1;
+ bool m_storageValid=true;
+ bool m_remember=false,m_busy=false,m_reading=false,m_inserting=false,m_restoring=false,m_preparing=false;
+ QTimer m_checkpoint,m_saveDelay;
+};
diff --git a/src/main.cpp b/src/main.cpp
index b977320..dedb748 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -1,5 +1,6 @@
#include "player.h"
#include "library.h"
+#include "listening.h"
#include "musicactions.h"
#ifdef SPUN_DIAGNOSTICS
#include "librarytest.h"
@@ -34,6 +35,7 @@
#include <QSaveFile>
#ifdef SPUN_DIAGNOSTICS
#include <QTest>
+#include <QQuickItemGrabResult>
#endif
#include <QTimer>
#include <QElapsedTimer>
@@ -115,14 +117,17 @@ public:
window->resize(targetWidth, targetHeight);
window->setMinimumWidth(targetWidth);
window->setMinimumHeight(targetHeight);
+ if (mini && window->property("menuOpen").toBool()) { window->setMask(QRegion(0,0,targetWidth,targetHeight));return; }
if (mini) {
QRegion region(6,6,288,288,QRegion::Ellipse);
if (window->property("backgroundBlur").toBool()) {
QPainterPath backdrop; backdrop.addRoundedRect(QRectF(0,0,300,targetHeight),21,21);
region=QRegion(backdrop.toFillPolygon().toPolygon());
}
- else region-=QRegion(136,136,28,28,QRegion::Ellipse);
+ else region-=window->property("vinyl").toBool()?QRegion(146,146,8,8,QRegion::Ellipse):QRegion(136,136,28,28,QRegion::Ellipse);
region |= QRegion(50,268,200,84);
+ if (auto *notice=window->findChild<QQuickItem *>("actionNotice"); notice && notice->isVisible())
+ region |= QRegion(notice->mapRectToScene(notice->boundingRect()).toAlignedRect());
window->setMask(region); return;
}
if (window->property("helpOpen").toBool() || window->property("menuOpen").toBool()) {
@@ -133,7 +138,7 @@ public:
window->setMask(QRegion(backdrop.toFillPolygon().toPolygon())); return;
}
QRegion region(44, 73, 442, 442, QRegion::Ellipse);
- region -= QRegion(243, 272, 44, 44, QRegion::Ellipse);
+ region -= window->property("vinyl").toBool()?QRegion(259,288,12,12,QRegion::Ellipse):QRegion(243,272,44,44,QRegion::Ellipse);
if (auto *bar = window->findChild<QQuickItem *>("sourceBar"))
region |= QRegion(bar->mapRectToScene(bar->boundingRect()).toAlignedRect());
if (auto *deck = window->findChild<QQuickItem *>("playerDeck"))
@@ -308,7 +313,7 @@ static int exerciseCiderQueue(const QString &temp) {
check(waitFor([&]{return !remote.queueBusy() && remote.queueError().isEmpty();}), "Cider queue recovers after endpoint failure");
remote.select(1);
check(waitFor([&]{return selected==1;}), "Cider queue selection sends the correct provider index");
- check(waitFor([&]{return !remote.queueBusy();}),"queue selection refresh settles before editing");
+ check(waitFor([&]{return !remote.controlBusy()&&!remote.queueBusy();}),"queue selection refresh settles before editing");
remote.refreshModes();check(waitFor([&]{return remote.modesReady();})&&!remote.shuffle()&&!remote.autoplay(),"Cider v2 reports shuffle and autoplay modes");
remote.setShuffle(true);remote.setShuffle(true);
check(waitFor([&]{return !remote.controlBusy();})&&remote.shuffle()&&shuffleMode&&modeEdits==1,"shuffle uses one API toggle and confirms the actual mode");
@@ -451,6 +456,15 @@ static int exercise(Player &player, Theme &theme, Lyrics &lyrics, QQuickWindow *
if (type->systemFamily() != "Google Sans Flex" && QFontDatabase::hasFamily("Google Sans Flex")) chosen = "Google Sans Flex";
else if (type->systemFamily() != "Noto Sans" && QFontDatabase::hasFamily("Noto Sans")) chosen = "Noto Sans";
check(!chosen.isEmpty() && chosen != type->systemFamily(), "an installed alternate font is available for the picker check");
+ window->setProperty("queueOpen",true);QTest::qWait(200);
+ click("menuButton");QTest::qWait(200);
+ auto *settingsPopup=window->findChild<QObject *>("settingsMenu");
+ const auto menuVolume=player.volume();
+ testKeyClick(window,Qt::Key_Down);testKeyClick(window,Qt::Key_Down);
+ check(settingsPopup&&settingsPopup->property("currentIndex").toInt()>=0&&player.volume()==menuVolume,"menu arrow navigation moves focus without changing playback volume");
+ testKeyClick(window,Qt::Key_Escape);QTest::qWait(200);
+ check(!settingsPopup->property("visible").toBool()&&window->property("queueOpen").toBool(),"Escape dismisses the settings menu without closing the queue behind it");
+ window->setProperty("queueOpen",false);QTest::qWait(200);
click("menuButton"); QTest::qWait(250);
auto *fontLoader=window->findChild<QObject *>("fontPickerLoader");
auto *fontPreferences=window->findChild<QObject *>("preferencesPopup");
@@ -468,6 +482,23 @@ static int exercise(Player &player, Theme &theme, Lyrics &lyrics, QQuickWindow *
check(waitFor([&] { return window->findChild<QObject *>("fontPicker") != nullptr; }), "Preferences prepares the font picker asynchronously");
std::cout << "FONT_PREPARE_MS " << fontPrepareMs << std::endl;
check(readyBeforePreferences, "cold font picker preparation finishes during the Preferences entrance");
+ auto *cdChoice=findItem(window->contentItem(),"cdStyleButton");
+ auto *vinylChoice=findItem(window->contentItem(),"vinylStyleButton");
+ const bool priorVinyl=player.vinyl();
+ cdChoice->forceActiveFocus(Qt::TabFocusReason);testKeyClick(window,Qt::Key_Right);
+ check(vinylChoice->hasActiveFocus()&&player.vinyl()==priorVinyl,"appearance arrows move focus without changing the disc");
+ testKeyClick(window,Qt::Key_Return);check(player.vinyl(),"Enter selects the focused Vinyl appearance");
+ testKeyClick(window,Qt::Key_Left);testKeyClick(window,Qt::Key_Return);
+ check(!player.vinyl(),"keyboard returns to the CD appearance");player.setVinyl(priorVinyl);
+ auto *motionSwitch=findItem(window->contentItem(),"motionToggle");
+ if (motionSwitch) {
+ motionSwitch->forceActiveFocus(Qt::TabFocusReason);
+ const bool priorMotion=player.motion();
+ testKeyClick(window,Qt::Key_Space);
+ check(player.motion()!=priorMotion,"Preferences switch toggles its setting with Space");
+ testKeyClick(window,Qt::Key_Space);
+ check(player.motion()==priorMotion,"Preferences switch restores its setting with the keyboard");
+ } else check(false,"Preferences motion switch exists");
click("fontChoice");
auto *picker = window->findChild<QObject *>("fontPicker");
check(picker && waitFor([&] { return picker->property("opened").toBool(); }), "font picker opens from Preferences");
@@ -479,7 +510,10 @@ static int exercise(Player &player, Theme &theme, Lyrics &lyrics, QQuickWindow *
search->setProperty("text", chosen); QTest::qWait(50);
check(list->property("count").toInt() > 0 && search->hasActiveFocus(), "installed fonts can be searched with keyboard focus");
capture("00-font-picker");
- testKeyClick(window, Qt::Key_Down); testKeyClick(window, Qt::Key_Return);
+ testKeyClick(window, Qt::Key_Down);
+ check(list->hasActiveFocus() && list->property("currentIndex").toInt()==0,"font keyboard navigation focuses the first result without selecting it");
+ capture("20-font-keyboard-focus");
+ testKeyClick(window, Qt::Key_Return);
check(waitFor([&] { return !picker->property("visible").toBool(); }) && type->selectedFamily() == chosen,
"keyboard selection applies the installed font and closes the picker");
check(window->property("font").value<QFont>().family() == chosen && songTitle->property("font").value<QFont>().family() == chosen,
@@ -526,6 +560,22 @@ static int exercise(Player &player, Theme &theme, Lyrics &lyrics, QQuickWindow *
"queue aligns with the source bar top and player card bottom");
check(qAbs(centerY("queueFooter") - playY) < .1,
"queue footer actions align with playback controls");
+ auto *localTab=findItem(window->contentItem(),"localSourceButton");
+ auto *ciderTab=findItem(window->contentItem(),"ciderSourceButton");
+ localTab->forceActiveFocus(Qt::TabFocusReason);
+ testKeyClick(window,Qt::Key_Right);
+ check(ciderTab->hasActiveFocus()&&!window->property("useCider").toBool(),"source arrows move focus without switching playback source");
+ testKeyClick(window,Qt::Key_Return);
+ check(window->property("useCider").toBool(),"Enter activates the focused Cider source");
+ testKeyClick(window,Qt::Key_Left);testKeyClick(window,Qt::Key_Return);
+ check(localTab->hasActiveFocus()&&!window->property("useCider").toBool(),"source keyboard navigation returns to Local");
+ auto *volumeControl=findItem(window->contentItem(),"volumeSlider");
+ const qreal originalVolume=player.volume();player.setVolume(.5);QTest::qWait(20);
+ volumeControl->forceActiveFocus(Qt::TabFocusReason);testKeyClick(window,Qt::Key_Right);
+ check(player.volume()>.5,"focused volume slider receives Right instead of the global seek shortcut");
+ testKeyClick(window,Qt::Key_Left);
+ check(qAbs(player.volume()-.5)<.01,"focused volume slider receives Left and restores the previous level");
+ player.setVolume(originalVolume);
click("ciderSourceButton"); check(window->property("useCider").toBool(), "Cider source selector");
click("localSourceButton"); check(!window->property("useCider").toBool(), "local source selector");
auto *sourceIndicator = findItem(window->contentItem(), "sourceIndicator");
@@ -636,7 +686,52 @@ static int exercise(Player &player, Theme &theme, Lyrics &lyrics, QQuickWindow *
return thumb && thumb->property("status").toInt() == 1;
}), "local queue artwork loads asynchronously beside the title");
check(waitFor([&]{ return !player.artworkLoading() && !window->property("swapRunning").toBool(); }), "cover and disc swap settle before disc interaction");
+ const auto queueResumePosition=player.position();
+ player.seek(10000);QTest::qWait(120);
+ qint64 expectedRemaining=0;const auto localRows=player.queue();
+ for(int i=player.currentIndex();i<localRows.size();++i)expectedRemaining+=localRows[i].toMap().value("duration").toLongLong();
+ expectedRemaining-=player.position();
+ check(qAbs(window->property("queueRemainingMs").toDouble()-expectedRemaining)<250,"queue listening time subtracts elapsed local playback");
+ player.seek(queueResumePosition);QTest::qWait(120);
capture("02-playing-queue-dark");
+ check(!findItem(window->contentItem(),"vinylTonearm"),"CD mode does not allocate a tonearm");
+ const auto vinylPosition=player.position(); const auto vinylTrack=player.currentIndex();
+ player.setVinyl(true);QTest::qWait(250);
+ check(window->property("vinyl").toBool()&&player.currentIndex()==vinylTrack&&player.position()==vinylPosition&&!player.playing(),"Vinyl switches appearance without changing playback");
+ { Player restored(temp+"/player.ini"); check(restored.vinyl(),"Vinyl preference survives relaunch"); }
+ check(!window->mask().contains(QPoint(265,294))&&window->mask().contains(QPoint(280,294)),"Vinyl uses a small spindle hole in the input mask");
+ auto *tonearm=findItem(window->contentItem(),"vinylTonearm");
+ auto *shaft=findItem(window->contentItem(),"tonearmShaft");
+ check(tonearm&&shaft&&tonearm->isVisible(),"vinyl creates a decorative tonearm");
+ if(tonearm&&shaft) {
+ check(tonearm->property("lowered").toDouble()==0,"paused vinyl parks its tonearm");
+ capture("14-tonearm-parked");
+ player.play();player.seek(0);QTest::qWait(650);
+ const double outerAngle=tonearm->property("armAngle").toDouble();
+ check(tonearm->property("lowered").toDouble()>.99,"playing lowers the tonearm onto the grooves");
+ capture("14-tonearm-playing");
+ player.seek(player.duration()*.85);QTest::qWait(650);
+ check(tonearm->property("armAngle").toDouble()>outerAngle+12,"tonearm tracks inward as song progress advances");
+ capture("14-tonearm-inner");
+ player.setMiniMode(true);QTest::qWait(450);
+ const auto tip=shaft->mapToScene(QPointF(0,213));
+ check(tonearm->isVisible()&&tip.x()>0&&tip.x()<300&&tip.y()>0&&tip.y()<268,"Mini tonearm stays on the record above its controls");
+ capture("14-tonearm-mini");player.setMiniMode(false);QTest::qWait(250);
+ player.pause();QTest::qWait(500);
+ check(tonearm->property("lowered").toDouble()==0&&qAbs(tonearm->property("armAngle").toDouble()+4)<.01,"pausing lifts and parks the arm");
+ const bool motion=player.motion();player.setMotion(false);player.play();QTest::qWait(80);
+ check(tonearm->property("lowered").toDouble()==1,"reduced motion lowers the arm without animation");
+ player.pause();QTest::qWait(30);check(tonearm->property("lowered").toDouble()==0,"reduced motion parks the arm immediately");
+ player.setMotion(motion);player.seek(vinylPosition);QTest::qWait(150);
+ window->setProperty("discFlipped",true);QTest::qWait(400);
+ check(!tonearm->isVisible(),"reverse view hides the tonearm and preserves its content");
+ window->setProperty("discFlipped",false);QTest::qWait(400);
+ const auto shaftPoint=shaft->mapToScene(QPointF(0,140)).toPoint();
+ QTest::mouseDClick(window,Qt::LeftButton,Qt::NoModifier,shaftPoint);QTest::qWait(400);
+ check(window->property("discFlipped").toBool(),"tonearm decoration does not intercept disc gestures");
+ window->setProperty("discFlipped",false);QTest::qWait(400);
+ }
+ capture("11-vinyl-front");
QTest::mouseMove(window,QPoint(265,185)); QTest::qWait(100);
QTest::mouseDClick(window, Qt::LeftButton, Qt::NoModifier, QPoint(265,185));
check(waitFor([&]{return window->property("discFlipped").toBool();}), "double-click flips the CD without playing audio");
@@ -654,7 +749,7 @@ static int exercise(Player &player, Theme &theme, Lyrics &lyrics, QQuickWindow *
auto *duration=findItem(window->contentItem(), "albumDuration"+QString::number(row));
check(number && title && duration && number->x()+number->width()<=title->x() && title->x()+title->width()<duration->x(), "album track columns have non-overlapping bounds");
}
- capture("02-disc-back");
+ capture("02-disc-back");capture("11-vinyl-reverse");
click("lyricsViewButton");
check(waitFor([&]{return !lyrics.loading() && lyrics.lines().size()==6;}), "lyrics toggle loads a matching local LRC file");
player.seek(5500);check(waitFor([&]{return lyrics.currentIndex()==1;}), "timed lyrics follow seeking");
@@ -678,7 +773,7 @@ static int exercise(Player &player, Theme &theme, Lyrics &lyrics, QQuickWindow *
testKeyClick(window,Qt::Key_Down);QTest::qWait(100);
check(!lyricList->property("following").toBool() && player.volume()==lyricsVolume, "manual lyric browsing pauses following without adjusting volume");
click("followLyricsButton");check(lyricList->property("following").toBool(), "follow control returns to the current lyric");
- player.setMiniMode(true);QTest::qWait(400);capture("02-mini-lyrics");
+ player.setMiniMode(true);QTest::qWait(400);capture("02-mini-lyrics");capture("11-vinyl-mini-lyrics");
check(window->width()==300 && lyrics.active(), "lyrics remain readable and active in Mini mode");
click("lyricHit1");check(waitFor([&]{return qAbs(player.position()-5000)<200;}), "timed lyric clicks work at Mini mode scale");
player.setMiniMode(false);QTest::qWait(200);
@@ -707,6 +802,28 @@ static int exercise(Player &player, Theme &theme, Lyrics &lyrics, QQuickWindow *
testKeyClick(window, Qt::Key_Return);
check(waitFor([&]{return player.currentIndex()==1;}), "Enter on filtered queue selects the original track index");
player.pause();
+ // Exercise Quick jump through real keyboard/mouse input and the audio backend.
+ QMetaObject::invokeMethod(window,"closeQueueSearch");player.select(0,false);player.pause();
+ window->contentItem()->forceActiveFocus();testKeyClick(window,Qt::Key_K,Qt::ControlModifier);QTest::qWait(250);
+ auto *localJump=window->findChild<QObject *>("quickJump");
+ auto *localJumpSearch=findItem(window->contentItem(),"quickJumpSearch");
+ check(localJump&&localJump->property("visible").toBool()&&localJumpSearch&&localJumpSearch->hasActiveFocus(),"local Ctrl+K opens and focuses Quick jump");
+ for(char ch:QByteArray("second"))testKeyClick(window,ch);
+ check(localJump->property("query").toString()=="second","local Quick jump receives typed song search without invoking player shortcuts");
+ testKeyClick(window,Qt::Key_Return);
+ check(waitFor([&]{return player.currentIndex()==1&&player.playing()&&!localJump->property("visible").toBool();}),"local Quick jump Enter selects and actually starts audio playback");
+ player.pause();player.setMiniMode(true);QTest::qWait(250);
+ QMetaObject::invokeMethod(window,"openQuickJump");QTest::qWait(200);localJump->setProperty("query","First Light");QTest::qWait(100);click("quickJumpRow0");
+ check(waitFor([&]{return player.currentIndex()==0&&player.playing();})&&player.miniMode(),"local Mini Quick jump click plays the selected song without expanding");
+ player.pause();player.setMiniMode(false);QTest::qWait(250);
+ QMetaObject::invokeMethod(window,"openQuickJump");QTest::qWait(200);localJump->setProperty("query","second");
+ player.move(1,0);QTest::qWait(100);testKeyClick(window,Qt::Key_Return);
+ check(localJump->property("visible").toBool()&&!localJump->property("notice").toString().isEmpty()&&!player.playing()&&player.title()=="First Light","local Quick jump refuses a result whose queue position has changed");
+ QMetaObject::invokeMethod(localJump,"close");QTest::qWait(200);player.move(0,1);player.select(1,false);player.pause();
+ QMetaObject::invokeMethod(window,"openQueueSearch");QTest::qWait(150);
+ player.setVinyl(false);QTest::qWait(150);
+ check(!window->property("vinyl").toBool(),"switching back to CD restores the original renderer");
+ check(!findItem(window->contentItem(),"vinylTonearm"),"switching to CD releases tonearm geometry");
capture("02-queue-search");
search->setProperty("text", "no-such-track"); QTest::qWait(100);
check(list->property("count").toInt()==0, "unmatched search shows an empty result set");
@@ -766,6 +883,9 @@ static int exercise(Player &player, Theme &theme, Lyrics &lyrics, QQuickWindow *
};
check(!player.miniOnTop() && pinMatches(false), "Mini pin defaults off");
click("menuButton"); QTest::qWait(200); click("preferencesAction"); QTest::qWait(250);
+ click("vinylStyleButton");check(player.vinyl(),"preferences selects Vinyl");click("vinylStyleButton");
+ check(player.vinyl()&&findItem(window->contentItem(),"vinylStyleButton")->property("checked").toBool(),"selected appearance cannot be unchecked");
+ capture("11-vinyl-settings");click("cdStyleButton");check(!player.vinyl(),"preferences restores CD");
auto *pinToggle = findItem(window->contentItem(), "miniPinToggle");
check(pinToggle && pinToggle->mapToScene(QPointF()).y() >= 0, "Mini pin toggle fits inside preferences");
if (!captures.isEmpty()) window->grabWindow().save(captures+"/03-pin-settings.png");
@@ -1005,6 +1125,7 @@ int main(int argc, char **argv) {
Lyrics lyrics(&player, &cider);
Library library(&cider);
MusicActions musicActions(&cider);
+ Listening listening(&cider);
DiscPresentation presentation;
Native native;
const qint64 backendReady = startup.elapsed();
@@ -1023,6 +1144,7 @@ int main(int argc, char **argv) {
engine.rootContext()->setContextProperty("cider", &cider);
engine.rootContext()->setContextProperty("library", &library);
engine.rootContext()->setContextProperty("musicActions", &musicActions);
+ engine.rootContext()->setContextProperty("listening", &listening);
engine.rootContext()->setContextProperty("testMode", test);
qint64 firstFrame = -1;
int frames = 0;
@@ -1078,7 +1200,15 @@ int main(int argc, char **argv) {
else if (parser.isSet("inspect-library")) QTimer::singleShot(650, &app, [&] {
int failures=0;
auto check=[&](bool ok,const char *name) { std::cout<<(ok?"PASS ":"FAIL ")<<name<<std::endl;if(!ok)++failures; };
- auto capture=[&](const QString &name) { if(parser.isSet("capture-dir")) { QDir().mkpath(parser.value("capture-dir"));QTest::qWait(900);check(window->grabWindow().save(parser.value("capture-dir")+"/"+name+".png"),"library capture saved"); } };
+ auto capture=[&](const QString &name) {
+ if(!parser.isSet("capture-dir"))return;
+ QDir().mkpath(parser.value("capture-dir"));QTest::qWait(900);
+ // Hidden Wayland workspaces can retain a surface at its old size.
+ // Capture the full current item tree, including the popup overlay.
+ auto grab=window->contentItem()->grabToImage();
+ const bool ready=grab&&waitFor([&]{if(grab->image().isNull())window->grabWindow();return !grab->image().isNull();},5000);
+ check(ready&&grab->image().save(parser.value("capture-dir")+"/"+name+".png"),"library capture saved");
+ };
window->setProperty("useCider",true);window->setProperty("libraryOpen",true);
library.setSection("albums");
check(waitFor([&]{return !library.busy();},15000)&&library.error().isEmpty()&&!library.items().isEmpty(),"live Cider library albums load");
@@ -1099,7 +1229,7 @@ int main(int argc, char **argv) {
if(!library.items().isEmpty()) {library.open(0);check(waitFor([&]{return !library.busy();},15000)&&library.error().isEmpty(),"live playlist tracks load");capture("playlist-tracks");library.back();}
library.setSection("search");
auto *search=window->findChild<QQuickItem *>("librarySearchInput");
- window->requestActivate();QTest::qWait(100);
+ focusTestWindow(window);QTest::qWait(100);
if (search) { QTest::mouseClick(window,Qt::LeftButton,Qt::NoModifier,search->mapToScene(QPointF(90,19)).toPoint());if(search->hasActiveFocus())for(char c:QByteArray("Daft Punk"))testKeyClick(window,c); }
check(library.query()=="Daft Punk","live search field accepts keyboard input");
check(waitFor([&]{return !library.busy();},15000)&&library.error().isEmpty()&&!library.items().isEmpty(),"live catalog song search works");capture("search-songs");
@@ -1107,6 +1237,121 @@ int main(int argc, char **argv) {
library.open(0);check(waitFor([&]{return !library.busy();},15000)&&library.error().isEmpty()&&!library.items().isEmpty(),"live catalog album tracks load");capture("catalog-album");library.back();
library.setKind("playlists");check(waitFor([&]{return !library.busy();},15000)&&library.error().isEmpty()&&!library.items().isEmpty(),"live catalog playlist search works");capture("search-playlists");
library.open(0);check(waitFor([&]{return !library.busy();},15000)&&library.error().isEmpty()&&!library.items().isEmpty(),"live catalog playlist tracks load");
+ library.back();library.showArtist("Daft Punk");
+ check(waitFor([&]{return !library.busy();},15000)&&library.collection().value("type")=="artists","live Cider connection opens an artist page");
+ if(library.collection().value("type")=="artists") {
+ library.setArtistView("songs");
+ check(waitFor([&]{return !library.busy();},15000)&&library.error().isEmpty()&&!library.items().isEmpty()&&library.items().first().toMap().value("type")=="songs","live artist top songs work with the existing Cider token");capture("artist-top-songs");
+ if(!library.items().isEmpty()) {
+ library.prepareRadio(library.items().first().toMap());
+ check(waitFor([&]{return !library.radioBusy();},15000)&&library.radioError().isEmpty(),"live song radio availability resolves without playback");
+ std::function<QObject*(QObject*)> findMenu=[&](QObject *parent)->QObject* {
+ if(parent->objectName()=="browserTrackMenu")return parent;
+ for(auto *child:parent->children())if(auto *found=findMenu(child))return found;
+ return nullptr;
+ };
+ if(auto *menu=findMenu(window)) {
+ menu->setProperty("selection",library.items().first());menu->setProperty("x",24);menu->setProperty("y",220);
+ QMetaObject::invokeMethod(menu,"open");waitFor([&]{return !library.radioBusy();},15000);capture("song-radio");QMetaObject::invokeMethod(menu,"close");
+ }
+ }
+ library.setArtistView("similar");
+ check(waitFor([&]{return !library.busy();},15000)&&library.error().isEmpty()&&!library.items().isEmpty(),"live similar artists resolve through Cider");capture("similar-artists");
+ library.setArtistView("albums");check(waitFor([&]{return !library.busy();},15000)&&library.error().isEmpty(),"live artist Albums switch remains available");
+ // Exercise local pins only with an explicitly isolated settings file.
+ if(parser.isSet("config")) {
+ const auto artist=library.collection();const bool wasPinned=library.isPinned(artist);
+ if(!wasPinned)library.togglePin(artist);
+ library.back();library.setQuery("");waitFor([&]{return !library.busy();},15000);capture("pinned-artist");
+ int pin=-1;const auto pins=library.pins();for(int i=0;i<pins.size();++i)if(pins[i].toMap().value("path")==artist.value("path"))pin=i;
+ library.playPin(pin);
+ check(waitFor([&]{return !library.busy();},15000)&&library.collection().value("type")=="artists"&&library.artistView()=="songs","live artist pin opens Top songs");capture("pinned-artist-open");
+ library.setSection("releases");
+ check(waitFor([&]{return !library.busy();},15000)&&library.error().isEmpty(),"live pinned artist releases load through batched Cider lookup");capture("pinned-releases");
+ if(!library.items().isEmpty()) { library.open(0);check(waitFor([&]{return !library.busy();},15000)&&library.error().isEmpty(),"live release opens album tracks");library.back(); }
+ library.setSection("search");
+ if(!wasPinned)library.togglePin(artist);
+ }
+ library.back();
+ }
+ library.setKind("stations");library.setQuery("Chill");
+ check(waitFor([&]{return !library.busy();},15000)&&library.error().isEmpty()&&!library.items().isEmpty()&&library.items().first().toMap()["type"]=="stations","live station search works with the existing token");capture("stations");
+ library.setSection("songs");library.setNewestFirst(true);
+ check(waitFor([&]{return !library.busy();},15000)&&library.error().isEmpty(),"live recently added songs load");capture("recently-added-songs");
+ library.setSection("albums");check(waitFor([&]{return !library.busy();},15000)&&library.error().isEmpty(),"live recently added albums load");capture("recently-added-albums");
+ auto *audio=window->findChild<QObject *>("crossfadeMenu");
+ if(audio) { QMetaObject::invokeMethod(audio,"open");check(waitFor([&]{return !cider.audioBusy()&&!cider.crossfadeBusy();},15000),"live audio settings finish loading");capture("audio-settings");QMetaObject::invokeMethod(audio,"close"); }
+ window->setProperty("queueOpen",true);
+ check(waitFor([&]{return !cider.queueBusy()&&cider.queueReady();},15000),"live queue loads for cleanup preview");
+ QMetaObject::invokeMethod(window,"previewQueueCleanup",Q_ARG(QVariant,"upcoming"));
+ auto *cleanup=window->findChild<QObject *>("cleanupPopup");
+ check(cleanup&&cleanup->property("visible").toBool(),"live cleanup preview opens without removing songs");capture("cleanup-preview");
+ if(cleanup)QMetaObject::invokeMethod(cleanup,"close");
+ if(parser.isSet("config") && cider.queueReady() && !cider.queue().isEmpty()) {
+ window->setProperty("libraryOpen",true);library.setSection("sessions");
+ waitFor([&]{return !cider.queueBusy();},15000);
+ const bool saved=library.saveQueue("Spun interface check");check(saved,"live queue can be saved in isolated test storage");
+ if(saved) {
+ library.open(0);QTest::qWait(200);const auto snapshot=library.collection();const auto id=snapshot.value("id").toString();
+ std::function<QQuickItem *(QQuickItem *)> findMark=[&](QQuickItem *parent)->QQuickItem * {
+ if(parent->objectName()=="alreadyQueued0")return parent;
+ for(auto *child:parent->childItems())if(auto *found=findMark(child))return found;
+ return nullptr;
+ };
+ auto *mark=findMark(window->contentItem());
+ check(mark && mark->isVisible(),"live current song is marked Already queued in the saved queue");capture("already-queued");
+ check(library.renameSavedQueue(snapshot,"Evening mix"),"isolated saved queue rename works with live metadata");
+ check(library.canUndoSavedQueue()&&library.undoSavedQueue()&&library.collection()["title"]==snapshot["title"],"native saved queue Undo restores a local name without changing playback");
+ library.renameSavedQueue(library.collection(),"Evening mix");
+ if(library.items().size()>1) {
+ check(library.editSavedTrack(0,1,false),"isolated saved queue reorders without changing Cider");
+ check(library.editSavedTrack(0,0,true),"isolated saved queue removes a local reference");
+ }
+ capture("edited-saved-queue");
+ const auto localTracks=library.savedTracks(id);
+ if(!localTracks.isEmpty()) {
+ QMetaObject::invokeMethod(window,"openSavedQueuePicker",Q_ARG(QVariant,QVariant(localTracks)),Q_ARG(QVariant,QVariant::fromValue(&library)));QTest::qWait(250);
+ auto *picker=window->findChild<QObject *>("savedQueuePicker");
+ check(picker&&picker->property("visible").toBool(),"native saved queue picker opens with live song metadata");
+ if(picker) {
+ picker->setProperty("selected",library.savedQueueChoices()["rows"].toList().first());
+ auto centered=[&] { return qAbs(picker->property("x").toDouble()+picker->property("width").toDouble()/2-window->width()/2.)<1 && qAbs(picker->property("y").toDouble()+picker->property("height").toDouble()/2-window->height()/2.)<1; };
+ check(centered(),"native saved picker is centered in the expanded player");capture("append-saved-queue");
+ window->setProperty("libraryOpen",false);QTest::qWait(250);
+ check(centered(),"native saved picker remains centered after the sidebar closes");capture("append-saved-queue-compact");
+ const auto before=library.savedTracks(id);QMetaObject::invokeMethod(picker,"submit");
+ waitFor([&]{return !picker->property("visible").toBool();},2000);
+ check(!picker->property("visible").toBool()&&library.savedTracks(id)==before,"native picker skips duplicates without changing the isolated snapshot");
+ }
+ }
+ window->setProperty("queueOpen",true);waitFor([&]{return !cider.queueBusy();},15000);
+ QMetaObject::invokeMethod(window,"selectUpcomingQueue");QTest::qWait(150);
+ check(window->property("queueSelectionCount").toInt()==qMax(0,cider.queue().size()-cider.currentIndex()-1),"native queue selection excludes history and the current song");capture("queue-selection");
+ QMetaObject::invokeMethod(window,"clearQueueSelection");
+ QMetaObject::invokeMethod(window,"openQuickJump");QTest::qWait(300);
+ auto *jump=window->findChild<QObject *>("quickJump");
+ check(jump&&jump->property("visible").toBool()&&waitFor([&]{return !jump->property("waitingForQueue").toBool();},10000),"native Quick jump loads pins, saved queues and current queue");
+ if(jump) {
+ jump->setProperty("query","Evening mix");capture("quick-jump");
+ QMetaObject::invokeMethod(jump,"activate",Q_ARG(QVariant,QVariant(QVariantMap{{"kind","saved"},{"key",id}})));QTest::qWait(250);
+ check(window->property("libraryOpen").toBool()&&library.collection()["id"]==id,"native Quick jump opens the chosen saved queue");
+ }
+ library.deleteSavedQueue(id);
+ }
+ }
+ player.setMiniMode(true);QTest::qWait(250);
+ auto *next=window->findChild<QQuickItem *>("miniNext");
+ if(next&&next->isEnabled()) {
+ QTest::mouseMove(window,next->mapToScene(QPointF(20,20)).toPoint());QTest::qWait(850);
+ auto *peek=next->findChild<QObject *>("nextTrackTip");
+ check(peek&&peek->property("visible").toBool()&&waitFor([&]{return !cider.queueBusy();},10000),"native Mini hover opens its next-song preview");capture("mini-next-preview");
+ QTest::mouseMove(window,QPoint(2,2));QTest::qWait(200);
+ }
+ QMetaObject::invokeMethod(window,"openQuickJump");QTest::qWait(300);capture("mini-quick-jump");
+ auto *miniJump=window->findChild<QObject *>("quickJump");
+ check(miniJump&&miniJump->property("visible").toBool()&&miniJump->property("width").toDouble()<=window->width(),"native Quick jump fits Mini mode");
+ if(miniJump)QMetaObject::invokeMethod(miniJump,"close");
+ check(waitFor([&]{return cider.liveConnected();},8000),"live Cider change stream is connected");
library.setActive(false);std::cout<<"RESULT "<<failures<<" failures"<<std::endl;app.exit(failures?1:0);
});
else if (parser.isSet("verify-cider") || parser.isSet("inspect-cider")) QTimer::singleShot(600, &app, [&] {
diff --git a/src/musicactions.cpp b/src/musicactions.cpp
index affdd38..e209c94 100644
--- a/src/musicactions.cpp
+++ b/src/musicactions.cpp
@@ -15,7 +15,7 @@ MusicActions::~MusicActions() {
for (auto reply : {m_read,m_write}) if (reply) { reply->disconnect(this); reply->abort(); }
}
void MusicActions::invalidateCurrent() {
- ++m_generation; m_ready=false; m_favorite=false; m_saved=false; m_error.clear();
+ ++m_generation; m_ready=false; m_disliked=false; m_favorite=false; m_saved=false; m_error.clear();
if (m_read) { m_read->disconnect(this); m_read->abort(); m_read->deleteLater(); m_read=nullptr; }
emit changed(); emit currentChanged();
if (m_observing) refresh();
@@ -33,7 +33,7 @@ void MusicActions::setObserving(bool value) {
void MusicActions::request(const QByteArray &method, const QString &path, const QJsonObject &body,
bool mutation, std::function<void(QJsonObject)> done) {
if (m_cider->m_apiToken.isEmpty()) {
- m_error="Connect Spun to Cider in Queue."; m_busy=false; m_ready=false;
+ m_batch.clear(); m_error="Connect Spun to Cider in Queue."; m_busy=false; m_ready=false;
emit changed(); if (mutation) emit feedback(m_error,true); return;
}
auto url=m_cider->m_rpcBase; url.setPath("/api/v2"+path); url.setQuery(QString());
@@ -59,6 +59,11 @@ void MusicActions::request(const QByteArray &method, const QString &path, const
else if (status==404 || status==405) message="This action isn’t available in your Cider version.";
else if (reply->error()==QNetworkReply::ConnectionRefusedError) message="Open Cider and try again.";
else message=mutation ? "Cider couldn’t confirm the action. Check Cider before retrying." : "Couldn’t read song status. Try again.";
+ if (mutation && !m_batch.isEmpty()) {
+ message=QString("%1 of %2 tracks confirmed. Check the queue before retrying; the last request may have reached Cider.").arg(m_batchDone).arg(m_batch.size());
+ m_batch.clear();
+ QTimer::singleShot(350,m_cider,[cider=m_cider] { if(cider->queueVisible())cider->refreshQueue(); });
+ }
if (generation==m_generation) { m_error=message; if (!mutation) m_ready=false; }
emit changed(); if (mutation) emit feedback(message,true); return;
}
@@ -67,18 +72,18 @@ void MusicActions::request(const QByteArray &method, const QString &path, const
});
}
void MusicActions::refresh() {
- if (!m_observing || m_read || m_busy) return;
+ if (!m_observing || m_read || busy()) return;
request("GET","/library/now-playing/status",{},false,[this](QJsonObject json) {
const auto data=json.value("data").toObject();
if (!data.value("inLibrary").isBool() || !data.value("rating").isDouble() ||
data.value("rating").toInt() < -1 || data.value("rating").toInt() > 1) {
m_ready=false; m_error="Song status unavailable."; return;
}
- m_saved=data.value("inLibrary").toBool(); m_favorite=data.value("rating").toInt()==1; m_ready=true;
+ m_saved=data.value("inLibrary").toBool(); m_favorite=data.value("rating").toInt()==1; m_disliked=data.value("rating").toInt()==-1; m_ready=true;
});
}
void MusicActions::enqueue(const QVariantMap &item, bool next) {
- if (m_busy || !item.value("playable").toBool()) return;
+ if (busy() || m_cider->controlBusy() || !item.value("playable").toBool()) return;
const auto type=item.value("type").toString(), id=item.value("id").toString();
if (!QStringList{"songs","albums","playlists","library-songs","library-albums","library-playlists"}.contains(type) ||
!QRegularExpression("^[A-Za-z0-9._-]+$").match(id).hasMatch()) return;
@@ -89,7 +94,7 @@ void MusicActions::enqueue(const QVariantMap &item, bool next) {
});
}
void MusicActions::changeCurrent(const QByteArray &method, const QString &path, const QJsonObject &body, const QString &message) {
- if (!m_observing || !m_ready || m_busy) return;
+ if (!m_observing || !m_ready || busy()) return;
// A status read already in flight must not restore the pre-action state.
if (m_read) { m_read->disconnect(this); m_read->abort(); m_read->deleteLater(); m_read=nullptr; }
const int generation=m_generation;
@@ -107,3 +112,34 @@ void MusicActions::toggleFavorite() {
void MusicActions::save() {
if (!m_saved) changeCurrent("POST","/library/now-playing/add",{},"Saved to library");
}
+
+void MusicActions::enqueueMany(const QVariantList &items, bool next) {
+ if(busy() || m_cider->controlBusy() || items.isEmpty())return;
+ static const QRegularExpression idPattern("^[A-Za-z0-9._-]+$");
+ for(const auto &value:items) {
+ const auto row=value.toMap();
+ if(!row.value("playable").toBool() || !QStringList{"songs","library-songs"}.contains(row.value("type").toString()) ||
+ !idPattern.match(row.value("id").toString()).hasMatch()) {
+ emit feedback("Select available songs to add to the queue.",true); return;
+ }
+ }
+ m_batch=items; m_batchNext=next; m_batchDone=0; m_error.clear(); emit changed(); enqueueBatchItem();
+}
+void MusicActions::enqueueBatchItem() {
+ if(m_batchDone>=m_batch.size()) {
+ const int total=m_batch.size();m_batch.clear();m_busy=false;emit changed();
+ emit feedback(QString(m_batchNext?"%1 tracks playing next":"%1 tracks added to queue").arg(total),false);
+ QTimer::singleShot(350,m_cider,[cider=m_cider] { if(cider->queueVisible())cider->refreshQueue(); });return;
+ }
+ // Each add-next inserts at the front; send in reverse so the final queue
+ // matches the visual selection order. Never replay an uncertain mutation.
+ const auto row=m_batch[m_batchNext?m_batch.size()-1-m_batchDone:m_batchDone].toMap();
+ m_busy=true;
+ request("POST",m_batchNext?"/queue/add-next":"/queue/add-later",{{"type",row.value("type").toString()},{"id",row.value("id").toString()}},true,
+ [this](QJsonObject) { ++m_batchDone; enqueueBatchItem(); });
+}
+
+void MusicActions::toggleDislike() {
+ changeCurrent(m_disliked ? "DELETE" : "POST",m_disliked ? "/library/now-playing/rating" : "/library/now-playing/dislike",
+ {},m_disliked ? "Rating cleared" : "Suggesting less like this");
+}
diff --git a/src/musicactions.h b/src/musicactions.h
index 09aabd5..07ef610 100644
--- a/src/musicactions.h
+++ b/src/musicactions.h
@@ -1,6 +1,7 @@
#pragma once
#include <QObject>
#include <QVariantMap>
+#include <QVariantList>
#include <QJsonObject>
#include <QNetworkAccessManager>
#include <QNetworkReply>
@@ -16,27 +17,35 @@ class MusicActions : public QObject {
Q_PROPERTY(bool busy READ busy NOTIFY changed)
Q_PROPERTY(bool ready READ ready NOTIFY changed)
Q_PROPERTY(bool favorite READ favorite NOTIFY changed)
+ Q_PROPERTY(bool disliked READ disliked NOTIFY changed)
Q_PROPERTY(bool saved READ saved NOTIFY changed)
Q_PROPERTY(QString error READ error NOTIFY changed)
public:
explicit MusicActions(Cider *cider, QObject *parent=nullptr);
~MusicActions() override;
bool observing() const { return m_observing; }
- bool busy() const { return m_busy; }
+ bool busy() const { return m_busy || !m_batch.isEmpty(); }
bool ready() const { return m_ready; }
bool favorite() const { return m_favorite; }
+ bool disliked() const { return m_disliked; }
bool saved() const { return m_saved; }
QString error() const { return m_error; }
void setObserving(bool value);
Q_INVOKABLE void refresh();
+ Q_INVOKABLE void enqueueMany(const QVariantList &items, bool next);
Q_INVOKABLE void enqueue(const QVariantMap &item, bool next);
Q_INVOKABLE void toggleFavorite();
Q_INVOKABLE void save();
+ Q_INVOKABLE void toggleDislike();
signals:
void changed();
void currentChanged();
void feedback(const QString &message, bool error);
private:
+ void enqueueBatchItem();
+ QVariantList m_batch;
+ int m_batchDone=0;
+ bool m_batchNext=false;
void request(const QByteArray &method, const QString &path, const QJsonObject &body,
bool mutation, std::function<void(QJsonObject)> done);
void changeCurrent(const QByteArray &method, const QString &path, const QJsonObject &body, const QString &message);
@@ -46,6 +55,6 @@ private:
QPointer<QNetworkReply> m_read, m_write;
QTimer m_poll;
int m_generation=0;
- bool m_observing=false, m_busy=false, m_ready=false, m_favorite=false, m_saved=false;
+ bool m_observing=false, m_busy=false, m_ready=false, m_favorite=false, m_disliked=false, m_saved=false;
QString m_error;
};
diff --git a/src/player.cpp b/src/player.cpp
index 56c780b..4080c85 100644
--- a/src/player.cpp
+++ b/src/player.cpp
@@ -37,6 +37,7 @@ Player::Player(const QString &settingsPath, QObject *parent)
m_shuffle = m_settings.value("shuffle", false).toBool();
m_repeat = qBound(0, m_settings.value("repeat", 0).toInt(), 2);
m_light = m_settings.value("light", false).toBool();
+ m_vinyl = m_settings.value("vinyl", false).toBool();
m_motion = m_settings.value("motion", true).toBool();
m_ciderAutoStart = m_settings.value("ciderAutoStart", false).toBool();
m_miniOnTop = m_settings.value("miniOnTop", false).toBool();
@@ -115,7 +116,7 @@ QString Player::trackId() const {
}
QVariantList Player::queue() const {
QVariantList result;
- for (const auto &t : m_tracks) result.append(QVariantMap{{"title", t.title}, {"artist", t.artist.isEmpty() ? "Unknown artist" : t.artist}, {"duration", t.duration}, {"artwork", queueArtworkUrl(t.path, t.cover)}});
+ for (const auto &t : m_tracks) result.append(QVariantMap{{"path", t.path}, {"title", t.title}, {"artist", t.artist.isEmpty() ? "Unknown artist" : t.artist}, {"duration", t.duration}, {"artwork", queueArtworkUrl(t.path, t.cover)}});
return result;
}
bool Player::supported(const QString &path) {
@@ -359,6 +360,7 @@ void Player::move(int from, int to) {
void Player::setMiniOnTop(bool value) { if (m_miniOnTop == value) return; m_miniOnTop = value; emit miniOnTopChanged(); save(); }
void Player::setMiniMode(bool value) { if (m_miniMode == value) return; m_miniMode = value; emit miniModeChanged(); save(); }
void Player::setBackgroundBlur(bool value) { if (m_backgroundBlur == value) return; m_backgroundBlur = value; emit backgroundBlurChanged(); save(); }
+void Player::setVinyl(bool value) { if (m_vinyl==value) return; m_vinyl=value; emit vinylChanged(); save(); }
void Player::setMotion(bool value) { m_motion = value; emit settingsChanged(); save(); }
void Player::fail(const QString &message) { m_error = message; emit errorChanged(); }
void Player::dismissError() { m_error.clear(); emit errorChanged(); }
@@ -367,6 +369,7 @@ void Player::save() {
m_settings.setValue("shuffle", m_shuffle);
m_settings.setValue("repeat", m_repeat);
m_settings.setValue("light", m_light);
+ m_settings.setValue("vinyl", m_vinyl);
m_settings.setValue("motion", m_motion);
m_settings.setValue("backgroundBlur", m_backgroundBlur);
m_settings.setValue("miniMode", m_miniMode);
diff --git a/src/player.h b/src/player.h
index 39a3cbc..c0a565a 100644
--- a/src/player.h
+++ b/src/player.h
@@ -39,6 +39,7 @@ class Player : public QObject {
Q_PROPERTY(bool shuffle READ shuffle WRITE setShuffle NOTIFY settingsChanged)
Q_PROPERTY(int repeatMode READ repeatMode WRITE setRepeatMode NOTIFY settingsChanged)
Q_PROPERTY(bool light READ light WRITE setLight NOTIFY settingsChanged)
+ Q_PROPERTY(bool vinyl READ vinyl WRITE setVinyl NOTIFY vinylChanged)
Q_PROPERTY(bool motion READ motion WRITE setMotion NOTIFY settingsChanged)
Q_PROPERTY(bool ciderAutoStart READ ciderAutoStart WRITE setCiderAutoStart NOTIFY settingsChanged)
Q_PROPERTY(bool miniOnTop READ miniOnTop WRITE setMiniOnTop NOTIFY miniOnTopChanged)
@@ -68,6 +69,8 @@ public:
bool shuffle() const { return m_shuffle; }
int repeatMode() const { return m_repeat; }
bool light() const { return m_light; }
+ bool vinyl() const { return m_vinyl; }
+ void setVinyl(bool value);
bool motion() const { return m_motion; }
bool ciderAutoStart() const { return m_ciderAutoStart; }
void setCiderAutoStart(bool value);
@@ -106,6 +109,7 @@ public:
static bool supported(const QString &path);
static Track readTrack(const QString &path);
signals:
+ void vinylChanged();
void discDetailsChanged();
void trackChanged();
void artworkChanged();
@@ -142,6 +146,7 @@ private:
QSet<QString> m_shuffleVisited;
QString m_artFile, m_error;
bool m_ciderAutoStart = false;
+ bool m_vinyl = false;
bool m_shuffle = false, m_light = false, m_motion = true, m_busy = false, m_backgroundBlur = false, m_miniMode = false, m_miniOnTop = false;
int m_repeat = 0;
qint64 m_restorePosition = -1;