From 5ded7b161015465c2d84dd77ead6d74ea84ac294 Mon Sep 17 00:00:00 2001 From: vicrodh <103399283+vicrodh@users.noreply.github.com> Date: Sat, 13 Jun 2026 21:34:30 -0600 Subject: [PATCH] perf(slint): immersive Coverflow - persistent elements + animated scroll (CSS/iPhone model) Rebuild that finally kills the per-click CPU spike, using the classic coverflow architecture (the owner's reference: Addy Osmani / iPhone-2007). Root cause of the spike (now removed): every navigation re-ran refresh_async which REPLACED the coverflow VecModels, so Slint dropped + rebuilt all 7 bound Image elements and re-uploaded/re-decoded every cover on each click. New architecture: - A single STABLE flat cover model, QueueState.coverflow-tracks = [history oldest..newest, NOW, upcoming...], + an int coverflow-index. An order-sensitive id-sequence hash gates the model setter: a pure track advance (same sequence, pointer moves) does NOT rebuild the model - only the index updates. So the Repeater is never rebuilt and visible covers never re-decode. Rebuild happens only on a real content change (new queue / shuffle / add / remove). - CoverflowPanel: a Repeater over coverflow-tracks; each card's transform is a pure function of offset = index - scroll. `scroll` is a float bound to coverflow-index with `animate scroll { 320ms }` - GPU-composited slide that repaints only during the transition then idles (no animation-tick / Timer, so idle = no continuous render). Flat scaled cards (no rotateY/skew/reflection), per-depth black-overlay dim, center painted last + non-interactive, ~7 visible. - Windowed lazy decode (+-4) reusing the DECODED_PIXEL_CACHE; at most the one newly-entering cover decodes per advance. - Side cards navigate via queue-wide play_history / play_coverflow_upcoming. - Bonus: atmosphere bg de-dupes by URL (ATMOSPHERE_LAST_URL) so a track change no longer re-blurs the same cover. [coverflow-perf] debug timers added. cc --- crates/qbz-slint/src/playback.rs | 63 +++- crates/qbz-slint/src/queue.rs | 272 +++++++++++----- .../ui/immersive/CoverflowPanel.slint | 298 ++++++++---------- crates/qbz-slint/ui/state.slint | 31 +- 4 files changed, 395 insertions(+), 269 deletions(-) diff --git a/crates/qbz-slint/src/playback.rs b/crates/qbz-slint/src/playback.rs index a0b02ff8c..7707b778c 100644 --- a/crates/qbz-slint/src/playback.rs +++ b/crates/qbz-slint/src/playback.rs @@ -1177,6 +1177,33 @@ fn load_now_playing_artwork(weak: slint::Weak, art: qbz_models::Artwo /// the 160px bar art. Mirrors [`load_now_playing_artwork`] but decodes larger /// and writes the separate `artwork-large` slot. Source-aware via the SAME /// `ArtworkRef` funnel (the caller passes a `Some(300)` ref). +/// Last resolved art URL the atmosphere (bg blur / glow / spectrum) was +/// generated for. The 300px decode + `generate_atmosphere` blur is the CPU cost +/// on every track change; this dedupe skips the regen when the SAME cover is +/// re-centered (e.g. a re-play of the current track, a QConnect echo). `None` = +/// nothing generated yet. Reset on track-clear (see `refresh_now_playing_meta`). +static ATMOSPHERE_LAST_URL: std::sync::Mutex> = std::sync::Mutex::new(None); + +/// Compare-and-record the atmosphere art-URL dedupe key. Returns `true` when it +/// differs from the last generated value (caller regenerates), recording it. A +/// `None`/empty url, or a poisoned lock, always regenerates (conservative). +fn atmosphere_url_changed(url: Option<&str>) -> bool { + let Some(u) = url.filter(|s| !s.is_empty()) else { + return true; + }; + match ATMOSPHERE_LAST_URL.lock() { + Ok(mut last) => { + if last.as_deref() == Some(u) { + false + } else { + *last = Some(u.to_string()); + true + } + } + Err(_) => true, + } +} + fn load_now_playing_artwork_large(weak: slint::Weak, art: qbz_models::ArtworkRef) { if art.is_empty() { return; @@ -1184,6 +1211,8 @@ fn load_now_playing_artwork_large(weak: slint::Weak, art: qbz_models: let Some(cache) = crate::artwork::shared_cache() else { return; }; + // Art-URL dedupe key for the atmosphere regen (bg/glow/spectrum). + let art_url = art.to_mpris_url(); tokio::spawn(async move { let Some((pixels, w, h)) = crate::artwork::fetch_and_decode_ref(&art, &cache, 300).await @@ -1192,19 +1221,34 @@ fn load_now_playing_artwork_large(weak: slint::Weak, art: qbz_models: }; let _ = weak.upgrade_in_event_loop(move |win| { let img = crate::artwork::pixels_to_image(&pixels, w, h); + // The hover-preview cover is ALWAYS needed (independent of the + // immersive overlay), so set it unconditionally first. + win.global::().set_artwork_large(img); + + // The atmosphere (bg blur / glow / spectrum colors) regen is the CPU + // cost on every track change. Skip the expensive generate_atmosphere + // blur when the SAME cover is already centered (art-URL dedupe) — the + // bg/glow/spectrum already reflect it. This is the compounding + // per-click cost the rebuild flagged (a re-play / QConnect echo of the + // current track no longer re-blurs). We deliberately do NOT gate on + // `ImmersiveState.open`: opening the overlay does not re-fire this + // path, so a closed-overlay skip would leave a stale bg on open; the + // overlay is conditionally mounted, so generating while closed is + // cheap insurance and the dedupe still prevents repeats. + let imm = win.global::(); + if !atmosphere_url_changed(art_url.as_deref()) { + return; + } if let Some((bg_pixels, bg_w, bg_h)) = crate::immersive::generate_atmosphere(&pixels, w, h) { let bg = crate::artwork::pixels_to_image(&bg_pixels, bg_w, bg_h); - win.global::().set_bg_image(bg); + imm.set_bg_image(bg); } - win.global::() - .set_glow_color(crate::immersive::glow_color(&pixels, w, h)); + imm.set_glow_color(crate::immersive::glow_color(&pixels, w, h)); let (spec_primary, spec_secondary) = crate::immersive::spectrum_colors(&pixels, w, h); - win.global::().set_spectrum_primary(spec_primary); - win.global::() - .set_spectrum_secondary(spec_secondary); - win.global::().set_artwork_large(img); + imm.set_spectrum_primary(spec_primary); + imm.set_spectrum_secondary(spec_secondary); }); }); } @@ -1276,6 +1320,11 @@ pub(crate) async fn refresh_now_playing_meta(runtime: &Runtime, weak: &slint::We if let Ok(mut last) = MPRIS_LAST_META.lock() { *last = None; } + // Reset the atmosphere art-URL dedupe so replaying the same track after a + // stop regenerates the immersive bg/glow/spectrum. + if let Ok(mut last) = ATMOSPHERE_LAST_URL.lock() { + *last = None; + } if let Some(t) = crate::tray::handle() { t.clear_track(); } diff --git a/crates/qbz-slint/src/queue.rs b/crates/qbz-slint/src/queue.rs index c359e8774..554e30ccf 100644 --- a/crates/qbz-slint/src/queue.rs +++ b/crates/qbz-slint/src/queue.rs @@ -46,6 +46,14 @@ pub struct QueueController { handle: tokio::runtime::Handle, playback: qbz_app::settings::playback::PlaybackPreferencesState, view: Arc>, + /// Last coverflow flat id-sequence fingerprint pushed to `QueueState`. + /// `refresh_async` compares the freshly-computed hash to this: equal means a + /// PURE ADVANCE/JUMP (same id-sequence, only the current pointer moved) — the + /// flat model setter is SKIPPED and only `coverflow-index` is updated, so the + /// Repeater never rebuilds and visible covers never re-decode. A different + /// hash (new queue / shuffle / add / remove) triggers the one-time rebuild. + /// `None` = nothing pushed yet (first refresh always rebuilds). + last_coverflow_seq: Arc>>, } // `PlaybackPreferencesState` is not `Clone`, but its sole field is an @@ -61,6 +69,7 @@ impl Clone for QueueController { store: Arc::clone(&self.playback.store), }, view: Arc::clone(&self.view), + last_coverflow_seq: Arc::clone(&self.last_coverflow_seq), } } } @@ -148,6 +157,7 @@ impl QueueController { handle, playback, view: Arc::new(Mutex::new(ViewState::default())), + last_coverflow_seq: Arc::new(Mutex::new(None)), } } @@ -200,6 +210,7 @@ impl QueueController { } async fn refresh_async(&self) { + let perf_start = std::time::Instant::now(); let state = self.runtime.core().get_queue_state_full().await; // --- NOW PLAYING -------------------------------------------------- @@ -261,21 +272,60 @@ impl QueueController { let history_rows: Vec = state.history.iter().map(|t| row_from(t, false)).collect(); - // --- COVERFLOW (unfiltered next-3 / prev-3) ----------------------- - // Built from the UNFILTERED queue so the immersive pyramid is correct - // regardless of sidebar page/search. Index 0 = next / most-recent. - let coverflow_up_rows: Vec = state - .upcoming - .iter() - .take(3) - .map(|t| row_from(t, false)) - .collect(); - let coverflow_hist_rows: Vec = state - .history - .iter() - .take(3) - .map(|t| row_from(t, false)) - .collect(); + // --- COVERFLOW (ONE stable flat model) ---------------------------- + // Built from the UNFILTERED queue, oldest-first: + // [history.reversed (oldest..newest), NOW-PLAYING, upcoming...] + // `QueueStateFull.history` is most-recent-first, so reverse it for the + // oldest-first flat order. The flat index of NOW = number of history + // entries (it sits right after the reversed history). On a PURE ADVANCE + // the id-sequence is unchanged and only `coverflow_index` moves -> the + // .slint `scroll` float animates, no model rebuild, no re-decode. + let mut coverflow_rows: Vec = Vec::with_capacity( + state.history.len() + 1 + state.upcoming.len(), + ); + for t in state.history.iter().rev() { + coverflow_rows.push(row_from(t, false)); + } + let coverflow_index: usize = if let Some(t) = state.current_track.as_ref() { + let idx = coverflow_rows.len(); + coverflow_rows.push(row_from(t, true)); + idx + } else { + // No current track: index points at the first upcoming (or 0 when + // the whole queue is empty). The flat list is history ++ upcoming. + coverflow_rows.len() + }; + for t in state.upcoming.iter() { + coverflow_rows.push(row_from(t, false)); + } + + // Order-sensitive rolling fingerprint over the flat id-sequence. Used to + // gate the model rebuild: equal hash => same membership+order => pure + // advance/jump => skip set_coverflow_tracks. Hashing the ordered ids + // (not a set) catches shuffle/reorder; folding the index-free id list + // keeps a same-sequence-different-pointer advance hashing identical. + let coverflow_seq_hash: u64 = { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + coverflow_rows.len().hash(&mut h); + for r in &coverflow_rows { + r.id.hash(&mut h); + } + h.finish() + }; + // Decide rebuild-vs-index-only BEFORE the event loop so the art-job set + // can be narrowed to the ±4 window. `seq_changed` true => rebuild path. + let seq_changed = { + let mut last = self.last_coverflow_seq.lock().ok(); + let changed = match last.as_deref() { + Some(Some(prev)) => *prev != coverflow_seq_hash, + _ => true, // None lock or first push -> rebuild + }; + if let Some(slot) = last.as_deref_mut() { + *slot = Some(coverflow_seq_hash); + } + changed + }; // --- Infinite-play flag ------------------------------------------ let infinite = self @@ -302,14 +352,22 @@ impl QueueController { art_jobs.push((ArtTarget::History(idx), row.artwork_url.clone())); } } - for (idx, row) in coverflow_up_rows.iter().enumerate() { - if !row.artwork_url.is_empty() { - art_jobs.push((ArtTarget::CoverflowUpcoming(idx), row.artwork_url.clone())); - } - } - for (idx, row) in coverflow_hist_rows.iter().enumerate() { - if !row.artwork_url.is_empty() { - art_jobs.push((ArtTarget::CoverflowHistory(idx), row.artwork_url.clone())); + // Coverflow art jobs are WINDOWED to ±4 around the current flat index + // (only ~9 rows can be near the visible ±3 fan), not the whole queue. + // The set is narrowed further on the event loop (skip rows that already + // carry a decoded handle) so a pure advance decodes AT MOST the one + // cover that just entered the window — see the closure below. + const CF_WINDOW: usize = 4; + let cf_lo = coverflow_index.saturating_sub(CF_WINDOW); + let cf_hi = (coverflow_index + CF_WINDOW).min(coverflow_rows.len().saturating_sub(1)); + let mut coverflow_art_jobs: Vec<(ArtTarget, String)> = Vec::new(); + if !coverflow_rows.is_empty() { + for flat_idx in cf_lo..=cf_hi { + let row = &coverflow_rows[flat_idx]; + if !row.artwork_url.is_empty() { + coverflow_art_jobs + .push((ArtTarget::CoverflowFlat(flat_idx), row.artwork_url.clone())); + } } } @@ -317,34 +375,47 @@ impl QueueController { let _ = weak.upgrade_in_event_loop(move |w| { let qs = w.global::(); - // Snapshot prior decoded handles per list BEFORE replacing the - // models, so unchanged tracks keep their decoded artwork instead of - // blanking to the default (which forced a full re-decode + blink on - // every click). Diffed per-list so a track present in both history - // and upcoming can't cross-map. - let prior_page = prior_art_map(&qs.get_upcoming_page()); - let prior_history = prior_art_map(&qs.get_history()); - let prior_cf_up = prior_art_map(&qs.get_coverflow_upcoming()); - let prior_cf_hist = prior_art_map(&qs.get_coverflow_history()); + // Snapshot prior decoded handles into ONE GLOBAL id -> artwork map + // covering EVERY prior list (now-playing + upcoming + history + + // both coverflow lists) BEFORE replacing the models. Coverflow + // navigation shifts a cover ACROSS lists every click (now-playing -> + // history, upcoming -> now-playing, ...), so a per-list diff misses + // the moved covers -> they blank to default -> full re-decode -> + // flicker + CPU spike. A global map reuses a cover's decoded handle + // no matter which list it sat in before; net per click only the one + // genuinely new track decodes. + let mut prior_all: std::collections::HashMap = + std::collections::HashMap::new(); + { + let np = qs.get_now_playing(); + if np.artwork.size().width > 0 { + prior_all.insert(np.id.clone(), np.artwork.clone()); + } + for m in [ + qs.get_upcoming_page(), + qs.get_history(), + qs.get_coverflow_tracks(), + ] { + for i in 0..m.row_count() { + if let Some(it) = m.row_data(i) { + if it.artwork.size().width > 0 { + prior_all.entry(it.id.clone()).or_insert(it.artwork.clone()); + } + } + } + } + } let np_item = now_playing .as_ref() - .map(|r| { - // Reuse the prior now-playing cover only if the same track. - let prior = qs.get_now_playing(); - let mut map = std::collections::HashMap::new(); - if prior.artwork.size().width > 0 { - map.insert(prior.id.clone(), prior.artwork.clone()); - } - to_item_reuse(r, &map) - }) + .map(|r| to_item_reuse(r, &prior_all)) .unwrap_or_default(); qs.set_has_current(now_playing.is_some()); qs.set_now_playing(np_item); qs.set_now_playing_favorite(now_playing_favorite); let page_items: Vec = - page_rows.iter().map(|r| to_item_reuse(r, &prior_page)).collect(); + page_rows.iter().map(|r| to_item_reuse(r, &prior_all)).collect(); qs.set_upcoming_page(slint::ModelRc::new(slint::VecModel::from(page_items))); qs.set_upcoming_total(upcoming_total as i32); qs.set_upcoming_remaining(remaining as i32); @@ -354,25 +425,68 @@ impl QueueController { qs.set_page_end(page_end as i32); let history_items: Vec = - history_rows.iter().map(|r| to_item_reuse(r, &prior_history)).collect(); + history_rows.iter().map(|r| to_item_reuse(r, &prior_all)).collect(); qs.set_history(slint::ModelRc::new(slint::VecModel::from(history_items))); - // Coverflow lists (unfiltered next-3 / prev-3), reusing handles. - let cf_up_items: Vec = coverflow_up_rows - .iter() - .map(|r| to_item_reuse(r, &prior_cf_up)) - .collect(); - qs.set_coverflow_upcoming(slint::ModelRc::new(slint::VecModel::from(cf_up_items))); - let cf_hist_items: Vec = coverflow_hist_rows - .iter() - .map(|r| to_item_reuse(r, &prior_cf_hist)) - .collect(); - qs.set_coverflow_history(slint::ModelRc::new(slint::VecModel::from(cf_hist_items))); + // --- COVERFLOW: gated flat-model update ----------------------- + // KEY INVARIANT. On a PURE ADVANCE/JUMP the id-sequence is unchanged + // (`!seq_changed`) so we DO NOT call set_coverflow_tracks: the + // Repeater model is untouched, every visible cover keeps its decoded + // `slint::Image` handle (no source reassignment, no re-decode), and + // only the int `coverflow-index` moves -> the .slint `scroll` float + // animates the fan to the new position. The model is rebuilt ONLY + // when the contents actually change (new queue / shuffle / add / + // remove), reusing the global id->handle map so even then only the + // genuinely-new covers decode. + if seq_changed { + let cf_items: Vec = coverflow_rows + .iter() + .map(|r| to_item_reuse(r, &prior_all)) + .collect(); + qs.set_coverflow_tracks(slint::ModelRc::new(slint::VecModel::from(cf_items))); + qs.set_coverflow_seq_hash(coverflow_seq_hash as i32); + log::debug!( + "[coverflow-perf] rebuild seq={coverflow_seq_hash} len={} idx={coverflow_index}", + coverflow_rows.len() + ); + } else { + log::debug!( + "[coverflow-perf] index-only idx={coverflow_index} (seq unchanged)" + ); + } + qs.set_coverflow_index(coverflow_index as i32); qs.set_infinite_play(infinite); // Keep the Slint tab property in sync with the view state so the // Queue/History body always matches the selected tab. qs.set_tab(tab); + + // --- COVERFLOW windowed lazy decode (inside the event loop so it + // can read the live model and SKIP rows that already carry a decoded + // handle). After a rebuild the to_item_reuse map already filled most + // window covers; after an index-only update the model is the prior + // one with handles intact. Either way we emit a decode job ONLY for a + // window row whose model cell is still a default (0-width) image -> + // at most ONE decode per advance (the cover that just entered ±4), + // often zero. Visible covers are NEVER re-decoded (the invariant). + let cf_model = qs.get_coverflow_tracks(); + let mut windowed_jobs: Vec<(ArtTarget, String)> = Vec::new(); + for (target, url) in coverflow_art_jobs.into_iter() { + let ArtTarget::CoverflowFlat(flat_idx) = target else { + continue; + }; + let needs = cf_model + .row_data(flat_idx) + .map(|it| it.artwork.size().width == 0) + .unwrap_or(false); + if needs { + windowed_jobs.push((target, url)); + } + } + if !windowed_jobs.is_empty() { + let plex = crate::plex_settings::get(); + load_artwork(w.as_weak(), windowed_jobs, plex.base_url, plex.token); + } }); // Plex creds for source-aware art: a Plex queue row carries a raw @@ -380,6 +494,11 @@ impl QueueController { // not a local-file read miss. Non-Plex paths ignore these. let plex = crate::plex_settings::get(); load_artwork(self.weak.clone(), art_jobs, plex.base_url, plex.token); + + log::debug!( + "[coverflow-perf] refresh_async total={}ms", + perf_start.elapsed().as_millis() + ); } // --- Callbacks -------------------------------------------------------- @@ -710,8 +829,8 @@ enum ArtTarget { NowPlaying, Upcoming(usize), History(usize), - CoverflowUpcoming(usize), - CoverflowHistory(usize), + /// A row in the single stable flat coverflow model, by flat index. + CoverflowFlat(usize), } /// Build a `QueueItem` from plain row data, REUSING a prior decoded artwork @@ -741,23 +860,6 @@ fn to_item_reuse( } } -/// Snapshot the current id -> decoded-artwork map for a Slint model, so the -/// rebuilt rows can reuse handles for tracks that did not change. Only rows -/// whose artwork is actually resolved (`width > 0`) are recorded. -fn prior_art_map( - model: &slint::ModelRc, -) -> std::collections::HashMap { - let mut map = std::collections::HashMap::new(); - for i in 0..model.row_count() { - if let Some(item) = model.row_data(i) { - if item.artwork.size().width > 0 { - map.insert(item.id.clone(), item.artwork.clone()); - } - } - } - map -} - #[cfg(test)] mod tests { use super::*; @@ -914,6 +1016,9 @@ fn load_artwork( }; if let Some(key) = cache_key.as_deref() { if let Some((pixels, w, h)) = crate::artwork::decoded_pixels(key, QUEUE_DECODE) { + if let ArtTarget::CoverflowFlat(i) = target { + log::debug!("[coverflow-perf] cache-hit flat_idx={i}"); + } let weak = weak.clone(); let _ = weak.upgrade_in_event_loop(move |win| { let img = crate::artwork::pixels_to_image(&pixels, w, h); @@ -923,7 +1028,14 @@ fn load_artwork( } } + let perf_url = match target { + ArtTarget::CoverflowFlat(i) => Some((i, cache_key.clone().unwrap_or_default())), + _ => None, + }; tokio::spawn(async move { + if let Some((i, u)) = perf_url.as_ref() { + log::debug!("[coverflow-perf] decode flat_idx={i} url={u}"); + } let Some((pixels, w, h)) = crate::artwork::fetch_and_decode_ref(&art, &cache, QUEUE_DECODE).await else { @@ -960,17 +1072,13 @@ fn apply_queue_art(win: &AppWindow, target: ArtTarget, img: slint::Image) { items.set_row_data(idx, item); } } - ArtTarget::CoverflowUpcoming(idx) => { - let items = qs.get_coverflow_upcoming(); - if let Some(mut item) = items.row_data(idx) { - item.artwork = img; - items.set_row_data(idx, item); - } - } - ArtTarget::CoverflowHistory(idx) => { - let items = qs.get_coverflow_history(); + ArtTarget::CoverflowFlat(idx) => { + let items = qs.get_coverflow_tracks(); if let Some(mut item) = items.row_data(idx) { item.artwork = img; + // set_row_data on a SINGLE flat row — does NOT replace the + // VecModel, so the Repeater is not rebuilt and the other covers' + // sources are untouched. Only this one cell's image changes. items.set_row_data(idx, item); } } diff --git a/crates/qbz-slint/ui/immersive/CoverflowPanel.slint b/crates/qbz-slint/ui/immersive/CoverflowPanel.slint index fed75ac12..b09951aa3 100644 --- a/crates/qbz-slint/ui/immersive/CoverflowPanel.slint +++ b/crates/qbz-slint/ui/immersive/CoverflowPanel.slint @@ -1,40 +1,39 @@ -// Coverflow foreground (Immersive mode 2) — a CHEAP "rocola" (jukebox) -// PYRAMID of flat scaled cards. +// Coverflow foreground (Immersive mode 2) — a CHEAP classic-CSS / iPhone-2007 +// coverflow built on the PERSISTENT-ELEMENT + ANIMATED-SCROLL architecture. // -// OWNER DECISION (binding, REPLACES the old true-3D-aspiring fan): NO rotateY / -// skew / perspective / reflection, NO far-edge shade gradient, NO transparency -// on the card root. Just flat scaled cards. Depth reads from (a) a step-down -// SCALE so the silhouette is a pyramid (center tallest) and (b) a per-depth -// semi-transparent BLACK overlay on an INNER rectangle (attenuation, darker -// the further out). A real blur is too expensive and is NOT used — the owner -// said "un blur o atenuación... basta", so attenuation + scale is the depth cue. +// ARCHITECTURE (binding — replaces the old 7 fixed-slot design): +// 1. PERSISTENT covers. The covers are a SINGLE stable, ordered list of the +// whole queue — `QueueState.coverflow-tracks` = [history oldest..newest, +// NOW-PLAYING, upcoming...]. This list + its decoded cover images do NOT +// change on a pure track advance/navigation; only the int +// `QueueState.coverflow-index` (the flat position of NOW) moves. The Rust +// controller rebuilds the model ONLY when the queue CONTENTS change +// (id-sequence diff). So a track advance NEVER rebuilds this Repeater and +// NEVER re-decodes a visible cover. +// 2. ANIMATED SCROLL. A single float `scroll` is bound to `coverflow-index` +// with `animate scroll { 320ms ease-in-out }`. When Rust sets the new int +// index, `scroll` EASES to it and the fan repaints ONLY during the 320ms, +// then idles. NO `animation-tick` (that would force continuous fps = the +// CPU cost we are avoiding); NO Timer. +// 3. TRANSFORM-ONLY layout. Each cover i derives offset = i - scroll; +// x = center + offset*pitch; size = base * scale(|offset|); a per-depth +// black overlay dims by |offset| on an INNER Rectangle (never root +// opacity). Covers with |offset| > 3 are `visible:false` (~7 on screen). +// This is CSS `transform: translateX()+scale()` done with Slint geometry — +// FLAT scaled cards (NO rotateY/skew/perspective/reflection; Slint has no +// 3D and the owner accepted flat). +// 4. NAVIGATION. A side card at flat index i plays that queue position by +// mapping i -> the existing queue-wide play-history / play-coverflow- +// upcoming calls; the subsequent refresh moves `coverflow-index` and +// `scroll` animates to it. The center (offset ~0) is non-interactive. // -// LAYOUT: 7 cards = 3 past (left, history) + center + 3 upcoming (right). The -// now-playing cover is ALWAYS centered and ALWAYS on top in Z (declared LAST = -// paints last). Cards may overlap toward the center (jukebox stack). -// -// PERF: the old version animated x / width / height over 500ms on every slot, -// re-laying-out clipped images each frame on every click. That is DROPPED — the -// cards snap to their new depth on a click (Option A). Combined with the Rust -// decoded-handle reuse (queue.rs) the covers no longer blink, so the snap is -// clean. A single 120ms opacity cross-fade on the INNER dim overlay (Option B) -// is the only motion — GPU-only, no relayout, no texture re-upload. -// -// SLINT GOTCHAS honored: `parent` is never read in any root binding (viewport -// dims passed as props; CoverSlot dims passed as props). Hand-placed fixed -// instances (no Repeater) and NO `changed x/y/width/height` watchers -> avoids -// the "Recursion detected" panic. `dim` is applied on an INNER Rectangle, never -// the slot root opacity (root opacity corrupts absolute positioning). The -// off-clamp uses Math.min (max-width is ignored on hand-positioned Rectangles). -// -// DATA MAPPING (unfiltered coverflow lists, correct regardless of sidebar -// page/search — populated in queue.rs refresh_async from state.upcoming[..3] / -// state.history[..3] with decoded-handle reuse): -// center (depth 0) <- NowPlayingState (unified source, also feeds the card) -// right-n (depth n) <- QueueState.coverflow-upcoming[n-1] (next tracks) -// left-n (depth n) <- QueueState.coverflow-history[n-1] (recent-first) -// Side covers navigate via QueueState.play-upcoming / play-history (index n-1); -// the center is non-interactive. +// SLINT GOTCHAS honored: `parent` is NEVER read in any root binding (viewport +// dims + the per-cover stage geometry are passed as props). Everything derives +// from the DATA value `i` and the `scroll` float — NO `changed x/y/width/height` +// watchers on rows (avoids the "Recursion detected" panic). `dim` is on an INNER +// Rectangle, never the slot root opacity. Math.min/max are 2-arg; clamp = +// Math.max(lo, Math.min(hi, x)). The center card is a SEPARATE top-most instance +// (Repeater can't reorder by data) so it paints over its neighbors. import { QualityBadgeFull } from "../primitives/QualityBadgeFull.slint"; import { NowPlayingState, QueueState } from "../state.slint"; @@ -87,36 +86,47 @@ component EqualizerBars inherits Rectangle { } } -// One flat card in the pyramid. Dims passed as props (NEVER `parent` in the -// root binding). `dim` is the per-depth attenuation (0 center .. 0.55 outermost) -// applied on an INNER Rectangle, never the root opacity. `has-art` is true when -// the cover image is resolved; otherwise a neutral placeholder shows instead of -// a 0-size collapse. NO animated geometry — the card snaps to its depth on a -// click; only the dim overlay cross-fades (120ms, GPU-only). -component CoverSlot inherits Rectangle { +// One flat coverflow card. ALL geometry is derived from `offset` (= i - scroll) +// + the stage props passed in (NEVER `parent` in the root binding). The card +// position/size/dim are pure functions of `offset`, so when the parent's +// animated `scroll` changes, every card eases to its new transform with NO +// model change and NO source reassignment. `dim` is on an INNER Rectangle. +component CoverCard inherits Rectangle { in property art; - in property slot-size; - in property center-x; // window-x of the cover CENTER + in property has-art: false; + in property offset; // signed distance from center (i - scroll) + in property base-art; // depth-0 (center) edge length + in property pitch; // x spacing between adjacent depths + in property stage-cx; // window-x of the center in property stage-height; - in property dim: 0.0; // 0..1 per-depth black-overlay opacity - in property has-art: false; // art image resolved (width > 0) in property interactive: false; callback navigate(); - width: root.slot-size; - height: root.slot-size; - x: root.center-x - root.slot-size / 2; - // Shared center band; the larger center card naturally rises. Small upward - // bias to leave room for the song card below. - y: (root.stage-height - root.slot-size) / 2 - 12px; + property ao: Math.abs(root.offset); + // Step-down scale: center 1.0 -> ~0.5 at |offset| >= ~2.8. + property scale: Math.max(0.5, 1.0 - 0.18 * root.ao); + property slot: root.base-art * root.scale; + // Per-depth black overlay: 0 at center, up to 0.55 outward. + property dim: Math.min(0.55, root.ao * 0.18); + + // Only ~7 cards near the center paint; the rest are dropped (no texture + // cost from off-screen rows — visible:false stops painting). + visible: root.ao <= 3.2; + + width: root.slot; + height: root.slot; + // Center the card on (stage-cx + offset*pitch); small upward bias to leave + // room for the song card below. + x: root.stage-cx + root.offset * root.pitch - root.slot / 2; + y: (root.stage-height - root.slot) / 2 - 12px; border-radius: 8px; clip: true; - // Static drop-shadow on the center card only (never animated, never on the - // side cards — the attenuation carries their depth). - drop-shadow-blur: root.dim == 0.0 ? 28px : 0px; + // Static drop-shadow on (near-)center cards only — the attenuation carries + // the depth for the side cards. Never animated. + drop-shadow-blur: root.ao < 0.5 ? 28px : 0px; drop-shadow-color: #00000066; - drop-shadow-offset-y: root.dim == 0.0 ? 8px : 0px; + drop-shadow-offset-y: root.ao < 0.5 ? 8px : 0px; // Neutral placeholder when the item exists but its art is unresolved. Rectangle { @@ -135,21 +145,17 @@ component CoverSlot inherits Rectangle { visible: root.has-art; } - // Per-depth attenuation — a semi-transparent BLACK overlay on an INNER - // Rectangle (never the slot root opacity). The ONLY animation: a short - // opacity cross-fade so the attenuation eases as a card changes depth. - // GPU-only (no relayout, no clipped-image re-raster) -> no CPU spike. + // Per-depth attenuation on an INNER Rectangle (never the root opacity). Rectangle { width: parent.width; height: parent.height; border-radius: 8px; background: #000000; opacity: root.dim; - animate opacity { duration: 120ms; easing: ease-out; } } // Side cards navigate; the center is non-interactive. - if root.interactive: TouchArea { + if root.interactive && root.ao > 0.5: TouchArea { mouse-cursor: pointer; clicked => { root.navigate(); } } @@ -168,41 +174,25 @@ export component CoverflowPanel inherits Rectangle { // clearance: reserve = pad-top(52) + info + clearance(132) = 364px. property base-art: Math.max(160px, Math.min(Math.min(root.viewport-height - 364px, root.viewport-width * 0.42), 440px)); + // X spacing between adjacent depths (overlapping inward). + property pitch: root.base-art * 0.42; - // Step-down SCALE (center tallest): depth0 1.00, depth1 0.80, depth2 0.64, - // depth3 0.50. - property size1: root.base-art * 0.80; - property size2: root.base-art * 0.64; - property size3: root.base-art * 0.50; + // --- Animated scroll (the ONLY motion) ------------------------------- + // Bound to the int current-index; Rust moving the index eases `scroll` over + // 320ms (repaints only during the transition, then idles). + property scroll: QueueState.coverflow-index; + animate scroll { duration: 320ms; easing: ease-in-out; } - // X offsets (center-anchored, overlapping inward). Spec ratios off1 0.42, - // off2 0.74, off3 1.02. Each clamped so the card stays inside the half-window - // with a 16px margin (Math.min — max-width is ignored on hand-positioned - // rects). Chain off1 < off2 < off3 so the order never crosses. - property half-w: root.viewport-width / 2; - property off3: Math.min(root.base-art * 1.02, - Math.max(0px, root.half-w - root.size3 / 2 - 16px)); - property off2: Math.min(root.base-art * 0.74, - Math.max(0px, root.off3 - root.size3 / 4)); - property off1: Math.min(root.base-art * 0.42, - Math.max(0px, root.off2 - root.size2 / 4)); - - // --- Center artwork source (unified NowPlayingState, like the siblings) -- + // Center card art prefers the unified large now-playing cover (sharper), + // falling back to the model row's small cover while it resolves. + property center-idx: QueueState.coverflow-index; property center-art: NowPlayingState.artwork-large.width > 0 ? NowPlayingState.artwork-large : NowPlayingState.artwork; property center-has-art: root.center-art.width > 0; - // --- Side item presence (unfiltered coverflow lists) ---------------- - property has-up1: QueueState.coverflow-upcoming.length > 0; - property has-up2: QueueState.coverflow-upcoming.length > 1; - property has-up3: QueueState.coverflow-upcoming.length > 2; - property has-hist1: QueueState.coverflow-history.length > 0; - property has-hist2: QueueState.coverflow-history.length > 1; - property has-hist3: QueueState.coverflow-history.length > 2; - - // --- Pyramid stage --------------------------------------------------- - fan := Rectangle { + // --- Cover fan stage ------------------------------------------------- + Rectangle { x: 0px; y: 52px; // pad-top, matches the siblings width: root.viewport-width; @@ -210,96 +200,62 @@ export component CoverflowPanel inherits Rectangle { property cx: root.viewport-width / 2; - // Declaration order = paint order: depth3 -> depth1 outward-to-inward, - // CENTER LAST (on top). Left/right of each depth interleaved. - // depth3 LEFT <- history[2] - CoverSlot { - slot-size: root.size3; - center-x: parent.cx - root.off3; + // All side + far covers from the stable flat model. The center is drawn + // separately (below) so it paints on top — a Repeater renders in data + // order and cannot reorder by |offset|. + for item[i] in QueueState.coverflow-tracks: CoverCard { + offset: i - root.scroll; + base-art: root.base-art; + pitch: root.pitch; + stage-cx: parent.cx; stage-height: parent.height; - dim: 0.55; - art: root.has-hist3 ? QueueState.coverflow-history[2].artwork : root.center-art; - has-art: root.has-hist3 && QueueState.coverflow-history[2].artwork.width > 0; - interactive: root.has-hist3; - visible: root.has-hist3; - navigate => { QueueState.play-history(2); } + art: item.artwork; + has-art: item.artwork.width > 0; + // The center (i == current index) is drawn by the top instance; this + // Repeater copy stays non-interactive and hides exactly at center so + // there is no double-draw flicker through the 320ms ease. + interactive: i != root.center-idx; + navigate => { + // Flat index -> queue-wide play call. Flat order is + // [history.reversed (oldest-first) ++ NOW ++ upcoming], and + // center-idx = history.len(): + // i < center-idx -> a history cover. flat history is + // oldest-first while QueueStateFull.history is most-recent- + // first, so hist_index = center-idx - 1 - i. + // i > center-idx -> an upcoming cover. + // up_index = i - center-idx - 1. + if (i < root.center-idx) { + QueueState.play-history(root.center-idx - 1 - i); + } else if (i > root.center-idx) { + QueueState.play-coverflow-upcoming(i - root.center-idx - 1); + } + } } - // depth3 RIGHT <- upcoming[2] - CoverSlot { - slot-size: root.size3; - center-x: parent.cx + root.off3; + + // CENTER card — drawn LAST so it paints over its neighbors. Bound to the + // current-index row's offset (eases to 0 with `scroll`). Uses the unified + // large cover for sharpness; non-interactive (matches the disabled Tauri + // center button). + CoverCard { + offset: root.center-idx - root.scroll; + base-art: root.base-art; + pitch: root.pitch; + stage-cx: parent.cx; stage-height: parent.height; - dim: 0.55; - art: root.has-up3 ? QueueState.coverflow-upcoming[2].artwork : root.center-art; - has-art: root.has-up3 && QueueState.coverflow-upcoming[2].artwork.width > 0; - interactive: root.has-up3; - visible: root.has-up3; - navigate => { QueueState.play-coverflow-upcoming(2); } - } - // depth2 LEFT <- history[1] - CoverSlot { - slot-size: root.size2; - center-x: parent.cx - root.off2; - stage-height: parent.height; - dim: 0.40; - art: root.has-hist2 ? QueueState.coverflow-history[1].artwork : root.center-art; - has-art: root.has-hist2 && QueueState.coverflow-history[1].artwork.width > 0; - interactive: root.has-hist2; - visible: root.has-hist2; - navigate => { QueueState.play-history(1); } - } - // depth2 RIGHT <- upcoming[1] - CoverSlot { - slot-size: root.size2; - center-x: parent.cx + root.off2; - stage-height: parent.height; - dim: 0.40; - art: root.has-up2 ? QueueState.coverflow-upcoming[1].artwork : root.center-art; - has-art: root.has-up2 && QueueState.coverflow-upcoming[1].artwork.width > 0; - interactive: root.has-up2; - visible: root.has-up2; - navigate => { QueueState.play-coverflow-upcoming(1); } - } - // depth1 LEFT <- history[0] - CoverSlot { - slot-size: root.size1; - center-x: parent.cx - root.off1; - stage-height: parent.height; - dim: 0.22; - art: root.has-hist1 ? QueueState.coverflow-history[0].artwork : root.center-art; - has-art: root.has-hist1 && QueueState.coverflow-history[0].artwork.width > 0; - interactive: root.has-hist1; - visible: root.has-hist1; - navigate => { QueueState.play-history(0); } - } - // depth1 RIGHT <- upcoming[0] - CoverSlot { - slot-size: root.size1; - center-x: parent.cx + root.off1; - stage-height: parent.height; - dim: 0.22; - art: root.has-up1 ? QueueState.coverflow-upcoming[0].artwork : root.center-art; - has-art: root.has-up1 && QueueState.coverflow-upcoming[0].artwork.width > 0; - interactive: root.has-up1; - visible: root.has-up1; - navigate => { QueueState.play-coverflow-upcoming(0); } - } - // CENTER (depth 0) <- NowPlayingState. Declared LAST = paints on top. - // Non-interactive, like the disabled Tauri center button. - CoverSlot { - slot-size: root.base-art; - center-x: parent.cx; - stage-height: parent.height; - dim: 0.0; - art: root.center-art; - has-art: root.center-has-art; + art: root.center-has-art ? root.center-art + : (QueueState.coverflow-tracks.length > root.center-idx + ? QueueState.coverflow-tracks[root.center-idx].artwork + : root.center-art); + has-art: root.center-has-art + || (QueueState.coverflow-tracks.length > root.center-idx + && QueueState.coverflow-tracks[root.center-idx].artwork.width > 0); interactive: false; } } // --- Song card below the pyramid ------------------------------------ // Reuses the StaticPanel pattern verbatim, fed by NowPlayingState. Pinned - // under the pyramid, respecting the 132px player clearance. + // under the fan, respecting the 132px player clearance. VerticalLayout { x: 0px; y: 0px; diff --git a/crates/qbz-slint/ui/state.slint b/crates/qbz-slint/ui/state.slint index c5bb9af6e..e01540456 100644 --- a/crates/qbz-slint/ui/state.slint +++ b/crates/qbz-slint/ui/state.slint @@ -3248,13 +3248,25 @@ export global QueueState { in property <[QueueItem]> history: []; // --- Immersive coverflow (mode 2) ------------------------------------ - // The next 3 / previous 3 tracks, taken from the UNFILTERED queue so the - // coverflow pyramid is correct regardless of the sidebar's page or search - // filter. Index 0 = next / most-recent. Decoded artwork handles are reused - // across refreshes (id-diff) so a one-position shift never re-decodes the - // covers still on screen. - in property <[QueueItem]> coverflow-upcoming: []; - in property <[QueueItem]> coverflow-history: []; + // ONE STABLE flat ordered model of the whole queue, oldest-first: + // [history.reversed (oldest..newest), NOW-PLAYING, upcoming...] + // This list and its decoded cover handles do NOT change on a pure track + // advance/jump — only `coverflow-index` (the flat position of NOW) moves, + // and the .slint `scroll` float animates to it. The model is rebuilt by the + // Rust controller ONLY when the queue CONTENTS change (different id-sequence: + // new queue / shuffle / add / remove), gated by `coverflow-seq-hash`. On a + // pure advance the model setter is SKIPPED entirely (no Repeater rebuild, no + // Image churn), so visible covers never re-decode. Windowed (±4) lazy decode + // keeps at most one new cover decoding per advance. + in property <[QueueItem]> coverflow-tracks: []; + // Flat index of the NOW-PLAYING cover within `coverflow-tracks` + // (= history.len() when a current track exists, else 0). The .slint panel + // binds an animated `scroll` float to this int so a change eases the fan. + in property coverflow-index: 0; + // Order-sensitive rolling fingerprint of the flat id-sequence. The Rust + // controller compares this to the value it last pushed; equal => pure + // advance => skip the model rebuild and only update `coverflow-index`. + in property coverflow-seq-hash: 0; // --- Shared ---------------------------------------------------------- // Active tab: 0 = Queue, 1 = History. @@ -3266,8 +3278,9 @@ export global QueueState { // Play the upcoming entry at `index` within the current page slice. callback play-upcoming(int); // Play an upcoming entry by its QUEUE-WIDE (unfiltered) index. Used by the - // immersive coverflow, whose cards index `coverflow-upcoming` (= the real - // next-3, page/search-independent) — NOT the paged play-upcoming. + // immersive coverflow: a side card at flat index `i > coverflow-index` maps + // to up_index = i - coverflow-index - 1 and dispatches here (page/search- + // independent) — NOT the paged play-upcoming. callback play-coverflow-upcoming(int); // Play a history entry by its `index` in the `history` list. callback play-history(int);