From dd32f573b43ec8c0d3a71856fcc7fad1642c2c00 Mon Sep 17 00:00:00 2001 From: vicrodh <103399283+vicrodh@users.noreply.github.com> Date: Tue, 23 Jun 2026 12:09:34 -0600 Subject: [PATCH] feat(slint): persist session across restarts (startup page, window geometry, playback) Three restart-persistence features built and tested together (they share ui_prefs + the enter_shell restore sequence, so kept as one change): - Startup page: persist + restore the last SAFE top-level view via the canonical apply_entry dispatcher (loads data, not a blank view). Wired to Settings > Appearance > "Where you left off"; ui_prefs startup_page/last_view. - Window geometry: persist logical size + outer position and restore them at launch, clamped to the current monitor so a smaller/disconnected display can never open an oversized or off-screen window (winit Resized/Moved hook). - Playback session: new session_persist module wiring qbz-app's SessionStore. Saves queue + current track + volume + shuffle/repeat + position on track-change / pause / ~5s tick / exit (incl. hide-to-tray and tray Quit); restores the queue PAUSED at launch. Position resume on first play threads the player's existing start_position_secs (no protected-audio change beyond passing that param). Gated on the persist_session / resume_playback_position playback prefs; opened per-user on login + boot-restore + offline entry. Known issue: the seek bar/timer do not visibly show the resume position until play is pressed (the audio resume itself works); marked in code for follow-up. cc --- crates/qbz-core/src/core.rs | 13 +- crates/qbz-player/src/player/mod.rs | 23 +- crates/qbz-slint/src/auth.rs | 6 + crates/qbz-slint/src/main.rs | 202 ++++++++++++ crates/qbz-slint/src/playback.rs | 44 ++- crates/qbz-slint/src/session_persist.rs | 306 ++++++++++++++++++ crates/qbz-slint/src/settings.rs | 22 +- crates/qbz-slint/src/tray/mod.rs | 2 + crates/qbz-slint/src/ui_prefs.rs | 61 ++++ .../ui/settings/AppearanceSettings.slint | 1 - crates/qbz-slint/ui/shell/AppShell.slint | 3 + crates/qbz-slint/ui/state.slint | 3 + 12 files changed, 672 insertions(+), 14 deletions(-) create mode 100644 crates/qbz-slint/src/session_persist.rs diff --git a/crates/qbz-core/src/core.rs b/crates/qbz-core/src/core.rs index a8e985384..dcceaff92 100644 --- a/crates/qbz-core/src/core.rs +++ b/crates/qbz-core/src/core.rs @@ -625,20 +625,29 @@ impl QbzCore { quality: Quality, offline: Option<&qbz_offline_cache::OfflineCacheState>, sink: Option<&qbz_offline_cache::CacheEventSink>, + start_position_secs: u64, ) -> Result<(), String> { if let Some(off) = offline { if let Some(bytes) = crate::offline_resolve::resolve_offline_bytes(track_id, off, sink).await { log::info!("[Core] track {} served from OFFLINE cache", track_id); - return self.player.play_data(bytes, track_id); + let r = self.player.play_data(bytes, track_id); + // Offline-cached bytes play from memory; honor a session-resume + // position with a best-effort seek (0 = from the start). + if r.is_ok() && start_position_secs > 0 { + let _ = self.player.seek(start_position_secs); + } + return r; } } let guard = self.client.read().await; let client = guard .as_ref() .ok_or_else(|| "No Qobuz client available".to_string())?; - self.player.play_track(client, track_id, quality).await + self.player + .play_track(client, track_id, quality, start_position_secs) + .await } /// Resolve the bytes for a GAPLESS successor. Tier order L1/L2 → offline → diff --git a/crates/qbz-player/src/player/mod.rs b/crates/qbz-player/src/player/mod.rs index 7eeb51664..a8cfba18b 100644 --- a/crates/qbz-player/src/player/mod.rs +++ b/crates/qbz-player/src/player/mod.rs @@ -3433,11 +3433,13 @@ impl Player { client: &QobuzClient, track_id: u64, quality: Quality, + start_position_secs: u64, ) -> Result<(), String> { log::info!( - "Player: Starting playback for track {} with quality {:?}", + "Player: Starting playback for track {} with quality {:?} (start {}s)", track_id, - quality + quality, + start_position_secs ); // Cache hit: replay instantly from L1/L2 unless the cached copy is @@ -3455,7 +3457,14 @@ impl Player { track_id, cached.size_bytes ); - return self.play_data(cached.data, track_id); + let r = self.play_data(cached.data, track_id); + // Cached tracks play from in-memory data (no streaming resume + // offset); honor a session-resume position with a best-effort + // seek once playback has been handed to the audio thread. + if r.is_ok() && start_position_secs > 0 { + let _ = self.seek(start_position_secs); + } + return r; } } @@ -3527,7 +3536,7 @@ impl Player { total_flac_size, speed_mbps, duration_secs, - 0, // no resume offset + start_position_secs, // session-resume offset (0 = from start) )?; // Spawn the background task that fetches + decrypts + pushes @@ -3604,7 +3613,11 @@ impl Player { } // Send to audio thread - self.play_data(audio_data, track_id) + let r = self.play_data(audio_data, track_id); + if r.is_ok() && start_position_secs > 0 { + let _ = self.seek(start_position_secs); + } + r } /// Download a track fully into the L1/L2 cache **without** starting diff --git a/crates/qbz-slint/src/auth.rs b/crates/qbz-slint/src/auth.rs index c7d620a3f..d99cba1e6 100644 --- a/crates/qbz-slint/src/auth.rs +++ b/crates/qbz-slint/src/auth.rs @@ -114,6 +114,9 @@ where crate::artist_blacklist::init_for_user(&dir); // Intelligent Search (cache + ranking), seeded from the persisted pref. crate::search_service::init(&dir, crate::ui_prefs::load().intelligent_search); + // Session persistence (queue + playback): open the per-user session.db + // and seed the persist/resume gates from the playback prefs. + crate::session_persist::init_for_user(&dir); } // Lyrics cache (per-user, shared lyrics.db with Tauri). crate::lyrics::init_for_user(core.client(), user_id); @@ -227,6 +230,9 @@ where crate::artist_blacklist::init_for_user(&dir); // Intelligent Search (cache + ranking), seeded from the pref. crate::search_service::init(&dir, crate::ui_prefs::load().intelligent_search); + // Session persistence (queue + playback): open the per-user + // session.db and seed the persist/resume gates. + crate::session_persist::init_for_user(&dir); } // Lyrics cache (per-user, shared lyrics.db with Tauri). crate::lyrics::init_for_user(core.client(), user_id); diff --git a/crates/qbz-slint/src/main.rs b/crates/qbz-slint/src/main.rs index 6c5d4095c..a0c2b80e4 100644 --- a/crates/qbz-slint/src/main.rs +++ b/crates/qbz-slint/src/main.rs @@ -100,6 +100,7 @@ mod recently; mod scrobble; mod scrobbler_settings; mod search; +mod session_persist; mod search_service; // WGPU UNDERLAY SPIKE: GPU fragment-shader background for ImmersiveView. mod shader_underlay; @@ -320,6 +321,9 @@ async fn enter_shell( // Store the miniplayer context (idempotent). The mini window itself is // created lazily on first enter. miniplayer::init(runtime.clone(), weak.clone(), tokio::runtime::Handle::current()); + // Bind the exit context so the window close handlers can flush a final + // session snapshot before the loop quits (idempotent). + session_persist::bind_exit_ctx(runtime.clone(), tokio::runtime::Handle::current()); // Load the sidebar playlists list. load_sidebar_playlists(runtime.clone(), weak.clone(), &tokio::runtime::Handle::current()); @@ -387,6 +391,75 @@ async fn enter_shell( reload_home(&runtime, &weak, &image_cache, "home".to_string()).await; + // Session persistence: restore the last queue + current track PAUSED (gated + // on `persist_session`). set_queue_with_order emits QueueUpdated so the queue + // sidebar repaints itself; the now-playing bar reads current_track, so we + // refresh its metadata explicitly. No audio is loaded — playback stays + // stopped until the user hits play (Phase B then seeks to the saved + // position when `resume_playback_position` is on). + if session_persist::restore(&runtime).await { + playback::refresh_now_playing_meta(&runtime, &weak).await; + // Repaint the queue sidebar/list — set_queue_with_order emits + // QueueUpdated, but the queue UI repaints from explicit refreshes. + playback::refresh_sidebar(true); + // Seed the seek bar + timers to the resume position so they show it + // immediately (refresh_now_playing_meta above reset them to 0; the poll + // loop only catches up once playback starts). Peeks — the actual resume + // still fires on first play. + // + // KNOWN ISSUE / NEEDS WORK: this seed does NOT visibly stick — at rest + // the bar + timer still read 0:00 and only jump to the resume position + // once the user presses play (the audio resume itself works correctly). + // Something repaints NowPlayingState position/progress back to 0 after + // this runs (a later refresh_now_playing_meta closure, the poll loop's + // idle tick reporting position 0 while no audio is loaded, or the bar + // binding not reflecting a paused non-loaded position). Left as-is on + // purpose — revisit the pre-play seek-bar seed for paused restore. + let resume_pos = session_persist::pending_resume_position(); + if resume_pos > 0 { + if let Some(track) = runtime.core().current_track().await { + let dur = track.duration_secs; + let _ = weak.upgrade_in_event_loop(move |w| { + playback::seed_seek_display(&w, resume_pos, dur); + }); + } + } + } + + // Startup page = "where you left off": restore the last SAFE top-level view + // (online only — the offline entry keeps its D12 LocalLibrary root). Home + // was loaded just above; if a different view is remembered, re-root the nav + // history there (on the UI thread, like the offline path) and apply_entry it + // — which loads the view's data, NOT a blank set_view (the Tauri precedent). + { + let prefs = crate::ui_prefs::load(); + if prefs.startup_page == "remember" { + let entry = match prefs.last_view.as_str() { + "favorites" => Some(nav::NavEntry::Favorites { tab: "tracks".to_string() }), + "local-library" => Some(nav::NavEntry::LocalLibrary { + tab: local_library::LibTab::Albums.tab_id().to_string(), + }), + "mixtapes" => Some(nav::NavEntry::Mixtapes), + "collections" => Some(nav::NavEntry::Collections), + // "home" / unknown → keep the Home already loaded above. + _ => None, + }; + if let Some(entry) = entry { + let root_entry = entry.clone(); + let _ = weak.upgrade_in_event_loop(move |_w| { + nav::reset_root(root_entry); + }); + apply_entry( + entry, + &runtime, + &weak, + &tokio::runtime::Handle::current(), + &image_cache, + ); + } + } + } + // Seed the favorites tab counts so the badges are ready before the // user opens each tab (they otherwise only count on first visit). let counts = favorites::load_counts(&runtime).await; @@ -442,6 +515,9 @@ async fn enter_shell_offline( // Intelligent Search (cache + ranking), seeded from the persisted pref. // Cached results stay searchable offline; live revalidation no-ops. crate::search_service::init(&dir, crate::ui_prefs::load().intelligent_search); + // Session persistence (queue + playback): open the per-user session.db + // and seed the persist/resume gates from the playback prefs. + crate::session_persist::init_for_user(&dir); } // Lyrics cache (per-user, shared file with Tauri) — offline sessions // serve cached lyrics (deviation D3, cache-first offline contract). @@ -487,6 +563,9 @@ async fn enter_shell_offline( // Store the miniplayer context (idempotent). The mini window itself is // created lazily on first enter. miniplayer::init(runtime.clone(), weak.clone(), tokio::runtime::Handle::current()); + // Bind the exit context so the window close handlers can flush a final + // session snapshot before the loop quits (idempotent). + session_persist::bind_exit_ctx(runtime.clone(), tokio::runtime::Handle::current()); // Load Audio + Playback settings into the Settings page in the // background — fully local, same path as the online entry. @@ -724,6 +803,37 @@ fn install_browser_mouse_nav(window: &AppWindow) { _ => EventResult::Propagate, } } + // Persist main-window geometry so the next launch restores it + // (mirrors miniplayer.rs). The startup restore clamps to the + // monitor; here we just record what the WM settled on. A change + // guard avoids redundant writes on the many no-op events the WM + // emits. The app minimum is 940x600 (app.slint) — ignore smaller + // frames (minimize reports 0x0, mid-transition frames undershoot). + WindowEvent::Resized(size) => { + let scale = slint_window.scale_factor().max(0.01) as f64; + let lw = (size.width as f64 / scale) as f32; + let lh = (size.height as f64 / scale) as f32; + if lw >= 940.0 && lh >= 600.0 { + let mut prefs = crate::ui_prefs::load(); + if (prefs.window_width - lw).abs() > 0.5 + || (prefs.window_height - lh).abs() > 0.5 + { + prefs.window_width = lw; + prefs.window_height = lh; + crate::ui_prefs::save(&prefs); + } + } + EventResult::Propagate + } + WindowEvent::Moved(pos) => { + let mut prefs = crate::ui_prefs::load(); + if prefs.window_x != pos.x || prefs.window_y != pos.y { + prefs.window_x = pos.x; + prefs.window_y = pos.y; + crate::ui_prefs::save(&prefs); + } + EventResult::Propagate + } _ => EventResult::Propagate, } }); @@ -837,6 +947,24 @@ fn is_offline_blocked_view(window: &AppWindow) -> bool { } } +/// Map a top-level view to its persisted key for "Startup page = where you left +/// off" — ONLY safe, id-free views (the main nav destinations). Detail views +/// (album/artist/playlist/…) need a context id that may be stale on restart, so +/// they return None and the last safe view is kept instead. +fn safe_view_key(view: ContentView) -> Option<&'static str> { + match view { + // Home is also the Discover landing (its tabs render in the Home view), + // so this covers both. Detail views (album/artist/playlist/…) + the + // endpoint-scoped DiscoverBrowse "View all" pages are not restorable. + ContentView::Home => Some("home"), + ContentView::Favorites => Some("favorites"), + ContentView::LocalLibrary => Some("local-library"), + ContentView::Mixtapes => Some("mixtapes"), + ContentView::Collections => Some("collections"), + _ => None, + } +} + /// Flip the `is-favorite` flag on every visible row matching `track_id`, /// across all track-list surfaces (album, artist Popular, search, /// playlist, mix, favorites). Used for the optimistic favorite toggle so @@ -4634,6 +4762,49 @@ fn main() -> Result<(), Box> { &restored_prefs.large_spectrum_mode, )); } + // Main window geometry: restore the persisted LOGICAL size + (best-effort) + // position, each clamped to the current monitor so a smaller / disconnected + // display never opens an oversized or stranded window. 0 size = never saved + // → keep the `.slint` preferred size. The monitor query is best-effort + // (`with_winit_window` returns None before the surface exists → the WM's own + // clamping is the fallback, and the Resized handler re-saves the result). + if restored_prefs.window_width >= 940.0 && restored_prefs.window_height >= 600.0 { + let mut w = restored_prefs.window_width; + let mut h = restored_prefs.window_height; + window.window().with_winit_window(|win| { + if let Some(mon) = win.current_monitor() { + let scale = win.scale_factor().max(0.01); + let avail_w = (mon.size().width as f64 / scale) as f32; + let avail_h = (mon.size().height as f64 / scale) as f32; + if avail_w >= 940.0 { + w = w.min(avail_w); + } + if avail_h >= 600.0 { + h = h.min(avail_h); + } + } + }); + window.window().set_size(slint::LogicalSize::new(w, h)); + } + if restored_prefs.window_x != i32::MIN && restored_prefs.window_y != i32::MIN { + let mut px = restored_prefs.window_x; + let mut py = restored_prefs.window_y; + window.window().with_winit_window(|win| { + if let Some(mon) = win.current_monitor() { + let m = mon.size(); + let mp = mon.position(); + // Keep the top-left inside the monitor rect, leaving ~100px so a + // sliver stays grabbable even if the saved spot is near an edge. + let max_x = (mp.x + m.width as i32 - 100).max(mp.x); + let max_y = (mp.y + m.height as i32 - 100).max(mp.y); + px = px.clamp(mp.x, max_x); + py = py.clamp(mp.y, max_y); + } + }); + window + .window() + .set_position(slint::PhysicalPosition::new(px, py)); + } // NOTE: the FFT tap is primed AFTER visualizer::install() (further below) — not // here — because install() registers the `on_set_enabled` handler this call // depends on. @@ -4666,6 +4837,9 @@ fn main() -> Result<(), Box> { window.global::().set_miniplayer_view_index( crate::ui_prefs::mini_default_view_index(&crate::ui_prefs::load().mini_default_view), ); + window.global::().set_startup_page_index( + crate::ui_prefs::startup_page_index(&crate::ui_prefs::load().startup_page), + ); // Theme: seed the dropdown list from the Rust registry, then restore the // persisted theme (slug is the source of truth; the dropdown index is @@ -6711,6 +6885,12 @@ fn main() -> Result<(), Box> { crate::ui_prefs::mini_default_view_for_index(index).to_string(); crate::ui_prefs::save(&prefs); } + "startup-page" => { + // 0 = Home, 1 = Where you left off (restore last_view). + let mut prefs = crate::ui_prefs::load(); + prefs.startup_page = crate::ui_prefs::startup_page_for_index(index).to_string(); + crate::ui_prefs::save(&prefs); + } "theme" => { // Slug is the source of truth: map the dropdown index -> stable // id, persist the slug, then hot-switch the live palette. @@ -8778,6 +8958,18 @@ fn main() -> Result<(), Box> { prefs.volume = fraction.clamp(0.0, 1.0); crate::ui_prefs::save(&prefs); }); + // Remember the last SAFE top-level view for "where you left off". + let weak = window.as_weak(); + shell.on_persist_view(move || { + let Some(w) = weak.upgrade() else { return }; + if let Some(key) = safe_view_key(w.global::().get_view()) { + let mut prefs = crate::ui_prefs::load(); + if prefs.last_view != key { + prefs.last_view = key.to_string(); + crate::ui_prefs::save(&prefs); + } + } + }); } { @@ -15577,9 +15769,14 @@ fn main() -> Result<(), Box> { // enabled and the tray is live; otherwise quit. if tray_settings::get().close_to_tray && tray::handle().is_some() { log::info!("[qbz-slint] close-to-tray (titlebar): hiding to tray"); + // Flush the session even when only hiding — the process may be + // killed from the tray / shell without a real quit afterwards. + session_persist::save_on_exit(); tray::hide_window(&weak); } else { log::info!("[qbz-slint] closing"); + // Flush the final session snapshot before quitting. + session_persist::save_on_exit(); let _ = slint::quit_event_loop(); } } @@ -15597,6 +15794,9 @@ fn main() -> Result<(), Box> { // Slint performs the hide (destroys the surface) for HideWindow; // we only sync the shown flag so the next tray toggle shows it. log::info!("[qbz-slint] close-to-tray (WM close): hiding to tray"); + // Flush the session even when only hiding — the process may be + // killed from the tray / shell without a real quit afterwards. + session_persist::save_on_exit(); tray::set_window_shown(false); // macOS: drop the Dock icon if the user opted in (no-op elsewhere). if settings.mac_hide_dock { @@ -15605,6 +15805,8 @@ fn main() -> Result<(), Box> { slint::CloseRequestResponse::HideWindow } else { log::info!("[qbz-slint] WM close requested: quitting"); + // Flush the final session snapshot before quitting. + session_persist::save_on_exit(); // Best-effort: stop the renderer + media server so a cast device // doesn't keep playing after the app quits (Tauri parity, #32). if let Some(cast) = cast_service::service() { diff --git a/crates/qbz-slint/src/playback.rs b/crates/qbz-slint/src/playback.rs index 5d9443dfd..f38914126 100644 --- a/crates/qbz-slint/src/playback.rs +++ b/crates/qbz-slint/src/playback.rs @@ -91,6 +91,9 @@ pub async fn after_track_change( // gapless (a cached track plays via `play_data`, which the audio // engine's gapless engine supports; a streamed track does not). kick_prefetch(runtime).await; + // Persist the session (queue + current track + position) so a restart can + // restore it. No-op unless `persist_session` is on. + crate::session_persist::capture_and_save(runtime).await; } /// How many upcoming queue tracks to prefetch into the player cache. @@ -503,9 +506,18 @@ async fn play_audible(runtime: &Runtime, weak: &slint::Weak, track_id // login. The sink drives the padlock while a CMAF bundle decrypts. let offline = crate::offline::get().await; let sink = crate::offline_cache::row_sink(weak.clone()); + // Session resume: if this is the track restored at launch, start it at the + // saved position (consumed once); any other track starts from 0. + let start_position_secs = crate::session_persist::take_resume_for(track_id); if let Err(e) = runtime .core() - .play_track_resolved(track_id, PLAYBACK_QUALITY, offline.as_deref(), Some(&sink)) + .play_track_resolved( + track_id, + PLAYBACK_QUALITY, + offline.as_deref(), + Some(&sink), + start_position_secs, + ) .await { log::error!("[qbz-slint] playback: play_track {track_id} failed: {e}"); @@ -1270,6 +1282,24 @@ fn fmt_remaining(position: u64, duration: u64) -> String { format!("-{}:{:02}", left / 60, left % 60) } +/// Seed the seek bar + timers on `NowPlayingState` to a fixed position (UI +/// thread). Used by the session restore so the bar shows the resume point +/// immediately — `refresh_now_playing_meta` resets these to 0, and the poll +/// loop only catches up once playback actually starts. +pub(crate) fn seed_seek_display(w: &AppWindow, position_secs: u64, duration_secs: u64) { + let np = w.global::(); + let progress = if duration_secs > 0 { + (position_secs as f32 / duration_secs as f32).clamp(0.0, 1.0) + } else { + 0.0 + }; + np.set_duration_secs(duration_secs as i32); + np.set_position_secs(position_secs as i32); + np.set_progress(progress); + np.set_elapsed(fmt_elapsed(position_secs).into()); + np.set_remaining(fmt_remaining(position_secs, duration_secs).into()); +} + /// Push the now-playing values for the current queue track onto /// `NowPlayingState`. Called when a new track starts so the song card /// updates immediately (the poll loop only refreshes position/progress). @@ -3184,6 +3214,9 @@ pub fn toggle_play_pause( if let Err(e) = runtime.core().pause() { log::error!("[qbz-slint] playback: pause failed: {e}"); } + // Persist the paused position so a restart resumes near where the + // user stopped (no-op unless `persist_session` is on). + crate::session_persist::capture_and_save(&runtime).await; return; } // Not playing: resume an existing stream, or cold-start the current @@ -3405,6 +3438,8 @@ pub fn start_poll_loop( let mut last_track_id: u64 = 0; let mut was_playing = false; let mut seen_position: u64 = 0; + // Throttle for the periodic session-position save (every ~11 ticks ≈ 5s). + let mut save_pos_tick: u64 = 0; // Track id we have already fired a gapless prefetch for, so the // 450ms ticker does not re-request it every tick. let mut gapless_requested_for: u64 = 0; @@ -3561,6 +3596,13 @@ pub fn start_poll_loop( let duration = event.duration; let is_playing = event.is_playing; let volume = event.volume; + // Persist the live position periodically (~5s) while playing so a + // crash keeps a near-current resume point (no-op unless + // `persist_session` is on; `position` is in seconds). + save_pos_tick = save_pos_tick.wrapping_add(1); + if is_playing && track_id != 0 && save_pos_tick % 11 == 0 { + crate::session_persist::save_position(position); + } // Streaming buffer fill, for the seek-bar cache overlay. let cache = event.buffer_progress.unwrap_or(0.0); // Seek lock: while streaming (`buffer_progress` is Some), the user diff --git a/crates/qbz-slint/src/session_persist.rs b/crates/qbz-slint/src/session_persist.rs new file mode 100644 index 000000000..d01ef57a5 --- /dev/null +++ b/crates/qbz-slint/src/session_persist.rs @@ -0,0 +1,306 @@ +//! Session persistence (queue + playback state) — the Slint wiring for the +//! `persist_session` / `resume_playback_position` playback preferences. +//! +//! The on-disk store is the frontend-agnostic [`SessionStore`] in +//! `qbz-app` (a per-user `session.db`, already built + tested). This module is +//! the thin frontend glue: it owns a process-global store handle (bound at +//! session activation), captures the live queue + playback state into the +//! persisted snapshot at meaningful edges, and restores it at startup. +//! +//! Gating: `persist_session` (restore the queue/session) and +//! `resume_playback_position` (also restore the exact position) are per-user +//! playback preferences. Both are cached here so the hot save path never reopens +//! the prefs DB; [`set_gates`] refreshes the cache when the toggles change, and +//! [`init_for_user`] seeds them synchronously when the store opens (no race with +//! the async settings snapshot load). +//! +//! Phase A (this module) restores the queue + current track PAUSED — it touches +//! NO protected-audio code beyond threading an existing `start_position_secs`. +//! The saved position rides along via [`take_resume_for`] and is consumed on the +//! first play of the restored track, reusing the player's session-resume offset. + +use std::path::Path; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; + +use qbz_app::session_store::{ + PersistedPlaybackSession, PersistedQueueTrack, PersistedSessionSnapshot, + PersistedShellViewState, SessionStore, +}; +use qbz_app::settings::playback::PlaybackPreferencesStore; +use qbz_app::shell::AppRuntime; +use qbz_models::{QueueTrack, RepeatMode}; + +use crate::adapter::SlintAdapter; + +type Runtime = Arc>; + +/// Per-user session store, bound at activation (None before login / on failure). +static STORE: Mutex> = Mutex::new(None); +/// Cached `persist_session` gate — captured/restored only when true. +static PERSIST_SESSION: AtomicBool = AtomicBool::new(false); +/// Cached `resume_playback_position` gate — primes [`PENDING_RESUME`] at restore. +static RESUME_POSITION: AtomicBool = AtomicBool::new(false); +/// Position (secs) to resume the restored current track at on the first play. +/// 0 = none. Written at restore (when resume is on); consumed on first play. +static PENDING_RESUME: AtomicU64 = AtomicU64::new(0); +/// Track id the pending resume position applies to, so ONLY the restored current +/// track resumes — playing any other track first starts from 0. 0 = none. +static PENDING_RESUME_TRACK: AtomicU64 = AtomicU64::new(0); +/// Runtime + tokio handle captured at shell entry, so the synchronous window +/// close handlers can flush a final full snapshot before the loop quits. +static EXIT_CTX: OnceLock<(Runtime, tokio::runtime::Handle)> = OnceLock::new(); + +/// Bind the runtime + tokio handle for [`save_on_exit`]. Called once at shell +/// entry (idempotent — later calls are ignored by `OnceLock`). +pub fn bind_exit_ctx(runtime: Runtime, handle: tokio::runtime::Handle) { + let _ = EXIT_CTX.set((runtime, handle)); +} + +/// Flush a final full snapshot synchronously (the window close handlers run on +/// the UI thread, off the tokio runtime, so we `block_on`). No-op until the exit +/// context is bound or unless `persist_session` is on. +pub fn save_on_exit() { + if !persist_enabled() { + return; + } + if let Some((runtime, handle)) = EXIT_CTX.get() { + handle.block_on(capture_and_save(runtime)); + } +} + +/// Open the per-user session store and seed the gate flags synchronously from +/// the playback preferences. Called at session activation alongside the other +/// `init_for_user` stores. Failures degrade to "no persistence" (logged). +pub fn init_for_user(base_dir: &Path) { + let opened = match SessionStore::new_at(base_dir) { + Ok(store) => { + *STORE.lock().unwrap() = Some(store); + true + } + Err(e) => { + log::warn!("[qbz-slint] session_persist: open failed: {e}"); + *STORE.lock().unwrap() = None; + false + } + }; + // Seed the gates from the per-user playback prefs so capture/restore work + // before the async settings snapshot has had a chance to call set_gates. + match PlaybackPreferencesStore::new_at(base_dir).and_then(|s| s.get_preferences()) { + Ok(prefs) => set_gates(prefs.persist_session, prefs.resume_playback_position), + Err(e) => { + log::warn!("[qbz-slint] session_persist: prefs read failed, gates off: {e}"); + set_gates(false, false); + } + } + log::info!( + "[qbz-slint] session_persist: init at {} (store_open={opened}, persist={}, resume={})", + base_dir.display(), + PERSIST_SESSION.load(Ordering::Relaxed), + RESUME_POSITION.load(Ordering::Relaxed) + ); +} + +/// Refresh the cached gate flags (called by the Settings toggle handlers and the +/// settings snapshot load so the cache tracks live preference changes). +pub fn set_gates(persist_session: bool, resume_position: bool) { + PERSIST_SESSION.store(persist_session, Ordering::Relaxed); + RESUME_POSITION.store(resume_position, Ordering::Relaxed); +} + +/// Whether session persistence is currently enabled. +pub fn persist_enabled() -> bool { + PERSIST_SESSION.load(Ordering::Relaxed) +} + +/// Take + clear the pending resume position IF it applies to `track_id` (the +/// restored current track). Returns the saved position once, then 0 forever — +/// and 0 for any other track, so playing something else first never resumes. +pub fn take_resume_for(track_id: u64) -> u64 { + if track_id != 0 && PENDING_RESUME_TRACK.swap(0, Ordering::Relaxed) == track_id { + PENDING_RESUME.swap(0, Ordering::Relaxed) + } else { + 0 + } +} + +/// Peek the pending resume position WITHOUT consuming it (so the seek bar can be +/// seeded at restore while the actual resume still fires on first play). 0 = none. +pub fn pending_resume_position() -> u64 { + if PENDING_RESUME_TRACK.load(Ordering::Relaxed) != 0 { + PENDING_RESUME.load(Ordering::Relaxed) + } else { + 0 + } +} + +fn repeat_to_str(mode: RepeatMode) -> &'static str { + match mode { + RepeatMode::Off => "off", + RepeatMode::All => "all", + RepeatMode::One => "one", + } +} + +fn repeat_from_str(s: &str) -> RepeatMode { + match s { + "all" => RepeatMode::All, + "one" => RepeatMode::One, + _ => RepeatMode::Off, + } +} + +fn to_persisted(t: &QueueTrack) -> PersistedQueueTrack { + PersistedQueueTrack { + id: t.id, + title: t.title.clone(), + artist: t.artist.clone(), + album: t.album.clone(), + duration_secs: t.duration_secs, + artwork_url: t.artwork_url.clone(), + hires: t.hires, + bit_depth: t.bit_depth, + sample_rate: t.sample_rate, + is_local: t.is_local, + album_id: t.album_id.clone(), + artist_id: t.artist_id, + streamable: t.streamable, + source: t.source.clone(), + parental_warning: t.parental_warning, + source_item_id_hint: t.source_item_id_hint.clone(), + } +} + +fn from_persisted(t: PersistedQueueTrack) -> QueueTrack { + QueueTrack { + id: t.id, + title: t.title, + // The persisted schema predates `version` (Tauri parity): the edition + // subtitle is not stored, so a restored track simply has no version. + version: None, + artist: t.artist, + album: t.album, + duration_secs: t.duration_secs, + artwork_url: t.artwork_url, + hires: t.hires, + bit_depth: t.bit_depth, + sample_rate: t.sample_rate, + is_local: t.is_local, + album_id: t.album_id, + artist_id: t.artist_id, + streamable: t.streamable, + source: t.source, + parental_warning: t.parental_warning, + source_item_id_hint: t.source_item_id_hint, + } +} + +/// Capture the live queue + playback state and persist it. No-op unless +/// `persist_session` is on and the store is open. Async (reads the queue lock). +pub async fn capture_and_save(runtime: &Runtime) { + if !persist_enabled() { + return; + } + let (tracks, current_index) = runtime.core().get_all_queue_tracks().await; + let full = runtime.core().get_queue_state_full().await; + let pb = runtime.core().get_playback_state(); + let snapshot = PersistedSessionSnapshot { + playback: PersistedPlaybackSession { + queue_tracks: tracks.iter().map(to_persisted).collect(), + current_index, + current_position_secs: pb.position, + volume: pb.volume, + shuffle_enabled: full.shuffle, + repeat_mode: repeat_to_str(full.repeat).to_string(), + was_playing: pb.is_playing, + saved_at: 0, // set inside save_session + }, + // Shell-view restoration is handled separately (ui_prefs startup_page); + // keep the Tauri view columns at their defaults so the schema round-trips. + shell_view: PersistedShellViewState::default(), + }; + let track_count = snapshot.playback.queue_tracks.len(); + if let Some(store) = STORE.lock().unwrap().as_ref() { + match store.save_session(&snapshot) { + Ok(()) => log::info!( + "[qbz-slint] session_persist: saved {track_count} queue tracks (pos {}s, playing {})", + snapshot.playback.current_position_secs, + snapshot.playback.was_playing + ), + Err(e) => log::warn!("[qbz-slint] session_persist: save failed: {e}"), + } + } else { + log::warn!("[qbz-slint] session_persist: capture skipped (store not open)"); + } +} + +/// Quick position-only save (a single cheap UPDATE) — for the poll loop's +/// throttled tick and the pause edge, so a crash keeps a near-current position. +pub fn save_position(position_secs: u64) { + if !persist_enabled() { + return; + } + if let Some(store) = STORE.lock().unwrap().as_ref() { + let _ = store.save_position(position_secs); + } +} + +/// Restore the persisted queue at startup. Returns true if a non-empty queue was +/// restored (so the caller refreshes the now-playing bar). Restores PAUSED; when +/// `resume_playback_position` is on, primes [`PENDING_RESUME`] for Phase B. +pub async fn restore(runtime: &Runtime) -> bool { + if !persist_enabled() { + log::info!("[qbz-slint] session_persist: restore skipped (persist_session off)"); + return false; + } + let snapshot = { + let guard = STORE.lock().unwrap(); + let Some(store) = guard.as_ref() else { + log::warn!("[qbz-slint] session_persist: restore skipped (store not open)"); + return false; + }; + match store.load_session() { + Ok(s) => s, + Err(e) => { + log::warn!("[qbz-slint] session_persist: load failed: {e}"); + return false; + } + } + }; + let pb_sess = snapshot.playback; + if pb_sess.queue_tracks.is_empty() { + log::info!("[qbz-slint] session_persist: nothing to restore (saved queue is empty)"); + return false; + } + let position = pb_sess.current_position_secs; + let count = pb_sess.queue_tracks.len(); + let index = pb_sess.current_index; + let tracks: Vec = pb_sess + .queue_tracks + .into_iter() + .map(from_persisted) + .collect(); + // The current track's id, so the resume position is applied ONLY when this + // exact track is the first one played after the restore. + let current_track_id = index.and_then(|i| tracks.get(i)).map(|t| t.id).unwrap_or(0); + runtime + .core() + .set_queue_with_order(tracks, index, pb_sess.shuffle_enabled, None) + .await; + runtime + .core() + .set_repeat_mode(repeat_from_str(&pb_sess.repeat_mode)) + .await; + // The queue session carries the authoritative last volume; apply it to the + // player (the slider also seeds from ui_prefs, but this keeps them in step). + let _ = runtime.core().set_volume(pb_sess.volume); + if RESUME_POSITION.load(Ordering::Relaxed) && position > 0 && current_track_id != 0 { + PENDING_RESUME.store(position, Ordering::Relaxed); + PENDING_RESUME_TRACK.store(current_track_id, Ordering::Relaxed); + } + log::info!( + "[qbz-slint] session_persist: restored {count} queue tracks (index {index:?}), paused; \ + resume position {position}s (consumed on first play when enabled)" + ); + true +} diff --git a/crates/qbz-slint/src/settings.rs b/crates/qbz-slint/src/settings.rs index 0b274f98b..f893e7e92 100644 --- a/crates/qbz-slint/src/settings.rs +++ b/crates/qbz-slint/src/settings.rs @@ -441,6 +441,9 @@ fn build_snapshot( prefs: qbz_app::settings::playback::PlaybackPreferences, streaming_quality_key: &str, ) -> SettingsSnapshot { + // Keep the session-persistence gates in step with the live playback prefs + // whenever a settings snapshot is built (startup load + post-reset rebuild). + crate::session_persist::set_gates(prefs.persist_session, prefs.resume_playback_position); let backend_types = BackendManager::available_backends(); let current_backend = audio.backend_type.unwrap_or_default(); let backend_index = backend_types @@ -861,12 +864,21 @@ pub async fn handle_bool( with_playback(&ctx.playback, |s| s.set_show_context_icon(value)).map(|_| Apply::None) } "persist-session" => { - with_playback(&ctx.playback, |s| s.set_persist_session(value)).map(|_| Apply::None) + let r = with_playback(&ctx.playback, |s| s.set_persist_session(value)) + .map(|_| Apply::None); + if let Ok(p) = with_playback(&ctx.playback, |s| s.get_preferences()) { + crate::session_persist::set_gates(p.persist_session, p.resume_playback_position); + } + r + } + "resume-position" => { + let r = with_playback(&ctx.playback, |s| s.set_resume_playback_position(value)) + .map(|_| Apply::None); + if let Ok(p) = with_playback(&ctx.playback, |s| s.get_preferences()) { + crate::session_persist::set_gates(p.persist_session, p.resume_playback_position); + } + r } - "resume-position" => with_playback(&ctx.playback, |s| { - s.set_resume_playback_position(value) - }) - .map(|_| Apply::None), other => { log::warn!("[qbz-slint] unknown settings bool key: {other}"); return; diff --git a/crates/qbz-slint/src/tray/mod.rs b/crates/qbz-slint/src/tray/mod.rs index 97f8e4f34..7c6226916 100644 --- a/crates/qbz-slint/src/tray/mod.rs +++ b/crates/qbz-slint/src/tray/mod.rs @@ -241,6 +241,8 @@ pub(crate) fn set_mac_dock_hidden(hidden: bool) { pub(crate) fn quit() { log::info!("[tray] quit requested"); let _ = slint::invoke_from_event_loop(|| { + // Flush the session before the loop tears down. + crate::session_persist::save_on_exit(); let _ = slint::quit_event_loop(); }); } diff --git a/crates/qbz-slint/src/ui_prefs.rs b/crates/qbz-slint/src/ui_prefs.rs index 5ddb12d8f..81e769682 100644 --- a/crates/qbz-slint/src/ui_prefs.rs +++ b/crates/qbz-slint/src/ui_prefs.rs @@ -94,6 +94,32 @@ fn default_volume() -> f32 { 1.0 } +fn default_startup_page() -> String { + "home".to_string() +} + +fn default_last_view() -> String { + "home".to_string() +} + +/// Startup-page select index (0 = Home, 1 = Where you left off) -> key. +pub fn startup_page_for_index(index: i32) -> &'static str { + if index == 1 { + "remember" + } else { + "home" + } +} + +/// Inverse: select index for a persisted startup-page key. +pub fn startup_page_index(key: &str) -> i32 { + if key == "remember" { + 1 + } else { + 0 + } +} + /// Miniplayer default-view select index -> persisted key (mirrors the /// miniplayer's own reader in `miniplayer.rs`). 0 = "remember". pub fn mini_default_view_for_index(index: i32) -> &'static str { @@ -190,6 +216,15 @@ pub struct UiPrefs { /// Player volume, 0.0..=1.0. Restored at startup. Default full. #[serde(default = "default_volume")] pub volume: f32, + /// Startup page: "home" (always Home) or "remember" (restore last_view). + /// Maps to Settings > Appearance > Startup page. + #[serde(default = "default_startup_page")] + pub startup_page: String, + /// Last visited SAFE top-level view (no required id), for "remember". One of + /// "home" | "discover" | "favorites" | "local-library" | "mixtapes" | + /// "collections". Detail views (album/artist/playlist/…) are never stored. + #[serde(default = "default_last_view")] + pub last_view: String, /// Immersive in-view search action: `"disabled"` | `"replace"` | `"next"` | /// `"queue"`. Doubles as the enable switch (`"disabled"` keeps the field /// inert). See [`DEFAULT_IMMERSIVE_SEARCH_ACTION`]. @@ -233,6 +268,26 @@ pub struct UiPrefs { /// Default-view key: "remember" | micro | compact | artwork | queue | lyrics. #[serde(default = "default_mini_default_view")] pub mini_default_view: String, + + // ---- Main window geometry ------------------------------------------ + /// Last main-window LOGICAL size. 0 = never saved → use the `.slint` + /// preferred size. Restored at startup, clamped to the monitor's size so a + /// smaller display never opens an oversized window. + #[serde(default)] + pub window_width: f32, + #[serde(default)] + pub window_height: f32, + /// Last main-window PHYSICAL outer position. `i32::MIN` = never saved → let + /// the window manager place it. Nice-to-have; clamped on-screen at restore. + #[serde(default = "default_window_pos")] + pub window_x: i32, + #[serde(default = "default_window_pos")] + pub window_y: i32, +} + +/// Sentinel for "no saved window position" (let the WM place the window). +fn default_window_pos() -> i32 { + i32::MIN } fn default_mini_surface() -> i32 { @@ -301,6 +356,8 @@ impl Default for UiPrefs { sidebar_state: 0, nav_in_sidebar: default_nav_in_sidebar(), volume: default_volume(), + startup_page: default_startup_page(), + last_view: default_last_view(), immersive_search_action: default_immersive_search_action(), immersive_default_view: default_immersive_default_view(), immersive_last_view_mode: 0, @@ -312,6 +369,10 @@ impl Default for UiPrefs { mini_height: default_mini_height(), mini_background_blur: false, mini_default_view: default_mini_default_view(), + window_width: 0.0, + window_height: 0.0, + window_x: default_window_pos(), + window_y: default_window_pos(), } } } diff --git a/crates/qbz-slint/ui/settings/AppearanceSettings.slint b/crates/qbz-slint/ui/settings/AppearanceSettings.slint index 893078338..7242133a6 100644 --- a/crates/qbz-slint/ui/settings/AppearanceSettings.slint +++ b/crates/qbz-slint/ui/settings/AppearanceSettings.slint @@ -594,7 +594,6 @@ export component AppearanceSettings inherits VerticalLayout { } } SettingRow { - unsupported: true; label: @tr("Startup page"); description: @tr("Choose which page to show when the app starts"); QbzSelect { diff --git a/crates/qbz-slint/ui/shell/AppShell.slint b/crates/qbz-slint/ui/shell/AppShell.slint index c803b4693..c31ac852a 100644 --- a/crates/qbz-slint/ui/shell/AppShell.slint +++ b/crates/qbz-slint/ui/shell/AppShell.slint @@ -129,6 +129,9 @@ export component AppShell inherits Rectangle { property tracked-view: NavState.view; changed tracked-view => { SearchActions.cortinilla-dismiss(); + // Remember the last top-level view for "Startup page = where you left + // off" (Rust filters to safe, id-free views before persisting). + ShellState.persist-view(); } // FFT visualizer tap — single source of truth. The tap (frontend-agnostic diff --git a/crates/qbz-slint/ui/state.slint b/crates/qbz-slint/ui/state.slint index 04b059aa6..7f39a8746 100644 --- a/crates/qbz-slint/ui/state.slint +++ b/crates/qbz-slint/ui/state.slint @@ -3406,6 +3406,9 @@ export global ShellState { // Persist the sidebar state / nav placement (wired to ui_prefs in Rust). callback persist-sidebar-state(int); callback persist-nav(bool); + // Persist the current top-level view for "Startup page = where you left off" + // (Rust reads NavState.view and stores only SAFE, id-free views). + callback persist-view(); public function cycle-sidebar() { root.sidebar-state = Math.mod(root.sidebar-state + 1, 3); if (root.sidebar-state != 0 && root.npb-mode == 3) {