Skip to content

armgit / Spun

Public Imported from GitHub
0

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

Add optional 3D players and fix artwork updates

yappologistic2518331dad76
diff --git a/CMakeLists.txt b/CMakeLists.txt
index d804a66..b398804 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -34,6 +34,10 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMAKE_CXX_COMPILER_ID MATCHES "GNU|Cla
endif()
endif()
find_package(Qt6 6.8 REQUIRED COMPONENTS Core Gui Quick Qml QuickControls2 Multimedia Concurrent DBus Network Svg)
+option(SPUN_ENABLE_3D "Build optional Qt Quick 3D player view" ON)
+if(SPUN_ENABLE_3D)
+ find_package(Qt6 6.8 QUIET COMPONENTS Quick3D)
+endif()
qt_policy(SET QTP0004 NEW)
find_package(PkgConfig REQUIRED)
pkg_check_modules(TAGLIB REQUIRED IMPORTED_TARGET taglib>=2.0)
@@ -46,6 +50,12 @@ qt_add_library(spun_core STATIC
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)
+if(TARGET Qt6::Quick3D AND SPUN_ENABLE_3D)
+ target_sources(spun_core PRIVATE src/deckgeometry.cpp src/deckgeometry.h src/mediageometry.cpp src/mediageometry.h)
+ target_link_libraries(spun_core PUBLIC Qt6::Quick3D)
+ target_compile_definitions(spun_core PUBLIC SPUN_WITH_3D=1)
+ set(SPUN_3D_QML qml/Player3D.qml)
+endif()
target_compile_definitions(spun_core PUBLIC SPUN_SOURCE_DIR="${CMAKE_CURRENT_SOURCE_DIR}")
target_compile_options(spun_core PRIVATE -Wall -Wextra -Wpedantic)
if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
@@ -67,7 +77,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/SpunButton.qml qml/SpunSlider.qml qml/SeekSlider.qml qml/QuickJump.qml qml/NextTrackTip.qml qml/SavedQueuePicker.qml qml/Tonearm.qml qml/CassetteReels.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)
+ QML_FILES ${SPUN_3D_QML} qml/SpunButton.qml qml/SpunSlider.qml qml/SeekSlider.qml qml/QuickJump.qml qml/NextTrackTip.qml qml/SavedQueuePicker.qml qml/Tonearm.qml qml/CassetteReels.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)
@@ -94,9 +104,15 @@ 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 src/eventstest.cpp src/mediauitest.cpp)
+ target_sources(spun-diagnostics PRIVATE src/librarytest.cpp src/librarytest.h src/eventstest.cpp src/mediauitest.cpp src/threedtest.cpp src/artworktest.cpp)
target_compile_definitions(spun-diagnostics PRIVATE SPUN_DIAGNOSTICS)
target_link_libraries(spun-diagnostics PRIVATE Qt6::Test)
+ if(TARGET Qt6::Quick3D AND SPUN_ENABLE_3D)
+ qt_add_executable(spun-geometry-test src/geometrytest.cpp)
+ target_link_libraries(spun-geometry-test PRIVATE spun_core Qt6::Test)
+ add_test(NAME spun-3d-geometry COMMAND spun-geometry-test)
+ set_tests_properties(spun-3d-geometry PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen;QT_QPA_PLATFORMTHEME=")
+ endif()
qt_add_executable(spun-media-test src/mediatest.cpp)
target_link_libraries(spun-media-test PRIVATE spun_core Qt6::Test)
find_program(SPUN_DBUS_RUN_SESSION dbus-run-session)
diff --git a/README.md b/README.md
index 456ae0c..042c0f5 100644
--- a/README.md
+++ b/README.md
@@ -22,13 +22,13 @@
<a href="#license">License</a>
</p>
-Play local music, or control Apple Music through Cider. Your album artwork becomes the disc, with a quiet interface inspired by Material Design 3 and colors that follow Noctalia. Browse songs, albums and playlists, search your library, and manage the queue without constantly switching apps.
+Play local music or control Apple Music through Cider. Spun puts your album artwork on a spinning CD, vinyl record or cassette, with an interface inspired by Material Design 3. Optional 3D players add physical depth and lighting that follows Noctalia's wallpaper palette.
-**Source-available · PolyForm Noncommercial 1.0.0.** Free for the purposes allowed by the license, including personal and noncommercial use. This is not an OSI-approved open-source project. [Read the license details](#license).
+**Source-available · PolyForm Noncommercial 1.0.0.** Personal and other permitted noncommercial use is free. This is not an OSI-approved open-source license. [Read the license details](#license).
## Install on CachyOS or Arch Linux
-Spun currently builds from source; there is no packaged installer yet. Open a terminal and run:
+Spun builds from source; there is no packaged installer yet. Open a terminal and run:
```bash
sudo pacman -S --needed base-devel git cmake ninja python qt6-base qt6-declarative qt6-multimedia qt6-svg taglib
@@ -39,89 +39,88 @@ cd Spun
./scripts/install-launcher.sh
```
-Open **Spun** from your application menu, or run `./scripts/run.sh` from the Spun folder. Keep that folder where it is: the launcher points to it. If you move it, run `./scripts/install-launcher.sh` again from its new location.
+**For 3D players**, also install `qt6-quick3d` and run the build command again. Spun includes 3D when that dependency is available. To build without it, add `-DSPUN_ENABLE_3D=OFF` to the build command.
+
+Open **Spun** from your application menu, or run `./scripts/run.sh` from its folder. The launcher points to that folder. If you move it, run `./scripts/install-launcher.sh` again.
<details>
<summary>Building on another Linux distribution</summary>
-Other Linux distributions need a C++20 compiler, CMake 3.22+, Ninja, pkg-config, Python 3, Qt 6.8+ with Quick Controls, Multimedia, SVG and development files, and TagLib 2.0+ development files. Package names differ between distributions. Spun is developed on CachyOS with Hyprland and Noctalia; desktop integration can vary elsewhere.
+You need a C++20 compiler, CMake 3.22+, Ninja, pkg-config, Python 3, Qt 6.8+ with Quick Controls, Multimedia, SVG and development files, and TagLib 2.0+ development files. Qt Quick 3D is optional. Package names differ between distributions. Spun is developed on CachyOS with Hyprland and Noctalia; desktop integration can vary elsewhere.
</details>
## Start listening
-**Local music:** choose **Local**, then **+** to add tracks. You can also drop audio files or a folder onto Spun. Use **More → Add music folder** to include songs in artist and album subfolders. Spun shows import progress, skips songs already in the queue, and lets you cancel without adding a partial import. Directory symlinks inside the folder are not followed. Your music files are not copied or modified. **More → Play demo** plays the included original soundcheck.
+**Local music:** choose **Local**, then **+** to add tracks, or drop files and folders onto Spun. **More → Add music folder** includes artist and album subfolders. Imports show progress, skip songs already in the queue and can be cancelled without adding a partial import. Directory symlinks inside the folder are not followed. Your music files are not copied or modified. **More → Play demo** plays the included original soundcheck.
-**Apple Music through Cider:** open Cider, sign in there, and choose **Cider** in Spun. Cider still handles authentication and streaming and must remain running. Apple Music playback requires the appropriate Apple Music access through Cider.
+**Apple Music through Cider:** open Cider, sign in there, then choose **Cider** in Spun. Cider handles authentication and streaming and must remain running. Apple Music playback requires the appropriate access through Cider.
-For search, library browsing and the full queue:
+For search, browsing and the full queue:
1. Enable Cider's local API.
-2. Open Spun’s **Queue** and choose **Connect to Cider**.
+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.
+For older Cider 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.
+Spun connects to the local API on port 10767. Basic playback controls use Linux's media-player interface, so working playback alone does not confirm API access. Available actions depend on your Cider version and permissions.
## Inside the player
-- **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.
-- **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.
-- **Interface size:** choose 85–150% in **Preferences → Interface size**. Text, controls and artwork scale together; large layouts fit the available screen.
-- **Fine seeking:** hold **Shift** while dragging a progress bar, the disc rim or vinyl needle. Progress bars preview your position and seek on release; **Esc** cancels. Cassette reels wind with the preview and respect reduced motion and the cassette sound preference.
-- **Artwork:** choose **View artwork** from the player's **⋯** menu to inspect the full cover without the disc cutout.
-- **Queue browsing:** scrolling away keeps your place when playback advances. **Current song** returns to the playing track and resumes following it.
-- **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.
-- **Disc appearance:** choose **CD**, **Vinyl** or **Cassette** 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. Cassette mode adds a tape shell, reels that turn counterclockwise during forward playback and reverse while rewinding, a horizontal progress bar and optional transport sounds. All three styles share playback, reverse-side details, lyrics and Mini mode. Your choice is remembered.
-- **Player bodies:** **Show player body** in Preferences adds a turntable, a portable cassette player or a CD tray with a clear lid. Mini mode keeps the compact medium. Cassette finishes include Clear, Smoke and Cream. Album changes briefly show a sleeve or case and move the lid and medium; playback starts immediately. Changing tracks within an album keeps the same medium. Reduced motion skips the loading sequence. The reverse uses a matching case or booklet for the existing album details and lyrics.
-- **CD speed:** enable **500 RPM** in CD Preferences for faster visual rotation. Audio speed stays unchanged; reduced motion still applies.
-- **Vinyl controls:** choose 33⅓ or 45 RPM, enable a horizontal progress bar, or add optional crackle, hiss and groove skips in Preferences. Drag the needle onto the grooves to seek and play.
-- **Albums as records:** enable **Play albums as records** in Vinyl preferences to give each album track its own groove band. Drop the needle to choose a song and position. Local mode uses the album tracks already loaded into Spun, in track-number order. With Cider, a drop starts the album in its queue, then verifies the track before seeking. Missing durations or unavailable tracks keep ordinary single-song seeking. The horizontal bar always seeks within the current song.
-- **Desktop controls:** Spun’s desktop media entry follows the selected Local or Cider source, including artwork, playback state, volume and seeking. Cider may also expose its own desktop entry.
-- **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 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.
+### CD, vinyl and cassette
+
+Choose a medium in **More → Preferences**. All three share playback controls, album details, lyrics and Mini mode.
+
+- **CD:** album artwork on the disc, with gentle rotation or an optional **500 RPM** setting. This changes the visual speed only.
+- **Vinyl:** a record with grooves, a gold tonearm and Relaxed, 33⅓ or 45 RPM rotation. Drag the needle to seek and play. Optional effects include crackle, hiss and groove skips.
+- **Cassette:** Clear, Smoke and Cream finishes, moving tape reels and optional transport sounds. Reels turn counterclockwise during forward playback and reverse while rewinding.
+- **Player bodies:** **Show player body** adds a turntable, portable cassette player or CD tray with a clear lid. Album changes exchange the medium with a brief sleeve or case animation. Tracks on the same album keep it in place, and playback starts immediately.
+- **3D:** enable **3D player** for modeled discs, reels, cases and tonearm parts, with metallic surfaces and lighting tinted by Noctalia's current palette. Playback controls stay in their familiar positions. Mini mode remains compact, and reverse-side details stay flat for reading.
+- **Seeking:** use the disc rim, vinyl needle or optional horizontal progress bar. Their previews stay in sync. Hold **Shift** for finer adjustments and **Esc** to cancel a drag.
+- **Albums as records:** enable **Play albums as records** in Vinyl preferences to give each album track a groove band. A needle drop selects the song and position. Local mode uses loaded album tracks in track-number order; Cider starts the album and verifies the track before seeking. Missing durations or unavailable tracks fall back to single-song seeking. The horizontal bar always seeks within the current song.
+- **Reverse view:** double-click the medium or press **F** for album details and tracks. Press **Y** for lyrics when available. Local lyrics can come from matching `.lrc` or `.txt` files or embedded metadata. **View artwork** opens the full cover.
+- **Mini mode:** a compact player with controls below the medium and an optional always-on-top setting. Hover or focus Next to preview the upcoming song when known.
+
+### Browse through Cider
+
+Use the top-left search button to browse songs, albums, playlists and artists without leaving Spun.
+
+- Search Apple Music, browse your library or recently played tracks, and filter songs inside albums and playlists.
+- Choose **Recently added** in Songs or Albums for newest-first browsing. Spun remembers your sorting choice.
+- Open **For You** on the empty Search page for personalized albums, playlists and stations. Recommendations load when requested, with a manual Refresh option.
+- Explore artist top songs, albums and similar artists. Filter discographies by full albums, singles and EPs, or live albums.
+- Pin artists, collections and stations. **Releases** shows the latest available release from each pinned artist when you open it.
+- Play stations, start song radio when available, or paste an Apple Music song, album, playlist or station link into Search.
+- Use song menus to favorite, save to your library, copy a public song link or adjust song recommendations where Cider supports the action. Writing to Apple Music playlists is not currently supported.
+
+### Queue and listening tools
+
+- **Queue:** view artwork, search, reorder and remove tracks. The header estimates remaining listening time. Scrolling away keeps your place; **Current song** returns to playback.
+- **Multiple tracks:** Ctrl-click individual tracks or Shift-click a range. Use the selection menu to queue or move them. Drag artwork sideways to reveal Queue and drop at a position among upcoming tracks.
+- **Queue from here:** append a song and the rest of its album, playlist or saved queue in collection order, including tracks hidden by search. Spun loads remaining pages first; navigating away cancels loading.
+- **Cleanup and Undo:** review duplicate removal or clearing upcoming songs before confirming. Removing a queued song offers a brief Undo when the queue has not changed. The current song and playback history are protected during cleanup.
+- **Saved queues:** save the current and upcoming tracks as a local snapshot. Rename it, reorder or remove songs, append more tracks, and undo the last edit. Snapshots contain track references, not downloaded audio or Apple Music playlists.
+- **Already queued:** a check beside browsing results marks current or upcoming songs. You can still add intentional repeats.
+- **Quick jump:** press **Ctrl+K** to find queue tracks, pins, saved queues and listening bookmarks. Selecting a queue track plays it. It also works in Mini mode.
+- **Bookmarks:** choose **Bookmark this moment** from the current Cider song's menu. Open it in Quick jump to resume at that position.
+- **Session recovery:** optionally enable **Remember Cider session** in Preferences. After a crash or an empty queue, choose **Recover session…** from Queue or Quick jump. Recovery asks for confirmation and only restores into an empty Cider queue. Turning the preference off removes the checkpoint.
+
+Cider changes refresh the visible queue and relevant details. Temporary connection failures preserve browsing results and offer reconnection when needed. Batch operations stop and report partial progress when Cider cannot confirm a change; uncertain playback actions are not retried automatically.
+
+### Preferences and desktop integration
+
+Choose your font, interface size, background blur, animations and media appearance in **More → Preferences**. Spun follows Noctalia's colors and reduced-motion setting when available. Reduced motion also skips loading sequences and perspective tilt.
+
+Spun's desktop media entry follows the selected Local or Cider source, including artwork, playback state, volume and seeking. Cider may also expose its own entry. Hyprland integration depends on the compositor's supported interfaces.
+
+**Audio settings** contains crossfade and, where supported by Cider, Automix and listening modes. **Audio quality** in the current song's menu shows what Cider reports and labels device output separately.
### Fonts
-Spun uses your system font by default. Choose any installed family in **More → Preferences → Font**, or return to **System default**. Fonts are not bundled or downloaded automatically.
+Spun uses your system font by default. Choose any installed family in **Preferences → Font**. Fonts are not bundled or downloaded automatically.
-For the intended appearance, we recommend [Google Sans Flex](https://github.com/googlefonts/googlesans-flex/releases). Download the font from its official releases, install the TTF with your desktop's font installer, reopen Spun, and select it in Preferences. The font has its own [SIL Open Font License](https://github.com/googlefonts/googlesans-flex/blob/main/OFL.txt); keep the accompanying license with your font files.
+For the intended appearance, we recommend [Google Sans Flex](https://github.com/googlefonts/googlesans-flex/releases). Install the TTF with your desktop's font installer, reopen Spun and select it in Preferences. The font has its own [SIL Open Font License](https://github.com/googlefonts/googlesans-flex/blob/main/OFL.txt).
<details>
<summary><strong>Keyboard shortcuts</strong></summary>
@@ -140,7 +139,7 @@ For the intended appearance, we recommend [Google Sans Flex](https://github.com/
| 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 |
+| Flip medium / switch lyrics | F / Y |
| Mute | M |
| Keyboard help | F1 |
| Back / dismiss | Escape |
@@ -163,52 +162,57 @@ To remove the application-menu entry:
rm "${XDG_DATA_HOME:-$HOME/.local/share}/applications/spun.desktop"
```
-You can then delete the Spun source folder. Your music stays where it was. Preferences remain in `~/.config/spun/` unless you choose to remove them separately.
+You can then delete the Spun source folder. Your music stays where it was. Preferences remain in `~/.config/spun/` unless you remove them separately.
## Troubleshooting and privacy
-**Cider plays, but search or the queue fails:** check that Cider is running, its local API is enabled, and Spun's application token is valid with the required permissions. A playback connection and an API connection are separate.
-
-**A font is missing:** install it on your system, reopen Spun and select it in Preferences. An unavailable saved font falls back to your system font.
-
-**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`, 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.
+- **Cider plays, but search or the queue fails:** check that its local API is enabled and Spun's token has the required permissions. Playback and API connections are separate.
+- **3D is unavailable:** install Qt Quick 3D and rebuild. Qt's software scenegraph backend does not support the 3D view; the regular player remains available.
+- **A font is missing:** install it, reopen Spun and select it again. An unavailable saved font falls back to the system font.
+- **An audio file will not play:** supported formats depend on the codecs available to Qt Multimedia on your distribution.
-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.
+Spun does not ask for your Apple Music password. Its Cider token is stored with owner-only file permissions in `~/.config/spun/cider-connection.json`. Preferences and local listening data also stay in `~/.config/spun/`. Artwork and music metadata may be fetched during playback and browsing. Do not include tokens, private configuration, listening history or personal logs in issue reports.
## Development
<details>
<summary>Build, test and benchmark</summary>
-Build the diagnostic companion and run isolated playback, API-fixture and UI checks:
+Build the diagnostic companion and run the registered tests:
```bash
./scripts/build.sh -DBUILD_TESTING=ON
-QT_QPA_PLATFORM=offscreen QT_QUICK_BACKEND=software QSG_RENDER_LOOP=basic QT_QPA_PLATFORMTHEME= ./build/spun --self-test
+ctest --test-dir build --output-on-failure
+```
+
+Tests use temporary preferences and synthetic local API fixtures. Audio checks need a working user audio session, and API fixtures need permission to listen on loopback. Desktop-control tests use a private D-Bus session. Diagnostics are separate from the normal player.
+
+For focused artwork, lighting, geometry and media checks:
+
+```bash
+./scripts/test-3d.sh
```
-For focused vinyl and cassette interaction checks, use `--test-media-ui` with the same offscreen environment. Run desktop-control checks with `ctest --test-dir build -R spun-desktop-media --output-on-failure`; they use a private D-Bus session and a fake Cider service.
+The default uses offscreen CPU rendering through Mesa and requires an available X display for its OpenGL context. It does not create visible windows. It checks rendered artwork and palette changes without exercising the full native window lifecycle.
-For recursive folder-import checks, run `QT_QPA_PLATFORM=offscreen QT_QPA_PLATFORMTHEME= ./build/spun-import-test`. Add `--stress` to test 20,000 nested sparse WAV files representing 625 GiB of audio without allocating that much disk space. The temporary files are removed after the run.
+For the complete 3D interaction and Cider-fixture suites, run `SPUN_TEST_RENDERER=native ./scripts/test-3d.sh` in a separate Wayland or X11 test session. This includes projected seeking, tonearm gestures, lid transitions, scaling and mode combinations. Set `SPUN_TEST_SCREEN` to the dedicated output name and `SPUN_TEST_OUTPUT` to a local capture directory. Missing 3D rendering fails the checks instead of silently skipping them.
-The tests use temporary preferences and synthetic local API fixtures. Audio checks need a working user audio session, and API fixtures need permission to listen on loopback. The normal player is built separately from the diagnostic executable.
+For large imports, run `QT_QPA_PLATFORM=offscreen QT_QPA_PLATFORMTHEME= ./build/spun-import-test --stress`. This creates 20,000 temporary sparse WAV files representing 625 GiB of audio without allocating that much disk space, then removes them.
-For a connected Cider instance, `--inspect-cider` and `--inspect-library` check live data without changing playback. The opt-in `--verify-cider-writes` also exercises playback, volume, repeat, queue insertion/removal/Undo and audio settings, then starts song radio. It restores its temporary queue and setting edits but leaves radio playing. Use `--config /path/to/test/settings.ini` with a privately paired test profile; never share its connection file or captured library data.
+`--inspect-cider` and `--inspect-library` inspect a live Cider connection without changing playback. The opt-in `--verify-cider-writes` changes playback, queue and audio settings and leaves song radio playing after restoring its temporary edits. Use a privately paired test profile with `--config /path/to/test/settings.ini`; never share its connection file or captured library data.
-For controlled performance measurements, run `python3 scripts/benchmark.py --output /tmp/spun-performance`. Its isolated scenes do not connect to your Cider instance. Offscreen measurements are useful comparisons, not whole-desktop GPU measurements. Regenerate the original soundcheck with `python3 scripts/make-demo.py` after building; this additionally requires FFmpeg.
+Run `python3 scripts/benchmark.py --output /tmp/spun-performance` for isolated performance comparisons. Offscreen results are not whole-desktop GPU measurements. `python3 scripts/make-demo.py` regenerates the original soundcheck after building and additionally requires FFmpeg.
</details>
-Bug reports are welcome. Before submitting substantial code contributions, open an issue to discuss scope and contributor licensing. Any future commercial distribution needs appropriate rights to contributed code as well as compliance with third-party licenses; submitting a patch does not transfer its copyright.
+Before submitting substantial code contributions, open an issue to discuss scope and contributor licensing. A patch does not transfer its copyright; future commercial distribution needs appropriate rights to contributed code and compliance with third-party licenses.
## License
-Spun's original code and assets are offered under the [PolyForm Noncommercial License 1.0.0](LICENSE), with the [required notice and third-party credits](NOTICE).
+Spun's original code and assets use the [PolyForm Noncommercial License 1.0.0](LICENSE), with [required notices and third-party credits](NOTICE).
-The license permits noncommercial use, specified personal uses, modification and redistribution under its terms. It also expressly permits use by certain charitable, educational, public research, public safety, health, environmental and government institutions, regardless of funding. It is therefore broader than “personal use only.” Uses outside its permissions require a separate license from the relevant rights holder. The full license controls.
+The license permits noncommercial use, specified personal uses, modification and redistribution under its terms. It also permits use by certain charitable, educational, public research, public safety, health, environmental and government institutions, regardless of funding. It is broader than personal use only. Uses outside its permissions require a separate license from the relevant rights holder. The full license controls.
-This licensing choice allows the author to offer separate commercial terms for code they own in the future. No paid edition is being offered here.
+The author may offer separate commercial terms for code they own in the future. No paid edition is offered here.
-Material Symbols Rounded icons remain under their own [Apache 2.0 license](licenses/MaterialSymbols-LICENSE.txt). Qt, TagLib and optional fonts retain their respective licenses; Spun's noncommercial terms do not replace those licenses. Spun is an independent project and is not endorsed by Google, Apple, Cider or Noctalia.
+Material Symbols Rounded icons retain their [Apache 2.0 license](licenses/MaterialSymbols-LICENSE.txt). Qt, TagLib and optional fonts retain their respective licenses. Spun is an independent project and is not endorsed by Google, Apple, Cider or Noctalia.
diff --git a/qml/Main.qml b/qml/Main.qml
index 48dd695..842b555 100644
--- a/qml/Main.qml
+++ b/qml/Main.qml
@@ -10,7 +10,8 @@ ApplicationWindow {
visible: true
readonly property real layoutWidth: miniMode ? 300 : sideOpen ? 860 : 530
readonly property real miniBaseHeight: showHorizontalSeek ? 382 : 354
- readonly property real layoutHeight: miniMode ? miniBaseHeight + (actionNotice.visible ? 48 : 0) : 730
+ readonly property real layoutHeight: miniMode ? miniBaseHeight + (actionNotice.visible ? 48 : 0)
+ : Math.max(730, actionNotice.visible ? actionNotice.y + actionNotice.height + 8 : 730)
onLayoutHeightChanged: Qt.callLater(updateMask)
readonly property real uiScale: testMode ? typography.uiScale : Math.min(typography.uiScale,
Math.max(.5, (Screen.desktopAvailableWidth - 40) / layoutWidth),
@@ -22,7 +23,45 @@ ApplicationWindow {
color: "transparent"
flags: Qt.Window | Qt.FramelessWindowHint | (miniPinned && !native.supportsBlur ? Qt.WindowStaysOnTopHint : 0)
font.family: SpunStyle.family
- readonly property bool bodyVisible: player.showPlayerBody && !miniMode
+ readonly property bool threeDGesture: !!activeSeekControl || scrubber.scrubbing || !!(armLoader.item && armLoader.item.dragging)
+ readonly property bool threeDRequested: supports3D && player.threeD && !miniMode && !discFlipped
+ readonly property bool threeDActive: threeDRequested && scene3D.status === Loader.Ready
+ onThreeDRequestedChanged: cancel3DPointer()
+ onThreeDActiveChanged: { cancel3DPointer(); cancelSeekPreview(); scrubber.cancelScrub(); stopSwap(); Qt.callLater(updateMask) }
+ readonly property var tonearm: armLoader.item
+ property var threeDPointer: null
+ function pointerEvent(control, point, modifiers) {
+ const p=control.mapFromItem(mediaSurface,point.x,point.y)
+ return {x:p.x,y:p.y,modifiers:modifiers,accepted:true}
+ }
+ function controlAt3DPoint(point) {
+ if(menuOpen || swapRunning)return null
+ let control=null
+ if(vinyl && tonearm && tonearm.canSeek) {
+ const p=tonearm.mapFromItem(mediaSurface,point.x,point.y),tip=tonearm.pointerInput.tip
+ if(Math.hypot(p.x-tip.x,p.y-tip.y)<=27)control=tonearm.pointerInput
+ }
+ if(!control && cassette && cassetteSeek.enabled) {
+ const p=cassetteSeek.mapFromItem(mediaSurface,point.x,point.y)
+ if(p.x>=0&&p.x<=cassetteSeek.width&&p.y>=0&&p.y<=cassetteSeek.height)control=cassetteSeek.pointerInput
+ }
+ if(!control && !cassette && scrubber.canSeek) {
+ const p=scrubber.mapFromItem(mediaSurface,point.x,point.y)
+ if(scrubber.onRim(p.x,p.y))control=scrubber
+ }
+ return control
+ }
+ function begin3DPointer(point, modifiers) {
+ cancel3DPointer()
+ const control=controlAt3DPoint(point)
+ if(control) { const event=pointerEvent(control,point,modifiers);control.beginPointer(event);if(event.accepted)threeDPointer=control }
+ }
+ function move3DPointer(point, modifiers) {
+ if(threeDPointer)threeDPointer.movePointer(pointerEvent(threeDPointer,point,modifiers))
+ }
+ function end3DPointer() { const control=threeDPointer;threeDPointer=null;if(control)control.endPointer() }
+ function cancel3DPointer() { const control=threeDPointer;threeDPointer=null;if(control)control.cancelPointer() }
+ readonly property bool bodyVisible: (player.showPlayerBody || threeDRequested) && !miniMode
readonly property real mediumScale: bodyVisible && !discFlipped ? .86 : 1
readonly property color cassetteShell: player.cassetteFinish === "cream" ? "#bab29c" : player.cassetteFinish === "clear" ? "#b06f8285" : root.surface
property real lidOpen: 0
@@ -43,7 +82,7 @@ ApplicationWindow {
if (crossfadeMenu.visible) { crossfadeMenu.service.refreshCrossfade(); crossfadeMenu.service.refreshAudioOptions() }
if (qualityPopup.visible) root.ciderService.refreshAudioQuality()
}
- Connections { target: player; function onMediumChanged() { root.spinSpeed = 0; root.stopSwap(); Qt.callLater(root.updateMask) } function onSettingsChanged() { if (!player.vinylAlbumMode || !player.vinyl) root.listeningService.cancelAlbumPosition() } }
+ Connections { target: player; function onMediumChanged() { root.cancel3DPointer(); root.spinSpeed = 0; root.stopSwap(); Qt.callLater(root.updateMask) } function onSettingsChanged() { if (!player.vinylAlbumMode || !player.vinyl) root.listeningService.cancelAlbumPosition() } }
Connections { target: root.listeningService; function onFeedback(message, error) { root.notifyAction(message, error) } }
Connections { target: root.ciderService; function onRemoteSettingsChanged() { root.refreshOpenCiderDetails() } }
Timer {
@@ -53,7 +92,7 @@ ApplicationWindow {
}
property var deckPlayer: useCider ? root.ciderService : player
readonly property string cassetteTrackIdentity: (useCider ? "cider:" : "local:") + (deckPlayer.trackKey || "")
- onCassetteTrackIdentityChanged: Qt.callLater(syncTapeSound)
+ onCassetteTrackIdentityChanged: { cancel3DPointer(); Qt.callLater(syncTapeSound) }
function syncTapeSound() { tapeSound.observe(useCider ? "cider" : "local", deckPlayer.trackKey || "") }
Binding { target: tapeSound; property: "enabled"; value: root.cassette && player.cassetteSounds }
Binding { target: tapeSound; property: "volume"; value: root.deckPlayer.volume }
@@ -75,7 +114,7 @@ ApplicationWindow {
running: root.vinyl && player.vinylSkips && root.deckPlayer.playing && !root.needleDragging
onTriggered: { root.skipGroove(); interval = 45000 + Math.floor(Math.random()*35000) }
}
- onUseCiderChanged: { if (!useCider) root.listeningService.cancelAlbumPosition(); cancelSeekPreview(); artworkPopup.close(); 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() }
+ onUseCiderChanged: { stopSwap(); presentation.clear(); cancel3DPointer(); if (!useCider) root.listeningService.cancelAlbumPosition(); cancelSeekPreview(); artworkPopup.close(); 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
@@ -88,7 +127,7 @@ ApplicationWindow {
function stopSwap() { discSwap.stop(); resetSwap(); presentation.releaseOutgoing() }
function presentDisc() {
const albumKey = deckPlayer.count ? (useCider ? "cider:" : "local:") + (deckPlayer.albumKey || deckPlayer.title) : ""
- presentation.present(deckPlayer.artwork, albumKey, animate && !discFlipped && visible && native.exposed, useCider || player.artworkLoading)
+ presentation.present(deckPlayer.artwork, albumKey, animate && !discFlipped && visible && native.exposed)
}
function syncLibrary() { if (!visible || visibility === Window.Minimized) { songMenu.close(); musicBrowser.closeActions() }; library.active = libraryOpen && useCider && visible && visibility !== Window.Minimized }
function syncLyrics() { lyrics.remote = useCider; lyrics.active = discFlipped && lyricsView && visible && visibility !== Window.Minimized }
@@ -115,6 +154,22 @@ ApplicationWindow {
readonly property string recordKey: recordMap ? (useCider ? "cider:" : "local:") + recordMap.rows.map(row => (row.track.id || row.track.path) + ":" + row.duration).join("|") : ""
onRecordKeyChanged: scrubber.cancelScrub()
readonly property real recordProgress: recordMap ? Math.max(0, Math.min(1, (recordMap.rows[recordMap.current].start + deckPlayer.position) / recordMap.total)) : progress
+ readonly property bool seekPreviewActive: !!activeSeekControl || scrubber.scrubbing || !!(tonearm && tonearm.dragging)
+ readonly property real recordVisualProgress: {
+ if (activeSeekControl) {
+ const fraction=activeSeekControl.previewValue
+ return recordMap ? (recordMap.rows[recordMap.current].start + fraction*recordMap.rows[recordMap.current].duration)/recordMap.total : fraction
+ }
+ if (scrubber.scrubbing) return scrubber.previewFraction
+ if (tonearm && tonearm.dragging) return tonearm.previewProgress
+ if (tonearm && tonearm.landing) return tonearm.landingProgress
+ return recordProgress
+ }
+ readonly property real trackVisualProgress: {
+ if (!recordMap) return recordVisualProgress
+ const target=recordTarget(recordVisualProgress)
+ return target ? target.position/recordMap.rows[target.index].duration : progress
+ }
function recordTarget(fraction) {
if (!recordMap) return null
const value = Math.max(0, Math.min(recordMap.total - 1, fraction * recordMap.total))
@@ -138,6 +193,12 @@ ApplicationWindow {
stopSwap()
syncLyrics()
}
+ function receiveMediaDrop(drop) {
+ const urls = drop.hasUrls ? drop.urls : []
+ if (urls.length && urls.every(url => url.toString().startsWith("file:"))) {
+ root.useLocal(); player.addUrls(urls); drop.acceptProposedAction()
+ } else if (root.openMusicLink(urls.length ? urls[0].toString() : drop.text, false)) drop.acceptProposedAction()
+ }
function flipDisc() { if (deckPlayer.count > 0) discFlipped = !discFlipped }
readonly property bool miniPinned: miniMode && player.miniOnTop
onMiniPinnedChanged: native.effects(root, backgroundBlur)
@@ -347,7 +408,7 @@ ApplicationWindow {
property real rememberedVolume: .65
property var activeSeekControl: null
property real tapeWindSpeed: 0
- readonly property real cassetteVisualProgress: activeSeekControl ? activeSeekControl.value : progress
+ readonly property real cassetteVisualProgress: trackVisualProgress
function cancelSeekPreview() { if (activeSeekControl) activeSeekControl.cancelSeek() }
property real cassetteLeftAngle: 0
property real cassetteRightAngle: 0
@@ -445,7 +506,7 @@ ApplicationWindow {
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(artworkPopup.visible) { artworkPopup.close();return }; if(root.activeSeekControl) { root.cancelSeekPreview();return }; if(scrubber.scrubbing) { scrubber.cancelScrub();return }; 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: "Escape"; onActivated: { if(root.threeDPointer) { root.cancel3DPointer();return }; if(artworkPopup.visible) { artworkPopup.close();return }; if(root.activeSeekControl) { root.cancelSeekPreview();return }; if(scrubber.scrubbing) { scrubber.cancelScrub();return }; 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 }
@@ -574,6 +635,11 @@ ApplicationWindow {
IconButton { visible: !native.hyprland; x: 300; y: 4; glyphName: "close"; tip: "Close Spun"; ink: root.mutedInk; hoverFill: root.hoverFill; onClicked: Qt.quit() }
}
+ Item {
+ id: mediaSurface
+ objectName: "mediaSurface"
+ opacity: root.threeDActive ? 0 : 1
+ width: 530; height: 530
PlayerBody {
objectName: "playerBody"
x: 45; y: 74; width: 440; height: 440
@@ -585,6 +651,7 @@ ApplicationWindow {
x: 45; y: 74; width: 440; height: 440
visible: root.bodyVisible && root.packageOpacity > 0
opacity: root.packageOpacity
+ transformOrigin: Item.TopLeft
medium: player.medium; surface: root.surface; artwork: presentation.artwork; part: 2
scale: .9 + .1 * root.packageOpacity
transform: Rotation { origin.x: 44; origin.y: 220; axis.x: 0; axis.y: 1; axis.z: 0; angle: root.vinyl ? 0 : -35*root.lidOpen }
@@ -1061,7 +1128,7 @@ ApplicationWindow {
objectName: "progressRing"
anchors.fill: parent
visible: !root.cassette && !(root.bodyVisible && root.discFlipped) && root.deckPlayer.count > 0
- progress: scrubber.scrubbing ? scrubber.previewFraction : root.recordProgress
+ progress: root.recordVisualProgress
phase: root.wavePhase
amplitude: root.deckPlayer.playing ? 2.8 : 0
accent: root.accent
@@ -1070,9 +1137,10 @@ ApplicationWindow {
MouseArea {
id: scrubber
objectName: "scrubber"
+ preventStealing: true
anchors.fill: parent
// Reverse-side lyrics keep their hover input; the rim remains seekable.
- containmentMask: QtObject { function contains(point) { return !root.discFlipped || scrubber.onRim(point.x, point.y) } }
+ containmentMask: QtObject { function contains(point: point): bool { return !root.discFlipped || scrubber.onRim(point.x, point.y) } }
hoverEnabled: true
property bool scrubbing: false
property real previewFraction: 0
@@ -1096,20 +1164,25 @@ ApplicationWindow {
lastFraction=pointer
}
function cancelScrub() { scrubbing = false }
- onPressed: mouse => {
+ function beginPointer(mouse) {
if (onRim(mouse.x,mouse.y) && canSeek) { updatePreview(mouse.x,mouse.y); lastFraction=previewFraction; if(mouse.modifiers & Qt.ShiftModifier)previewFraction=root.recordProgress; scrubbing=true }
else mouse.accepted=false
}
- onPositionChanged: mouse => { if(scrubbing)dragPreview(mouse.x,mouse.y,mouse.modifiers & Qt.ShiftModifier);else if(onRim(mouse.x,mouse.y))updatePreview(mouse.x,mouse.y) }
- onReleased: {
+ function movePointer(mouse) { if(scrubbing)dragPreview(mouse.x,mouse.y,mouse.modifiers & Qt.ShiftModifier);else if(onRim(mouse.x,mouse.y))updatePreview(mouse.x,mouse.y) }
+ function endPointer() {
if (scrubbing && canSeek) { if (root.recordMap) root.dropRecordNeedle(previewFraction); else root.deckPlayer.seek(root.deckPlayer.duration * previewFraction) }
scrubbing=false
}
- onCanceled: cancelScrub()
+ function cancelPointer() { cancelScrub() }
+ onPressed: mouse => beginPointer(mouse)
+ onPositionChanged: mouse => movePointer(mouse)
+ onReleased: endPointer()
+ onCanceled: cancelPointer()
onWheel: wheel => { if (root.discFlipped && !onRim(wheel.x,wheel.y)) { wheel.accepted=false; return }; root.deckPlayer.volume = Math.max(0, Math.min(1, root.deckPlayer.volume + wheel.angleDelta.y/2400)); wheel.accepted=true }
}
SeekSlider {
app: root
+ id: cassetteSeek
objectName: "cassetteSeek"
visible: (root.cassette || (root.bodyVisible && root.discFlipped)) && root.deckPlayer.count > 0
x: 70; y: root.bodyVisible && root.discFlipped ? 388 : 365; width: 300; height: 36
@@ -1118,12 +1191,7 @@ ApplicationWindow {
DropArea {
anchors.fill: parent
onEntered: drag => { if (!drag.hasUrls && !drag.hasText) drag.accepted=false }
- onDropped: drop => {
- const urls = drop.hasUrls ? drop.urls : []
- if (urls.length && urls.every(url => url.toString().startsWith("file:"))) {
- root.useLocal(); player.addUrls(urls); drop.acceptProposedAction()
- } else if (root.openMusicLink(urls.length ? urls[0].toString() : drop.text, false)) drop.acceptProposedAction()
- }
+ onDropped: drop => root.receiveMediaDrop(drop)
Rectangle {
anchors.fill: parent; radius: width / 2
visible: parent.containsDrag
@@ -1137,7 +1205,7 @@ ApplicationWindow {
PlayerBody {
objectName: "playerLid"
x: 45; y: 74; width: 440; height: 440
- visible: root.bodyVisible && !root.discFlipped
+ visible: root.bodyVisible && !root.discFlipped && !root.threeDActive
medium: player.medium; surface: root.surface; part: 1
opacity: 1 - .75*root.lidOpen
transform: Scale { origin.x: 220; origin.y: root.cassette ? 112 : 26; yScale: 1 - .35*root.lidOpen }
@@ -1145,7 +1213,7 @@ ApplicationWindow {
Rectangle {
id: rimPreview
objectName: "rimPreview"
- visible: scrubber.showPreview
+ visible: !root.threeDActive && scrubber.showPreview
z: 10
readonly property real angle: scrubber.previewFraction * 2 * Math.PI
readonly property point location: platter.mapToItem(root.contentItem, 220 + Math.sin(angle)*170, 220 - Math.cos(angle)*170)
@@ -1154,6 +1222,28 @@ ApplicationWindow {
color: root.surface
SpunText { anchors.centerIn: parent; text: { const target=root.recordTarget(scrubber.previewFraction); return target ? (target.index+1) + " · " + root.time(target.position) : root.time(root.deckPlayer.duration * scrubber.previewFraction) } font.pixelSize: SpunStyle.caption; color: root.accent }
}
+ }
+ Loader {
+ id: scene3D
+ objectName: "scene3DLoader"
+ x: 0; y: 60; width: 530; height: 470
+ active: root.threeDRequested
+ onActiveChanged: if(active)setSource(player3DUrl, {app: root, surfaceItem: mediaSurface})
+ Component.onCompleted: if(active)setSource(player3DUrl, {app: root, surfaceItem: mediaSurface})
+ }
+ DropArea {
+ objectName: "threeDMediaDrop"
+ x: 0; y: 60; width: 530; height: 470
+ enabled: root.threeDActive
+ onEntered: drag => { if(!drag.hasUrls && !drag.hasText)drag.accepted=false }
+ onDropped: drop => root.receiveMediaDrop(drop)
+ Rectangle {
+ anchors.fill: parent; radius: SpunStyle.panelRadius
+ visible: parent.containsDrag; color: root.inset; opacity: .94
+ border.width: 2; border.color: root.accent
+ SpunText { anchors.centerIn: parent; text: "Open music"; color: root.ink }
+ }
+ }
SeekSlider {
app: root; objectName: "miniHorizontalSeek"
visible: root.miniMode && root.showHorizontalSeek
@@ -1992,7 +2082,14 @@ ApplicationWindow {
onToggled: player.cd500Rpm = checked
onActiveFocusChanged: if(activeFocus)preferenceScroll.reveal(this)
}
- PreferenceSwitch { objectName: "playerBodyToggle"; app: root; width: parent.width; text: "Show player body"; glyphName: "disc"; checked: player.showPlayerBody; onToggled: player.showPlayerBody = checked; onActiveFocusChanged: if(activeFocus)preferenceScroll.reveal(this) }
+ PreferenceSwitch {
+ objectName: "threeDToggle"; app: root; width: parent.width
+ visible: supports3D; height: visible ? implicitHeight : 0
+ text: "3D player"; glyphName: "disc"; checked: player.threeD
+ onToggled: player.threeD = checked
+ onActiveFocusChanged: if(activeFocus)preferenceScroll.reveal(this)
+ }
+ PreferenceSwitch { objectName: "playerBodyToggle"; app: root; width: parent.width; visible: !supports3D || !player.threeD; height: visible ? implicitHeight : 0; text: "Show player body"; glyphName: "disc"; checked: player.showPlayerBody; onToggled: player.showPlayerBody = checked; onActiveFocusChanged: if(activeFocus)preferenceScroll.reveal(this) }
Row {
visible: root.cassette; height: visible ? 40 : 0; spacing: 6; width: parent.width
Repeater {
diff --git a/qml/Player3D.qml b/qml/Player3D.qml
new file mode 100644
index 0000000..307a5f5
--- /dev/null
+++ b/qml/Player3D.qml
@@ -0,0 +1,352 @@
+import QtQuick
+import QtQuick3D
+import Spun 1.0
+
+View3D {
+ id: view
+ required property var app
+ required property Item surfaceItem
+ objectName: "player3DView"
+ clip: true
+ property real pitchOffset: 0
+ property real yawOffset: 0
+ readonly property real progress: app.cassette ? app.cassetteVisualProgress : app.recordVisualProgress
+ Behavior on pitchOffset { enabled: app.animate && !app.threeDGesture; NumberAnimation { duration: 140 } }
+ Behavior on yawOffset { enabled: app.animate && !app.threeDGesture; NumberAnimation { duration: 140 } }
+ function tilt(point) {
+ if(!app.animate || app.threeDGesture || app.menuOpen)return
+ pitchOffset=(point.y/height-.5)*2
+ yawOffset=(point.x/width-.5)*3
+ }
+ Connections { target: app; function onAnimateChanged(){if(!app.animate){view.pitchOffset=0;view.yawOffset=0}} }
+ // Noctalia already exports the wallpaper palette. Reuse its accent without
+ // reading wallpaper files or sampling the desktop on every frame.
+ // A palette accent is a UI color, often pastel or dark. Preserve its hue
+ // while giving the illumination enough brightness and chroma to be visible.
+ readonly property color lightingColor: Qt.hsva(Math.max(0,app.accent.hsvHue), Math.min(.55,app.accent.hsvSaturation*1.5), 1, 1)
+ property color keyTint: Qt.tint("#ffffff", Qt.alpha(lightingColor, .30))
+ property color fillTint: Qt.tint("#ffffff", Qt.alpha(lightingColor, .80))
+ property color ambientTint: Qt.tint("#45474a", Qt.alpha(lightingColor, .18))
+ Behavior on keyTint { enabled: app.animate; ColorAnimation { duration: 450 } }
+ Behavior on fillTint { enabled: app.animate; ColorAnimation { duration: 450 } }
+ Behavior on ambientTint { enabled: app.animate; ColorAnimation { duration: 450 } }
+ camera: sceneCamera
+ environment: SceneEnvironment {
+ backgroundMode: SceneEnvironment.Transparent
+ antialiasingMode: SceneEnvironment.MSAA
+ antialiasingQuality: SceneEnvironment.Medium
+ specularAAEnabled: true
+ lightProbe: Texture { textureData: StudioTexture { tint: view.app.accent } }
+ probeExposure: .55
+ aoEnabled: true; aoStrength: 18; aoDistance: 12; aoSoftness: 50; aoSampleRate: 2
+ }
+ PerspectiveCamera { id: sceneCamera; z: 710+(app.vinyl?0:app.lidOpen*65); clipNear: 10; clipFar: 1500; fieldOfView: 38 }
+ DirectionalLight { objectName: "threeDKeyLight"; color: view.keyTint; eulerRotation: Qt.vector3d(-30,-35,0); brightness: .85; ambientColor: view.ambientTint; castsShadow: true; shadowFactor: 35; shadowMapQuality: Light.ShadowMapQualityMedium; shadowMapFar: 1200 }
+ DirectionalLight { objectName: "threeDFillLight"; color: view.fillTint; eulerRotation: Qt.vector3d(-10,45,0); brightness: .65 }
+ property color caseTint: Qt.tint(app.surface,Qt.alpha(app.accent,.07))
+ property color plateTint: Qt.tint(app.surface,Qt.alpha(app.ink,app.light?.12:.045))
+ property color metalTint: Qt.tint("#b8bdc0",Qt.alpha(app.accent,.13))
+ property color glassTint: Qt.tint("#dce8ed",Qt.alpha(app.accent,.18))
+ Behavior on caseTint { enabled: app.animate; ColorAnimation { duration: 450 } }
+ Behavior on plateTint { enabled: app.animate; ColorAnimation { duration: 450 } }
+ Behavior on metalTint { enabled: app.animate; ColorAnimation { duration: 450 } }
+ Behavior on glassTint { enabled: app.animate; ColorAnimation { duration: 450 } }
+ Texture { id: brushedGrain; generateMipmaps: true; mipFilter: Texture.Linear; textureData: SurfaceTexture { kind: "brushed" } }
+ Texture { id: turnedGrain; generateMipmaps: true; mipFilter: Texture.Linear; textureData: SurfaceTexture { kind: "turned" } }
+ Texture { id: metalMicroSurface; generateMipmaps: true; mipFilter: Texture.Linear; textureData: SurfaceTexture { kind: "metal-normal" } }
+ Texture { id: moldedGrain; generateMipmaps: true; mipFilter: Texture.Linear; textureData: SurfaceTexture { kind: "molded" } }
+ Texture { id: vinylGrain; generateMipmaps: true; mipFilter: Texture.Linear; textureData: SurfaceTexture { kind: "vinyl" } }
+ Texture { id: opticalFilm; generateMipmaps: true; mipFilter: Texture.Linear; textureData: SurfaceTexture { kind: "disc" } }
+ Texture {
+ id: cover; generateMipmaps: true; mipFilter: Texture.Linear
+ property CoverTexture imageData: CoverTexture { objectName: "currentCoverTexture"; artwork: presentation.artwork }
+ textureData: imageData.texture
+ }
+ Texture {
+ id: tapeLabel; generateMipmaps: true; mipFilter: Texture.Linear
+ property CoverTexture imageData: CoverTexture { objectName: "cassetteCoverTexture"; artwork: presentation.artwork; paper: true; title: app.deckPlayer.album || app.deckPlayer.title; artist: app.deckPlayer.artist }
+ textureData: imageData.texture
+ }
+ Texture {
+ id: oldCover; generateMipmaps: true; mipFilter: Texture.Linear
+ property CoverTexture imageData: CoverTexture { artwork: presentation.outgoing }
+ textureData: imageData.texture
+ }
+ PrincipledMaterial { id: metal; baseColor: view.metalTint; metalness: .86; roughness: .36; roughnessMap: brushedGrain }
+ PrincipledMaterial { id: rubber; baseColor: Qt.tint("#15191d",Qt.alpha(app.inset,.20)); roughness: .95; roughnessMap: moldedGrain }
+ PrincipledMaterial { id: blackVinyl; baseColor: "#17191d"; metalness: 0; roughness: .48; roughnessMap: vinylGrain; clearcoatAmount: .14; clearcoatRoughnessAmount: .3 }
+ PrincipledMaterial { id: gold; baseColor: Qt.tint("#d6ae58",Qt.alpha(app.accent,.045)); metalness: 1; roughness: .26; roughnessMap: brushedGrain; normalMap: metalMicroSurface; normalStrength: .12 }
+ PrincipledMaterial { id: steel; baseColor: Qt.tint("#cbd0d4",Qt.alpha(app.accent,.025)); metalness: 1; roughness: .34; roughnessMap: turnedGrain; normalMap: metalMicroSurface; normalStrength: .24 }
+ PrincipledMaterial { id: platterMetal; baseColor: Qt.tint("#737b80",Qt.alpha(app.accent,.04)); metalness: 1; roughness: .5; roughnessMap: turnedGrain }
+ PrincipledMaterial { id: label; baseColorMap: cover; roughness: .98; roughnessMap: moldedGrain }
+ component Solid: Model {
+ id: solidNode
+ property vector3d size: Qt.vector3d(20,20,10)
+ property real rounding: 2
+ property color tint: "#30363b"
+ geometry: DeckGeometry { dimensions: solidNode.size; radius: solidNode.rounding }
+ property Material finish: PrincipledMaterial { baseColor: solidNode.tint; metalness: .12; roughness: .55; roughnessMap: moldedGrain }
+ materials: [finish]
+ }
+ component Ring: Model {
+ id: ringNode
+ property real radius: 10
+ property real hole: 3
+ property real depth: 2
+ property bool grooves: false
+ geometry: RecordGeometry { radius: ringNode.radius; hole: ringNode.hole; depth: ringNode.depth; grooves: ringNode.grooves }
+ property Material finish: rubber
+ materials: [finish]
+ }
+ Node {
+ id: assembly
+ eulerRotation: Qt.vector3d(-24+view.pitchOffset,-7+view.yawOffset,0)
+ Solid {
+ objectName: "threeDEnclosure"
+ y: app.cassette?-4.5:0; z: -15
+ size: app.cassette?Qt.vector3d(402,283,28):Qt.vector3d(428,428,28)
+ rounding: app.cassette?23:app.vinyl?22:214; tint: view.caseTint
+ }
+ Solid {
+ objectName: "threeDTopPlate"
+ y: app.cassette?-4.5:0; z: .1
+ size: app.cassette?Qt.vector3d(388,269,2):Qt.vector3d(414,414,2)
+ rounding: app.cassette?19:app.vinyl?17:207; tint: view.plateTint
+ }
+ Repeater3D {
+ model: app.vinyl?4:0
+ Node {
+ required property int index
+ x: index%2?193:-193; y: index<2?193:-193; z: 2
+ Ring { radius: 3.2; hole: .25; depth: 1.2; finish: metal }
+ Solid { size: Qt.vector3d(4,.7,.3); z: .8; rounding: .2; tint: "#202228" }
+ }
+ }
+ Repeater3D {
+ model: 4
+ Model {
+ required property int index
+ source: "#Cylinder"; x: (index%2?1:-1)*(app.cassette?157:app.vinyl?160:120)
+ y: (index<2?1:-1)*(app.cassette?107:app.vinyl?162:120); z: -33
+ eulerRotation.x: 90; scale: Qt.vector3d(.24,.1,.24); materials: rubber
+ }
+ }
+ Ring { visible: !app.cassette; radius: 182; hole: 3; depth: 7; z: -1; finish: rubber }
+ Ring { visible: !app.cassette; radius: 180; hole: 176.5; depth: 1.1; z: 2.1; finish: app.vinyl?platterMetal:metal }
+ Ring { visible: !app.cassette; radius: 183; hole: 179; depth: 3; z: 0; finish: app.vinyl?platterMetal:metal }
+ Node {
+ id: medium
+ objectName: "threeDMedium"
+ x: app.swapOffset*.86
+ opacity: app.incomingOpacity
+ Node {
+ visible: !app.cassette
+ eulerRotation.z: -app.spinAngle
+ Ring { objectName: "threeDRecord"; radius: 176; hole: app.vinyl?3.5:15; depth: app.vinyl?2.8:1.2; grooves: app.vinyl; z: 4; finish: app.vinyl?blackVinyl:metal }
+ Repeater3D {
+ objectName: "threeDTrackBands"
+ model: app.recordMap ? app.recordMap.rows.length-1 : 0
+ Ring {
+ required property int index
+ readonly property real boundaryAngle: app.recordMap ? (6+20*app.recordMap.rows[index+1].start/app.recordMap.total)*Math.PI/180 : 0
+ radius: Math.hypot(173-197*Math.sin(boundaryAngle),-105+197*Math.cos(boundaryAngle))*.86
+ hole: radius-.8; depth: .08; z: 5.48
+ finish: PrincipledMaterial { baseColor: "#43484a"; metalness: .2; roughness: .38 }
+ }
+ }
+ Ring { objectName: "threeDRecordLabel"; radius: app.vinyl?62:169; hole: app.vinyl?3.5:32; depth: .25; z: app.vinyl?5.6:4.8; finish: label }
+ Ring { objectName: "threeDOpticalRim"; visible: !app.vinyl; radius: 175.5; hole: 169.2; depth: .18; z: 4.72; finish: PrincipledMaterial { baseColorMap: opticalFilm; metalness: .8; roughness: .19; clearcoatAmount: .65; clearcoatRoughnessAmount: .12 } }
+ Ring { visible: !app.vinyl; radius: 33; hole: 31.5; depth: .2; z: 5; finish: metal }
+ Ring { castsShadows: false; visible: !app.vinyl; radius: 32; hole: 15; depth: .4; z: 4.9; finish: PrincipledMaterial { baseColor: view.glassTint; metalness: .3; roughness: .15; alphaMode: PrincipledMaterial.Blend; opacity: .6 } }
+ }
+ Node {
+ visible: app.cassette
+ objectName: "threeDCassette"
+ Solid { size: Qt.vector3d(346,214,12); y: 4; z: 4; rounding: 12; finish: PrincipledMaterial { baseColor: Qt.darker(app.cassetteShell,1.4); alphaMode: PrincipledMaterial.Blend; opacity: player.cassetteFinish === "clear" ? .68 : 1; roughness: .32 } }
+ Solid { size: Qt.vector3d(318,34,1.5); y: 91; z: 14; rounding: 6; finish: PrincipledMaterial { baseColorMap: tapeLabel; roughness: .88 } }
+ Solid { size: Qt.vector3d(326,34,9); y: -76; z: 12; rounding: 6; tint: app.cassetteShell }
+ Repeater3D {
+ model: 2
+ Node {
+ id: reel
+ required property int index
+ objectName: "threeDReel"+index
+ x: index?78.6:-78.6; y: 13; z: 13
+ readonly property real fill: index?view.progress:1-view.progress
+ Ring { radius: 60; hole: .2; depth: .6; z: -2; finish: rubber }
+ Ring { radius: Math.sqrt(1936+3993*reel.fill)*.77; hole: 31; depth: 5; grooves: true; finish: PrincipledMaterial { baseColor: "#32231b"; roughness: .64 } }
+ Ring { objectName: "threeDReelBezel"+reel.index; radius: 62; hole: 60; depth: 1.5; z: 8; finish: rubber }
+ Ring { castsShadows: false; radius: 60; hole: 1; depth: .8; z: 8; finish: PrincipledMaterial { baseColor: view.glassTint; alphaMode: PrincipledMaterial.Blend; opacity: .035; roughness: .2; cullMode: Material.NoCulling } }
+ Node {
+ objectName: "threeDHub"+reel.index
+ eulerRotation.z: -(reel.index?app.cassetteRightAngle:app.cassetteLeftAngle)
+ Ring { radius: 32; hole: 13; depth: 6; z: 2; finish: PrincipledMaterial { baseColor: "#c9c4b5"; roughness: .5 } }
+ Repeater3D {
+ model: 6
+ Solid { required property int index; x: Math.cos(index*Math.PI/3)*11.5; y: Math.sin(index*Math.PI/3)*11.5; z: 2; size: Qt.vector3d(8,5,6); rounding: 1; eulerRotation.z: index*60; tint: "#c9c4b5" }
+ }
+ }
+ }
+ }
+ Solid { objectName: "threeDTapeRibbon"; size: Qt.vector3d(280,2.5,3); y: -52; z: 14; rounding: .3; tint: "#352017" }
+ Repeater3D {
+ model: 2
+ Node {
+ required property int index
+ x: index?143:-143; y: -48; z: 13
+ Ring { radius: 10; hole: 3; depth: 7; finish: rubber }
+ Ring { radius: 3; hole: .5; depth: 8; finish: metal }
+ }
+ }
+ Solid { size: Qt.vector3d(33,16,7); y: -83; z: 15; rounding: 3; finish: metal }
+ Repeater3D {
+ model: 8
+ Solid { required property int index; x: (index<4?-1:1)*(123+(index%4)*8); y: -73; z: 17; size: Qt.vector3d(2,20,1); rounding: .5; tint: Qt.darker(app.cassetteShell,1.3) }
+ }
+ Solid { size: Qt.vector3d(5,93,11); y: 9; z: 15; rounding: 2; tint: app.cassetteShell }
+ Repeater3D {
+ model: 4
+ Node {
+ required property int index
+ x: (index%2?1:-1)*159; y: (index<2?1:-1)*94; z: 13
+ Ring { radius: 3.8; hole: .4; depth: 2; finish: metal }
+ Solid { size: Qt.vector3d(5,1,1); z: 1.2; rounding: .2; tint: "#202428" }
+ }
+ }
+ }
+ }
+ Node {
+ objectName: "threeDOutgoingMedium"
+ visible: app.outgoingOpacity>0
+ x: app.outgoingOffset*.86; opacity: app.outgoingOpacity
+ Ring { visible: !app.cassette; radius: 176; hole: app.vinyl?3.5:15; depth: 2.8; grooves: app.vinyl; z: 4; finish: app.vinyl?blackVinyl:metal }
+ Ring { visible: !app.cassette; radius: app.vinyl?62:169; hole: app.vinyl?3.5:32; depth: .25; z: 5.6; eulerRotation.z: -app.outgoingAngle; finish: PrincipledMaterial { baseColorMap: oldCover; roughness: .85 } }
+ Solid { visible: app.cassette; size: Qt.vector3d(346,214,15); rounding: 12; z: 6; tint: app.cassetteShell }
+ }
+ Node {
+ id: lidPivot
+ visible: !app.vinyl
+ y: app.cassette?108:194; z: 18
+ eulerRotation.x: -app.lidOpen*40
+ Solid {
+ objectName: "threeDLid"
+ castsShadows: false; receivesShadows: false
+ y: app.cassette?-112.5:-194
+ size: app.cassette?Qt.vector3d(356,225,2):Qt.vector3d(388,388,2)
+ rounding: app.cassette?12:194
+ finish: PrincipledMaterial { baseColor: view.glassTint; alphaMode: PrincipledMaterial.Blend; opacity: .065; metalness: .1; roughness: .16; cullMode: Material.NoCulling }
+ }
+ }
+ Repeater3D {
+ model: 2
+ Model { required property int index; source: "#Cylinder"; x: (index?1:-1)*(app.cassette?124:app.vinyl?140:48); y: app.cassette?109:app.vinyl?207:191; z: 14; eulerRotation.z: 90; scale: Qt.vector3d(.065,.24,.065); materials: metal }
+ }
+ Model { visible: !app.cassette; source: "#Cylinder"; z: 9; eulerRotation.x: 90; scale: app.vinyl?Qt.vector3d(.07,.16,.07):Qt.vector3d(.39,.055,.39); materials: metal }
+ Node {
+ visible: app.vinyl && !!app.tonearm
+ objectName: "threeDTonearm"
+ x: 135.88; y: 103.2; z: 11
+ Model { source: "#Cylinder"; eulerRotation.x: 90; scale: Qt.vector3d(.25,.12,.25); materials: rubber }
+ Ring { objectName: "threeDBearingHousing"; radius: 15; hole: 9; depth: 10; z: 8; eulerRotation.x: 90; finish: steel }
+ Model { source: "#Cylinder"; z: 8; eulerRotation.x: 90; scale: Qt.vector3d(.16,.09,.16); materials: gold }
+ Node {
+ id: armPivot
+ eulerRotation.z: app.tonearm?-app.tonearm.armAngle:4
+ eulerRotation.x: app.tonearm?-6*(1-app.tonearm.lowered):0
+ z: 12
+ Model { objectName: "threeDArmTube"; source: "#Cylinder"; y: -79; scale: Qt.vector3d(.045,1.58,.045); materials: gold }
+ Model { objectName: "threeDCounterweight"; source: "#Cylinder"; y: 23; scale: Qt.vector3d(.23,.24,.23); materials: steel }
+ Model { source: "#Cylinder"; y: 10; scale: Qt.vector3d(.10,.06,.10); materials: rubber }
+ Model { source: "#Cylinder"; y: 34; scale: Qt.vector3d(.24,.03,.24); materials: rubber }
+ Solid { objectName: "threeDFingerLift"; x: 9; y: -158; z: 6; size: Qt.vector3d(14,3,2); rounding: 1; eulerRotation.y: -18; finish: steel }
+ Repeater3D {
+ model: 2
+ Model { required property int index; source: "#Cylinder"; x: index?3:-3; y: -160; z: 5; eulerRotation.x: 90; scale: Qt.vector3d(.022,.025,.022); materials: metal }
+ }
+ Solid { objectName: "threeDCartridge"; y: -165; z: -2; size: Qt.vector3d(12,21,11); rounding: 3; tint: Qt.tint(app.surface,Qt.alpha("#c6a25a",.15)) }
+ Solid { y: -167; z: 4; size: Qt.vector3d(6,10,1); rounding: 1; finish: gold }
+ Solid { y: -169.42; z: -7; size: Qt.vector3d(3,6,5); rounding: .5; tint: "#171b1d" }
+ Model { objectName: "threeDStylus"; source: "#Cone"; y: -169.42; z: -13; eulerRotation.x: -90; scale: Qt.vector3d(.015,.09,.015); materials: metal }
+ }
+ }
+ Node {
+ visible: app.packageOpacity>0; opacity: app.packageOpacity
+ x: 126; y: -107; z: 28; eulerRotation.z: -12
+ Solid { objectName: "threeDAlbumCase"; size: Qt.vector3d(130,130,5); rounding: 3; finish: metal }
+ Solid { size: Qt.vector3d(120,122,.5); x: 3; z: 3; rounding: 1; finish: label }
+ }
+ Model {
+ visible: app.deckPlayer.count>0
+ geometry: WaveGeometry { progress: view.progress; phase: app.wavePhase; amplitude: app.deckPlayer.playing?2.4:0; linear: app.cassette }
+ materials: PrincipledMaterial { baseColor: app.accent; lighting: PrincipledMaterial.NoLighting; cullMode: Material.NoCulling }
+ }
+ }
+ // Pointer math intersects the same plane as the physical controls. It never
+ // installs a Qt Quick 3D transform on the shared 2D control tree.
+ function projectSurface(x,y) {
+ const p=mapFrom3DScene(assembly.mapPositionToScene(Qt.vector3d(x-265,294-y,.5)))
+ return Qt.point(p.x,p.y)
+ }
+ function unprojectSurface(x,y) {
+ const a=assembly.mapPositionFromScene(mapTo3DScene(Qt.vector3d(x,y,0)))
+ const b=assembly.mapPositionFromScene(mapTo3DScene(Qt.vector3d(x,y,1000)))
+ const t=(.5-a.z)/(b.z-a.z)
+ return Qt.point(a.x+(b.x-a.x)*t+265,294-a.y-(b.y-a.y)*t)
+ }
+ function lidBounds() {
+ let left=width,top=height,right=0,bottom=0
+ for(let i=0;i<32;++i){const a=i*Math.PI/16;const point=app.cassette?Qt.vector3d(i%2?178:-178,i<16?0:-225,0):Qt.vector3d(194*Math.cos(a),-194+194*Math.sin(a),0);const p=mapFrom3DScene(lidPivot.mapPositionToScene(point));left=Math.min(left,p.x);right=Math.max(right,p.x);top=Math.min(top,p.y);bottom=Math.max(bottom,p.y)}
+ return Qt.rect(left,top,right-left,bottom-top)
+ }
+ MouseArea {
+ id: pointer
+ objectName: "threeDPointer"
+ property var hoveredControl: null
+ property bool hintDismissed: false
+ property point pressPoint
+ property bool windowDragAllowed: false
+ property string hint: ""
+ function updateHint(x,y) {
+ const point=view.unprojectSurface(x,y)
+ const target=view.app.controlAt3DPoint(point)
+ if(target!==hoveredControl)hintDismissed=false
+ hoveredControl=target
+ if(!target){hint="";return}
+ if(view.app.vinyl && view.app.tonearm && target===view.app.tonearm.pointerInput) {
+ hint="Drag to seek · Shift for precision"
+ } else {
+ const p=view.app.pointerEvent(target,point,0)
+ let fraction
+ if(view.app.cassette)fraction=target.fraction(p.x)
+ else { let a=Math.atan2(p.y-220,p.x-220)+Math.PI/2;if(a<0)a+=2*Math.PI;fraction=a/(2*Math.PI) }
+ const track=view.app.recordTarget(fraction)
+ hint=track?track.track.title+" · "+view.app.time(track.position):"Seek to "+view.app.time(fraction*view.app.deckPlayer.duration)
+ }
+ }
+ anchors.fill: parent; hoverEnabled: true; preventStealing: true; acceptedButtons: Qt.AllButtons
+ onPressed: mouse => { hintDismissed=true;pressPoint=Qt.point(mouse.x,mouse.y);if(mouse.button===Qt.LeftButton)view.app.begin3DPointer(view.unprojectSurface(mouse.x,mouse.y),mouse.modifiers);windowDragAllowed=mouse.button===Qt.LeftButton && !view.app.threeDPointer }
+ onPositionChanged: mouse => {
+ if(pressed) {
+ view.app.move3DPointer(view.unprojectSurface(mouse.x,mouse.y),mouse.modifiers)
+ if(windowDragAllowed && !view.app.threeDPointer && (pressedButtons & Qt.LeftButton) && Math.hypot(mouse.x-pressPoint.x,mouse.y-pressPoint.y)>12)view.app.startSystemMove()
+ } else { updateHint(mouse.x,mouse.y);if(!hoveredControl)view.tilt(Qt.point(mouse.x,mouse.y)) }
+ }
+ onReleased: view.app.end3DPointer()
+ onCanceled: view.app.cancel3DPointer()
+ onClicked: mouse => { if(mouse.button===Qt.RightButton)view.app.openSettings() }
+ onDoubleClicked: mouse => { if(mouse.button===Qt.LeftButton && !view.app.controlAt3DPoint(view.unprojectSurface(mouse.x,mouse.y)))view.app.flipDisc() }
+ onExited: { hoveredControl=null;hint="";hintDismissed=false;if(!pressed){view.pitchOffset=0;view.yawOffset=0} }
+ onWheel: wheel => { if(!view.app.menuOpen)view.app.deckPlayer.volume=Math.max(0,Math.min(1,view.app.deckPlayer.volume+wheel.angleDelta.y/2400));wheel.accepted=true }
+ cursorShape: view.app.threeDGesture?Qt.ClosedHandCursor:hoveredControl?Qt.PointingHandCursor:Qt.ArrowCursor
+ }
+ SpunToolTip {
+ objectName: "threeDToolTip"
+ parent: pointer
+ x: Math.max(8,Math.min(view.width-width-8,pointer.mouseX-width/2))
+ y: Math.max(8,pointer.mouseY-height-18)
+ visible: pointer.containsMouse && !!pointer.hoveredControl && !pointer.hintDismissed && !pointer.pressed && !view.app.menuOpen && !view.app.swapRunning && view.app.visible
+ text: pointer.hint
+ timeout: 2500
+ onClosed: pointer.hintDismissed=true
+ }
+}
diff --git a/qml/SeekSlider.qml b/qml/SeekSlider.qml
index 86735c5..1572d1f 100644
--- a/qml/SeekSlider.qml
+++ b/qml/SeekSlider.qml
@@ -4,6 +4,7 @@ import Spun 1.0
SpunSlider {
id: control
required property var app
+ property alias pointerInput: seekPointer
enabled: visible && !app.swapRunning && app.deckPlayer.duration > 0 && (!app.useCider || app.ciderService.canSeek)
property bool scrubbing: false
property real previewValue: 0
@@ -12,7 +13,7 @@ SpunSlider {
property double lastMove: 0
property string seekTrack: ""
previewing: scrubbing
- value: scrubbing ? previewValue : app.progress
+ value: scrubbing ? previewValue : app.trackVisualProgress
function cancelSeek() {
scrubbing=false; windDirection=0
if(app.activeSeekControl===control)app.activeSeekControl=null
@@ -28,7 +29,7 @@ SpunSlider {
anchors.fill: parent; preventStealing: true; acceptedButtons: Qt.LeftButton
cursorShape: Qt.PointingHandCursor
function fraction(x) { return Math.max(0, Math.min(1,(x-control.leftPadding)/(control.availableWidth-control.handle.width))) }
- onPressed: mouse => {
+ function beginPointer(mouse) {
control.forceActiveFocus(Qt.MouseFocusReason)
control.seekTrack=control.app.cassetteTrackIdentity
control.previewValue=(mouse.modifiers & Qt.ShiftModifier)?control.app.progress:fraction(mouse.x)
@@ -36,21 +37,25 @@ SpunSlider {
control.scrubbing=true;control.app.activeSeekControl=control
if(control.app.cassette)tapeSound.transport()
}
- onPositionChanged: mouse => {
- if(!pressed || !control.scrubbing)return
+ function movePointer(mouse) {
+ if(!control.scrubbing)return
const delta=(mouse.x-control.lastPointer)/(control.availableWidth-control.handle.width)
control.previewValue=Math.max(0,Math.min(1,control.previewValue+delta*((mouse.modifiers & Qt.ShiftModifier)?.1:1)))
control.lastPointer=mouse.x
if(delta!==0){control.windDirection=Math.sign(delta);control.lastMove=Date.now()}
}
- onReleased: {
+ function endPointer() {
if(!control.scrubbing)return
const valid=control.enabled && control.seekTrack===control.app.cassetteTrackIdentity
const position=control.previewValue
control.cancelSeek()
if(valid){control.app.deckPlayer.seek(position*control.app.deckPlayer.duration);if(control.app.cassette)tapeSound.transport()}
}
- onCanceled: control.cancelSeek()
+ function cancelPointer() { control.cancelSeek() }
+ onPressed: mouse => beginPointer(mouse)
+ onPositionChanged: mouse => { if(pressed)movePointer(mouse) }
+ onReleased: endPointer()
+ onCanceled: cancelPointer()
onWheel: wheel => wheel.accepted=false
}
Keys.onShortcutOverride: event => { if(event.key===Qt.Key_Escape && scrubbing)event.accepted=true }
diff --git a/qml/Tonearm.qml b/qml/Tonearm.qml
index 8ce2160..8c54617 100644
--- a/qml/Tonearm.qml
+++ b/qml/Tonearm.qml
@@ -5,8 +5,9 @@ Item {
id: arm
objectName: "vinylTonearm"
required property var app
+ property alias pointerInput: needleHit
readonly property bool motion: app.animate && visible && app.visible && native.exposed
- readonly property bool engaged: visible && app.deckPlayer.count > 0 && ((app.deckPlayer.playing && !app.swapRunning) || landing)
+ readonly property bool engaged: visible && app.deckPlayer.count > 0 && ((app.deckPlayer.playing && !app.swapRunning) || landing || app.seekPreviewActive)
readonly property bool canSeek: visible && app.deckPlayer.duration > 0 && (!app.useCider || (app.ciderService.canSeek && !app.listeningService.busy))
property bool dragging: false
property real dragAngle: -4
@@ -19,10 +20,10 @@ Item {
property real landingProgress: 0
readonly property real previewProgress: Math.max(0, Math.min(1, (rawAngle - 6) / 20))
property real lowered: dragging ? .12 : engaged ? 1 : 0
- property real groove: landing ? landingProgress : Math.max(0, Math.min(1, app.recordProgress))
+ property real groove: Math.max(0, Math.min(1, app.recordVisualProgress))
property real armAngle: dragging ? dragAngle : engaged ? 6 + 20 * groove : -4
Behavior on armAngle {
- enabled: arm.motion && !arm.dragging
+ enabled: arm.motion && !arm.app.seekPreviewActive
SpringAnimation { id: angleSpring; spring: 6; damping: .55; epsilon: .01 }
}
function cancelDrag(resume) {
@@ -54,6 +55,11 @@ Item {
Timer { id: landingTimeout; interval: 1200; onTriggered: arm.landing = false }
Connections {
target: arm.app
+ function onSeekPreviewActiveChanged() {
+ if (arm.app.seekPreviewActive && !arm.dragging) { arm.landing=false; landingTimeout.stop() }
+ }
+ function onThreeDRequestedChanged() { arm.cancelDrag(true) }
+ function onVisibleChanged() { if(!arm.app.visible)arm.cancelDrag(true) }
function onCassetteTrackIdentityChanged() { arm.cancelDrag(false); arm.landing = false }
function onRecordKeyChanged() { arm.cancelDrag(true); arm.landing = false }
}
@@ -75,7 +81,7 @@ Item {
SpunToolTip {
objectName: "needleToolTip"
parent: arm; x: 184; y: 60
- visible: arm.canSeek && arm.app.visible && (arm.dragging || (!needleHit.hintDismissed && needleHit.hoveringNeedle) || (needleHit.activeFocus && !needleHit.pointerFocus))
+ visible: !arm.app.threeDActive && arm.canSeek && arm.app.visible && (arm.dragging || (!needleHit.hintDismissed && needleHit.hoveringNeedle) || (needleHit.activeFocus && !needleHit.pointerFocus))
delay: arm.dragging ? 0 : 650
text: {
const target = arm.app.recordTarget(arm.previewProgress)
@@ -189,13 +195,13 @@ Item {
return Qt.point(378 - 197 * Math.sin(angle), 100 + 197 * Math.cos(angle))
}
containmentMask: QtObject {
- function contains(point) { return Math.hypot(point.x - needleHit.tip.x, point.y - needleHit.tip.y) <= 27 }
+ function contains(point: point): bool { return Math.hypot(point.x - needleHit.tip.x, point.y - needleHit.tip.y) <= 27 }
}
cursorShape: arm.dragging ? Qt.ClosedHandCursor : Qt.OpenHandCursor
Accessible.role: Accessible.Slider
Accessible.name: "Needle position"
Accessible.description: "Drag onto the grooves to seek and play. Hold Shift for precision. Arrow keys seek; Enter starts playback; Escape cancels dragging."
- onPressed: mouse => {
+ function beginPointer(mouse) {
if (Math.hypot(mouse.x - tip.x, mouse.y - tip.y) > 27) { mouse.accepted = false; return }
pointerFocus = true
forceActiveFocus()
@@ -206,8 +212,8 @@ Item {
arm.dragging = true; arm.landing = false; landingTimeout.stop()
if (arm.wasPlaying) arm.app.deckPlayer.pause()
}
- onPositionChanged: mouse => {
- if (!pressed || !arm.dragging) return
+ function movePointer(mouse) {
+ if (!arm.dragging) return
const dx = mouse.x - 378, dy = mouse.y - 100
arm.pointerDistance = Math.hypot(dx, dy)
const pointer = Math.atan2(-dx, dy) * 180 / Math.PI
@@ -217,8 +223,12 @@ Item {
arm.lastPointerAngle=pointer
arm.dragAngle = Math.max(-8, Math.min(38, arm.rawAngle))
}
- onReleased: { hintDismissed = true; arm.dropNeedle() }
- onCanceled: { hintDismissed = true; arm.cancelDrag(true) }
+ function endPointer() { hintDismissed = true; arm.dropNeedle() }
+ function cancelPointer() { hintDismissed = true; arm.cancelDrag(true) }
+ onPressed: mouse => beginPointer(mouse)
+ onPositionChanged: mouse => { if(pressed)movePointer(mouse) }
+ onReleased: endPointer()
+ onCanceled: cancelPointer()
onWheel: wheel => { wheel.accepted = false }
Keys.onShortcutOverride: event => { if ([Qt.Key_Escape,Qt.Key_Left,Qt.Key_Right,Qt.Key_Return,Qt.Key_Enter].includes(event.key)) event.accepted = true }
Keys.onEscapePressed: arm.cancelDrag(true)
diff --git a/scripts/test-3d.sh b/scripts/test-3d.sh
new file mode 100755
index 0000000..af77715
--- /dev/null
+++ b/scripts/test-3d.sh
@@ -0,0 +1,41 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+# The default checks use CPU rendering and do not create visible windows.
+# Set SPUN_TEST_RENDERER=native only in a separate test desktop/session.
+# Fixtures never connect to the user's Cider account.
+cd "$(dirname "$0")/.."
+renderer=${SPUN_TEST_RENDERER:-cpu}
+if [[ $renderer == cpu ]]; then
+ if [[ -z ${DISPLAY:-} ]]; then
+ echo 'CPU 3D rendering needs an existing X display socket for its software GL context.' >&2
+ exit 2
+ fi
+ export QT_QPA_PLATFORM=offscreen QT_QUICK_BACKEND=rhi QSG_RHI_BACKEND=opengl QSG_RENDER_LOOP=basic
+ export LIBGL_ALWAYS_SOFTWARE=1 __GLX_VENDOR_LIBRARY_NAME=mesa LP_NUM_THREADS=2
+ export QT_QPA_PLATFORMTHEME=
+ suites=(artwork 3d-lighting media-ui)
+ echo 'Running focused offscreen CPU checks. Native lifecycle tests require SPUN_TEST_RENDERER=native.'
+elif [[ $renderer == native ]]; then
+ if [[ ${QT_QUICK_BACKEND:-} == software || ${QT_QPA_PLATFORM:-wayland} == offscreen || ( -z ${WAYLAND_DISPLAY:-} && -z ${DISPLAY:-} ) ]]; then
+ echo 'Native lifecycle tests require a separate Wayland or X11 test session.' >&2
+ exit 2
+ fi
+ suites=(artwork 3d-lighting 3d-ui 3d-library media-ui)
+else
+ echo 'SPUN_TEST_RENDERER must be cpu or native.' >&2
+ exit 2
+fi
+build_dir=${SPUN_BUILD_DIR:-build}
+report_dir=${SPUN_TEST_OUTPUT:-/tmp/spun-3d-tests}
+mkdir -p "$report_dir"
+if [[ ! -x "$build_dir/spun-geometry-test" || ! -x "$build_dir/spun-diagnostics" ]]; then
+ echo 'Build with SPUN_ENABLE_3D=ON and BUILD_TESTING=ON first.' >&2
+ exit 2
+fi
+QT_QPA_PLATFORM=offscreen QT_QPA_PLATFORMTHEME= "$build_dir/spun-geometry-test" 2>&1 | tee "$report_dir/geometry.log"
+for suite in "${suites[@]}"; do
+ suite_env=()
+ if [[ $renderer == cpu && $suite == media-ui ]]; then suite_env=(env QT_QUICK_BACKEND=software QSG_RENDER_LOOP=basic); fi
+ timeout "${SPUN_TEST_TIMEOUT:-240}s" nice -n 10 "${suite_env[@]}" "$build_dir/spun" "--test-$suite" --capture-dir "$report_dir/$suite" 2>&1 | tee "$report_dir/$suite.log"
+done
diff --git a/src/artworktest.cpp b/src/artworktest.cpp
new file mode 100644
index 0000000..5744023
--- /dev/null
+++ b/src/artworktest.cpp
@@ -0,0 +1,245 @@
+#include "artworktest.h"
+#include "player.h"
+#include "cider.h"
+#include "disc.h"
+#include <QQmlContext>
+#include <QQuickWindow>
+#include <QQuickItem>
+#include <QTest>
+#include <QBuffer>
+#include <QTcpServer>
+#include <QTcpSocket>
+#include <QPointer>
+#include <QDir>
+#include <QFile>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <functional>
+#include <iostream>
+#ifdef SPUN_WITH_3D
+#include "mediageometry.h"
+#endif
+
+// Connection availability is fixed; metadata and image requests use Cider's
+// production implementation without connecting to a desktop account.
+class ArtworkCider : public Cider {
+ Q_OBJECT
+ Q_PROPERTY(int count READ fixtureCount NOTIFY trackChanged)
+ Q_PROPERTY(QString trackKey READ fixtureKey NOTIFY trackChanged)
+public:
+ ArtworkCider(const QString &connection={},const QUrl &base=QUrl("http://localhost:10767")):Cider(false,connection,base){}
+ int fixtureCount() const { return title()=="Cider"?0:1; }
+ QString fixtureKey() const { return identity; }
+ QString identity;
+ void track(const QString &id,const QUrl &url,const QString &album="Remote album") {
+ identity=id;
+ const QVariantMap changes{{"Metadata",QVariantMap{
+ {"mpris:trackid",id},{"xesam:title",id},{"xesam:artist",QStringList{"Remote artist"}},
+ {"xesam:album",album},{"mpris:artUrl",url.toString()},{"mpris:length",32000000LL}}}};
+ QMetaObject::invokeMethod(this,"propertiesChanged",Qt::DirectConnection,
+ Q_ARG(QString,QString("org.mpris.MediaPlayer2.Player")),Q_ARG(QVariantMap,changes),Q_ARG(QStringList,QStringList{}));
+ }
+};
+
+int exerciseArtwork(Player &player,QQuickWindow *window,const QString &temp,const QString &captures) {
+ int checks=0,failures=0;QString context;
+ const auto check=[&](bool ok,const char *name){++checks;if(!ok)++failures;std::cout<<(ok?"PASS ":"FAIL ")<<context.toStdString()<<": "<<name<<std::endl;return ok;};
+ const auto wait=[](const std::function<bool()> &f,int timeout=2500){QElapsedTimer t;t.start();while(!f()&&t.elapsed()<timeout)QTest::qWait(20);return f();};
+ auto *presenter=qobject_cast<DiscPresentation*>(qmlContext(window)->contextProperty("presentation").value<QObject*>());
+ if(!presenter)return 2;
+ ArtworkCider remote;const auto originalSource=window->property("ciderService");
+ window->setProperty("ciderService",QVariant::fromValue(static_cast<QObject*>(&remote)));
+ player.setMotion(false);player.setVolume(0);player.demo();player.pause();window->setProperty("useCider",false);
+ if(!check(wait([&]{return player.count()>0&&!player.busy()&&!player.artworkLoading();}),"local fixture imports"))return 2;
+ player.pause();
+ check(Disc::placeholderArt()!=Disc::fallbackArt(512),"missing-art placeholder is distinct from demo artwork");
+ QImage red(64,64,QImage::Format_RGBA8888),blue=red,green=red;
+ red.fill(Qt::red);blue.fill(Qt::blue);green.fill(Qt::green);
+ red.save(temp+"/art-red.png");blue.save(temp+"/art-blue.png");green.save(temp+"/art-green.png");
+ const auto secondTrack=temp+"/second-local.flac";
+ if(!QFile::copy(player.currentUrl().toLocalFile(),secondTrack))return 2;
+ player.addUrls({QUrl::fromLocalFile(secondTrack)},false);
+ if(!check(wait([&]{return player.count()==2&&!player.busy();}),"second local track imports"))return 2;
+ player.select(1,false);player.setCover(QUrl::fromLocalFile(temp+"/art-blue.png"));
+ if(!wait([&]{return !player.artworkLoading();}))return 2;
+ player.select(0,false);
+ const auto colorIs=[](const QImage &image,QColor c){return !image.isNull()&&image.pixelColor(0,0)==c;};
+ const auto publish=[&](const QString &id,const QString &file,const QString &album="Remote album") {remote.track(id,file.isEmpty()?QUrl():QUrl::fromLocalFile(file),album);};
+ const auto inspect=[&](QColor color,bool threeD) {
+ if(!wait([&]{return colorIs(presenter->artwork(),color);}))return false;
+ if(!threeD){auto *disc=window->findChild<Disc*>("discFace");return disc&&colorIs(disc->artwork(),color);}
+#ifdef SPUN_WITH_3D
+ auto *view=window->findChild<QObject*>("player3DView");
+ if(!view)return false;
+ auto *cover=view->findChild<CoverTexture*>("currentCoverTexture");
+ auto *paper=view->findChild<CoverTexture*>("cassetteCoverTexture");
+ if(!cover||!paper)return false;
+ const auto pixels=cover->textureData();
+ const auto label=paper->textureData();
+ if(pixels.isEmpty()||label.isEmpty())return false;
+ QImage image(reinterpret_cast<const uchar*>(pixels.constData()),512,512,QImage::Format_RGBA8888);
+ QImage paperImage(reinterpret_cast<const uchar*>(label.constData()),1024,170,QImage::Format_RGBA8888);
+ return image.pixelColor(200,200)==color&&paperImage.pixelColor(60,60)==color;
+#else
+ return false;
+#endif
+ };
+ QList<bool> modes{false};if(qmlContext(window)->contextProperty("supports3D").toBool())modes.append(true);
+ for(bool threeD:modes)for(const QString &medium:{QString("cd"),QString("vinyl"),QString("cassette")}) {
+ context=medium+(threeD?" 3D":" 2D");player.setMedium(medium);player.setThreeD(threeD);QTest::qWait(80);
+ window->setProperty("useCider",false);player.setCover(QUrl::fromLocalFile(temp+"/art-green.png"));
+ check(wait([&]{return !player.artworkLoading();})&&inspect(Qt::green,threeD),"local artwork reaches the active medium");
+ player.select(1,false);check(inspect(Qt::blue,threeD),"selecting the next local song updates its cover");
+ player.select(0,false);check(inspect(Qt::green,threeD),"returning to the previous local song restores its cover");
+ publish("remote-red",temp+"/art-red.png");window->setProperty("useCider",true);
+ check(inspect(Qt::red,threeD),"switching to Cider replaces local artwork");
+ publish("remote-blue",temp+"/art-blue.png");check(inspect(Qt::blue,threeD),"same-album track change updates artwork");
+ const auto reused=temp+"/reused.png";red.save(reused);publish("reused-one",reused);check(inspect(Qt::red,threeD),"first reusable URL loads");
+ blue.save(reused);publish("reused-two",reused);check(inspect(Qt::blue,threeD),"new track reloads artwork when the URL is reused");
+ publish("missing",{});QTest::qWait(50);check(presenter->artwork().isNull(),"missing artwork never retains the previous song cover");
+ publish("rapid-red",temp+"/art-red.png");publish("rapid-blue",temp+"/art-blue.png");publish("rapid-green",temp+"/art-green.png");
+ check(inspect(Qt::green,threeD),"rapid track changes keep only the latest decoded image");
+ window->setProperty("useCider",false);check(inspect(Qt::green,threeD),"returning to Local restores its current artwork");
+ publish("no-remote-cover",{});window->setProperty("useCider",true);QTest::qWait(50);
+ check(presenter->artwork().isNull(),"source switch without artwork does not borrow Local's cover");
+ publish("capture-blue",temp+"/art-blue.png");check(inspect(Qt::blue,threeD),"artwork recovers after an empty result");
+ if(!captures.isEmpty()){QDir().mkpath(captures);window->grabWindow().save(captures+"/"+medium+(threeD?"-3d":"-2d")+".png");}
+ }
+#ifdef SPUN_WITH_3D
+ // Inspect the rendered label as well as its CPU-side pixel buffer. A stale
+ // scene-graph texture can have correct textureData() and still show an old cover.
+ const auto renderedCover=[&](QColor expected,const QString &name) {
+ auto *view=window->findChild<QQuickItem*>("player3DView");
+ if(!view)return false;
+ const bool tape=player.medium()=="cassette";
+ QVariant projected;
+ QMetaObject::invokeMethod(view,"projectSurface",Q_RETURN_ARG(QVariant,projected),
+ Q_ARG(QVariant,tape?128.:player.medium()=="cd"?345.:285.),Q_ARG(QVariant,tape?203.:294.));
+ const QPointF position=view->mapToScene(projected.toPointF());
+ const QImage frame=window->grabWindow();
+ if(frame.isNull())return false;
+ const double scale=frame.width()/double(window->width());
+ const QPoint center=(position*scale).toPoint();
+ int matches=0,total=0;
+ for(int y=-4;y<=4;++y)for(int x=-4;x<=4;++x) {
+ const QPoint p=center+QPoint(x,y);if(!frame.rect().contains(p))continue;
+ const QColor actual=frame.pixelColor(p);++total;
+ const int channel=expected.red()?actual.red():expected.green()?actual.green():actual.blue();
+ const int otherA=expected.red()?actual.green():actual.red();
+ const int otherB=expected.blue()?actual.green():actual.blue();
+ if(actual.alpha()>128&&channel>40&&channel>otherA*1.4&&channel>otherB*1.4)++matches;
+ }
+ if(!captures.isEmpty()){QDir().mkpath(captures);frame.save(captures+"/render-"+name+".png");}
+ return total>0&&matches>total*.7;
+ };
+ for(const QString &medium:{QString("vinyl"),QString("cd"),QString("cassette")}) {
+ context=medium+" rendered artwork";
+ player.setThreeD(false);player.setMedium(medium);player.setMotion(false);
+ publish("render-start",temp+"/art-red.png","First render album");
+ check(wait([&]{return colorIs(presenter->artwork(),Qt::red);}),"first render cover loads");
+ player.setThreeD(true);QTest::qWait(300);
+ QPointer<QObject> originalView=window->findChild<QObject*>("player3DView");
+ check(renderedCover(Qt::red,medium+"-initial"),"initial cover is visible on the 3D medium");
+ publish("render-next",temp+"/art-blue.png","First render album");
+ check(inspect(Qt::blue,true),"next cover reaches texture data without switching modes");QTest::qWait(200);
+ check(renderedCover(Qt::blue,medium+"-next"),"next song changes the visible cover without switching modes");
+ player.setMotion(true);
+ publish("render-album",temp+"/art-green.png","Second render album");
+ check(inspect(Qt::green,true),"album change reaches texture data with animations enabled");QTest::qWait(1200);
+ check(renderedCover(Qt::green,medium+"-album"),"album animation ends with the new cover visible");
+ check(originalView&&originalView==window->findChild<QObject*>("player3DView"),"artwork refresh preserves the active 3D scene");
+ player.setMotion(false);
+ }
+ for(const QString &origin:{QString("cd"),QString("cassette")}) {
+ context=origin+" to vinyl";
+ player.setMedium(origin);publish("switch-start",temp+"/art-red.png");
+ check(inspect(Qt::red,true),"cover loads before switching medium");
+ player.setMedium("vinyl");QTest::qWait(250);
+ check(renderedCover(Qt::red,origin+"-to-vinyl"),"switching to vinyl displays the current artwork");
+ publish("switch-next",temp+"/art-blue.png");
+ check(inspect(Qt::blue,true),"next track loads after switching to vinyl");QTest::qWait(200);
+ check(renderedCover(Qt::blue,origin+"-to-vinyl-next"),"vinyl keeps updating after the mode switch");
+ }
+#endif
+ context="album animation";
+ DiscPresentation staged;int swaps=0;
+ QObject::connect(&staged,&DiscPresentation::swapRequested,&staged,[&]{++swaps;});
+ staged.present(red,"album-one",true);staged.present({},"album-two",true);
+ check(staged.artwork().isNull()&&staged.outgoing()==red&&swaps==1,"loading cover retains the old image only as the outgoing disc");
+ staged.present(blue,"album-two",true);
+ check(staged.artwork()==blue&&staged.outgoing()==red&&swaps==1,"arriving artwork updates without replaying the album swap");
+ staged.present(green,"album-two",true);
+ check(staged.artwork()==green&&swaps==1,"same-album cover changes never exchange the medium");
+ staged.clear();check(staged.artwork().isNull()&&staged.outgoing().isNull(),"changing source clears both presentation images");
+ // Serve a deliberately late old image, followed by an immediate new one.
+ context="delayed network";QTcpServer server;QByteArray redBytes,blueBytes;
+ QBuffer rb(&redBytes),bb(&blueBytes);rb.open(QIODevice::WriteOnly);bb.open(QIODevice::WriteOnly);red.save(&rb,"PNG");blue.save(&bb,"PNG");
+ check(server.listen(QHostAddress::LocalHost),"local artwork fixture listens");
+ QJsonObject apiCurrent;int apiDelay=0,apiRequests=0,apiStatus=200;
+ QObject::connect(&server,&QTcpServer::newConnection,&server,[&]{
+ while(auto *socket=server.nextPendingConnection()){
+ QObject::connect(socket,&QTcpSocket::disconnected,socket,&QObject::deleteLater);
+ QObject::connect(socket,&QTcpSocket::readyRead,socket,[&,socket]{
+ const auto request=socket->readAll();if(socket->property("sent").toBool())return;socket->setProperty("sent",true);
+ const bool api=request.contains("/api/v2/playback/now-playing");
+ const bool slow=request.contains("/slow");QPointer<QTcpSocket> guarded=socket;
+ if(api)++apiRequests;
+ const QByteArray bytes=api?QJsonDocument(QJsonObject{{"data",apiCurrent}}).toJson(QJsonDocument::Compact):slow?redBytes:blueBytes;
+ const int status=api?apiStatus:200;
+ QTimer::singleShot(api?apiDelay:slow?450:0,&server,[guarded,bytes,status]{if(!guarded)return;guarded->write("HTTP/1.1 "+QByteArray::number(status)+" Reply\r\nContent-Type: application/octet-stream\r\nContent-Length: "+QByteArray::number(bytes.size())+"\r\nConnection: close\r\n\r\n"+bytes);guarded->disconnectFromHost();});
+ });
+ }
+ });
+ const QString base="http://127.0.0.1:"+QString::number(server.serverPort());
+ remote.track("slow",QUrl(base+"/slow"));QTest::qWait(50);remote.track("fast",QUrl(base+"/fast"));
+ check(wait([&]{return colorIs(remote.artwork(),Qt::blue);}),"new network cover wins over an older request");QTest::qWait(500);
+ check(colorIs(remote.artwork(),Qt::blue)&&colorIs(presenter->artwork(),Qt::blue),"late response cannot replace the current cover");
+ remote.track("slow-clear",QUrl(base+"/slow"));QTest::qWait(30);remote.track("empty",{});QTest::qWait(500);
+ check(remote.artwork().isNull()&&presenter->artwork().isNull(),"clearing artwork cancels pending network results");
+ const auto connection=temp+"/artwork-api.json";
+ {QFile file(connection);if(!file.open(QIODevice::WriteOnly))return 2;file.write("{\"token\":\"isolated-test-token\"}");}
+ ArtworkCider paired(connection,QUrl(base));
+ window->setProperty("ciderService",QVariant::fromValue(static_cast<QObject*>(&paired)));
+ paired.setLiveVisible(false);
+ const auto current=[&](const QString &id,const QString &cover){return QJsonObject{
+ {"name",id},{"albumName","Album"},{"artistName","Remote artist"},
+ {"playParams",QJsonObject{{"id","library-"+id},{"catalogId",id}}},
+ {"artwork",QJsonObject{{"url",cover}}}};};
+ for(bool threeD:modes)for(const QString &medium:{QString("cd"),QString("vinyl"),QString("cassette")}) {
+ context=medium+(threeD?" paired 3D":" paired 2D");player.setMedium(medium);player.setThreeD(threeD);QTest::qWait(60);
+ apiCurrent=current("album-a",base+"/slow");paired.track("album-a",QUrl(base+"/slow"),"Album A");
+ check(inspect(Qt::red,threeD),"paired artwork uses the API's matching catalog identity");
+ const auto stableAlbum=paired.albumKey();
+ apiCurrent=current("album-a-next",base+"/fast");paired.track("album-a-next",QUrl(base+"/slow"),"Album A");
+ check(paired.albumKey()==stableAlbum,"starting a new cover request preserves the album identity");
+ check(inspect(Qt::blue,threeD)&&paired.albumKey()==stableAlbum,"finishing a same-album cover does not trigger another disc exchange");
+ apiCurrent=current("album-a",base+"/slow");
+ paired.track("album-b",QUrl(base+"/slow"),"Album B");QTest::qWait(120);
+ check(paired.artwork().isNull()&&presenter->artwork().isNull(),"new album with old desktop URL and old API item stays empty");
+ apiCurrent=current("album-b",base+"/fast");
+ check(inspect(Qt::blue,threeD),"retry accepts the new album cover once the API catches up");
+ paired.track("album-b",QUrl(base+"/slow?stale=1"),"Album B");
+ check(inspect(Qt::blue,threeD),"late desktop artwork cannot overwrite the identity-checked API cover");
+ apiCurrent=current("album-c",base+"/slow");paired.track("album-b",QUrl(base+"/slow?ahead=1"),"Album B");QTest::qWait(120);
+ check(presenter->artwork().isNull(),"API arriving before desktop track identity cannot show the next album early");
+ paired.track("album-c",QUrl(base+"/fast"),"Album C");
+ check(inspect(Qt::red,threeD),"desktop catching up resolves an API-first album change");
+ apiCurrent=current("album-old",base+"/slow");apiDelay=400;paired.track("album-old",QUrl(base+"/slow"));QTest::qWait(50);
+ apiDelay=0;apiCurrent=current("album-latest",base+"/fast");paired.track("album-latest",QUrl(base+"/slow"));
+ check(inspect(Qt::blue,threeD),"rapid album selection cancels the previous API lookup");QTest::qWait(450);
+ check(inspect(Qt::blue,threeD),"late album lookup cannot replace the latest cover");
+ }
+ context="paired retry limits";const int before=apiRequests;
+ apiCurrent=current("never-current",base+"/slow");paired.track("no-match",QUrl(base+"/slow"));QTest::qWait(2000);
+ check(paired.artwork().isNull()&&presenter->artwork().isNull(),"unmatched API item never becomes current artwork");
+ check(wait([&]{return apiRequests-before>=4;},6500),"bounded retries reach the final attempt");
+ QTest::qWait(400);check(apiRequests-before==4,"mismatched artwork lookup stops after four attempts");
+ apiCurrent=current("still-old",base+"/slow");paired.track("late-ready",QUrl(base+"/slow"));QTest::qWait(1200);
+ apiCurrent=current("late-ready",base+"/fast");
+ check(wait([&]{return colorIs(paired.artwork(),Qt::blue);},4500),"album metadata arriving after one second still recovers");
+ apiStatus=404;paired.track("legacy-api",QUrl(base+"/fast"));
+ check(wait([&]{return colorIs(paired.artwork(),Qt::blue);}),"unsupported now-playing API retains desktop artwork support");
+ window->setProperty("useCider",false);window->setProperty("ciderService",originalSource);player.setThreeD(false);QTest::qWait(30);
+ std::cout<<"ARTWORK RESULT "<<failures<<" failures / "<<checks<<" checks"<<std::endl;return failures?1:0;
+}
+#include "artworktest.moc"
diff --git a/src/artworktest.h b/src/artworktest.h
new file mode 100644
index 0000000..1eb88f7
--- /dev/null
+++ b/src/artworktest.h
@@ -0,0 +1,5 @@
+#pragma once
+class Player;
+class QQuickWindow;
+class QString;
+int exerciseArtwork(Player &, QQuickWindow *, const QString &, const QString &);
diff --git a/src/cider.cpp b/src/cider.cpp
index 39fca9e..9915724 100644
--- a/src/cider.cpp
+++ b/src/cider.cpp
@@ -41,6 +41,8 @@ static QVariantMap asMap(QVariant v) {
Cider::Cider(bool enabled, const QString &connectionPath, const QUrl &rpcBase, QObject *parent)
: QObject(parent), m_enabled(enabled), m_connectionPath(connectionPath), m_rpcBase(rpcBase) {
m_rpcNetwork.setProxy(QNetworkProxy::NoProxy);
+ m_coverRetry.setSingleShot(true);
+ connect(&m_coverRetry,&QTimer::timeout,this,&Cider::requestCurrentArtwork);
QFile connection(m_connectionPath);
if (connection.open(QIODevice::ReadOnly))
m_apiToken = QJsonDocument::fromJson(connection.readAll()).object().value("token").toString();
@@ -57,6 +59,7 @@ Cider::Cider(bool enabled, const QString &connectionPath, const QUrl &rpcBase, Q
emit liveChanged();
});
connect(&m_events,&CiderEvents::event,this,[this](const QString &type) {
+ if(type=="playbackStatus.nowPlayingItemDidChange")m_eventTrack=true;
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;
@@ -64,6 +67,7 @@ Cider::Cider(bool enabled, const QString &connectionPath, const QUrl &rpcBase, Q
});
connect(&m_eventCoalesce,&QTimer::timeout,this,[this] {
const bool queue=std::exchange(m_eventQueue,false),settings=std::exchange(m_eventSettings,false);
+ if(std::exchange(m_eventTrack,false)) { refresh(); refreshArtwork(); }
if(queue && (m_queueVisible || m_libraryVisible))refreshQueue();
if(settings)emit remoteSettingsChanged();
});
@@ -77,7 +81,7 @@ Cider::Cider(bool enabled, const QString &connectionPath, const QUrl &rpcBase, Q
if (owner.isEmpty()) {
m_tick.stop();
m_available = m_playing = false; m_title.clear(); m_artist.clear(); m_album.clear();
- m_position = m_duration = 0; loadArt({});
+ m_position = m_duration = 0; m_track.clear(); m_desktopArtUrl=QUrl(); refreshArtwork();
m_queue.clear(); m_queueIndex = -1; ++m_queueRevision; m_queueReady = false; m_modesReady=false; emit settingsChanged(); emit currentIndexChanged(); emit queueChanged(); emit queueStatusChanged();
emit trackChanged(); emit playingChanged(); emit positionChanged();
} else refresh();
@@ -101,7 +105,8 @@ void Cider::refresh() {
auto message = QDBusMessage::createMethodCall(service, path, props, "GetAll");
message << iface;
auto *watch = new QDBusPendingCallWatcher(QDBusConnection::sessionBus().asyncCall(message, 1500), this);
- connect(watch, &QDBusPendingCallWatcher::finished, this, [this, watch] {
+ const auto metadataRevision=m_metadataRevision;
+ connect(watch, &QDBusPendingCallWatcher::finished, this, [this, watch, metadataRevision] {
QDBusPendingReply<QVariantMap> reply = *watch;
watch->deleteLater(); m_refreshing = false;
if (reply.isError()) {
@@ -109,7 +114,10 @@ void Cider::refresh() {
return;
}
const bool wasAvailable = m_available; m_available = true;
- apply(reply.value());
+ auto values=reply.value();
+ // A PropertiesChanged signal can overtake an older GetAll reply.
+ if(metadataRevision!=m_metadataRevision) { values.remove("Metadata"); values.remove("Position"); }
+ apply(values);
if (!wasAvailable) { emit trackChanged(); refreshModes(); }
if (m_launchTimer.isActive()) { m_launchTimer.stop(); emit launchChanged(); }
});
@@ -125,11 +133,14 @@ void Cider::apply(const QVariantMap &v) {
auto id = unwrap(meta.value("mpris:trackid"));
const auto track = id.canConvert<QDBusObjectPath>() ? id.value<QDBusObjectPath>().path() : id.toString();
const auto duration = unwrap(meta.value("mpris:length")).toLongLong()/1000;
- metadataChanged = title != m_title || artist != m_artist || album != m_album || track != m_track || duration != m_duration;
+ const bool identityChanged = title != m_title || artist != m_artist || album != m_album || track != m_track;
+ metadataChanged = identityChanged || duration != m_duration;
if (track != m_track) { m_position = 0; m_clock.restart(); }
m_title = title; m_artist = artist; m_album = album; m_track = track; m_duration = duration;
const auto url = QUrl(unwrap(meta.value("mpris:artUrl")).toString());
- if (url != m_artUrl) loadArt(url);
+ const bool artworkChanged=identityChanged || url!=m_desktopArtUrl;
+ m_desktopArtUrl=url;
+ if(artworkChanged)refreshArtwork();
}
if (v.contains("PlaybackStatus")) {
const auto status = unwrap(v.value("PlaybackStatus")).toString();
@@ -170,7 +181,7 @@ void Cider::apply(const QVariantMap &v) {
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(); }
+ if (interface == iface) { if(values.contains("Metadata") || invalidated.contains("Metadata"))++m_metadataRevision; apply(values); if (!invalidated.isEmpty()) refresh(); }
}
void Cider::seeked(qlonglong value) {
m_desktopPosition=value/1000;
@@ -284,10 +295,65 @@ void Cider::raise() {
QDBusConnection::sessionBus().asyncCall(QDBusMessage::createMethodCall(service,path,"org.mpris.MediaPlayer2","Raise"));
} else ensureRunning();
}
+void Cider::refreshArtwork() {
+ ++m_coverGeneration; m_coverAttempts=0; m_coverRetry.stop();
+ if(m_coverReply) { auto *reply=m_coverReply.data();m_coverReply=nullptr;reply->abort();reply->deleteLater(); }
+ // Paired Cider supplies artwork and track identity in one API response.
+ // Desktop metadata may momentarily combine a new track with an old URL.
+ if(m_apiToken.isEmpty()) { loadArt(m_desktopArtUrl); return; }
+ loadArt({});
+ if(!m_title.isEmpty())requestCurrentArtwork();
+}
+void Cider::requestCurrentArtwork() {
+ if(m_coverReply || m_apiToken.isEmpty() || m_title.isEmpty())return;
+ ++m_coverAttempts;
+ const auto generation=m_coverGeneration;
+ const auto tokenGeneration=m_tokenGeneration;
+ auto url=m_rpcBase;url.setPath("/api/v2/playback/now-playing");url.setQuery(QString());
+ QNetworkRequest request(url);request.setTransferTimeout(4000);
+ request.setAttribute(QNetworkRequest::RedirectPolicyAttribute,QNetworkRequest::ManualRedirectPolicy);
+ request.setRawHeader("apptoken",m_apiToken.toUtf8());
+ auto *reply=m_rpcNetwork.get(request);m_coverReply=reply;
+ connect(reply,&QNetworkReply::readyRead,reply,[reply]{if(reply->bytesAvailable()>512*1024)reply->abort();});
+ connect(reply,&QNetworkReply::finished,this,[this,reply,generation,tokenGeneration]{
+ reply->deleteLater();
+ if(generation!=m_coverGeneration || tokenGeneration!=m_tokenGeneration)return;
+ m_coverReply=nullptr;
+ const int status=reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
+ const auto json=QJsonDocument::fromJson(reply->readAll()).object();
+ const auto current=json.value("data").toObject();
+ const auto params=current.value("playParams").toObject();
+ const auto desktopId=m_track.section('/',-1);
+ QStringList ids;
+ for(const auto &key:{"id","catalogId","reportingId","libraryId"}) {
+ const auto id=params.value(key).toString();if(!id.isEmpty())ids.append(id);
+ }
+ // IDs take precedence over display names, including library/catalog aliases.
+ const bool sameTrack=!desktopId.isEmpty() && !ids.isEmpty() ? ids.contains(desktopId) :
+ current.value("name").toString()==m_title && !m_title.isEmpty() &&
+ current.value("albumName").toString()==m_album && current.value("artistName").toString()==m_artist;
+ if(reply->error()==QNetworkReply::NoError && status==200 && sameTrack) {
+ QString cover=current.value("artwork").toObject().value("url").toString();
+ cover.replace("{w}","1200").replace("{h}","1200").replace("{f}","jpg");
+ const QUrl art(cover);
+ if(!art.isEmpty() && (art.isLocalFile() || art.scheme()=="https" || art.scheme()=="http") && art.userInfo().isEmpty()) {
+ loadArt(art);return;
+ }
+ }
+ // Older Cider versions or restricted tokens retain desktop-only support.
+ if(status==401 || status==403 || status==404) { loadArt(m_desktopArtUrl); return; }
+ // Album playback and crossfade can expose the previous API item briefly.
+ // Never fall back to its artwork; retry only a bounded number of times.
+ if(m_coverAttempts<4) {
+ static constexpr int delays[]{250,750,2000};
+ m_coverRetry.start(delays[m_coverAttempts-1]);
+ }
+ });
+}
void Cider::loadArt(const QUrl &url) {
++m_artGeneration; m_pendingArtBytes.clear(); m_pendingArtFile.clear();
m_artUrl = url;
- if (m_artReply) { m_artReply->abort(); m_artReply->deleteLater(); }
+ if (m_artReply) { auto *previous=m_artReply.data(); m_artReply=nullptr; previous->abort(); previous->deleteLater(); }
m_art = {}; emit artworkChanged();
if (url.isLocalFile()) { m_pendingArtFile=url.toLocalFile(); decodeArt(); return; }
if (url.scheme() != "https" && url.scheme() != "http") return;
@@ -296,8 +362,10 @@ void Cider::loadArt(const QUrl &url) {
m_artReply = m_network.get(request);
auto *reply = m_artReply.data();
connect(reply, &QNetworkReply::downloadProgress, this, [reply](qint64 received, qint64 total) { if (received > 12*1024*1024 || total > 12*1024*1024) reply->abort(); });
- connect(reply, &QNetworkReply::finished, this, [this, reply, url] {
- if (url == m_artUrl && reply->error() == QNetworkReply::NoError) {
+ const auto generation=m_artGeneration;
+ connect(reply, &QNetworkReply::finished, this, [this, reply, generation] {
+ if (m_artReply == reply) m_artReply=nullptr;
+ if (generation == m_artGeneration && reply->error() == QNetworkReply::NoError) {
m_pendingArtBytes = reply->readAll();
decodeArt();
}
@@ -369,7 +437,7 @@ void Cider::connectQueue(const QString &token) {
++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_volumeReady=false;refreshVolume(); m_needsToken=false; m_queueError.clear();updateEvents();
+ m_apiToken=value; refreshArtwork(); m_volumeReady=false;refreshVolume(); 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();
@@ -1028,7 +1096,7 @@ void Cider::setLiveVisible(bool visible) {
}
void Cider::updateEvents() {
m_events.configure(m_liveVisible,m_rpcBase,m_apiToken.toUtf8());
- if(!m_liveVisible) { m_eventCoalesce.stop();m_eventQueue=m_eventSettings=false; }
+ if(!m_liveVisible) { m_eventCoalesce.stop();m_eventQueue=m_eventSettings=m_eventTrack=false; }
}
void Cider::editQueueSelection(const QVariantList &indices, const QString &operation, int revision) {
diff --git a/src/cider.h b/src/cider.h
index 7ab6a52..5e9e922 100644
--- a/src/cider.h
+++ b/src/cider.h
@@ -100,7 +100,7 @@ public:
QString title() const { return m_title.isEmpty() ? "Cider" : m_title; }
QString artist() const { return m_artist; }
QString album() const { return m_album; }
- QString albumKey() const { return m_album.isEmpty() ? m_track : m_album+"|"+m_artUrl.path(); }
+ QString albumKey() const { return m_album.isEmpty() ? m_track : m_album+"|"+m_desktopArtUrl.path(); }
QVariantMap discDetails() const { return m_discDetails; }
bool discVisible() const { return m_discVisible; }
bool discLoading() const { return m_discLoading; }
@@ -203,7 +203,7 @@ private slots:
private:
void updateEvents();
bool m_listeningBusy=false;
- bool m_liveVisible=false, m_eventQueue=false, m_eventSettings=false;
+ bool m_liveVisible=false, m_eventQueue=false, m_eventSettings=false, m_eventTrack=false;
CiderEvents m_events;
QTimer m_eventCoalesce;
QString m_audioQuality;
@@ -260,6 +260,8 @@ private:
void set(const QString &key, const QVariant &value);
void decodeArt();
void loadArt(const QUrl &url);
+ void refreshArtwork();
+ void requestCurrentArtwork();
void fail(const QString &message);
void schedule(const QString &key, std::function<void()> action);
void flushCommands();
@@ -271,7 +273,11 @@ private:
bool m_canSeek = false, m_canNext = false, m_canPrevious = false;
QString m_playbackStatus="Stopped";
QString m_title, m_artist, m_album, m_track, m_error;
- QUrl m_artUrl;
+ QUrl m_artUrl, m_desktopArtUrl;
+ QTimer m_coverRetry;
+ QPointer<QNetworkReply> m_coverReply;
+ quint64 m_coverGeneration=0, m_metadataRevision=0;
+ int m_coverAttempts=0;
QImage m_art;
QFutureWatcher<QImage> m_artLoader;
QByteArray m_pendingArtBytes;
diff --git a/src/deckgeometry.cpp b/src/deckgeometry.cpp
new file mode 100644
index 0000000..1025b5c
--- /dev/null
+++ b/src/deckgeometry.cpp
@@ -0,0 +1,57 @@
+#include "deckgeometry.h"
+#include <QVector2D>
+#include <cmath>
+#include <array>
+
+DeckGeometry::DeckGeometry(QQuick3DObject *parent):QQuick3DGeometry(parent) {
+ connect(this,&DeckGeometry::shapeChanged,this,&DeckGeometry::rebuild);rebuild();
+}
+void DeckGeometry::rebuild() {
+ struct Vertex {float x,y,z,nx,ny,nz,u,v;};
+ QByteArray vertices;
+ const float w=qMax(.01f,m_dimensions.x()/2),h=qMax(.01f,m_dimensions.y()/2),d=qMax(.01f,m_dimensions.z()/2);
+ const float r=qBound(.001f,m_radius,qMin(w,h));
+ const float bevel=qMin(qMin(3.f,d/2),r*.75f);
+ constexpr int perimeter=68;
+ const auto outward=[](int i){
+ const int corner=(i/17)%4;
+ const float angle=(corner*90+(i%17)*90.f/16)*float(M_PI)/180;
+ return QVector3D(std::cos(angle),std::sin(angle),0);
+ };
+ const auto point=[&](int i,float inset,float z){
+ const int corner=(i/17)%4;
+ const auto n=outward(i);
+ return QVector3D((corner==0||corner==3?w-r:-w+r)+(r-inset)*n.x(),
+ (corner<2?h-r:-h+r)+(r-inset)*n.y(),z);
+ };
+ const auto add=[&](QVector3D a,QVector3D b,QVector3D c,QVector3D na,QVector3D nb,QVector3D nc){
+ if(QVector3D::crossProduct(b-a,c-a).lengthSquared()<1e-12f)return;
+ const std::array<QVector3D,3> points={a,b,c},normals={na,nb,nc};
+ for(int i=0;i<3;++i){const auto v=points[i],n=normals[i];const Vertex out{v.x(),v.y(),v.z(),n.x(),n.y(),n.z(),.5f+v.x()/(2*w),.5f-v.y()/(2*h)};vertices.append(reinterpret_cast<const char*>(&out),sizeof(out));}
+ };
+ // Quarter-circle edge profiles give highlights an actual rounded surface.
+ struct Edge {float inset,z,radial,vertical;};
+ std::array<Edge,8> rings;
+ for(int k=0;k<4;++k){
+ const float angle=k*float(M_PI)/6;
+ rings[k]={bevel*(1-std::sin(angle)),-d+bevel*(1-std::cos(angle)),std::sin(angle),-std::cos(angle)};
+ rings[7-k]={rings[k].inset,-rings[k].z,rings[k].radial,-rings[k].vertical};
+ }
+ for(int i=0;i<perimeter;++i){
+ const int j=(i+1)%perimeter;
+ add({0,0,d},point(i,bevel,d),point(j,bevel,d),{0,0,1},{0,0,1},{0,0,1});
+ add({0,0,-d},point(j,bevel,-d),point(i,bevel,-d),{0,0,-1},{0,0,-1},{0,0,-1});
+ for(int k=0;k<7;++k){
+ const auto lo=rings[k],hi=rings[k+1];
+ const auto a=point(i,lo.inset,lo.z),b=point(j,lo.inset,lo.z),c=point(j,hi.inset,hi.z),e=point(i,hi.inset,hi.z);
+ const auto na=outward(i)*lo.radial+QVector3D(0,0,lo.vertical),nb=outward(j)*lo.radial+QVector3D(0,0,lo.vertical);
+ const auto nc=outward(j)*hi.radial+QVector3D(0,0,hi.vertical),ne=outward(i)*hi.radial+QVector3D(0,0,hi.vertical);
+ add(a,b,c,na,nb,nc);add(a,c,e,na,nc,ne);
+ }
+ }
+ clear();setStride(sizeof(Vertex));setVertexData(vertices);setPrimitiveType(QQuick3DGeometry::PrimitiveType::Triangles);
+ addAttribute(QQuick3DGeometry::Attribute::PositionSemantic,0,QQuick3DGeometry::Attribute::F32Type);
+ addAttribute(QQuick3DGeometry::Attribute::NormalSemantic,3*sizeof(float),QQuick3DGeometry::Attribute::F32Type);
+ addAttribute(QQuick3DGeometry::Attribute::TexCoord0Semantic,6*sizeof(float),QQuick3DGeometry::Attribute::F32Type);
+ setBounds(QVector3D(-w,-h,-d),QVector3D(w,h,d));update();
+}
diff --git a/src/deckgeometry.h b/src/deckgeometry.h
new file mode 100644
index 0000000..527a587
--- /dev/null
+++ b/src/deckgeometry.h
@@ -0,0 +1,17 @@
+#pragma once
+#include <QQuick3DGeometry>
+#include <QVector3D>
+
+class DeckGeometry : public QQuick3DGeometry {
+ Q_OBJECT
+ Q_PROPERTY(QVector3D dimensions MEMBER m_dimensions NOTIFY shapeChanged)
+ Q_PROPERTY(float radius MEMBER m_radius NOTIFY shapeChanged)
+public:
+ explicit DeckGeometry(QQuick3DObject *parent=nullptr);
+signals:
+ void shapeChanged();
+private:
+ void rebuild();
+ QVector3D m_dimensions{428,428,26};
+ float m_radius=22;
+};
diff --git a/src/disc.cpp b/src/disc.cpp
index 3fcde97..cedaaeb 100644
--- a/src/disc.cpp
+++ b/src/disc.cpp
@@ -58,10 +58,19 @@ QImage Disc::fallbackArt(int size) {
return image;
}
+QImage Disc::placeholderArt(int size) {
+ QImage image(size,size,QImage::Format_ARGB32_Premultiplied);
+ QPainter painter(&image);
+ QLinearGradient finish(0,0,size,size);
+ finish.setColorAt(0,QColor("#44474d"));finish.setColorAt(1,QColor("#2b2d33"));
+ painter.fillRect(image.rect(),finish);
+ return image;
+}
+
// All media use the identical fallback pixels. Share one immutable image even
// after switching appearances; each painted item retains only an implicit copy.
static const QImage &sharedFallbackArt() {
- static const QImage image = Disc::fallbackArt();
+ static const QImage image = Disc::placeholderArt();
return image;
}
@@ -395,25 +404,21 @@ QSGNode *ProgressRing::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *)
return node;
}
-DiscPresentation::DiscPresentation(QObject *parent):QObject(parent) {
- m_wait.setSingleShot(true); m_wait.setInterval(1500);
- connect(&m_wait,&QTimer::timeout,this,[this]{const auto key=m_pendingKey;present({},key,m_pendingAnimate,false);});
-}
+DiscPresentation::DiscPresentation(QObject *parent):QObject(parent) {}
void DiscPresentation::releaseOutgoing() {
if (m_outgoing.isNull()) return;
m_outgoing = {};
emit changed();
}
-void DiscPresentation::present(const QImage &art,const QString &key,bool animate,bool waitForArt) {
- if(art.isNull() && waitForArt && !m_key.isEmpty() && !key.isEmpty()){
- m_pendingAnimate=animate;
- if(m_pendingKey!=key || !m_wait.isActive()){m_pendingKey=key;m_wait.start();}
- return;
- }
- m_wait.stop(); m_pendingKey.clear();
+void DiscPresentation::present(const QImage &image,const QString &key,bool animate) {
+ // Only the outgoing animation may retain a previous cover. The current
+ // medium must not borrow artwork while a new track or source is loading.
+ const QImage art=key.isEmpty()?QImage():image;
const bool swap=!key.isEmpty() && !m_key.isEmpty() && key!=m_key && animate;
+ const bool clearedOutgoing=(!animate || key.isEmpty()) && !m_outgoing.isNull();
if(swap)m_outgoing=m_art;
- if (!swap && m_key == key && m_art.cacheKey() == art.cacheKey()) return;
+ else if(clearedOutgoing)m_outgoing={};
+ if (!swap && !clearedOutgoing && m_key == key && m_art.cacheKey() == art.cacheKey()) return;
m_art=art; m_key=key; emit changed();
if(swap)emit swapRequested();
}
diff --git a/src/disc.h b/src/disc.h
index 7d6b671..6201571 100644
--- a/src/disc.h
+++ b/src/disc.h
@@ -1,7 +1,6 @@
#pragma once
#include <QQuickPaintedItem>
#include <QImage>
-#include <QTimer>
// A static view of the already decoded cover; no additional fetch or image cache.
class ArtworkView : public QQuickPaintedItem {
@@ -47,6 +46,7 @@ public:
QColor labelColor() const { return m_labelColor; }
void setLabelColor(const QColor &value) { if (m_labelColor==value) return; m_labelColor=value; update(); emit labelColorChanged(); }
static QImage fallbackArt(int size = 1000);
+ static QImage placeholderArt(int size = 512);
signals:
void vinylChanged();
void cassetteChanged();
@@ -101,14 +101,13 @@ public:
explicit DiscPresentation(QObject *parent=nullptr);
QImage artwork() const { return m_art; }
QImage outgoing() const { return m_outgoing; }
- Q_INVOKABLE void present(const QImage &art, const QString &key, bool animate, bool waitForArt=false);
+ Q_INVOKABLE void present(const QImage &art, const QString &key, bool animate);
Q_INVOKABLE void releaseOutgoing();
+ Q_INVOKABLE void clear() { present({}, {}, false); }
signals:
void changed();
void swapRequested();
private:
QImage m_art, m_outgoing;
- QString m_key, m_pendingKey;
- bool m_pendingAnimate=false;
- QTimer m_wait;
+ QString m_key;
};
diff --git a/src/geometrytest.cpp b/src/geometrytest.cpp
new file mode 100644
index 0000000..1eee659
--- /dev/null
+++ b/src/geometrytest.cpp
@@ -0,0 +1,92 @@
+#include "mediageometry.h"
+#include "deckgeometry.h"
+#include <QTest>
+#include <QPointer>
+#include <cmath>
+
+class GeometryTest : public QObject {
+ Q_OBJECT
+private slots:
+ void recordTopology_data() {
+ QTest::addColumn<float>("hole");QTest::addColumn<bool>("grooves");
+ QTest::newRow("CD")<<15.f<<false;QTest::newRow("vinyl")<<3.5f<<true;QTest::newRow("tape-pack")<<31.f<<false;
+ }
+ void recordTopology() {
+ QFETCH(float,hole);QFETCH(bool,grooves);
+ RecordGeometry record;record.setProperty("hole",hole);record.setProperty("grooves",grooves);
+ const auto data=record.vertexData();QVERIFY(!data.isEmpty());QCOMPARE(data.size()%(3*record.stride()),0);
+ const float *values=reinterpret_cast<const float*>(data.constData());const int stride=record.stride()/sizeof(float);
+ float minZ=100,maxZ=-100;
+ for(int i=0;i<data.size()/int(sizeof(float));i+=stride){
+ for(int j=0;j<stride;++j)QVERIFY(std::isfinite(values[i+j]));
+ const float x=values[i],y=values[i+1],z=values[i+2];
+ QVERIFY(std::hypot(x,y)>=hole-.01);QVERIFY(std::hypot(x,y)<=176.01);
+ const auto n=QVector3D(values[i+3],values[i+4],values[i+5]);QVERIFY(std::abs(n.length()-1)<.001);
+ QVERIFY(values[i+6]>=0&&values[i+6]<=1);QVERIFY(values[i+7]>=0&&values[i+7]<=1);
+ minZ=qMin(minZ,z);maxZ=qMax(maxZ,z);
+ }
+ QVERIFY(minZ<0&&maxZ>0);QVERIFY(record.boundsMin().z()<=minZ);QVERIFY(record.boundsMax().z()>=maxZ);
+ }
+ void cartridgeProportions() {
+ DeckGeometry body;body.setProperty("dimensions",QVector3D(12,21,11));body.setProperty("radius",3.f);
+ QCOMPARE(body.boundsMax()-body.boundsMin(),QVector3D(12,21,11));
+ QVERIFY(body.vertexData().size()>0);
+ }
+ void thinMachinedPartsStayInsideBounds() {
+ for(const auto size:{QVector3D(4,.7,.3),QVector3D(428,428,28),QVector3D(12,21,11)}){
+ DeckGeometry body;body.setProperty("dimensions",size);body.setProperty("radius",2.f);
+ const auto bytes=body.vertexData();const auto *v=reinterpret_cast<const float*>(bytes.constData());
+ for(int i=0;i<bytes.size()/int(sizeof(float));i+=8){
+ for(int axis=0;axis<3;++axis)QVERIFY(std::abs(v[i+axis])<=size[axis]/2+.001f);
+ QVERIFY(std::abs(QVector3D(v[i+3],v[i+4],v[i+5]).length()-1)<.001f);
+ }
+ }
+ }
+ void materialMapsAreBoundedAndRepeatable() {
+ QByteArray previous;
+ for(const QString kind:{QString("brushed"),QString("molded"),QString("vinyl"),QString("disc"),QString("turned"),QString("metal-normal")}){
+ SurfaceTexture first,second;first.setProperty("kind",kind);second.setProperty("kind",kind);
+ QCOMPARE(first.size(),QSize(256,256));QCOMPARE(first.textureData().size(),256*256*4);
+ QCOMPARE(first.textureData(),second.textureData());QVERIFY(first.textureData()!=previous);
+ previous=first.textureData();
+ }
+ }
+ void coversUseBoundedIndependentPixels() {
+ CoverTexture cover;QImage input(1200,600,QImage::Format_RGBA8888);input.fill(Qt::red);cover.setProperty("artwork",input);
+ QCOMPARE(cover.size(),QSize(512,512));QCOMPARE(cover.textureData().size(),512*512*4);
+ input.fill(Qt::blue);QCOMPARE(static_cast<unsigned char>(cover.textureData()[0]),255);
+ cover.setProperty("artwork",input);QCOMPARE(static_cast<unsigned char>(cover.textureData()[2]),255);
+ cover.setProperty("artwork",QImage());QCOMPARE(cover.textureData().size(),512*512*4);
+ }
+ void coverSnapshotsReplaceAndRetireTextures() {
+ CoverTexture cover;QImage image(64,64,QImage::Format_RGBA8888);image.fill(Qt::red);
+ cover.setProperty("artwork",image);
+ QPointer<QQuick3DTextureData> previous=cover.texture();
+ const auto pixels=previous->textureData();
+ image.fill(Qt::blue);cover.setProperty("artwork",image);
+ QVERIFY(cover.texture()!=previous);QCOMPARE(previous->textureData(),pixels);
+ QCoreApplication::sendPostedEvents(nullptr,QEvent::DeferredDelete);
+ QVERIFY(previous.isNull());
+ const auto *unchanged=cover.texture();
+ cover.setProperty("artwork",image.copy());QCOMPARE(cover.texture(),unchanged);
+ for(int i=0;i<30;++i){image.fill(i%2?Qt::red:Qt::blue);cover.setProperty("artwork",image);}
+ QCoreApplication::sendPostedEvents(nullptr,QEvent::DeferredDelete);
+ QCOMPARE(cover.findChildren<QQuick3DTextureData*>().size(),1);
+ QCOMPARE(cover.textureData().size(),512*512*4);
+ }
+ void paperLabelsAndWallpaperProbe() {
+ CoverTexture label;label.setProperty("paper",true);label.setProperty("title",QString("Test album"));
+ QCOMPARE(label.size(),QSize(1024,170));QCOMPARE(label.textureData().size(),1024*170*4);
+ StudioTexture probe;const auto neutral=probe.textureData();probe.setProperty("tint",QColor("#80b8e8"));
+ QCOMPARE(probe.size(),QSize(512,256));QCOMPARE(probe.textureData().size(),512*256*4);QVERIFY(probe.textureData()!=neutral);
+ const auto blue=probe.textureData();probe.setProperty("tint",QColor("#e8ac80"));QVERIFY(probe.textureData()!=blue);
+ }
+ void waveIsFiniteAtEndpoints() {
+ for(bool linear:{false,true})for(float progress:{0.f,.25f,1.f}){
+ WaveGeometry wave;wave.setProperty("linear",linear);wave.setProperty("progress",progress);wave.setProperty("amplitude",2.4f);
+ const auto bytes=wave.vertexData();const auto *values=reinterpret_cast<const float*>(bytes.constData());for(int i=0;i<bytes.size()/int(sizeof(float));++i)QVERIFY(std::isfinite(values[i]));
+ }
+ }
+};
+QTEST_MAIN(GeometryTest)
+#include "geometrytest.moc"
diff --git a/src/main.cpp b/src/main.cpp
index d3dd9f2..6207cf2 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -1,3 +1,8 @@
+#ifdef SPUN_WITH_3D
+#include "deckgeometry.h"
+#include "mediageometry.h"
+#include <QtQuick3D/qquick3d.h>
+#endif
#include "player.h"
#include "tapesound.h"
#include "vinylnoise.h"
@@ -7,6 +12,8 @@
#ifdef SPUN_DIAGNOSTICS
#include "librarytest.h"
#include "mediauitest.h"
+#include "artworktest.h"
+#include "threedtest.h"
#include "testinput.h"
#endif
#include "lyrics.h"
@@ -173,7 +180,8 @@ public:
if(cassette)if(auto *seek=window->findChild<QQuickItem *>("cassetteSeek"))region|=itemRegion(seek);
if(window->property("swapRunning").toBool())region|=QRegion(45,74,440,440);
}
- if(!cassette && !body)region -= window->property("vinyl").toBool()?QRegion(259,288,12,12,QRegion::Ellipse):QRegion(243,272,44,44,QRegion::Ellipse);
+ if(window->property("threeDActive").toBool())region=QRegion(12,62,506,460);
+ if(!cassette && !body && !window->property("threeDActive").toBool())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 |= itemRegion(bar);
if (auto *deck = window->findChild<QQuickItem *>("playerDeck"))
@@ -400,22 +408,23 @@ static int exerciseCiderQueue(const QString &temp) {
QImage red(24,24,QImage::Format_ARGB32), blue=red;
red.fill(Qt::red); blue.fill(Qt::blue);
red.save(temp+"/red.png"); blue.save(temp+"/blue.png");
+ Cider artRemote(false);
auto artworkUrl = [&](const QUrl &url) {
const QVariantMap changes{{"Metadata",QVariantMap{{"mpris:artUrl",url.toString()}}}};
- return QMetaObject::invokeMethod(&remote,"propertiesChanged",Qt::DirectConnection,
+ return QMetaObject::invokeMethod(&artRemote,"propertiesChanged",Qt::DirectConnection,
Q_ARG(QString,QString("org.mpris.MediaPlayer2.Player")),Q_ARG(QVariantMap,changes),Q_ARG(QStringList,QStringList{}));
};
check(artworkUrl(QUrl::fromLocalFile(temp+"/red.png")), "Cider artwork fixture delivers metadata");
artworkUrl(QUrl::fromLocalFile(temp+"/blue.png"));
- check(waitFor([&]{return !remote.artwork().isNull() && remote.artwork().pixelColor(0,0)==QColor(Qt::blue);}),
+ check(waitFor([&]{return !artRemote.artwork().isNull() && artRemote.artwork().pixelColor(0,0)==QColor(Qt::blue);}),
"asynchronous Cider artwork keeps the latest cover and original pixels");
QImage large(3600,2400,QImage::Format_RGB32); large.fill(Qt::cyan);
large.save(temp+"/large-cover.jpg","JPEG",95);
artworkUrl(QUrl::fromLocalFile(temp+"/large-cover.jpg"));
- check(waitFor([&]{return remote.artwork().size()==QSize(1200,800);}),
+ check(waitFor([&]{return artRemote.artwork().size()==QSize(1200,800);}),
"oversized Cider covers use the full disc resolution with correct proportions");
artworkUrl(QUrl::fromLocalFile(temp+"/red.png")); artworkUrl({}); QTest::qWait(150);
- check(remote.artwork().isNull(), "disconnecting while Cider artwork decodes rejects the stale image");
+ check(artRemote.artwork().isNull(), "disconnecting while Cider artwork decodes rejects the stale image");
return failures;
}
@@ -502,8 +511,8 @@ static int exercise(Player &player, Theme &theme, Lyrics &lyrics, QQuickWindow *
QImage first(16,16,QImage::Format_ARGB32);first.fill(Qt::red);QImage second=first;second.fill(Qt::blue);
staged.present(first,"album-one",true); staged.present(first,"album-one",true);
check(swaps==0, "startup and tracks from the same album do not swap discs");
- staged.present({},"album-two",true,true);check(staged.artwork()==first, "old artwork stays until the incoming cover arrives");
- staged.present(second,"album-two",true,true);check(swaps==1 && staged.outgoing()==first && staged.artwork()==second, "album swap retains the outgoing artwork separately");
+ staged.present({},"album-two",true);check(staged.artwork().isNull() && staged.outgoing()==first, "pending cover clears the current medium while retaining only the outgoing disc");
+ staged.present(second,"album-two",true);check(swaps==1 && staged.outgoing()==first && staged.artwork()==second, "album swap retains the outgoing artwork separately");
staged.present(first,"album-three",false);check(swaps==1 && staged.artwork()==first, "reduced motion replaces artwork immediately");
staged.releaseOutgoing();check(staged.outgoing().isNull() && staged.artwork()==first,
"finished disc swaps release the previous cover without changing the current disc");
@@ -545,6 +554,12 @@ static int exercise(Player &player, Theme &theme, Lyrics &lyrics, QQuickWindow *
player.clear();window->setProperty("queueOpen",false);QTest::qWait(100);
}
if (type) {
+ // The queue fixture leaves import feedback visible. Dismiss it before
+ // checking the base size; visible feedback intentionally adds height.
+ auto *notice = findItem(window->contentItem(), "actionNotice");
+ if (notice && notice->isVisible()) click("dismissActionNotice");
+ check(waitFor([&] { return !notice || !notice->isVisible(); }),
+ "scaling checks start after import feedback is dismissed");
type->setUiScale(1.25);QTest::qWait(150);
check(window->width()==qRound(window->property("layoutWidth").toReal()*1.25)
&&qFuzzyCompare(window->property("contentItem").value<QQuickItem*>()->scale(),1.25)
@@ -1501,7 +1516,7 @@ int main(int argc, char **argv) {
for (int i=1; i<argc; ++i) {
const QByteArray option = QByteArray(argv[i]).split('=').first();
if (option == "--") break;
- if (option == "--self-test" || option == "--test-media-ui" || option == "--test-import-ui" || option == "--test-library" || option == "--smoke-live"
+ if (option == "--self-test" || option == "--test-media-ui" || option == "--test-artwork" || option == "--test-3d-lighting" || option == "--test-3d-ui" || option == "--test-3d-library" || option == "--test-import-ui" || option == "--test-library" || option == "--smoke-live"
|| option == "--verify-cider" || option == "--verify-cider-writes" || option == "--inspect-cider" || option == "--inspect-library") {
const auto executable = QFileInfo(QStringLiteral("/proc/self/exe")).symLinkTarget();
const auto diagnostics = QFile::encodeName(QFileInfo(executable).absolutePath() + "/spun-diagnostics");
@@ -1521,6 +1536,9 @@ int main(int argc, char **argv) {
if (!qEnvironmentVariableIsSet("QT_FFMPEG_ENCODING_HW_DEVICE_TYPES"))
qputenv("QT_FFMPEG_ENCODING_HW_DEVICE_TYPES", ",");
QGuiApplication app(argc, argv);
+#ifdef SPUN_WITH_3D
+ QSurfaceFormat::setDefaultFormat(QQuick3D::idealSurfaceFormat());
+#endif
const qint64 applicationReady = startup.elapsed();
app.setApplicationName("spun"); app.setApplicationDisplayName("Spun");
app.setOrganizationName("Spun"); app.setApplicationVersion("0.1.0");
@@ -1530,6 +1548,10 @@ int main(int argc, char **argv) {
parser.addOption({"benchmark-medium", "Appearance for isolated measurements", "medium", "cd"});
parser.addOption({"test-library", "Run isolated music browser checks"});
parser.addOption({"self-test", "Run isolated playback and UI checks"});
+ parser.addOption({"test-artwork", "Verify artwork updates across playback sources and physical media"});
+ parser.addOption({"test-3d-lighting", "Verify live palette changes in rendered 3D pixels"});
+ parser.addOption({"test-3d-ui", "Run isolated native 3D interaction and lifecycle checks"});
+ parser.addOption({"test-3d-library", "Run isolated library checks with 3D enabled"});
parser.addOption({"test-media-ui", "Run isolated vinyl and cassette interaction checks"});
parser.addOption({"test-import-ui", "Run isolated folder import UI checks"});
parser.addOption({"smoke-live", "Run isolated checks on the live desktop"});
@@ -1543,7 +1565,8 @@ int main(int argc, char **argv) {
parser.addPositionalArgument("files", "Music files or album folders to play", "[files…]");
parser.process(app);
if (parser.isSet("export-cover")) return Disc::fallbackArt().save(parser.value("export-cover")) ? 0 : 1;
- const bool test = parser.isSet("test-media-ui") || parser.isSet("benchmark") || parser.isSet("test-import-ui") || parser.isSet("self-test") || parser.isSet("smoke-live") || parser.isSet("test-library");
+ const bool test = parser.isSet("test-artwork") || parser.isSet("test-3d-lighting") || parser.isSet("test-3d-ui") || parser.isSet("test-3d-library") || parser.isSet("test-media-ui") || parser.isSet("benchmark") || parser.isSet("test-import-ui") || parser.isSet("self-test") || parser.isSet("smoke-live") || parser.isSet("test-library");
+ if(test && qEnvironmentVariableIsSet("SPUN_TEST_SCREEN"))app.setDesktopFileName("spun-diagnostics");
if (!test && !parser.isSet("config")) {
auto bus = QDBusConnection::sessionBus();
if (bus.interface() && bus.interface()->isServiceRegistered("org.mpris.MediaPlayer2.spun")) {
@@ -1588,12 +1611,29 @@ int main(int argc, char **argv) {
const qint64 backendReady = startup.elapsed();
qmlRegisterType<Symbol>("Spun", 1, 0, "Symbol");
+#ifdef SPUN_WITH_3D
+ qmlRegisterType<DeckGeometry>("Spun",1,0,"DeckGeometry");
+ qmlRegisterType<RecordGeometry>("Spun",1,0,"RecordGeometry");
+ qmlRegisterType<CoverTexture>("Spun",1,0,"CoverTexture");
+ qmlRegisterType<SurfaceTexture>("Spun",1,0,"SurfaceTexture");
+ qmlRegisterType<StudioTexture>("Spun",1,0,"StudioTexture");
+ qmlRegisterType<WaveGeometry>("Spun",1,0,"WaveGeometry");
+#endif
qmlRegisterType<PlayerBody>("Spun",1,0,"PlayerBody");
qmlRegisterType<Disc>("Spun", 1, 0, "Disc");
qmlRegisterType<ArtworkView>("Spun", 1, 0, "ArtworkView");
qmlRegisterType<ProgressRing>("Spun", 1, 0, "ProgressRing");
QQmlApplicationEngine engine;
+ if(test) QObject::connect(&engine, &QQmlEngine::warnings, &app, [](const QList<QQmlError> &errors) {
+ for(const auto &error:errors) std::cerr << "QML " << error.toString().toStdString() << std::endl;
+ });
engine.addImageProvider("queueart", new QueueArtworkProvider);
+#ifdef SPUN_WITH_3D
+ engine.rootContext()->setContextProperty("supports3D", qEnvironmentVariable("QT_QUICK_BACKEND") != "software");
+#else
+ engine.rootContext()->setContextProperty("supports3D", false);
+#endif
+ engine.rootContext()->setContextProperty("player3DUrl", QUrl(QStringLiteral("qrc:/qml/Player3D.qml")));
engine.rootContext()->setContextProperty("player", &player);
engine.rootContext()->setContextProperty("theme", &theme);
engine.rootContext()->setContextProperty("typography", &typography);
@@ -1641,6 +1681,14 @@ int main(int argc, char **argv) {
qmlReady = startup.elapsed();
if (engine.rootObjects().isEmpty()) return 1;
auto *window = qobject_cast<QQuickWindow *>(engine.rootObjects().first());
+ if (test && qEnvironmentVariableIsSet("SPUN_TEST_SCREEN")) {
+ const auto name=qEnvironmentVariable("SPUN_TEST_SCREEN");
+ QScreen *screen=nullptr;
+ for(auto *candidate:app.screens())if(candidate->name()==name)screen=candidate;
+ if(!screen){std::cerr<<"Requested test screen is unavailable.\n";return 2;}
+ window->setScreen(screen);
+ window->setPosition(screen->availableGeometry().topLeft()+QPoint(60,60));
+ }
if (!test) { if (auto *mediaControls = registerMpris(&player, &cider)) mediaControls->setSourceWindow(window); }
QObject::connect(&app, &QCoreApplication::aboutToQuit, &player, &Player::save);
if (parser.isSet("benchmark")) {
@@ -2022,6 +2070,10 @@ int main(int argc, char **argv) {
std::cout << "RESULT " << failures << " failures" << std::endl;
app.exit(failures ? 1 : 0);
});
+ else if (parser.isSet("test-artwork")) QTimer::singleShot(650, &app, [&] { app.exit(exerciseArtwork(player,window,temp.path(),parser.value("capture-dir"))); });
+ else if (parser.isSet("test-3d-lighting")) QTimer::singleShot(650, &app, [&] { app.exit(exerciseThreeDLighting(player,window,temp.path(),parser.value("capture-dir"))); });
+ else if (parser.isSet("test-3d-ui")) QTimer::singleShot(650, &app, [&] { app.exit(exerciseThreeD(player,window,temp.path(),parser.value("capture-dir"))); });
+ else if (parser.isSet("test-3d-library")) QTimer::singleShot(650, &app, [&] { player.setThreeD(true); if(!waitFor([&]{return window->property("threeDActive").toBool();})) { std::cerr << "FAIL 3D scene must be active for Cider integration tests" << std::endl;app.exit(2);return; } app.exit(exerciseLibrary(window,temp.path(),parser.value("capture-dir")) ? 1 : 0); });
else if (parser.isSet("test-media-ui")) QTimer::singleShot(650, &app, [&] { app.exit(exerciseMediaUi(player,window,temp.path(),parser.value("capture-dir"))); });
else if (parser.isSet("test-library")) QTimer::singleShot(650, &app, [&] { app.exit(exerciseLibrary(window,temp.path(),parser.value("capture-dir")) ? 1 : 0); });
else if (test) QTimer::singleShot(650, &app, [&] {
diff --git a/src/mediageometry.cpp b/src/mediageometry.cpp
new file mode 100644
index 0000000..1241d31
--- /dev/null
+++ b/src/mediageometry.cpp
@@ -0,0 +1,128 @@
+#include "mediageometry.h"
+#include "disc.h"
+#include <QVector3D>
+#include <QPainter>
+#include <QGuiApplication>
+#include <QFontMetrics>
+#include <cmath>
+
+namespace {
+struct Vertex { float x,y,z,nx,ny,nz,u,v; };
+void triangle(QByteArray &data,QVector3D a,QVector3D b,QVector3D c,float radius,bool smoothRadial=false) {
+ const auto n=QVector3D::crossProduct(b-a,c-a).normalized();
+ for(const auto &p:{a,b,c}){
+ auto normal=n;
+ if(smoothRadial && std::hypot(p.x(),p.y())>.001f) {
+ const float radial=std::hypot(n.x(),n.y());
+ const float direction=QVector3D::dotProduct(n,QVector3D(p.x(),p.y(),0))<0?-1:1;
+ const auto xy=QVector3D(p.x(),p.y(),0).normalized()*radial*direction;
+ normal=QVector3D(xy.x(),xy.y(),n.z()).normalized();
+ }
+ const Vertex v{p.x(),p.y(),p.z(),normal.x(),normal.y(),normal.z(),.5f+p.x()/(radius*2),.5f-p.y()/(radius*2)};data.append(reinterpret_cast<const char*>(&v),sizeof(v));}
+}
+void upload(QQuick3DGeometry *geometry,const QByteArray &data,QVector3D low,QVector3D high) {
+ geometry->clear();geometry->setStride(sizeof(Vertex));geometry->setVertexData(data);geometry->setPrimitiveType(QQuick3DGeometry::PrimitiveType::Triangles);
+ geometry->addAttribute(QQuick3DGeometry::Attribute::PositionSemantic,0,QQuick3DGeometry::Attribute::F32Type);
+ geometry->addAttribute(QQuick3DGeometry::Attribute::NormalSemantic,3*sizeof(float),QQuick3DGeometry::Attribute::F32Type);
+ geometry->addAttribute(QQuick3DGeometry::Attribute::TexCoord0Semantic,6*sizeof(float),QQuick3DGeometry::Attribute::F32Type);
+ geometry->setBounds(low,high);geometry->update();
+}
+}
+RecordGeometry::RecordGeometry(QQuick3DObject *parent):QQuick3DGeometry(parent){connect(this,&RecordGeometry::shapeChanged,this,&RecordGeometry::rebuild);rebuild();}
+void RecordGeometry::rebuild() {
+ const float radius=qBound(1.f,m_radius,300.f),hole=qBound(.1f,m_hole,radius-.1f),depth=qBound(.05f,m_depth,60.f);
+ QByteArray data;const int radial=m_grooves?80:1,segments=128;
+ constexpr float grooveHeight=.012f;
+ data.reserve((radial+3)*segments*6*sizeof(Vertex));
+ const auto point=[](float r,int i,float z){const float a=i*2*float(M_PI)/128;return QVector3D(r*std::cos(a),r*std::sin(a),z);};
+ const auto quad=[&](QVector3D a,QVector3D b,QVector3D c,QVector3D d){triangle(data,a,b,c,radius,true);triangle(data,a,c,d,radius,true);};
+ for(int i=0;i<segments;++i){
+ for(int j=0;j<radial;++j){const float a=hole+(radius-hole)*j/radial,b=hole+(radius-hole)*(j+1)/radial;const float za=depth/2+(m_grooves&&j%2?grooveHeight:0),zb=depth/2+(m_grooves&&(j+1)%2?grooveHeight:0);quad(point(a,i,za),point(b,i,zb),point(b,i+1,zb),point(a,i+1,za));}
+ quad(point(hole,i,-depth/2),point(hole,i+1,-depth/2),point(radius,i+1,-depth/2),point(radius,i,-depth/2));
+ quad(point(radius,i,-depth/2),point(radius,i+1,-depth/2),point(radius,i+1,depth/2),point(radius,i,depth/2));
+ quad(point(hole,i,depth/2),point(hole,i+1,depth/2),point(hole,i+1,-depth/2),point(hole,i,-depth/2));
+ }
+ upload(this,data,{-radius,-radius,-depth/2},{radius,radius,depth/2+grooveHeight});
+}
+CoverTexture::CoverTexture(QObject *parent):QObject(parent){connect(this,&CoverTexture::artworkChanged,this,&CoverTexture::rebuild);rebuild();}
+void CoverTexture::rebuild(){
+ QImage image=m_artwork.isNull()?Disc::placeholderArt(512):m_artwork;
+ const int side=qMin(image.width(),image.height());image=image.copy((image.width()-side)/2,(image.height()-side)/2,side,side).scaled(512,512,Qt::KeepAspectRatio,Qt::SmoothTransformation).convertToFormat(QImage::Format_RGBA8888);
+ if(m_paper) {
+ const QImage art=image;image=QImage(1024,170,QImage::Format_RGBA8888);image.fill(QColor("#dfd6bf"));
+ QPainter p(&image);p.setRenderHint(QPainter::Antialiasing);
+ for(int y=0;y<170;y+=2){p.setPen(QColor(70,58,40,(y*17)%7));p.drawLine(0,y,1024,y);}
+ p.drawImage(QRect(13,13,144,144),art);p.setPen(QColor("#423e35"));
+ QFont font=QGuiApplication::font();font.setPixelSize(39);font.setWeight(QFont::Medium);p.setFont(font);
+ p.drawText(QRect(184,19,812,56),Qt::AlignVCenter,QFontMetrics(font).elidedText(m_title,Qt::ElideRight,800));
+ font.setPixelSize(29);font.setWeight(QFont::Normal);p.setFont(font);p.setPen(QColor("#726a59"));
+ p.drawText(QRect(184,84,812,43),Qt::AlignVCenter,QFontMetrics(font).elidedText(m_artist,Qt::ElideRight,800));
+ p.setPen(QPen(QColor("#a4977c"),1));p.drawLine(184,148,995,148);p.end();
+ }
+ const QByteArray pixels(reinterpret_cast<const char*>(image.constBits()),image.sizeInBytes());
+ if(m_texture&&m_texture->size()==image.size()&&m_texture->textureData()==pixels)return;
+ // Qt 6.11 reuses raw texture storage on update without regenerating its
+ // mipmaps. A new snapshot keeps minified labels and full-size covers in sync.
+ auto *next=new QQuick3DTextureData;
+ next->setParent(this);
+ next->setSize(image.size());next->setFormat(QQuick3DTextureData::RGBA8);
+ next->setHasTransparency(false);next->setTextureData(pixels);
+ auto *previous=m_texture;m_texture=next;
+ emit textureChanged();
+ if(previous)previous->deleteLater();
+}
+WaveGeometry::WaveGeometry(QQuick3DObject *parent):QQuick3DGeometry(parent){connect(this,&WaveGeometry::shapeChanged,this,&WaveGeometry::rebuild);rebuild();}
+void WaveGeometry::rebuild(){
+ QByteArray data;const float progress=qBound(0.f,m_progress,1.f);const int count=qMax(1,int(256*progress));
+ const auto p=[&](float f,float side){const float wave=std::sin(f*(m_linear?45.f:150.f)+m_phase)*m_amplitude;
+ if(m_linear)return QVector3D(-123+246*f,-125+wave+side,5);
+ const float a=f*2*float(M_PI),r=186+wave+side;return QVector3D(r*std::sin(a),r*std::cos(a),5);
+ };
+ for(int i=0;i<count;++i){const float a=progress*i/count,b=progress*(i+1)/count;triangle(data,p(a,-1.3f),p(b,-1.3f),p(b,1.3f),200);triangle(data,p(a,-1.3f),p(b,1.3f),p(a,1.3f),200);}
+ upload(this,data,{-200,-200,4},{200,200,6});
+}
+
+StudioTexture::StudioTexture(QQuick3DObject *parent):QQuick3DTextureData(parent) {
+ connect(this,&StudioTexture::tintChanged,this,&StudioTexture::rebuild);rebuild();
+}
+void StudioTexture::rebuild() {
+ QImage image(512,256,QImage::Format_RGBA8888);image.fill(QColor("#303239"));
+ QPainter p(&image);
+ QLinearGradient gradient(0,0,0,256);gradient.setColorAt(0,QColor("#888c92"));gradient.setColorAt(.5,QColor("#454850"));gradient.setColorAt(1,QColor("#181a1e"));p.fillRect(image.rect(),gradient);
+ for(const QRect rect:{QRect(60,38,60,125),QRect(325,62,120,65)}) { QRadialGradient light(rect.center(),rect.width());light.setColorAt(0,QColor("#ffffff"));light.setColorAt(1,QColor(200,206,215,0));p.fillRect(rect,light); }
+ QColor tint=m_tint.isValid()?m_tint:QColor(Qt::white);
+ QColor bounce=QColor::fromHsvF(qMax(0.,tint.hsvHueF()),qMin(.55,tint.hsvSaturationF()*1.5),1,.35);p.fillRect(image.rect(),bounce);
+ p.end();setSize(image.size());setFormat(RGBA8);setHasTransparency(false);setTextureData(QByteArray(reinterpret_cast<const char*>(image.constBits()),image.sizeInBytes()));
+}
+
+SurfaceTexture::SurfaceTexture(QQuick3DObject *parent):QQuick3DTextureData(parent) {
+ connect(this,&SurfaceTexture::kindChanged,this,&SurfaceTexture::rebuild);rebuild();
+}
+void SurfaceTexture::rebuild() {
+ // Small deterministic material maps, generated once per material rather
+ // than every frame. Geometry supplies the silhouette and physical grooves.
+ QImage image(256,256,QImage::Format_RGBA8888);
+ const auto noise=[](unsigned x,unsigned y){unsigned n=x*374761393u+y*668265263u;n=(n^(n>>13))*1274126177u;return int((n^(n>>16))&255);};
+ for(int y=0;y<256;++y)for(int x=0;x<256;++x) {
+ QColor color;
+ if(m_kind=="disc") {
+ const double a=std::atan2(y-127.5,x-127.5);
+ const double hue=(a+M_PI)/(2*M_PI);
+ color=QColor::fromHsvF(hue,.18,.88+.06*std::sin(a*3));
+ } else if(m_kind=="metal-normal") {
+ const float slope=(noise(0,(y+1)%256)-noise(0,(y+255)%256))/1024.f;
+ const auto n=QVector3D(0,slope,1).normalized();
+ color=QColor(qRound((n.x()+1)*127.5),qRound((n.y()+1)*127.5),qRound((n.z()+1)*127.5));
+ } else {
+ int value=0;
+ if(m_kind=="brushed")value=205+noise(0,y)/12+noise(x,y)/64;
+ else if(m_kind=="turned")value=175+noise(0,y)/5+noise(x,y)/64;
+ else if(m_kind=="vinyl") {const double r=std::hypot(x-127.5,y-127.5);value=210+int(4*std::sin(r*5))+noise(x,y)/64;}
+ else value=222+noise(x,y)/32;
+ color=QColor(value,value,value);
+ }
+ image.setPixelColor(x,y,color);
+ }
+ setSize(image.size());setFormat(RGBA8);setHasTransparency(false);
+ setTextureData(QByteArray(reinterpret_cast<const char*>(image.constBits()),image.sizeInBytes()));
+}
diff --git a/src/mediageometry.h b/src/mediageometry.h
new file mode 100644
index 0000000..4db6a9c
--- /dev/null
+++ b/src/mediageometry.h
@@ -0,0 +1,81 @@
+#pragma once
+#include <QQuick3DGeometry>
+#include <QQuick3DTextureData>
+#include <QImage>
+
+class RecordGeometry : public QQuick3DGeometry {
+ Q_OBJECT
+ Q_PROPERTY(float radius MEMBER m_radius NOTIFY shapeChanged)
+ Q_PROPERTY(float hole MEMBER m_hole NOTIFY shapeChanged)
+ Q_PROPERTY(float depth MEMBER m_depth NOTIFY shapeChanged)
+ Q_PROPERTY(bool grooves MEMBER m_grooves NOTIFY shapeChanged)
+public:
+ explicit RecordGeometry(QQuick3DObject *parent=nullptr);
+signals:
+ void shapeChanged();
+private:
+ void rebuild();
+ float m_radius=176,m_hole=3,m_depth=2;
+ bool m_grooves=false;
+};
+class CoverTexture : public QObject {
+ Q_OBJECT
+ Q_PROPERTY(QQuick3DTextureData *texture READ texture NOTIFY textureChanged)
+ Q_PROPERTY(QImage artwork MEMBER m_artwork NOTIFY artworkChanged)
+ Q_PROPERTY(bool paper MEMBER m_paper NOTIFY artworkChanged)
+ Q_PROPERTY(QString title MEMBER m_title NOTIFY artworkChanged)
+ Q_PROPERTY(QString artist MEMBER m_artist NOTIFY artworkChanged)
+public:
+ explicit CoverTexture(QObject *parent=nullptr);
+ QQuick3DTextureData *texture() const { return m_texture; }
+ QSize size() const { return m_texture->size(); }
+ QByteArray textureData() const { return m_texture->textureData(); }
+signals:
+ void artworkChanged();
+ void textureChanged();
+private:
+ void rebuild();
+ QQuick3DTextureData *m_texture=nullptr;
+ QImage m_artwork;
+ bool m_paper=false;
+ QString m_title,m_artist;
+};
+class WaveGeometry : public QQuick3DGeometry {
+ Q_OBJECT
+ Q_PROPERTY(float progress MEMBER m_progress NOTIFY shapeChanged)
+ Q_PROPERTY(float phase MEMBER m_phase NOTIFY shapeChanged)
+ Q_PROPERTY(float amplitude MEMBER m_amplitude NOTIFY shapeChanged)
+ Q_PROPERTY(bool linear MEMBER m_linear NOTIFY shapeChanged)
+public:
+ explicit WaveGeometry(QQuick3DObject *parent=nullptr);
+signals:
+ void shapeChanged();
+private:
+ void rebuild();
+ float m_progress=0,m_phase=0,m_amplitude=0;
+ bool m_linear=false;
+};
+
+class StudioTexture : public QQuick3DTextureData {
+ Q_OBJECT
+ Q_PROPERTY(QColor tint MEMBER m_tint NOTIFY tintChanged)
+public:
+ explicit StudioTexture(QQuick3DObject *parent=nullptr);
+signals:
+ void tintChanged();
+private:
+ void rebuild();
+ QColor m_tint=Qt::white;
+};
+
+class SurfaceTexture : public QQuick3DTextureData {
+ Q_OBJECT
+ Q_PROPERTY(QString kind MEMBER m_kind NOTIFY kindChanged)
+public:
+ explicit SurfaceTexture(QQuick3DObject *parent=nullptr);
+signals:
+ void kindChanged();
+private:
+ void rebuild();
+ QString m_kind="brushed";
+};
diff --git a/src/mediauitest.cpp b/src/mediauitest.cpp
index 2a14ce8..e08c4dd 100644
--- a/src/mediauitest.cpp
+++ b/src/mediauitest.cpp
@@ -24,11 +24,18 @@ int exerciseMediaUi(Player &player, QQuickWindow *window, const QString &temp, c
for(auto *child:parent->childItems())if(auto *result=find(child,name))return result;
return nullptr;
};
- auto item=[&](const QString &name){return find(window->contentItem(),name);};
+ auto item=[&](const QString &name){auto *result=find(window->contentItem(),name);return result ? result : window->findChild<QQuickItem*>(name);};
auto capture=[&](const QString &name){
if(captures.isEmpty())return;
if(!window->isExposed()){std::cout<<"SKIP capture on hidden native workspace"<<std::endl;return;}
QDir().mkpath(captures);
+ if(window->property("threeDActive").toBool()) {
+ const auto frame=window->grabWindow();
+ int pixels=0;
+ for(int y=100;y<qMin(510,frame.height());y+=3)for(int x=40;x<qMin(490,frame.width());x+=3)if(qAlpha(frame.pixel(x,y))>128)++pixels;
+ check(pixels>3000,"3D frame contains rendered physical geometry");
+ check(!frame.isNull()&&frame.save(captures+"/"+name+".png"),"media capture saved");return;
+ }
auto grab=window->contentItem()->grabToImage();
check(grab&&wait([&]{return !grab->image().isNull();})&&grab->image().save(captures+"/"+name+".png"),"media capture saved");
};
@@ -44,6 +51,25 @@ int exerciseMediaUi(Player &player, QQuickWindow *window, const QString &temp, c
player.addUrls(files,false);check(wait([&]{return !player.busy();})&&player.count()==3,"album fixture imports three tracks");
player.setVinyl(true);player.setVinylAlbumMode(true);QTest::qWait(350);
check(!window->property("recordKey").toString().isEmpty(),"album grooves expose a stable gesture identity");
+ player.setHorizontalSeek(true);QTest::qWait(100);
+ auto *horizontal=item("horizontalSeek"),*albumRim=item("scrubber"),*previewArm=item("vinylTonearm");
+ if(horizontal&&albumRim&&previewArm) {
+ previewArm->setProperty("landingProgress",.05);previewArm->setProperty("landing",true);
+ const auto point=horizontal->mapToScene(QPointF(horizontal->width()*.6,horizontal->height()/2)).toPoint();
+ QTest::mousePress(window,Qt::LeftButton,Qt::NoModifier,point);
+ check(!previewArm->property("landing").toBool(),"new seek preview supersedes a pending needle landing");
+ const double trackFraction=horizontal->property("previewValue").toDouble();
+ check(std::abs(window->property("recordVisualProgress").toDouble()-trackFraction/3)<.01,"horizontal preview maps the current song into the album timeline");
+ check(std::abs(previewArm->property("armAngle").toDouble()-(6+20*trackFraction/3))<.3,"paused album tonearm follows the horizontal preview immediately");
+ QTest::mouseRelease(window,Qt::LeftButton,Qt::NoModifier,point);
+ const auto ringStart=albumRim->mapToScene(QPointF(436,220)).toPoint(),ringEnd=albumRim->mapToScene(QPointF(220,436)).toPoint();
+ QTest::mousePress(window,Qt::LeftButton,Qt::NoModifier,ringStart);
+ QMouseEvent move(QEvent::MouseMove,ringEnd,window->mapToGlobal(ringEnd),Qt::NoButton,Qt::LeftButton,Qt::NoModifier);QGuiApplication::sendEvent(window,&move);
+ check(albumRim->property("scrubbing").toBool()&&std::abs(window->property("recordVisualProgress").toDouble()-.5)<.01,"album ring retains an actual pointer drag");
+ check(std::abs(horizontal->property("value").toDouble()-.5)<.01&&std::abs(previewArm->property("armAngle").toDouble()-16)<.3,"album ring preview synchronizes the next song position and tonearm");
+ QTest::mouseRelease(window,Qt::LeftButton,Qt::NoModifier,ringEnd);
+ } else check(false,"shared album seeking controls exist");
+ player.pause();player.select(0,false);player.seek(0);player.setHorizontalSeek(false);QTest::qWait(100);
auto *arm=item("vinylTonearm"),*shaft=item("tonearmShaft");
check(arm&&shaft&&item("albumGrooves"),"album needle and groove boundaries are visible");
if(arm&&shaft){
@@ -166,5 +192,90 @@ int exerciseMediaUi(Player &player, QQuickWindow *window, const QString &temp, c
if(palette.open(QIODevice::WriteOnly|QIODevice::Truncate)){palette.write(original);palette.close();}
}
+ if(qmlContext(window)->contextProperty("supports3D").toBool()) {
+ player.pause();player.setMotion(false);player.setThreeD(true);
+ check(wait([&]{return window->property("threeDActive").toBool();}),"optional 3D view loads successfully");
+ {Player restored(temp+"/player.ini");check(restored.threeD(),"3D preference survives relaunch");}
+ for(const auto &medium:QStringList{"vinyl","cd","cassette"}) {
+ player.setMedium(medium);QTest::qWait(300);
+ capture("3d-"+medium);
+ auto *view=item("player3DView");
+ check(view&&view->isVisible(),"each physical medium has a 3D view");
+
+ check(view&&view->property("camera").value<QObject*>(),"3D scene has an active camera");
+ check(item("playerDeck")->mapToScene(QPointF())==deckPos&&item("sourceBar")->mapToScene(QPointF())==barPos,"3D leaves playback and source controls in their familiar positions");
+ if(view&&window->isExposed()) {
+ player.seek(0);QTest::qWait(80);
+ const auto sourcePoint=medium=="cassette" ? item("cassetteSeek")->mapToItem(item("mediaSurface"),QPointF(80,18)) : item("scrubber")->mapToItem(item("mediaSurface"),QPointF(436,220));
+ QVariant mapped;
+ QMetaObject::invokeMethod(view,"projectSurface",Q_RETURN_ARG(QVariant,mapped),Q_ARG(QVariant,sourcePoint.x()),Q_ARG(QVariant,sourcePoint.y()));
+ QTest::mouseClick(window,Qt::LeftButton,Qt::NoModifier,view->mapToScene(mapped.toPointF()).toPoint());
+ check(wait([&]{return qAbs(player.position()-player.duration()*.25)<1200;}),"projected 3D progress control seeks accurately");
+ if(medium=="cd") {
+ for(double zoom:{.85,1.5}) {
+ typography->setProperty("uiScale",zoom);QTest::qWait(120);player.seek(0);
+ const auto point=item("scrubber")->mapToItem(item("mediaSurface"),QPointF(436,220));QVariant out;
+ QMetaObject::invokeMethod(view,"projectSurface",Q_RETURN_ARG(QVariant,out),Q_ARG(QVariant,point.x()),Q_ARG(QVariant,point.y()));
+ QTest::mouseClick(window,Qt::LeftButton,Qt::NoModifier,view->mapToScene(out.toPointF()).toPoint());
+ check(wait([&]{return qAbs(player.position()-player.duration()*.25)<1200;}),"3D seeking remains accurate after interface scaling");
+ }
+ typography->setProperty("uiScale",1.);QTest::qWait(120);
+ }
+ if(medium=="vinyl") {
+ player.seek(8000);QTest::qWait(80);
+ const auto oldRim=item("scrubber")->mapToScene(QPointF(220,2)).toPoint();
+ QTest::mouseClick(window,Qt::LeftButton,Qt::NoModifier,oldRim);QTest::qWait(80);
+ check(qAbs(player.position()-8000)<700,"empty 3D space cannot activate the hidden flat seek control");
+ const auto project=[&](QPointF p){QVariant out;QMetaObject::invokeMethod(view,"projectSurface",Q_RETURN_ARG(QVariant,out),Q_ARG(QVariant,p.x()),Q_ARG(QVariant,p.y()));return view->mapToScene(out.toPointF()).toPoint();};
+ auto *needle=item("needleHandle");auto *tonearm=item("vinylTonearm");
+ const auto start=project(tonearm->mapToItem(item("mediaSurface"),needle->property("tip").toPointF()));
+ const double angle=16.*M_PI/180.;
+ const auto finish=project(tonearm->mapToItem(item("mediaSurface"),QPointF(378-197*std::sin(angle),100+197*std::cos(angle))));
+ QTest::mousePress(window,Qt::LeftButton,Qt::NoModifier,start);QTest::qWait(30);
+ check(tonearm->property("dragging").toBool(),"3D needle accepts a grab at its projected position");
+ for(int step=1;step<=8;++step){QTest::mouseMove(window,start+(finish-start)*step/8);QTest::qWait(20);}
+ QTest::mouseRelease(window,Qt::LeftButton,Qt::NoModifier,finish);
+ check(wait([&]{return player.playing()&&qAbs(player.position()-player.duration()*.5)<1300;}),"3D needle drop seeks and resumes playback");player.pause();
+ }
+
+ }
+ }
+ player.setMotion(true);auto *view=item("player3DView");
+ if(view&&window->isExposed()) {
+ QTest::mouseMove(window,view->mapToScene(QPointF(430,180)).toPoint());QTest::qWait(250);
+ check(std::abs(view->property("yawOffset").toDouble())>0.1,"3D responds to gentle pointer tilt");
+ player.setMotion(false);QTest::qWait(50);
+ check(view->property("yawOffset").toDouble()==0&&view->property("pitchOffset").toDouble()==0,"reduced motion disables perspective tilt");
+ }
+ player.setMiniMode(true);QTest::qWait(100);
+ check(!window->property("threeDActive").toBool(),"Mini mode unloads the 3D view");
+ player.setMiniMode(false);QTest::qWait(150);
+ window->setProperty("discFlipped",true);QTest::qWait(150);
+ check(!window->property("threeDActive").toBool(),"reverse details remain flat and readable");
+ window->setProperty("discFlipped",false);player.setThreeD(false);QTest::qWait(150);
+ check(!window->property("threeDActive").toBool()&&!item("scene3DLoader")->property("active").toBool(),"disabling 3D releases its scene");
+ }
+
+ player.setThreeD(false);player.setMotion(false);
+ auto *notice=item("actionNotice");auto *dismiss=item("dismissActionNotice");
+ for(const QString &medium:{QString("cd"),QString("vinyl"),QString("cassette")})
+ for(bool mini:{false,true})for(bool horizontal:{false,true}) {
+ player.setMedium(medium);player.setMiniMode(mini);player.setHorizontalSeek(horizontal);
+ QMetaObject::invokeMethod(window,"notifyAction",Q_ARG(QVariant,QString("Playback message")),Q_ARG(QVariant,true));
+ QTest::qWait(180);
+ for(double scale:{.65,1.,1.5}) {
+ typography->setProperty("uiScale",scale);QTest::qWait(60);
+ const auto bounds=notice->mapRectToScene(notice->boundingRect());
+ const auto *controls=item(mini?"miniControls":"playerDeck");
+ const auto controlsBounds=controls->mapRectToScene(controls->boundingRect());
+ check(notice->isVisible()&&bounds.top()>=controlsBounds.bottom()
+ &&QRectF(0,0,window->width(),window->height()).contains(bounds),
+ qPrintable(medium+QString(" %1 horizontal %2 scale %3: feedback fits below controls").arg(mini?"Mini":"full").arg(horizontal).arg(scale)));
+ }
+ QTest::mouseClick(window,Qt::LeftButton,Qt::NoModifier,dismiss->mapToScene(QPointF(dismiss->width()/2,dismiss->height()/2)).toPoint());
+ check(wait([&]{return !notice->isVisible();}),"scaled feedback dismissal remains clickable");
+ }
+ typography->setProperty("uiScale",1.);player.setMiniMode(false);player.setHorizontalSeek(false);QTest::qWait(100);
+ check(window->property("layoutHeight").toInt()==730,"full player returns to its regular height after feedback closes");
std::cout<<"MEDIA UI RESULT "<<failures<<" failures"<<std::endl;return failures?1:0;
}
diff --git a/src/player.cpp b/src/player.cpp
index 8d8b981..a93f579 100644
--- a/src/player.cpp
+++ b/src/player.cpp
@@ -41,6 +41,7 @@ Player::Player(const QString &settingsPath, QObject *parent)
m_light = m_settings.value("light", false).toBool();
m_medium=m_settings.value("medium",m_settings.value("vinyl",false).toBool()?"vinyl":"cd").toString();
if(!QStringList{"cd","vinyl","cassette"}.contains(m_medium))m_medium="cd";
+ m_threeD=m_settings.value("threeD",false).toBool();
m_cd500Rpm=m_settings.value("cd500Rpm",false).toBool();
m_vinylSpeed=m_settings.value("vinylSpeed",33).toInt();
if(m_vinylSpeed!=0&&m_vinylSpeed!=33&&m_vinylSpeed!=45)m_vinylSpeed=33;
@@ -477,6 +478,7 @@ void Player::setMedium(const QString &value) {
}
void Player::setShowPlayerBody(bool value) { if(value==m_showPlayerBody)return;m_showPlayerBody=value;emit settingsChanged();save(); }
void Player::setCassetteFinish(const QString &value) { if(value==m_cassetteFinish || !QStringList{"clear","smoke","cream"}.contains(value))return;m_cassetteFinish=value;emit settingsChanged();save(); }
+void Player::setThreeD(bool value) { if(value==m_threeD)return;m_threeD=value;emit settingsChanged();save(); }
void Player::setCd500Rpm(bool value) { if(value==m_cd500Rpm)return;m_cd500Rpm=value;emit settingsChanged();save(); }
void Player::setVinylSpeed(int value) { if((value!=0&&value!=33&&value!=45)||value==m_vinylSpeed)return;m_vinylSpeed=value;emit settingsChanged();save(); }
void Player::setHorizontalSeek(bool value) { if(value==m_horizontalSeek)return;m_horizontalSeek=value;emit settingsChanged();save(); }
@@ -496,6 +498,7 @@ void Player::save() {
m_settings.setValue("medium", m_medium);
m_settings.setValue("motion", m_motion);
m_settings.setValue("cassetteSounds", m_cassetteSounds);
+ m_settings.setValue("threeD",m_threeD);
m_settings.setValue("cd500Rpm",m_cd500Rpm);
m_settings.setValue("vinylSpeed",m_vinylSpeed);
m_settings.setValue("vinylAlbumMode",m_vinylAlbumMode);
diff --git a/src/player.h b/src/player.h
index 4b929e7..77a995c 100644
--- a/src/player.h
+++ b/src/player.h
@@ -23,6 +23,7 @@ struct ImportedTracks { QList<Track> tracks; QString firstPath; };
class Player : public QObject {
Q_OBJECT
Q_PROPERTY(QString trackKey READ trackKey NOTIFY trackChanged)
+ Q_PROPERTY(bool threeD READ threeD WRITE setThreeD NOTIFY settingsChanged)
Q_PROPERTY(bool cd500Rpm READ cd500Rpm WRITE setCd500Rpm NOTIFY settingsChanged)
Q_PROPERTY(int vinylSpeed READ vinylSpeed WRITE setVinylSpeed NOTIFY settingsChanged)
Q_PROPERTY(bool vinylAlbumMode READ vinylAlbumMode WRITE setVinylAlbumMode NOTIFY settingsChanged)
@@ -65,6 +66,8 @@ public:
explicit Player(const QString &settingsPath, QObject *parent = nullptr);
~Player() override;
QString trackKey() const { return currentUrl().toString(); }
+ bool threeD() const { return m_threeD; }
+ void setThreeD(bool value);
bool cd500Rpm() const { return m_cd500Rpm; }
void setCd500Rpm(bool value);
int vinylSpeed() const { return m_vinylSpeed; }
@@ -191,6 +194,7 @@ private:
QSet<QString> m_shuffleVisited;
QString m_artFile, m_error;
bool m_ciderAutoStart = false;
+ bool m_threeD=false;
bool m_cd500Rpm=false;
int m_vinylSpeed=33;
bool m_vinylAlbumMode=false;
diff --git a/src/threedtest.cpp b/src/threedtest.cpp
new file mode 100644
index 0000000..875b2b5
--- /dev/null
+++ b/src/threedtest.cpp
@@ -0,0 +1,293 @@
+#include "threedtest.h"
+#include "player.h"
+#include "disc.h"
+#include "theme.h"
+#include "testinput.h"
+#include <QQmlContext>
+#include <QQuickItem>
+#include <QQuickWindow>
+#include <QPointer>
+#include <QTest>
+#include <QElapsedTimer>
+#include <QDir>
+#include <QFile>
+#include <QSaveFile>
+#include <QWheelEvent>
+#ifdef SPUN_WITH_3D
+#include <QQuick3DGeometry>
+#endif
+#include <taglib/fileref.h>
+#include <taglib/tag.h>
+#include <cmath>
+#include <functional>
+#include <iostream>
+
+namespace {
+bool until(const std::function<bool()> &condition,int timeout=2500) {
+ QElapsedTimer t;t.start();while(!condition()&&t.elapsed()<timeout)QTest::qWait(20);return condition();
+}
+QQuickItem *findItem(QQuickItem *parent,const QString &name) {
+ if(parent->objectName()==name)return parent;
+ for(auto *child:parent->childItems())if(auto *found=findItem(child,name))return found;
+ return nullptr;
+}
+}
+
+int exerciseThreeD(Player &player,QQuickWindow *window,const QString &temp,const QString &captures) {
+ int failures=0,checks=0;
+ QString context="setup";
+ const auto check=[&](bool ok,const char *name){++checks;if(!ok)++failures;std::cout<<(ok?"PASS ":"FAIL ")<<context.toStdString()<<": "<<name<<std::endl;return ok;};
+ if(!check(qmlContext(window)->contextProperty("supports3D").toBool(),"Quick 3D is available"))return 2;
+ if(!check(until([&]{return window->isExposed();}),"native test window is exposed"))return 2;
+ auto *typography=qmlContext(window)->contextProperty("typography").value<QObject*>();
+ const auto item=[&](const QString &name){auto *result=findItem(window->contentItem(),name);return result ? result : window->findChild<QQuickItem*>(name);};
+ const auto invoke=[&](const char *name){QMetaObject::invokeMethod(window,name);};
+ const auto click=[&](const QString &name){auto *control=item(name);if(!check(control&&control->isVisible()&&control->isEnabled(),qPrintable(name+" is actionable")))return;QTest::mouseClick(window,Qt::LeftButton,Qt::NoModifier,control->mapToScene(QPointF(control->width()/2,control->height()/2)).toPoint());QTest::qWait(40);};
+ const auto project=[&](QQuickItem *control,QPointF point){
+ auto *view=item("player3DView");auto *surface=item("mediaSurface");
+ if(!view||!surface||!control)return QPoint(-1000,-1000);
+ const auto local=control->mapToItem(surface,point);QVariant result;
+ QMetaObject::invokeMethod(view,"projectSurface",Q_RETURN_ARG(QVariant,result),Q_ARG(QVariant,local.x()),Q_ARG(QVariant,local.y()));
+ return view->mapToScene(result.toPointF()).toPoint();
+ };
+ const auto hoverOutside=[&]{QTest::mouseMove(window,QPoint(12,12));QTest::qWait(60);};
+ const auto drag=[&](QPoint from,QPoint to,Qt::KeyboardModifiers mods=Qt::NoModifier){
+ QTest::mousePress(window,Qt::LeftButton,mods,from);
+ for(int step=1;step<=8;++step){const auto p=from+(to-from)*step/8;QMouseEvent event(QEvent::MouseMove,p,window->mapToGlobal(p),Qt::NoButton,Qt::LeftButton,mods);QGuiApplication::sendEvent(window,&event);QTest::qWait(15);}
+ QTest::mouseRelease(window,Qt::LeftButton,mods,to);QTest::qWait(60);
+ };
+ const auto render=[&](const QString &name){
+ const auto frame=window->grabWindow();
+ if(!check(!frame.isNull(),"rendered frame is available"))return;
+ const auto sx=frame.width()/double(window->width());const auto scale=window->property("uiScale").toDouble()*sx;
+ int opaque=0,total=0;
+ for(int y=130;y<490;y+=8)for(int x=65;x<465;x+=8){++total;const QPoint p(qRound(x*scale),qRound(y*scale));if(frame.rect().contains(p)&&frame.pixelColor(p).alpha()>128)++opaque;}
+ check(opaque>total/3,"3D medium is actually rendered");
+ if(!captures.isEmpty()){QDir().mkpath(captures);check(frame.save(captures+"/"+name+".png"),"capture saved");}
+ };
+ player.setVolume(0);player.setMotion(false);player.setThreeD(false);player.setMiniMode(false);player.setShuffle(false);player.setRepeatMode(0);
+ window->setProperty("useCider",false);player.clear();
+ QList<QUrl> files;
+ for(int i=0;i<4;++i){const auto path=temp+QString("/three-d-%1.flac").arg(i);QFile::copy(QStringLiteral(SPUN_SOURCE_DIR "/assets/First-Light.flac"),path);TagLib::FileRef file(QFile::encodeName(path).constData());file.tag()->setAlbum(i<3?"Test record":"Next record");file.tag()->setTitle(TagLib::String(QString("Test track %1").arg(i+1).toUtf8().constData(),TagLib::String::UTF8));file.tag()->setTrack(i+1);file.save();files.append(QUrl::fromLocalFile(path));}
+ player.addUrls(files,false);if(!check(until([&]{return !player.busy()&&player.count()==4;}),"isolated album fixtures imported"))return 1;
+ player.setThreeD(true);if(!check(until([&]{return window->property("threeDActive").toBool();}),"3D scene loads"))return 1;
+ QTest::qWait(300);
+ for(const auto &medium:QStringList{"cd","vinyl","cassette"}) {
+ player.setMedium(medium);player.setVinylAlbumMode(false);player.setHorizontalSeek(false);player.select(0,false);QTest::qWait(200);
+ for(double zoom:{.85,1.,1.5}) {
+ context=medium+QString(" scale %1").arg(zoom);typography->setProperty("uiScale",zoom);QTest::qWait(200);
+ auto *control=item(medium=="cassette"?"cassetteSeek":"scrubber");
+ if(!check(control!=nullptr,"projected seek control exists"))continue;
+ player.seek(0);
+ const auto quarter=project(control,medium=="cassette"?QPointF(80,18):QPointF(436,220));
+ QTest::mouseClick(window,Qt::LeftButton,Qt::NoModifier,quarter);
+ check(until([&]{return std::abs(player.position()-player.duration()*.25)<1200;}),"projected click seeks to 25 percent");
+ const auto threeQuarter=project(control,medium=="cassette"?QPointF(224,18):QPointF(4,220));
+ if(medium=="cassette")drag(quarter,threeQuarter);
+ else {
+ QTest::mousePress(window,Qt::LeftButton,Qt::NoModifier,quarter);
+ for(int step=1;step<=16;++step){const double angle=(.5+step/16.)*std::acos(-1.);const auto p=project(control,QPointF(220+216*std::sin(angle),220-216*std::cos(angle)));QMouseEvent event(QEvent::MouseMove,p,window->mapToGlobal(p),Qt::NoButton,Qt::LeftButton,Qt::NoModifier);QGuiApplication::sendEvent(window,&event);QTest::qWait(12);}
+ QTest::mouseRelease(window,Qt::LeftButton,Qt::NoModifier,threeQuarter);QTest::qWait(60);
+ }
+ check(until([&]{return std::abs(player.position()-player.duration()*.75)<1400;}),"projected drag seeks to 75 percent");
+ check(!window->property("threeDGesture").toBool(),"release clears seek gesture");
+ hoverOutside();
+ player.seek(0);click("playButton");check(until([&]{return player.playing();}),"play works after 3D drag");
+ click("playButton");check(!player.playing(),"pause works after 3D drag");
+ player.select(0,false);click("nextButton");check(until([&]{return player.currentIndex()==1;}),"next selects the next song");player.pause();player.seek(0);
+ click("previousButton");check(until([&]{return player.currentIndex()==0;}),"previous selects the preceding song");player.pause();
+ click("shuffleButton");check(player.shuffle(),"shuffle toggles on");click("shuffleButton");check(!player.shuffle(),"shuffle toggles off");
+ player.setRepeatMode(0);for(int n=1;n<=3;++n){click("repeatButton");check(player.repeatMode()==n%3,"repeat cycles correctly");}
+ click("volumeSlider");check(player.volume()>0,"volume slider still receives untransformed input");player.setVolume(0);
+ click("queueButton");check(window->property("queueOpen").toBool(),"queue opens alongside 3D");QTest::qWait(150);
+ player.seek(0);QTest::mouseClick(window,Qt::LeftButton,Qt::NoModifier,project(control,medium=="cassette"?QPointF(80,18):QPointF(436,220)));
+ check(until([&]{return std::abs(player.position()-player.duration()*.25)<1200;}),"seeking stays aligned with queue open");
+ click("queueButton");check(!window->property("queueOpen").toBool(),"queue closes after projected interaction");
+ hoverOutside();
+ }
+ typography->setProperty("uiScale",1.);player.pause();player.seek(4000);QTest::qWait(180);context=medium+" lifecycle";render(medium);
+#ifdef SPUN_WITH_3D
+ const auto geometryFor=[&](const char *name){auto *model=window->findChild<QObject*>(name);return model?qobject_cast<QQuick3DGeometry*>(model->property("geometry").value<QObject*>()):nullptr;};
+ if(medium!="cassette") {
+ auto *record=geometryFor("threeDRecord"),*labelMesh=geometryFor("threeDRecordLabel");
+ check(record&&record->boundsMax().z()>record->boundsMin().z(),"record has physical thickness");
+ check(labelMesh&&std::abs(labelMesh->boundsMax().x()-(medium=="vinyl"?62:169))<.1,"label mesh has the intended physical proportions");
+ } else {
+ auto *cartridge=window->findChild<QObject*>("threeDReel0");check(cartridge!=nullptr,"cassette has modeled reels");
+ }
+#endif
+
+ for(bool motion:{false,true}) {
+ player.setMotion(motion);player.play();QTest::qWait(150);
+ invoke("flipDisc");check(until([&]{return window->property("discFlipped").toBool()&&!window->property("threeDActive").toBool();}),"flip opens readable reverse while playing");
+ check(player.playing(),"flipping preserves playback");
+ hoverOutside();invoke("flipDisc");check(until([&]{return window->property("threeDActive").toBool();}),"return from reverse restores 3D");
+ player.setMiniMode(true);check(until([&]{return !window->property("threeDActive").toBool();}),"Mini unloads 3D");hoverOutside();
+ player.setMiniMode(false);check(until([&]{return window->property("threeDActive").toBool();}),"full mode restores 3D");
+ player.setThreeD(false);hoverOutside();check(!window->property("threeDActive").toBool()&&item("mediaSurface")->parentItem()->objectName()!="threeDTextureRoot","flat controls survive 3D destruction");
+ player.setThreeD(true);QTest::qWait(180);hoverOutside();check(window->property("threeDActive").toBool(),"3D can be enabled again after hovering flat controls");
+ }
+ player.pause();player.setMotion(false);
+ }
+ context="needle combinations";player.setMedium("vinyl");QTest::qWait(150);
+ for(bool album:{false,true}) {
+ player.setVinylAlbumMode(album);player.select(0,false);player.seek(0);QTest::qWait(180);
+ auto *arm=item("vinylTonearm");auto *needle=item("needleHandle");
+ if(!check(arm&&needle,"tonearm exists"))continue;
+ const auto from=project(arm,needle->property("tip").toPointF());const double angle=16*std::acos(-1.)/180.;const auto to=project(arm,QPointF(378-197*std::sin(angle),100+197*std::cos(angle)));
+ auto *bands=window->findChild<QObject*>("threeDTrackBands");
+ check(bands&&bands->property("count").toInt()==(album?2:0),"album track boundaries appear only in record mode");
+ drag(from,to);check(until([&]{return player.playing()&&player.currentIndex()==(album?1:0)&&std::abs(player.position()-16000)<1800;}),"needle maps song or album position correctly");player.pause();
+ for(int transition=0;transition<3;++transition){
+ QTest::qWait(100);needle=item("needleHandle");arm=item("vinylTonearm");
+ const auto tip=project(arm,needle->property("tip").toPointF());QTest::mousePress(window,Qt::LeftButton,Qt::NoModifier,tip);QTest::qWait(30);
+ check(arm->property("dragging").toBool(),"needle grab begins before mode change");
+ if(transition==0)player.setThreeD(false);else if(transition==1)player.setMiniMode(true);else window->setProperty("discFlipped",true);
+ QTest::qWait(70);check(!arm->property("dragging").toBool(),"mode change cancels needle grab");
+ QTest::mouseRelease(window,Qt::LeftButton,Qt::NoModifier,tip);hoverOutside();
+ player.setMiniMode(false);window->setProperty("discFlipped",false);player.setThreeD(true);QTest::qWait(140);
+ }
+ }
+ context="projected shortcuts and hints";player.setMedium("cd");player.setMotion(false);player.setVinylAlbumMode(false);QTest::qWait(150);
+ auto *view=item("player3DView");
+ const QPoint center=view->mapToScene(QPointF(view->width()/2,view->height()/2)).toPoint();
+ QTest::mouseDClick(window,Qt::LeftButton,Qt::NoModifier,center);
+ check(until([&]{return window->property("discFlipped").toBool();}),"double clicking the 3D medium opens its reverse");
+ invoke("flipDisc");QTest::qWait(180);
+ QTest::mouseClick(window,Qt::RightButton,Qt::NoModifier,center);
+ check(until([&]{return window->property("menuOpen").toBool();}),"right click opens settings in 3D");
+ testKeyClick(window,Qt::Key_Escape);QTest::qWait(180);
+ check(!window->property("menuOpen").toBool(),"Escape dismisses the 3D context menu");
+ hoverOutside();auto *rim=item("scrubber");
+ const QPoint rimPoint=project(rim,QPointF(436,220));QTest::mouseMove(window,rimPoint);QTest::qWait(850);
+ auto *hint=window->findChild<QObject*>("threeDToolTip");
+ check(hint&&hint->property("visible").toBool(),"projected seek hover has a correctly placed hint");
+ QTest::qWait(2700);check(hint&&!hint->property("visible").toBool(),"projected hint expires while stationary");
+ hoverOutside();QTest::mouseMove(window,rimPoint);QTest::qWait(850);
+ check(hint&&hint->property("visible").toBool(),"leaving and returning allows the hint again");
+ hoverOutside();QTest::qWait(150);check(hint&&!hint->property("visible").toBool(),"leaving the player dismisses the hint");
+ player.seek(0);QTest::mousePress(window,Qt::LeftButton,Qt::NoModifier,rimPoint);testKeyClick(window,Qt::Key_Escape);QTest::mouseRelease(window,Qt::LeftButton,Qt::NoModifier,rimPoint);
+ check(!window->property("threeDGesture").toBool()&&player.position()<1000,"Escape cancels a projected drag without seeking");
+ QTest::mousePress(window,Qt::LeftButton,Qt::NoModifier,rimPoint);player.select(1,false);QTest::mouseRelease(window,Qt::LeftButton,Qt::NoModifier,rimPoint);
+ check(!window->property("threeDGesture").toBool()&&player.position()<1000,"song changes cancel a projected drag without seeking the next song");
+ context="wallpaper lighting";
+ auto *theme=qobject_cast<Theme*>(qmlContext(window)->contextProperty("theme").value<QObject*>());
+ QFile palette(temp+"/config/gtk-4.0/noctalia.css");if(!check(palette.open(QIODevice::ReadOnly),"isolated theme fixture opens"))return 1;const auto originalPalette=palette.readAll();palette.close();
+ for(const QByteArray &accent:{QByteArray("#82bed5"),QByteArray("#e4a17f")}) {
+ auto css=originalPalette;css.replace("#e6b599",accent);if(!check(palette.open(QIODevice::WriteOnly),"theme fixture can change"))return 1;palette.write(css);palette.close();if(theme)theme->reload();QTest::qWait(180);
+ auto *light=window->findChild<QObject*>("threeDFillLight");const QColor tint=light?light->property("color").value<QColor>():QColor();
+ check(tint.isValid()&&(accent=="#82bed5"?tint.blue()>tint.red():tint.red()>tint.blue()),"3D fill light follows the live Noctalia accent");
+ check(tint.redF()>.6&&tint.greenF()>.6&&tint.blueF()>.6,"wallpaper lighting keeps a neutral base for readable materials");
+ render(accent=="#82bed5"?"cool-lighting":"warm-lighting");
+ }
+ if(!check(palette.open(QIODevice::WriteOnly),"theme fixture can be restored"))return 1;
+ palette.write(originalPalette);palette.close();if(theme)theme->reload();
+ context="CD lid and album transitions";player.setMedium("cd");player.setVinylAlbumMode(false);player.setMotion(true);player.setThreeD(true);QTest::qWait(200);
+ auto *presentation=qobject_cast<DiscPresentation*>(qmlContext(window)->contextProperty("presentation").value<QObject*>());
+ if(check(presentation!=nullptr,"album presenter is available")) {
+ presentation->present(player.artwork(),"3d-first-record",false);
+ presentation->present(player.artwork(),"3d-second-record",true);
+ check(window->property("swapRunning").toBool(),"album change starts the lid sequence");
+ player.play();check(player.playing(),"lid motion does not delay playback");
+ bool stayedInside=true,sawOpen=false;QElapsedTimer timer;timer.start();
+ while(timer.elapsed()<1400) {
+ QTest::qWait(30);auto *view=item("player3DView");if(!view){stayedInside=false;break;}
+ QVariant result;QMetaObject::invokeMethod(view,"lidBounds",Q_RETURN_ARG(QVariant,result));const auto bounds=result.toRectF();
+ stayedInside=stayedInside&&bounds.left()>=0&&bounds.top()>=0&&bounds.right()<=view->width()&&bounds.bottom()<=view->height();
+ if(!sawOpen&&window->property("lidOpen").toDouble()>.95){sawOpen=true;render("cd-lid-open");}
+ }
+ check(sawOpen,"lid reaches its open position");check(stayedInside,"lid remains below top controls and inside its viewport throughout motion");
+ check(!window->property("swapRunning").toBool()&&window->property("lidOpen").toDouble()==0&&window->property("packageOpacity").toDouble()==0,"completed transition clears lid and packaging state");
+ for(int interruption=0;interruption<4;++interruption) {
+ player.setMotion(true);presentation->present(player.artwork(),QString("3d-interrupt-%1").arg(interruption),true);QTest::qWait(80+interruption*60);
+ if(interruption==0)player.setThreeD(false);else if(interruption==1)player.setMiniMode(true);else if(interruption==2)window->setProperty("discFlipped",true);else player.setMotion(false);
+ QTest::qWait(90);check(!window->property("swapRunning").toBool()&&window->property("lidOpen").toDouble()==0,"interrupting the lid sequence leaves no stale overlay");
+ hoverOutside();player.setMiniMode(false);window->setProperty("discFlipped",false);player.setThreeD(true);QTest::qWait(140);
+ }
+ player.pause();
+ }
+ context="lifecycle stress";player.setVinylAlbumMode(false);
+ for(int cycle=0;cycle<30;++cycle) {
+ player.setMotion(cycle%2);player.setMedium(QStringList{"cd","vinyl","cassette"}[cycle%3]);player.setHorizontalSeek(cycle%2);player.setCd500Rpm(cycle%2);player.setCassetteFinish(QStringList{"clear","cream","smoke"}[cycle%3]);
+ player.select(cycle%4,true);player.setThreeD(true);QTest::qWait(35);hoverOutside();
+ if(cycle%3==0)window->setProperty("discFlipped",true);else if(cycle%3==1)player.setMiniMode(true);else player.setThreeD(false);
+ QTest::qWait(35);hoverOutside();player.setMiniMode(false);window->setProperty("discFlipped",false);player.setThreeD(true);QTest::qWait(35);
+ check(window->property("threeDActive").toBool(),"mixed medium, playback, motion and presentation cycle completes");
+ }
+ player.pause();player.setMotion(false);player.setThreeD(false);hoverOutside();player.setThreeD(true);QTest::qWait(200);
+ window->hide();QTest::qWait(100);window->show();check(until([&]{return window->isExposed();}),"3D window survives hide and show");QTest::qWait(150);hoverOutside();render("after-stress");
+ player.clear();check(player.count()==0,"clearing the queue leaves a valid empty 3D player");hoverOutside();
+ player.setThreeD(false);QTest::qWait(100);hoverOutside();
+ std::cout<<"3D RESULT "<<failures<<" failures / "<<checks<<" checks"<<std::endl;return failures?1:0;
+}
+
+int exerciseThreeDLighting(Player &player,QQuickWindow *window,const QString &temp,const QString &captures) {
+ int failures=0,checks=0;
+ const auto check=[&](bool ok,const char *name){++checks;if(!ok)++failures;std::cout<<(ok?"PASS ":"FAIL ")<<name<<std::endl;return ok;};
+ auto *theme=qobject_cast<Theme*>(qmlContext(window)->contextProperty("theme").value<QObject*>());
+ if(!check(theme&&qmlContext(window)->contextProperty("supports3D").toBool(),"native 3D lighting is available"))return 2;
+ player.setVolume(0);player.setMotion(false);window->setProperty("useCider",false);player.demo();player.pause();player.setThreeD(true);
+ if(!check(until([&]{return window->isExposed()&&window->property("threeDActive").toBool();}),"3D scene is exposed"))return 2;
+ QFile palette(temp+"/config/gtk-4.0/noctalia.css");if(!palette.open(QIODevice::ReadOnly))return 2;const auto original=palette.readAll();palette.close();
+ for(const auto &medium:QStringList{"cd","vinyl","cassette"}) {
+ player.setMedium(medium);QTest::qWait(200);double coolBalance=0;
+ for(const auto &accent:QStringList{"#82bed5","#e4a17f","#d9bafa","#916ba8"}) {
+ auto css=original;css.replace("#e6b599",accent.toUtf8());
+ const bool lightPalette=accent=="#916ba8";
+ if(lightPalette){css.replace("#17191f","#f6f0e8");css.replace("#eee5dc","#342d29");css.replace("#24252b","#e9e0d5");}
+ QSaveFile replacement(palette.fileName());
+ if(!replacement.open(QIODevice::WriteOnly))return 2;
+ replacement.write(css);if(!replacement.commit())return 2;
+ check(until([&]{return theme->colors().value("accent").value<QColor>()==QColor(accent);}),"atomic palette replacement reaches the live theme watcher");
+ QTest::qWait(550);
+ auto *view=findItem(window->contentItem(),"player3DView");QVariant projected;
+ // Sample the physical medium, away from artwork labels, controls,
+ // accent-colored progress indicators and the tonearm.
+ const QPointF surfacePoint=medium=="cassette"?QPointF(320,369):QPointF(150,349);
+ if(!view)return 2;
+ if(lightPalette)check(view->property("caseTint").value<QColor>().lightnessF()>.75,"light Noctalia palette updates the physical enclosure material");
+ QMetaObject::invokeMethod(view,"projectSurface",Q_RETURN_ARG(QVariant,projected),Q_ARG(QVariant,surfacePoint.x()),Q_ARG(QVariant,surfacePoint.y()));
+ const auto scenePoint=view->mapToScene(projected.toPointF());const QImage frame=window->grabWindow();
+ if(!check(!frame.isNull(),"lighting test captures rendered pixels"))return 2;
+ const double scale=frame.width()/double(window->width());const QPoint center(qRound(scenePoint.x()*scale),qRound(scenePoint.y()*scale));
+ double red=0,blue=0;int samples=0;
+ for(int y=-5;y<=5;++y)for(int x=-5;x<=5;++x){const auto pos=center+QPoint(x,y);if(!frame.rect().contains(pos))continue;const auto c=frame.pixelColor(pos);if(c.alpha()<240)continue;red+=c.red();blue+=c.blue();++samples;}
+ check(samples>=90,"lighting sample is on an opaque physical surface");
+ const double balance=samples?(red-blue)/samples:0;
+ std::cout<<"LIGHTING "<<medium.toStdString()<<" "<<accent.toStdString()<<" red-minus-blue "<<balance<<std::endl;
+ if(accent=="#82bed5")coolBalance=balance;
+ if(accent=="#e4a17f")check(balance-coolBalance>8,"changing cool to warm visibly changes the material pixels");
+ if(!captures.isEmpty()){QDir().mkpath(captures);frame.save(captures+"/"+medium+"-"+accent.mid(1)+".png");}
+ }
+ }
+ player.setMedium("vinyl");player.setHorizontalSeek(true);player.pause();player.seek(4000);QTest::qWait(180);
+ auto *bar=findItem(window->contentItem(),"horizontalSeek");
+ auto *arm=findItem(window->contentItem(),"vinylTonearm");
+ auto *rim=findItem(window->contentItem(),"scrubber");
+ auto *view=findItem(window->contentItem(),"player3DView");
+ if(check(bar&&arm&&rim&&view,"all synchronized seek surfaces are available")) {
+ const auto consistent=[&](double fraction) {
+ return std::abs(window->property("recordVisualProgress").toDouble()-fraction)<.015
+ && std::abs(view->property("progress").toDouble()-fraction)<.015
+ && std::abs(bar->property("value").toDouble()-fraction)<.015
+ && std::abs(arm->property("armAngle").toDouble()-(6+20*fraction))<.35;
+ };
+ const QPoint start=bar->mapToScene(QPointF(bar->width()*.25,bar->height()/2)).toPoint();
+ QTest::mousePress(window,Qt::LeftButton,Qt::NoModifier,start);
+ const QPoint finish=bar->mapToScene(QPointF(bar->width()*.7,bar->height()/2)).toPoint();
+ QMouseEvent move(QEvent::MouseMove,finish,window->mapToGlobal(finish),Qt::NoButton,Qt::LeftButton,Qt::NoModifier);QGuiApplication::sendEvent(window,&move);
+ check(consistent(bar->property("previewValue").toDouble()),"horizontal drag updates the 3D ring and paused tonearm before release");
+ QTest::mouseRelease(window,Qt::LeftButton,Qt::NoModifier,finish);QTest::qWait(100);
+ auto *surface=findItem(window->contentItem(),"mediaSurface");
+ const auto projected=[&](QPointF point){const auto local=rim->mapToItem(surface,point);QVariant result;QMetaObject::invokeMethod(view,"projectSurface",Q_RETURN_ARG(QVariant,result),Q_ARG(QVariant,local.x()),Q_ARG(QVariant,local.y()));return view->mapToScene(result.toPointF()).toPoint();};
+ const QPoint ringStart=projected(QPointF(436,220));QTest::mousePress(window,Qt::LeftButton,Qt::NoModifier,ringStart);
+ QPoint last=ringStart;
+ for(int step=1;step<=8;++step){const double angle=(.5+step/8.)*std::acos(-1.);last=projected(QPointF(220+216*std::sin(angle),220-216*std::cos(angle)));QMouseEvent event(QEvent::MouseMove,last,window->mapToGlobal(last),Qt::NoButton,Qt::LeftButton,Qt::NoModifier);QGuiApplication::sendEvent(window,&event);}
+ check(rim->property("scrubbing").toBool()&&consistent(.75),"ring retains its drag and updates the horizontal bar and tonearm before release");
+ QTest::mouseRelease(window,Qt::LeftButton,Qt::NoModifier,last);
+ check(until([&]{return std::abs(player.position()-player.duration()*.75)<1200;}),"releasing the ring commits the selected position");
+ check(!window->property("seekPreviewActive").toBool(),"release clears the shared preview");
+ }
+ player.setThreeD(false);QTest::qWait(100);
+ std::cout<<"LIGHTING RESULT "<<failures<<" failures / "<<checks<<" checks"<<std::endl;return failures?1:0;
+}
diff --git a/src/threedtest.h b/src/threedtest.h
new file mode 100644
index 0000000..f0ebe01
--- /dev/null
+++ b/src/threedtest.h
@@ -0,0 +1,7 @@
+#pragma once
+class Player;
+class QQuickWindow;
+class QString;
+int exerciseThreeD(Player &player, QQuickWindow *window, const QString &temp, const QString &captures);
+
+int exerciseThreeDLighting(Player &player, QQuickWindow *window, const QString &temp, const QString &captures);