Merge feature/viewport-scroll-plumbing into pre-release

cc
This commit is contained in:
vicrodh committed 2026-07-07 09:13:34 -06:00
commit 722dda025e
14 files changed
+736 -55

No files matched your search

@@ -210,6 +210,19 @@ export component ArtistReleasesView inherits Rectangle {
card-width: root.album-w;
card-height: root.album-h;
card-gap: root.gap;
// Viewport windowing (Phase 1): only cards near the
// visible band mount. The offset is the page's
// padding-top (8px) — the loading / error branches are
// mutually exclusive with the grid, so nothing else
// sits above it; the grid's one-viewport margin absorbs
// any small error.
windowed: true;
visible-top: -flick.viewport-y;
visible-height: flick.height;
content-offset: 8px;
// Element windowing only; artwork stays per-page —
// pages arrive index-keyed with covers already on the
// model (id-keyed banding is a future migration).
open-album(id) => { root.open-album(id); }
open-artist(id) => { root.open-artist(id); }
media-action(kind, id, action) => {
@@ -313,6 +313,19 @@ export component AwardAlbumsView inherits Rectangle {
card-width: root.album-w;
card-height: root.album-h;
card-gap: root.gap;
// Viewport windowing (Phase 1): only cards near the
// visible band mount. The offset is the page's
// padding-top (8px) — the spinner / error / empty
// branches are mutually exclusive with the grid, so
// nothing else sits above it; the grid's one-viewport
// margin absorbs any small error.
windowed: true;
visible-top: -flick.viewport-y;
visible-height: flick.height;
content-offset: 8px;
// Element windowing only; artwork stays per-page —
// pages arrive index-keyed with covers already on the
// model (id-keyed banding is a future migration).
open-album(id) => { root.open-album(id); }
// Improvement #2 — wire open-artist (Tauri leaves it dead).
open-artist(id) => { root.open-artist(id); }
@@ -47,23 +47,75 @@ component AlbumGrid inherits Rectangle {
? self.rows * root.card-height + Math.max(0, self.rows - 1) * root.card-gap
: 0px;
// Row band = visible rows ± one full viewport. Row-granular ints, so the
// `changed` handlers only fire when a row boundary is crossed (~every
// Target band = visible rows ± one full viewport. Row-granular ints, so
// the `changed` handlers only fire when a row boundary is crossed (~every
// 270px of scroll), not per scrolled pixel.
property <length> row-stride: root.card-height + root.card-gap;
property <length> local-top: root.visible-top - root.content-offset;
property <int> first-window-row: root.windowed
property <int> target-first-row: root.windowed
? Math.max(0, Math.floor((root.local-top - root.visible-height) / root.row-stride))
: 0;
property <int> last-window-row: root.windowed
property <int> target-last-row: root.windowed
? Math.max(0, Math.floor((root.local-top + 2 * root.visible-height) / root.row-stride))
: 0;
changed first-window-row => { root.notify-window(); }
changed last-window-row => { root.notify-window(); }
// Mounted band = target band + contract hysteresis. Expansion follows the
// target immediately (a card must be mounted before it can reach the
// visible area); contraction lags by `hysteresis-rows`, so a few-px
// oscillation across a row boundary cannot mount/unmount a whole row of
// cards on every direction change.
property <int> hysteresis-rows: 1;
property <int> first-window-row: 0;
property <int> last-window-row: 0;
pure function desired-first-row() -> int {
if (root.target-first-row < root.first-window-row) {
return root.target-first-row;
}
if (root.target-first-row > root.first-window-row + root.hysteresis-rows) {
return root.target-first-row - root.hysteresis-rows;
}
return root.first-window-row;
}
pure function desired-last-row() -> int {
if (root.target-last-row > root.last-window-row) {
return root.target-last-row;
}
if (root.target-last-row < root.last-window-row - root.hysteresis-rows) {
return root.target-last-row + root.hysteresis-rows;
}
return root.last-window-row;
}
function apply-window() {
if (root.desired-first-row() != root.first-window-row
|| root.desired-last-row() != root.last-window-row) {
root.first-window-row = root.desired-first-row();
root.last-window-row = root.desired-last-row();
root.notify-window();
}
}
changed target-first-row => { root.apply-window(); }
changed target-last-row => { root.apply-window(); }
// Column count changes on first layout and on window resize — the band's
// ITEM indices depend on it, so re-notify.
changed columns => { root.notify-window(); }
init => { root.notify-window(); }
// Post-layout seed. Reading the target bindings from `init` would pull
// `absolute-position` (a grouped section's content-offset) while layout
// is still evaluating — the documented "Recursion detected" panic. A
// one-shot Timer a tick after mount is the sanctioned probe (same
// pattern as the modal focus timers); until it fires, the default [0,0]
// band keeps at most the first row mounted for one frame. The `changed`
// handlers run from the post-layout change queue, so they stay direct.
property <bool> seeded: false;
Timer {
interval: 16ms;
running: root.windowed && !root.seeded;
triggered => {
self.running = false;
root.seeded = true;
root.first-window-row = root.target-first-row;
root.last-window-row = root.target-last-row;
root.notify-window();
}
}
function notify-window() {
if (root.windowed) {
root.window-changed(
@@ -123,9 +175,12 @@ export component AlbumCollectionView inherits VerticalLayout {
in property <length> card-height: 246px;
in property <length> card-gap: 24px;
in property <length> list-row-gap: 4px;
// Viewport windowing — forwarded to the FLAT grid only (grouped sections
// keep full mounts; their per-section offsets are unknown here). OFF by
// default so Discover Browse / Labels / Favorites are untouched.
// Viewport windowing — forwarded to the flat grid AND to each grouped
// section grid (each section derives its own offset from an
// absolute-position delta at the instance). Grouped sections window their
// MOUNTS only; grouped-mode artwork stays full-dispatch (consumers send
// the whole set id-keyed), so `window-changed` fires from the flat grid
// alone. OFF by default so untouched consumers keep full mounts.
in property <bool> windowed: false;
in property <length> visible-top: 0px;
in property <length> visible-height: 0px;
@@ -173,7 +228,18 @@ export component AlbumCollectionView inherits VerticalLayout {
}
}
}
// Grid view: a card grid for this section.
// Grid view: a card grid for this section — windowed like the
// flat grid. The section's offset inside the scroll content is
// root.content-offset (the ACV's own y there, supplied by the
// surface) plus this grid's y inside the ACV, measured as the
// absolute-position DELTA: self and root live in the same
// Flickable content, so the delta is scroll-invariant (both move
// together), and absolute-position is EXACT in plain
// Flickable/if/for chains (the double-count bug is
// ListView-only). `window-changed` stays UNBOUND here: grouped
// artwork is dispatched in full, id-keyed, by every consumer, so
// per-section banding callbacks would be meaningless — sections
// window their element mounts only.
if root.view-mode != "list": AlbumGrid {
albums: section.albums;
show-favorite: root.show-favorite;
@@ -182,6 +248,11 @@ export component AlbumCollectionView inherits VerticalLayout {
card-width: root.card-width;
card-height: root.card-height;
card-gap: root.card-gap;
windowed: root.windowed;
visible-top: root.visible-top;
visible-height: root.visible-height;
content-offset: root.content-offset
+ self.absolute-position.y - root.absolute-position.y;
open-album(id) => {
root.open-album(id);
}
+82 -8
View File
@@ -90,6 +90,67 @@ export component Carousel inherits VerticalLayout {
// scrolled right). Zero when everything fits.
property <length> max-scroll: Math.max(0px, root.content-width - flick.width);
// --- Horizontal element windowing (always on) -------------------------
// Only cards within ~one viewport of the visible band mount a real
// AlbumCard; the rest are same-footprint placeholder slots, so the
// content-width formula above (the scroll geometry) never changes.
// Element-count only — NO artwork banding: every section's loader
// dispatches artwork for the whole strip up front and it lands on the
// model, so a card mounting later picks its cover up instantly.
// The strip starts at x=0 inside the Flickable's content (no leading
// padding), so local-left is just the negated viewport-x.
// Target band = visible columns ± one full viewport. Column-granular
// ints, so the `changed` handlers only fire when a column boundary is
// crossed (~every 232px of scroll), not per scrolled pixel — and a page
// jump from the nav buttons is just a big boundary crossing.
property <length> col-stride: root.card-width + root.gap;
property <length> local-left: -flick.viewport-x;
property <int> target-first-col: Math.max(
0,
Math.floor((root.local-left - flick.width) / root.col-stride));
property <int> target-last-col: Math.max(
0,
Math.floor((root.local-left + 2 * flick.width) / root.col-stride));
// Mounted band = target band + contract hysteresis. Expansion follows
// the target immediately (a card must be mounted before it can reach the
// visible area); contraction lags by `hysteresis-cols`, so a few-px
// oscillation across a column boundary cannot mount/unmount cards on
// every direction change.
property <int> hysteresis-cols: 1;
property <int> first-window-col: 0;
property <int> last-window-col: 0;
pure function desired-first-col() -> int {
if (root.target-first-col < root.first-window-col) {
return root.target-first-col;
}
if (root.target-first-col > root.first-window-col + root.hysteresis-cols) {
return root.target-first-col - root.hysteresis-cols;
}
return root.first-window-col;
}
pure function desired-last-col() -> int {
if (root.target-last-col > root.last-window-col) {
return root.target-last-col;
}
if (root.target-last-col < root.last-window-col - root.hysteresis-cols) {
return root.target-last-col + root.hysteresis-cols;
}
return root.last-window-col;
}
function apply-window() {
if (root.desired-first-col() != root.first-window-col
|| root.desired-last-col() != root.last-window-col) {
root.first-window-col = root.desired-first-col();
root.last-window-col = root.desired-last-col();
}
}
changed target-first-col => { root.apply-window(); }
changed target-last-col => { root.apply-window(); }
init => {
root.first-window-col = root.target-first-col;
root.last-window-col = root.target-last-col;
}
spacing: 12px;
// --- Header: title + page controls -----------------------------------
@@ -155,14 +216,27 @@ export component Carousel inherits VerticalLayout {
HorizontalLayout {
spacing: root.gap;
for album in root.section.albums: AlbumCard {
album: album;
card-height: root.card-height;
clicked(id) => {
root.album-clicked(id);
}
media-action(kind, id, action) => {
root.media-action(kind, id, action);
for album[i] in root.section.albums: card-slot := Rectangle {
// Fixed-footprint slot: carries the card's exact size so
// the layout (and thus content-width / scroll geometry)
// is unchanged while the card itself is unmounted.
width: root.card-width;
height: root.card-height;
property <bool> in-window: i >= root.first-window-col
&& i <= root.last-window-col;
// Placeholder tile while the real card is unmounted
// (fast scroll / far page jump).
border-radius: 8px;
background: card-slot.in-window ? transparent : Theme.surface-elevated;
if card-slot.in-window: AlbumCard {
album: album;
card-height: root.card-height;
clicked(id) => {
root.album-clicked(id);
}
media-action(kind, id, action) => {
root.media-action(kind, id, action);
}
}
}
}
@@ -312,6 +312,19 @@ export component DiscoverBrowseView inherits Rectangle {
card-height: root.album-h;
card-gap: root.gap;
list-row-gap: root.list-row-gap;
// Viewport windowing (Phase 1): only cards near the
// visible band mount. The offset is the page's
// padding-top (8px) — the spinner / empty branches are
// mutually exclusive with the grid, so nothing else
// sits above it; the grid's one-viewport margin absorbs
// any small error.
windowed: true;
visible-top: -flick.viewport-y;
visible-height: flick.height;
content-offset: 8px;
// Element windowing only; artwork stays per-page —
// pages arrive index-keyed with covers already on the
// model (id-keyed banding is a future migration).
open-album(id) => { root.open-album(id); }
open-artist(id) => { root.open-artist(id); }
media-action(kind, id, action) => {
@@ -1115,6 +1115,18 @@ export component FavoritesView inherits Rectangle {
view-mode: FavoritesState.albums-view-mode;
is-grouped: FavoritesState.albums-group-mode != "off";
show-source: false;
// Viewport windowing (Phase 1): only cards near the
// visible band mount + get artwork dispatched. The
// offset is the page's padding-top (16px); the grid's
// one-viewport margin absorbs the small extras
// (empty-state texts) above the grid.
windowed: true;
visible-top: -other-flick.viewport-y;
visible-height: other-flick.height;
content-offset: 16px;
window-changed(first, last) => {
FavoritesActions.albums-window-changed(first, last);
}
open-album(id) => {
root.open-album(id);
}
@@ -268,6 +268,19 @@ export component LabelReleasesView inherits Rectangle {
view-mode: LabelState.view-mode;
show-source: false;
list-row-gap: root.list-row-gap;
// Viewport windowing (Phase 1): only cards near the
// visible band mount. The offset approximates the static
// content above the grid: 11px padding-top + 22px spacer
// + 180px label header + 24px spacer + ~42px toolbar +
// 24px spacer ≈ 303px; the grid's one-viewport margin
// absorbs the small error.
windowed: true;
visible-top: -flick.viewport-y;
visible-height: flick.height;
content-offset: 303px;
// Element windowing only; artwork stays per-page — pages
// arrive index-keyed with covers already on the model
// (id-keyed banding is a future migration).
open-album(id) => {
root.open-album(id);
}
@@ -186,6 +186,20 @@ component AlbumGrid inherits Rectangle {
property <length> card-w: 200px;
property <length> card-h: 246px;
property <length> gap: 24px;
// --- Viewport windowing (opt-in; default OFF = identical to before) ---
// ELEMENT windowing only: with `windowed` on, cards within ~one viewport
// of the visible band mount a real AlbumCard; the rest are same-footprint
// placeholders, so the height formula (the scroll geometry) never
// changes. No window-changed callback here — search artwork is
// dispatched per loaded page, index-keyed onto the directly-rendered
// model, so covers are already present when a card mounts.
// `visible-top`/`visible-height` arrive in the surrounding Flickable's
// CONTENT coordinates; `content-offset` is this grid's approximate y
// inside that content — small errors are absorbed by the margin.
in property <bool> windowed: false;
in property <length> visible-top: 0px;
in property <length> visible-height: 0px;
in property <length> content-offset: 0px;
property <int> columns:
Math.max(1, Math.floor((self.width + root.gap) / (root.card-w + root.gap)));
property <int> row-count: Math.ceil(root.albums.length / root.columns);
@@ -194,15 +208,76 @@ component AlbumGrid inherits Rectangle {
? root.row-count * root.card-h + (root.row-count - 1) * root.gap
: 0px;
for album[i] in root.albums: AlbumCard {
// Target band = visible rows ± one full viewport. Row-granular ints, so
// the `changed` handlers only fire when a row boundary is crossed, not
// per scrolled pixel.
property <length> row-stride: root.card-h + root.gap;
property <length> local-top: root.visible-top - root.content-offset;
property <int> target-first-row: root.windowed
? Math.max(0, Math.floor((root.local-top - root.visible-height) / root.row-stride))
: 0;
property <int> target-last-row: root.windowed
? Math.max(0, Math.floor((root.local-top + 2 * root.visible-height) / root.row-stride))
: 0;
// Mounted band = target band + contract hysteresis. Expansion follows the
// target immediately (a card must be mounted before it can reach the
// visible area); contraction lags by `hysteresis-rows`, so a few-px
// oscillation across a row boundary cannot mount/unmount a whole row of
// cards on every direction change.
property <int> hysteresis-rows: 1;
property <int> first-window-row: 0;
property <int> last-window-row: 0;
pure function desired-first-row() -> int {
if (root.target-first-row < root.first-window-row) {
return root.target-first-row;
}
if (root.target-first-row > root.first-window-row + root.hysteresis-rows) {
return root.target-first-row - root.hysteresis-rows;
}
return root.first-window-row;
}
pure function desired-last-row() -> int {
if (root.target-last-row > root.last-window-row) {
return root.target-last-row;
}
if (root.target-last-row < root.last-window-row - root.hysteresis-rows) {
return root.target-last-row + root.hysteresis-rows;
}
return root.last-window-row;
}
function apply-window() {
if (root.desired-first-row() != root.first-window-row
|| root.desired-last-row() != root.last-window-row) {
root.first-window-row = root.desired-first-row();
root.last-window-row = root.desired-last-row();
}
}
changed target-first-row => { root.apply-window(); }
changed target-last-row => { root.apply-window(); }
init => {
root.first-window-row = root.target-first-row;
root.last-window-row = root.target-last-row;
}
for album[i] in root.albums: card-slot := Rectangle {
x: Math.mod(i, root.columns) * (root.card-w + root.gap);
y: Math.floor(i / root.columns) * (root.card-h + root.gap);
album: album;
clicked(id) => {
root.open(id);
}
media-action(k, ii, a) => {
root.media-action(k, ii, a);
width: root.card-w;
height: root.card-h;
property <bool> in-window: !root.windowed
|| (Math.floor(i / root.columns) >= root.first-window-row
&& Math.floor(i / root.columns) <= root.last-window-row);
// Placeholder tile while the real card is unmounted (fast scroll).
border-radius: 8px;
background: card-slot.in-window ? transparent : Theme.surface-elevated;
if card-slot.in-window: AlbumCard {
album: album;
clicked(id) => {
root.open(id);
}
media-action(k, ii, a) => {
root.media-action(k, ii, a);
}
}
}
}
@@ -555,6 +630,17 @@ export component SearchResultsView inherits Rectangle {
}
if SearchState.tab == 1: AlbumGrid {
albums: SearchState.albums;
// Element windowing: on the Albums tab the grid is the
// first thing in the scroll content (the nav row and tab
// strip sit ABOVE the Flickable; body has no top
// padding), so its content offset is ~0. LL-style
// approximation — the ±one-viewport margin absorbs about
// a row of drift either way. Applies to tab 1 only; the
// other tabs' sections are unaffected.
windowed: true;
visible-top: -flick.viewport-y;
visible-height: flick.height;
content-offset: 0px;
open(id) => { root.open-album(id); }
media-action(k, i, a) => { root.media-action(k, i, a); }
}
+3
View File
@@ -4679,6 +4679,9 @@ export global FavoritesActions {
callback albums-set-sort(string /* sort key */);
callback albums-set-group(string /* off | alpha | artist */);
callback albums-shuffle();
// Windowed grid: the visible row band changed (item indices into
// albums-visible, prefetch margin included) — dispatch artwork for it.
callback albums-window-changed(int /* first */, int /* last */);
callback unfavorite-track(string /* track id */);
callback unfavorite-album(string /* album id */);
callback retry-load();
+26 -13
View File
@@ -136,8 +136,12 @@ pub enum ArtworkTarget {
LocationArtist { index: usize },
/// A row in FavoritesState.tracks[index].
FavoriteTrack { index: usize },
/// A card in FavoritesState.albums[index].
FavoriteAlbum { index: usize },
/// A Favorites album cover, addressed BY ID (windowed dispatch over
/// `albums-visible` — id-keyed delivery is immune to derive re-sorts
/// between dispatch and apply). `gen` is the favorites-albums generation
/// at fetch time; a stale cover (the model was replaced by a reload) is
/// dropped.
FavoriteAlbumById { id: String, gen: u64 },
/// A card in DiscoverBrowseState.albums[index].
DiscoverBrowseAlbum { index: usize },
/// A Local Library album cover, addressed BY ID (windowed dispatch over
@@ -386,8 +390,17 @@ pub fn spawn_loads(jobs: Vec<ArtworkJob>, window: slint::Weak<AppWindow>, cache:
tokio::spawn(async move {
let _permit = semaphore.acquire().await.ok()?;
let decode_size = job.target.decode_size();
let (pixels, width, height) =
fetch_and_decode(&job.url, &cache, decode_size).await?;
let Some((pixels, width, height)) =
fetch_and_decode(&job.url, &cache, decode_size).await
else {
// Failed fetch/decode never reaches apply_artwork — free the
// windowed-dispatch dedupe slot here so a later band pass can
// retry this cover instead of skipping it for the session.
if let ArtworkTarget::FavoriteAlbumById { id, .. } = &job.target {
crate::favorites::album_artwork_job_done(id);
}
return None;
};
let target = job.target;
let url = job.url;
let _ = window.upgrade_in_event_loop(move |w| {
@@ -1217,16 +1230,16 @@ fn apply_artwork(
crate::favorites::set_track_artwork(window, &id, image);
}
}
ArtworkTarget::FavoriteAlbum { index } => {
let model = window.global::<crate::FavoritesState>().get_albums();
if let Some(mut item) = model.row_data(index) {
item.artwork = image.clone();
let id = item.id.to_string();
model.set_row_data(index, item);
// Also reach the rendered visible/grouped model (clones when
// a sort/group is active — they don't share `albums`).
crate::favorites::set_album_artwork(window, &id, image);
ArtworkTarget::FavoriteAlbumById { id, gen } => {
// The job is done either way — free its in-flight slot so the
// window dispatcher can re-request it after an eviction.
crate::favorites::album_artwork_job_done(&id);
// Drop the cover if a reload superseded the set it belongs to.
if !crate::favorites::albums_gen_current(gen) {
return;
}
// Set by id onto the full set + visible + grouped sections.
crate::favorites::set_album_artwork(window, &id, image);
}
ArtworkTarget::DiscoverBrowseAlbum { index } => {
let model = window.global::<crate::DiscoverBrowseState>().get_albums();
+255 -14
View File
@@ -10,6 +10,7 @@
use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, LazyLock, Mutex};
use qbz_app::shell::AppRuntime;
@@ -19,7 +20,7 @@ use serde::Deserialize;
use slint::{ComponentHandle, Model, ModelRc, VecModel};
use crate::album_map::{self, map_album, to_item, AlbumCard};
use crate::artwork::{ArtworkJob, ArtworkTarget};
use crate::artwork::{ArtworkJob, ArtworkTarget, ImageCache};
use crate::search::{self, PlaylistRow};
use crate::{
AlbumCardItem, AlphaJump, AppWindow, DiscoverSection, FavArtistSection, FavoriteArtistItem,
@@ -535,8 +536,8 @@ pub fn apply_favorites(window: &AppWindow, data: FavData) {
}
FavData::Albums { items, total } => {
// Everything in the Albums tab is a favorite -> filled heart.
// (Blocked albums are already dropped at the FavData source so the
// model + artwork jobs stay index-aligned.)
// (Blocked albums are already dropped at the FavData source;
// artwork delivery is id-keyed, so no index alignment to keep.)
let cards: Vec<AlbumCardItem> = items
.into_iter()
.map(|c| {
@@ -869,6 +870,229 @@ pub fn shuffled_tracks() -> Vec<Track> {
tracks
}
// ---- Windowed albums artwork (mirrors local_library's albums grid) ------
/// Generation guard, bumped on every Albums-tab (re)load. A stale in-flight
/// cover fetch (an older load's job) is discarded on apply so it can't land
/// on the replacement set.
static FAV_ALBUMS_GEN: AtomicU64 = AtomicU64::new(0);
/// True if `gen` is still the current favorites-albums generation. The
/// artwork pipeline calls this before applying a decoded cover so an
/// in-flight job from a superseded load doesn't paint the new model.
pub fn albums_gen_current(gen: u64) -> bool {
FAV_ALBUMS_GEN.load(Ordering::SeqCst) == gen
}
/// Last row band reported by the windowed albums grid (item indices into
/// `albums-visible`, prefetch margin already included by the grid). Kept so
/// model rebuilds (load/derive) can re-dispatch — the grid only fires its
/// callback when the band CHANGES, not when the rows under it change.
static FAV_ALBUMS_WINDOW: std::sync::Mutex<(usize, usize)> = std::sync::Mutex::new((0, 59));
/// Cover ids currently in the artwork pipeline for the albums window
/// (dedupe during fast scroll). Freed on apply; cleared on reloads.
fn fav_albums_inflight() -> &'static std::sync::Mutex<std::collections::HashSet<String>> {
static S: std::sync::OnceLock<std::sync::Mutex<std::collections::HashSet<String>>> =
std::sync::OnceLock::new();
S.get_or_init(|| std::sync::Mutex::new(std::collections::HashSet::new()))
}
/// Image-cache handle captured at load time so the window dispatcher can
/// spawn artwork jobs outside the load path. Favorite covers are Qobuz CDN
/// URLs (plain `spawn_loads`), so no Plex params ride along here.
fn fav_albums_dispatch_ctx() -> &'static std::sync::Mutex<Option<ImageCache>> {
static S: std::sync::OnceLock<std::sync::Mutex<Option<ImageCache>>> =
std::sync::OnceLock::new();
S.get_or_init(|| std::sync::Mutex::new(None))
}
/// A windowed artwork job finished (applied or dropped) — free its slot so
/// the dispatcher can request the id again after an eviction.
pub fn album_artwork_job_done(id: &str) {
fav_albums_inflight().lock().unwrap().remove(id);
}
/// Reset the windowed-albums artwork pipeline for a fresh Albums-tab load:
/// bump the generation (orphans every in-flight job — dropped on apply),
/// free their dedupe slots and stash the image-cache handle the dispatchers
/// spawn jobs with. Runs on the UI thread BEFORE `apply_favorites`, whose
/// `derive_albums` dispatches the covers against the new generation.
pub fn begin_albums_artwork(image_cache: ImageCache) {
FAV_ALBUMS_GEN.fetch_add(1, Ordering::SeqCst);
fav_albums_inflight().lock().unwrap().clear();
*fav_albums_dispatch_ctx().lock().unwrap() = Some(image_cache);
}
/// Dispatch throttle for the grid's band reports (leading + trailing edge,
/// UI thread). During a fling the grid crosses a row boundary every ~270px
/// and each crossing used to spawn artwork jobs for rows flying straight
/// past the viewport; coalescing to one dispatch per interval keeps the
/// decode pipeline on rows the user can actually see.
const FAV_ALBUMS_DISPATCH_THROTTLE_MS: u64 = 180;
thread_local! {
static FAV_ALBUMS_BAND: crate::viewport::BandDispatcher =
crate::viewport::BandDispatcher::new(FAV_ALBUMS_DISPATCH_THROTTLE_MS);
}
/// The windowed grid reported a new visible row band. The band is stored
/// immediately (model rebuilds re-read it); the artwork dispatch is
/// throttled, and gen-guarded so a pass scheduled before a reload cannot
/// dispatch/evict against the replacement model — the reload's own
/// `derive_albums` dispatch is authoritative for the new generation.
pub fn albums_window_changed(window: &AppWindow, first: i32, last: i32) {
let first = first.max(0) as usize;
let last = last.max(first as i32) as usize;
*FAV_ALBUMS_WINDOW.lock().unwrap() = (first, last);
let gen = FAV_ALBUMS_GEN.load(Ordering::SeqCst);
let weak = window.as_weak();
FAV_ALBUMS_BAND.with(|d| {
d.report(Box::new(move || {
if !albums_gen_current(gen) {
return;
}
if let Some(w) = weak.upgrade() {
dispatch_fav_albums_window(&w);
}
}));
});
}
/// Dispatch covers for the current albums window (over `albums-visible`) and
/// evict decoded covers far outside it back to the placeholder, so cover RAM
/// scales with the viewport instead of the library. Delivery is id-keyed
/// (`FavoriteAlbumById`), so a derive re-sort between dispatch and apply
/// cannot land a cover on the wrong card; a tab reload bumps
/// `FAV_ALBUMS_GEN` and the apply arm drops the stale image.
pub fn dispatch_fav_albums_window(window: &AppWindow) {
let (first, last) = *FAV_ALBUMS_WINDOW.lock().unwrap();
let Some(image_cache) = fav_albums_dispatch_ctx().lock().unwrap().clone() else {
return;
};
let gen = FAV_ALBUMS_GEN.load(Ordering::SeqCst);
let state = window.global::<FavoritesState>();
let visible = state.get_albums_visible();
let len = visible.row_count();
if len == 0 {
return;
}
let last = last.min(len - 1);
if first > last {
return;
}
// Retention = the window plus one window-span on each side. Beyond it,
// covers return to the placeholder; re-entry is cheap (byte-budgeted
// decoded cache, else a bounded re-decode through the disk cache).
let span = last - first + 1;
let keep_lo = first.saturating_sub(span);
let keep_hi = (last + span).min(len - 1);
let mut jobs = Vec::new();
{
let mut inflight = fav_albums_inflight().lock().unwrap();
for vi in first..=last {
let Some(item) = visible.row_data(vi) else { continue };
if item.artwork.size().width > 0 || item.artwork_url.is_empty() {
continue;
}
let id = item.id.to_string();
if inflight.insert(id.clone()) {
jobs.push(ArtworkJob {
target: ArtworkTarget::FavoriteAlbumById { id, gen },
url: item.artwork_url.to_string(),
});
}
}
}
for vi in (0..keep_lo).chain(keep_hi + 1..len) {
let Some(item) = visible.row_data(vi) else { continue };
if item.artwork.size().width > 0 {
set_album_artwork(window, item.id.as_str(), slint::Image::default());
}
}
if !jobs.is_empty() {
crate::artwork::spawn_loads(jobs, window.as_weak(), image_cache);
}
}
/// Flat LIST-view artwork: same `albums-visible` model as the grid, but the
/// list is not windowed (only `AlbumGrid` fires `window-changed`) — dispatch
/// every missing cover, no eviction. Phase 1 limit.
fn dispatch_fav_albums_all_visible(window: &AppWindow) {
let Some(image_cache) = fav_albums_dispatch_ctx().lock().unwrap().clone() else {
return;
};
let gen = FAV_ALBUMS_GEN.load(Ordering::SeqCst);
let state = window.global::<FavoritesState>();
let visible = state.get_albums_visible();
let mut jobs = Vec::new();
{
let mut inflight = fav_albums_inflight().lock().unwrap();
for vi in 0..visible.row_count() {
let Some(item) = visible.row_data(vi) else { continue };
if item.artwork.size().width > 0 || item.artwork_url.is_empty() {
continue;
}
let id = item.id.to_string();
if inflight.insert(id.clone()) {
jobs.push(ArtworkJob {
target: ArtworkTarget::FavoriteAlbumById { id, gen },
url: item.artwork_url.to_string(),
});
}
}
}
if !jobs.is_empty() {
crate::artwork::spawn_loads(jobs, window.as_weak(), image_cache);
}
}
/// The Albums grid/list view-mode toggled. Switching TO the list needs a full
/// dispatch (the list is not windowed and the grid's window may have evicted
/// covers the list now shows); switching to the grid is handled by AlbumGrid's
/// own post-layout seed Timer on mount (it re-fires `window-changed`).
pub fn albums_view_mode_changed(window: &AppWindow) {
let state = window.global::<FavoritesState>();
if state.get_albums_group_mode() == "off" && state.get_albums_view_mode() == "list" {
dispatch_fav_albums_all_visible(window);
}
}
/// Grouped-mode artwork: `albums-visible` is EMPTY there (the sections render
/// from `albums-grouped`), so the viewport window doesn't apply — keep the
/// pre-windowing behavior and dispatch every missing cover. Phase 1 limit;
/// per-section windowing needs the sections' content offsets.
fn dispatch_fav_albums_all_grouped(window: &AppWindow) {
let Some(image_cache) = fav_albums_dispatch_ctx().lock().unwrap().clone() else {
return;
};
let gen = FAV_ALBUMS_GEN.load(Ordering::SeqCst);
let state = window.global::<FavoritesState>();
let grouped = state.get_albums_grouped();
let mut jobs = Vec::new();
{
let mut inflight = fav_albums_inflight().lock().unwrap();
for gi in 0..grouped.row_count() {
let Some(sec) = grouped.row_data(gi) else { continue };
for i in 0..sec.albums.row_count() {
let Some(item) = sec.albums.row_data(i) else { continue };
if item.artwork.size().width > 0 || item.artwork_url.is_empty() {
continue;
}
let id = item.id.to_string();
if inflight.insert(id.clone()) {
jobs.push(ArtworkJob {
target: ArtworkTarget::FavoriteAlbumById { id, gen },
url: item.artwork_url.to_string(),
});
}
}
}
}
if !jobs.is_empty() {
crate::artwork::spawn_loads(jobs, window.as_weak(), image_cache);
}
}
/// Re-derive the rendered Albums list (`albums-visible`) from the full
/// `albums` set + the search query and sort key. Empty query + default
/// order shares the full model so artwork stays live; otherwise forks a
@@ -890,6 +1114,17 @@ pub fn derive_albums(window: &AppWindow) {
state.set_albums_visible(all);
state.set_albums_grouped(empty_sections());
state.set_albums_shown(n);
if state.get_albums_view_mode() == "list" {
// The LIST view renders the same albums-visible model but is NOT
// windowed (only AlbumGrid fires window-changed) — dispatch every
// missing cover and do no eviction, like pre-windowing.
dispatch_fav_albums_all_visible(window);
} else {
// The rows under the window band changed (fresh load / cleared
// filter) but the band itself didn't — the grid won't re-fire,
// so re-dispatch.
dispatch_fav_albums_window(window);
}
return;
}
@@ -908,6 +1143,14 @@ pub fn derive_albums(window: &AppWindow) {
if group == "off" {
state.set_albums_visible(ModelRc::new(VecModel::from(filtered)));
state.set_albums_grouped(empty_sections());
if state.get_albums_view_mode() == "list" {
// Non-windowed list — full dispatch, no eviction (see above).
dispatch_fav_albums_all_visible(window);
} else {
// The rows under the window band changed (search/sort/filter) but
// the band itself didn't — the grid won't re-fire, so re-dispatch.
dispatch_fav_albums_window(window);
}
return;
}
@@ -959,6 +1202,7 @@ pub fn derive_albums(window: &AppWindow) {
.collect();
state.set_albums_grouped(ModelRc::new(VecModel::from(sections)));
state.set_albums_visible(ModelRc::new(VecModel::from(Vec::<AlbumCardItem>::new())));
dispatch_fav_albums_all_grouped(window);
}
/// First-letter bucket key for alpha grouping (# for non-alphabetic).
@@ -1160,10 +1404,12 @@ fn set_artwork_in_albums(model: &ModelRc<AlbumCardItem>, id: &str, image: &slint
}
}
/// Set a freshly-decoded album cover (by id) on the rendered favorites
/// album models (flat `albums-visible` + every `albums-grouped` section).
/// Set a freshly-decoded album cover (by id) on every favorites album model:
/// the full `albums` set + the flat `albums-visible` + every `albums-grouped`
/// section (mirrors `local_library::set_local_album_artwork`).
pub fn set_album_artwork(window: &AppWindow, id: &str, image: slint::Image) {
let st = window.global::<FavoritesState>();
set_artwork_in_albums(&st.get_albums(), id, &image);
set_artwork_in_albums(&st.get_albums_visible(), id, &image);
let grouped = st.get_albums_grouped();
for s in 0..grouped.row_count() {
@@ -1345,15 +1591,10 @@ pub fn artwork_jobs(data: &FavData) -> Vec<ArtworkJob> {
target: ArtworkTarget::FavoriteTrack { index: i },
})
.collect(),
FavData::Albums { items, .. } => items
.iter()
.enumerate()
.filter(|(_, a)| !a.artwork_url.is_empty())
.map(|(i, a)| ArtworkJob {
url: a.artwork_url.clone(),
target: ArtworkTarget::FavoriteAlbum { index: i },
})
.collect(),
// WINDOWED (mirrors the Local Library albums grid): no all-at-once
// jobs for the full set — covers are dispatched by the viewport-band
// dispatchers after apply/derive (see `begin_albums_artwork`).
FavData::Albums { .. } => Vec::new(),
FavData::Artists { items, .. } => items
.iter()
.enumerate()
+28 -2
View File
@@ -307,12 +307,38 @@ pub fn album_artwork_job_done(id: &str) {
albums_inflight().lock().unwrap().remove(id);
}
/// The windowed grid reported a new visible row band.
/// Dispatch throttle for the grid's band reports (leading + trailing edge,
/// UI thread). During a fling the grid crosses a row boundary every ~270px
/// and each crossing used to spawn artwork jobs for rows flying straight
/// past the viewport; coalescing to one dispatch per interval keeps the
/// decode pipeline on rows the user can actually see.
const ALBUMS_DISPATCH_THROTTLE_MS: u64 = 180;
thread_local! {
static ALBUMS_BAND: crate::viewport::BandDispatcher =
crate::viewport::BandDispatcher::new(ALBUMS_DISPATCH_THROTTLE_MS);
}
/// The windowed grid reported a new visible row band. The band is stored
/// immediately (model rebuilds re-read it); the artwork dispatch is
/// throttled, and gen-guarded so a pass scheduled before a reload cannot
/// dispatch/evict against the replacement model — the reload's own
/// `derive_albums` dispatch is authoritative for the new generation.
pub fn albums_window_changed(window: &AppWindow, first: i32, last: i32) {
let first = first.max(0) as usize;
let last = last.max(first as i32) as usize;
*ALBUMS_WINDOW.lock().unwrap() = (first, last);
dispatch_albums_window(window);
let gen = ALBUMS_GEN.load(Ordering::SeqCst);
let weak = window.as_weak();
ALBUMS_BAND.with(|d| {
d.report(Box::new(move || {
if !albums_gen_current(gen) {
return;
}
if let Some(w) = weak.upgrade() {
dispatch_albums_window(&w);
}
}));
});
}
/// Dispatch covers for the current albums window (over `albums-visible`) and
+26
View File
@@ -130,6 +130,7 @@ pub use qbz_slint_common::toast;
mod tray;
mod tray_settings;
mod ui_prefs;
mod viewport;
mod whats_new;
use std::sync::Arc;
@@ -2886,7 +2887,17 @@ fn navigate_favorites(
match favorites::load_favorites(&runtime, tab).await {
Ok(data) => {
let jobs = favorites::artwork_jobs(&data);
// WINDOWED artwork for the Albums tab (was: a job for every
// favorite album). Reset the pipeline BEFORE apply — apply's
// `derive_albums` dispatches the covers itself (flat grid =
// viewport band; list/grouped = full set). Other tabs keep
// the all-at-once `jobs` dispatch.
let is_albums = matches!(&data, favorites::FavData::Albums { .. });
let image_cache_for_ui = image_cache.clone();
let _ = weak.upgrade_in_event_loop(move |w| {
if is_albums {
favorites::begin_albums_artwork(image_cache_for_ui);
}
favorites::apply_favorites(&w, data);
});
artwork::spawn_loads(jobs, weak.clone(), image_cache.clone());
@@ -18799,10 +18810,25 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
.on_albums_set_view(move |v| {
if let Some(w) = weak.upgrade() {
w.global::<FavoritesState>().set_albums_view_mode(v);
// Switching to the (non-windowed) list view needs covers
// the grid's window may have evicted.
favorites::albums_view_mode_changed(&w);
favorites_prefs::save(&w);
}
});
}
{
// Windowed albums grid: dispatch covers for the reported row band
// and evict the ones far outside it.
let weak = window.as_weak();
window
.global::<FavoritesActions>()
.on_albums_window_changed(move |first, last| {
if let Some(w) = weak.upgrade() {
favorites::albums_window_changed(&w, first, last);
}
});
}
{
// Group the favorite albums (off / alpha / artist).
let weak = window.as_weak();
+77
View File
@@ -0,0 +1,77 @@
//! Shared scroll-viewport plumbing for windowed surfaces (LL albums grid
//! today; the Phase-2 rollout surfaces reuse it). This side owns the band
//! dispatcher that turns raw `window-changed` reports from a .slint grid
//! into throttled artwork dispatches. Element windowing (card vs
//! placeholder) and the contract hysteresis on the band live .slint-side
//! (`AlbumGrid` in AlbumCollectionView.slint). Generation guarding is the
//! caller's job: capture the surface's gen when scheduling and check it
//! inside the action.
use slint::{Timer, TimerMode};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::time::{Duration, Instant};
/// Throttle with leading + trailing edge for viewport band reports.
/// UI-thread only (holds a `slint::Timer`) — wrap instances in
/// `thread_local!`. The first report after a quiet period runs immediately,
/// so a slow scroll gets artwork with no perceptible delay; while reports
/// keep arriving (a fling crosses a row boundary every ~270px) they coalesce
/// into at most one run per `interval`, always ending with a trailing run
/// for the final band.
pub struct BandDispatcher {
timer: Timer,
interval: Duration,
last_run: Rc<Cell<Option<Instant>>>,
pending: Rc<RefCell<Option<Box<dyn FnOnce()>>>>,
}
impl BandDispatcher {
pub fn new(interval_ms: u64) -> Self {
Self {
timer: Timer::default(),
interval: Duration::from_millis(interval_ms),
last_run: Rc::new(Cell::new(None)),
pending: Rc::new(RefCell::new(None)),
}
}
/// Report a band change. `action` either runs now (leading edge) or
/// replaces the pending trailing run — only the newest report survives
/// coalescing, which is sound because every action re-reads the live
/// band state when it runs.
pub fn report(&self, action: Box<dyn FnOnce()>) {
let now = Instant::now();
let quiet = self
.last_run
.get()
.map_or(true, |t| now.duration_since(t) >= self.interval);
if quiet && !self.timer.running() {
self.last_run.set(Some(now));
action();
return;
}
*self.pending.borrow_mut() = Some(action);
if !self.timer.running() {
let elapsed = self
.last_run
.get()
.map_or(Duration::ZERO, |t| now.duration_since(t));
let delay = self
.interval
.saturating_sub(elapsed)
.max(Duration::from_millis(1));
let pending = self.pending.clone();
let last_run = self.last_run.clone();
self.timer.start(TimerMode::SingleShot, delay, move || {
last_run.set(Some(Instant::now()));
// Release the RefCell borrow BEFORE running the action — it
// may synchronously re-enter `report()` via model updates.
let action = pending.borrow_mut().take();
if let Some(f) = action {
f();
}
});
}
}
}