From b1ac402cf751673ac629890e9f17554c43ebe093 Mon Sep 17 00:00:00 2001 From: vicrodh <103399283+vicrodh@users.noreply.github.com> Date: Sun, 21 Jun 2026 11:19:00 -0600 Subject: [PATCH] feat(slint): extend cortinilla with Local Library + Plex + per-source artwork Add local albums/artists/tracks sections to the main header cortinilla (below the Qobuz results) and local albums to the immersive cortinilla, derived by grouping the on-device track rows. Merge the Plex cache into the local search so Plex-only content surfaces (db.search is local_tracks-only). Route each cover by source via spawn_search_loads (Qobuz http / Plex /library PlexThumb / local file). Widen the local section caps when offline or signed out. Rename the section lore from "on this device" to "on Local Library". Also clear the search input after a cortinilla element is activated (row click / View more / Enter) so lingering text can no longer re-invoke the dropdown when focus returns to the field; replicated in the immersive search field via a dedicated raw-text property. cc --- crates/qbz-slint/src/artwork.rs | 56 +++ crates/qbz-slint/src/main.rs | 229 ++++++++++-- crates/qbz-slint/src/search.rs | 347 +++++++++++++++--- .../ui/immersive/ImmersiveView.slint | 5 + crates/qbz-slint/ui/shell/HeaderBar.slint | 4 + crates/qbz-slint/ui/state.slint | 14 + 6 files changed, 563 insertions(+), 92 deletions(-) diff --git a/crates/qbz-slint/src/artwork.rs b/crates/qbz-slint/src/artwork.rs index 0cd8072a4..41044f347 100644 --- a/crates/qbz-slint/src/artwork.rs +++ b/crates/qbz-slint/src/artwork.rs @@ -417,6 +417,62 @@ pub fn spawn_local_or_plex_loads( } } +/// Artwork dispatch for the SEARCH cortinilla, whose rows mix three sources in a +/// single payload: Qobuz catalog covers (http(s) URLs), Local Library covers +/// (absolute filesystem paths) and Plex covers (`/library/…` / `/photo/…` thumb +/// paths). Each job is routed by its url's shape — http → the HTTP cache path +/// (gated offline, like Qobuz CDN covers); a Plex thumb → `PlexThumb` (tokenized +/// LAN fetch, NOT gated by induced offline); anything else → `LocalFile` +/// (`fs::read`). Plex creds empty / absent → Plex thumbs fall back to a local +/// read (which fails soft to the placeholder). +pub fn spawn_search_loads( + jobs: Vec, + plex_base_url: String, + plex_token: String, + window: slint::Weak, + cache: ImageCache, +) { + let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT)); + let plex_base_url = Arc::new(plex_base_url); + let plex_token = Arc::new(plex_token); + for job in jobs { + let semaphore = semaphore.clone(); + let window = window.clone(); + let cache = cache.clone(); + let plex_base_url = plex_base_url.clone(); + let plex_token = plex_token.clone(); + tokio::spawn(async move { + let _permit = semaphore.acquire().await.ok()?; + let decode_size = job.target.decode_size(); + let is_http = + job.url.starts_with("http://") || job.url.starts_with("https://"); + let is_plex_path = + job.url.starts_with("/library/") || job.url.starts_with("/photo/"); + let (pixels, width, height) = if is_http { + // Qobuz CDN cover (internet) — offline-gated inside fetch_and_decode. + fetch_and_decode(&job.url, &cache, decode_size).await? + } else if is_plex_path && !plex_base_url.is_empty() && !plex_token.is_empty() { + let art = ArtworkRef::PlexThumb { + base_url: (*plex_base_url).clone(), + token: (*plex_token).clone(), + path: job.url.clone(), + size: Some(decode_size), + }; + fetch_and_decode_ref(&art, &cache, decode_size).await? + } else { + let art = ArtworkRef::LocalFile(job.url.clone()); + fetch_and_decode_ref(&art, &cache, decode_size).await? + }; + let target = job.target; + let url = job.url; + let _ = window.upgrade_in_event_loop(move |w| { + apply_artwork(&w, target, &url, &pixels, width, height); + }); + Some(()) + }); + } +} + /// Resolve a remote URL to raw bytes via the shared disk cache: a hit reads /// from disk, a miss downloads and stores. HTTP(S) only. /// diff --git a/crates/qbz-slint/src/main.rs b/crates/qbz-slint/src/main.rs index 861bf93ae..043279042 100644 --- a/crates/qbz-slint/src/main.rs +++ b/crates/qbz-slint/src/main.rs @@ -5052,7 +5052,7 @@ fn main() -> Result<(), Box> { // The results-page debounce below is untouched; the cortinilla is a // separate, additive surface gated on the kill switch. if crate::search_service::is_enabled() { - if let Some(w) = weak.upgrade() { + let expand_local = if let Some(w) = weak.upgrade() { let st = w.global::(); // Always reset the keyboard selection + scroll on (re)open or // refine — never leave a stale "active row" from a prior @@ -5062,7 +5062,14 @@ fn main() -> Result<(), Box> { st.set_cortinilla_open(true); st.set_cortinilla_query(q.clone().into()); st.set_cortinilla_loading(true); - } + // Offline OR an unauthenticated (offline) session → the Qobuz + // half is empty, so the dropdown is local-only; widen the + // on-device section caps. + let off = w.global::(); + off.get_offline() || off.get_offline_session() + } else { + false + }; let cort_version = search::next_cortinilla_version(); // No cached instant-paint. The cached -> fresh swap (plus the @@ -5089,7 +5096,7 @@ fn main() -> Result<(), Box> { let image_cache = image_cache.clone(); let q = q.clone(); handle.spawn(async move { - match search::load_cortinilla(&runtime, &q).await { + match search::load_cortinilla(&runtime, &q, expand_local).await { Ok((data, local_rows)) => { let jobs = search::cortinilla_artwork_jobs(&data); let _ = weak.clone().upgrade_in_event_loop(move |w| { @@ -5102,7 +5109,16 @@ fn main() -> Result<(), Box> { search::apply_cortinilla(&w, data); } }); - artwork::spawn_loads(jobs, weak.clone(), image_cache); + // Mixed payload (Qobuz http / local fs / Plex + // /library/) — route each cover by scheme. + let plex = crate::plex_settings::get(); + artwork::spawn_search_loads( + jobs, + plex.base_url, + plex.token, + weak.clone(), + image_cache, + ); } Err(e) => { log::error!("[qbz-slint] cortinilla load failed: {e}"); @@ -5389,6 +5405,10 @@ fn main() -> Result<(), Box> { } let st = w.global::(); st.set_cortinilla_open(false); + // Activating the cortinilla's Enter affordance clears the input + // too (consistent with row-click / View-more), so it can't + // re-invoke the dropdown over the results page. + st.set_header_search_text("".into()); // Enter always lands on Search > All, never a per-type tab. st.set_tab(0); SEARCH_DEBOUNCE.with(|t| t.stop()); @@ -5421,14 +5441,56 @@ fn main() -> Result<(), Box> { if q.chars().count() < 2 { return; } - w.global::().set_cortinilla_open(false); + { + let st = w.global::(); + st.set_cortinilla_open(false); + // Clear the input so it can't re-invoke the dropdown later. + st.set_header_search_text("".into()); + } SEARCH_DEBOUNCE.with(|t| t.stop()); // On-device "View more": leave the Qobuz results page entirely - // and open the LocalLibrary Tracks tab pre-filtered to the live + // and open the matching LocalLibrary tab pre-filtered to the live // query (D1/D2: local results never live in the Qobuz results - // page). Set the tracks search, navigate to the Tracks tab, then - // reload so the filtered set renders. + // page). Albums / Artists / Tracks each route to their own tab, + // setting that tab's search filter then forcing a re-derive so the + // filtered set renders on both first-visit and re-entry. + if kind == "local-album" { + w.global::().set_albums_search(q.clone().into()); + nav::record(nav::NavEntry::LocalLibrary { + tab: local_library::LibTab::Albums.tab_id().to_string(), + }); + navigate_local_library( + runtime.clone(), + weak.clone(), + &handle, + image_cache.clone(), + local_library::LibTab::Albums, + ); + // Force a reload so the freshly-set search filter applies even + // when the Albums tab was already loaded (re-entry). + local_library::reload_albums(weak.clone(), handle.clone(), image_cache.clone()); + update_nav_flags(&w); + return; + } + if kind == "local-artist" { + w.global::().set_artists_search(q.clone().into()); + nav::record(nav::NavEntry::LocalLibrary { + tab: local_library::LibTab::Artists.tab_id().to_string(), + }); + navigate_local_library( + runtime.clone(), + weak.clone(), + &handle, + image_cache.clone(), + local_library::LibTab::Artists, + ); + // Re-derive in place so the filter applies on re-entry (the + // async first-load re-derives with the same filter on its own). + local_library::derive_artists(&w); + update_nav_flags(&w); + return; + } if kind == "local" { w.global::().set_tracks_search(q.clone().into()); nav::record(nav::NavEntry::LocalLibrary { @@ -5503,8 +5565,14 @@ fn main() -> Result<(), Box> { .get_cortinilla_query() .to_string(); - // Dismiss the dropdown before acting. - w.global::().set_cortinilla_open(false); + // Dismiss the dropdown before acting AND clear the header input — + // once the user activates a row, leftover text would otherwise + // re-invoke the cortinilla when focus bounces back to the field. + { + let st = w.global::(); + st.set_cortinilla_open(false); + st.set_header_search_text("".into()); + } // Feed Capa B: a clicked QOBUZ row is an interaction with the // search-surfaced entity. action = Play for tracks (they play on @@ -5522,25 +5590,55 @@ fn main() -> Result<(), Box> { } if row.source == "local" { - // On-device row: play through the LOCAL seam, not the Qobuz - // media-action. Resolve the clicked `LocalTrack` (+ its - // sibling on-device rows, so the queue continues down the - // list) from the per-query snapshot, then start at the - // clicked one. `row.id` is the library row id. - let tracks = LAST_CORTINILLA_LOCAL.with(|c| c.borrow().clone()); - let start = tracks - .iter() - .position(|t| t.id.to_string() == row.id) - .unwrap_or(0); - if !tracks.is_empty() { - playback::play_local_tracks( - runtime.clone(), - weak.clone(), - handle.clone(), - tracks, - start, - false, - ); + // On-device rows route by kind (the "links go to LocalLibrary" + // requirement): a local ALBUM opens the LocalAlbum view by its + // group key; a local ARTIST opens the LocalLibrary Artists tab + // by NAME (local artists have no id); a local TRACK plays + // through the LOCAL seam. + match row.kind.as_str() { + "album" => { + // `row.id` is the album_group_key (a local album key). + let key = row.id.clone(); + nav::record(nav::NavEntry::LocalAlbum(key.clone())); + navigate_local_album( + runtime.clone(), + weak.clone(), + &handle, + image_cache.clone(), + key, + ); + update_nav_flags(&w); + } + "artist" => { + // Local artists are keyed by NAME (`row.title`). + open_local_artist( + &runtime, + &weak, + &handle, + &image_cache, + row.title.clone(), + ); + } + _ => { + // Track: play this on-device row + its siblings (so the + // queue continues down the list), starting at the + // clicked one. `row.id` is the library row id. + let tracks = LAST_CORTINILLA_LOCAL.with(|c| c.borrow().clone()); + let start = tracks + .iter() + .position(|t| t.id.to_string() == row.id) + .unwrap_or(0); + if !tracks.is_empty() { + playback::play_local_tracks( + runtime.clone(), + weak.clone(), + handle.clone(), + tracks, + start, + false, + ); + } + } } return; } @@ -5724,6 +5822,12 @@ fn main() -> Result<(), Box> { im.set_search_selected_index(-1); im.set_search_scroll_y(0.0); } + // Offline OR an unauthenticated session → widen the on-device + // album cap (immersive shows local albums only). + let expand_local = { + let off = w.global::(); + off.get_offline() || off.get_offline_session() + }; let version = search::next_immersive_search_version(); let runtime = runtime.clone(); @@ -5741,7 +5845,7 @@ fn main() -> Result<(), Box> { let image_cache = image_cache.clone(); let q = q.clone(); handle.spawn(async move { - match search::load_immersive_search(&runtime, &q).await { + match search::load_immersive_search(&runtime, &q, expand_local).await { Ok(data) => { let jobs = search::immersive_cortinilla_artwork_jobs(&data); @@ -5753,7 +5857,16 @@ fn main() -> Result<(), Box> { search::apply_immersive_search(&w, &data); } }); - artwork::spawn_loads(jobs, weak.clone(), image_cache); + // Mixed payload (Qobuz http / Plex /library/) — + // route each cover by scheme. + let plex = crate::plex_settings::get(); + artwork::spawn_search_loads( + jobs, + plex.base_url, + plex.token, + weak.clone(), + image_cache, + ); } Err(e) => { log::error!( @@ -5891,9 +6004,15 @@ fn main() -> Result<(), Box> { }); let Some(row) = row else { return }; - // Close the dropdown (STAY in immersive — no navigation). The - // query is kept so the field still reflects what was searched. - w.global::().set_search_open(false); + // Close the dropdown (STAY in immersive — no navigation) AND clear + // the field, mirroring the main cortinilla: once a result is + // activated, a lingering query would re-invoke the dropdown when + // focus returns to the field. + { + let im = w.global::(); + im.set_search_open(false); + im.set_search_input_text("".into()); + } // Read the configured action fresh (it can change in Settings // while immersive is open). "disabled" is also gated upstream in @@ -5903,6 +6022,48 @@ fn main() -> Result<(), Box> { if action == "disabled" { return; } + + // Local album rows queue the ON-DEVICE album per the action + // (immersive shows local albums only). Branch BEFORE the Qobuz + // (kind, action) match — `play_album`/`enqueue_album*` expect a + // numeric Qobuz id, but a local album's id is a group key. + if row.source == "local" { + let group_key = row.id.clone(); + match action.as_str() { + "replace" => playback::play_local_album( + runtime.clone(), + weak.clone(), + handle.clone(), + group_key, + None, + ), + next_or_queue @ ("next" | "queue") => { + // Fetch the album's local tracks off-thread (covers + // filled like play_local_album), then enqueue: "next" + // inserts after the current track, "queue" appends. + let next = next_or_queue == "next"; + let runtime = runtime.clone(); + let handle = handle.clone(); + handle.clone().spawn(async move { + let tracks = tokio::task::spawn_blocking(move || { + let mut t = crate::local_library::fetch_album_tracks_blocking( + &group_key, + ); + playback::fill_missing_covers(&mut t); + t + }) + .await + .unwrap_or_default(); + if !tracks.is_empty() { + playback::enqueue_local_tracks(runtime, handle, tracks, next); + } + }); + } + _ => {} + } + return; + } + let id = row.id.clone(); match (row.kind.as_str(), action.as_str()) { // ---- Replace the queue and play (the play_* seams) ------- diff --git a/crates/qbz-slint/src/search.rs b/crates/qbz-slint/src/search.rs index 355302dee..137b45666 100644 --- a/crates/qbz-slint/src/search.rs +++ b/crates/qbz-slint/src/search.rs @@ -560,8 +560,8 @@ pub fn map_search_all_to_cortinilla( .or_else(|| albums.first().cloned()); // Assemble sections in display order (spec §6.2.3): Albums, Artists, - // Tracks, Playlists. The local "On this device" section is appended LAST, - // outside this function (see `append_local_section`). + // Tracks, Playlists. The local "on this device" sections are appended LAST, + // outside this function (see `append_local_sections`). let mut sections: Vec = Vec::new(); let mut push_section = |title: &str, kind: &str, rows: Vec, total: u32| { if !rows.is_empty() { @@ -684,8 +684,139 @@ pub fn map_search_all_to_immersive(query: &str, results: &SearchAllResults) -> C data } -/// How many on-disk rows the local cortinilla section shows before "View more". -const CORTINILLA_LOCAL_PER_SECTION: usize = 3; +/// Per-section caps for the LOCAL cortinilla sections. Two profiles: the NORMAL +/// (online + signed-in) profile keeps the on-device block compact since the +/// Qobuz catalog dominates the dropdown; the EXPANDED profile (offline OR not +/// signed in, so the cortinilla is local-only) turns it into a small on-device +/// browser with more rows per section. +#[derive(Debug, Clone, Copy)] +pub struct LocalCaps { + pub albums: usize, + pub artists: usize, + pub tracks: usize, +} + +impl LocalCaps { + /// Normal profile (Qobuz present): compact on-device block. + const NORMAL: LocalCaps = LocalCaps { + albums: 3, + artists: 2, + tracks: 3, + }; + /// Expanded profile (offline / not signed in → local-only dropdown). + const EXPANDED: LocalCaps = LocalCaps { + albums: 8, + artists: 4, + tracks: 8, + }; + + /// Pick the profile for the current session state. `expand` is true when the + /// session is offline OR unauthenticated (the cortinilla has no Qobuz half). + pub fn for_session(expand: bool) -> LocalCaps { + if expand { + Self::EXPANDED + } else { + Self::NORMAL + } + } + + /// How many raw local TRACK rows to fetch so the grouped album/artist + /// sections can be filled. Albums/artists are derived by grouping tracks, so + /// a single album can swallow many rows — over-fetch well beyond the shown + /// caps to surface enough distinct groups. + fn fetch_limit(self) -> u64 { + ((self.albums.max(self.tracks) * 12) + 40) as u64 + } +} + +/// The artwork key for a local/Plex cortinilla row: the RAW path, so the search +/// artwork dispatcher (`artwork::spawn_search_loads`) can route it by scheme — +/// `/library/…` & `/photo/…` → PlexThumb, http(s) → Qobuz CDN, anything else +/// (an absolute filesystem path) → `LocalFile` (decoded with `fs::read`, so NO +/// `file://` prefix). A stray `file://` is stripped for the same reason. +fn local_artwork_url(path: Option<&str>) -> String { + path.map(|p| p.strip_prefix("file://").unwrap_or(p).to_string()) + .unwrap_or_default() +} + +/// The canonical "artist" attributed to a local track for grouping: the +/// album-artist tag when present, else the track performer. Mirrors the album- +/// grouping helper in `local_library` so cortinilla artists line up with the +/// LocalLibrary Artists tab (which `open_local_artist` selects by NAME). +fn local_album_artist(t: &qbz_library::LocalTrack) -> String { + t.album_artist + .clone() + .filter(|s| !s.is_empty()) + .unwrap_or_else(|| t.artist.clone()) +} + +/// Group local TRACK rows into local ALBUM cortinilla rows (`source = "local"`, +/// `kind = "album"`). Grouped by `album_group_key` in first-seen order (the DB +/// returns rows by match relevance). `id` is the group key — the click router +/// opens the LocalAlbum view with it (`navigate_local_album`). Returns the +/// capped rows plus whether more distinct albums existed than shown. +fn derive_local_album_rows(rows: &[qbz_library::LocalTrack], cap: usize) -> (Vec, bool) { + let mut seen: HashSet = HashSet::new(); + let mut out: Vec = Vec::new(); + let mut total = 0usize; + for t in rows { + let key = t.album_group_key.clone(); + if key.is_empty() || !seen.insert(key.clone()) { + continue; + } + total += 1; + if out.len() >= cap { + continue; // keep counting for an honest has_more + } + let title = if t.album_group_title.is_empty() { + t.album.clone() + } else { + t.album_group_title.clone() + }; + out.push(CortRow { + kind: "album".into(), + id: key, + source: "local".into(), + title, + subtitle: local_album_artist(t), + artwork_url: local_artwork_url(t.artwork_path.as_deref()), + flat_index: 0, + }); + } + let has_more = total > out.len(); + (out, has_more) +} + +/// Group local TRACK rows into local ARTIST cortinilla rows (`source = "local"`, +/// `kind = "artist"`). Grouped by the canonical album-artist, case-insensitively, +/// in first-seen order. Local artists have no id — the click router opens the +/// LocalLibrary Artists tab by NAME (the row `title`), so `id` is left empty. +fn derive_local_artist_rows(rows: &[qbz_library::LocalTrack], cap: usize) -> (Vec, bool) { + let mut seen: HashSet = HashSet::new(); + let mut out: Vec = Vec::new(); + let mut total = 0usize; + for t in rows { + let name = local_album_artist(t); + if name.is_empty() || !seen.insert(name.to_lowercase()) { + continue; + } + total += 1; + if out.len() >= cap { + continue; + } + out.push(CortRow { + kind: "artist".into(), + id: String::new(), + source: "local".into(), + title: name, + subtitle: String::new(), + artwork_url: local_artwork_url(t.artwork_path.as_deref()), + flat_index: 0, + }); + } + let has_more = total > out.len(); + (out, has_more) +} /// Map one `LocalTrack` to a cortinilla `CortRow` tagged `source = "local"`. /// @@ -701,17 +832,7 @@ const CORTINILLA_LOCAL_PER_SECTION: usize = 3; /// local-library DB query returns user files / offline copies only, never the /// Plex cache). fn map_local_track_to_cort_row(t: &qbz_library::LocalTrack) -> CortRow { - let artwork_url = t - .artwork_path - .as_ref() - .map(|p| { - if p.starts_with("file://") { - p.clone() - } else { - format!("file://{p}") - } - }) - .unwrap_or_default(); + let artwork_url = local_artwork_url(t.artwork_path.as_deref()); // Subtitle: "artist · album" when both are present, else whichever exists. let subtitle = match (t.artist.is_empty(), t.album.is_empty()) { (false, false) => format!("{} · {}", t.artist, t.album), @@ -730,45 +851,105 @@ fn map_local_track_to_cort_row(t: &qbz_library::LocalTrack) -> CortRow { } } -/// Append the "On this device" local section to a cortinilla payload (placed -/// LAST, after every Qobuz category, per D1/D2 — local results live ONLY in the -/// cortinilla, and the on-device block sits below the catalog matches). `rows` -/// is the FULL local result set (the load path fetches up to 6); this caps the -/// shown rows at [`CORTINILLA_LOCAL_PER_SECTION`] and sets `has_more` when more -/// were found. No-op when `rows` is empty (no empty section). Re-runs -/// `assign_flat_indices` so the local rows get contiguous flat indices AFTER -/// the Qobuz sections. -pub fn append_local_section(data: &mut CortinillaData, rows: &[qbz_library::LocalTrack]) { +/// Append the local "on this device" sections to a MAIN cortinilla payload, +/// placed LAST (after every Qobuz category, per D1/D2 — local results live ONLY +/// in the cortinilla). Three sections in display order: **Albums**, **Artists**, +/// **Tracks** (mirrors the Qobuz section order), each capped per [`LocalCaps`]. +/// Albums/artists are DERIVED by grouping the local track rows. Section `kind`s +/// are `local-album` / `local-artist` / `local` so the "View more" router opens +/// the matching LocalLibrary tab; per-row `kind` stays album/artist/track so the +/// thumbnail shape + the row click router route correctly. No-op when `rows` is +/// empty. Re-runs `assign_flat_indices` so the local rows get contiguous flat +/// indices AFTER the Qobuz sections. +pub fn append_local_sections( + data: &mut CortinillaData, + rows: &[qbz_library::LocalTrack], + caps: LocalCaps, +) { if rows.is_empty() { return; } - let total = rows.len(); - let cort_rows: Vec = rows + let (album_rows, albums_more) = derive_local_album_rows(rows, caps.albums); + if !album_rows.is_empty() { + data.sections.push(CortSection { + title: "Albums on Local Library".to_string(), + kind: "local-album".to_string(), + rows: album_rows, + has_more: albums_more, + }); + } + let (artist_rows, artists_more) = derive_local_artist_rows(rows, caps.artists); + if !artist_rows.is_empty() { + data.sections.push(CortSection { + title: "Artists on Local Library".to_string(), + kind: "local-artist".to_string(), + rows: artist_rows, + has_more: artists_more, + }); + } + let track_rows: Vec = rows .iter() - .take(CORTINILLA_LOCAL_PER_SECTION) + .take(caps.tracks) .map(map_local_track_to_cort_row) .collect(); - let shown = cort_rows.len(); + if !track_rows.is_empty() { + let shown = track_rows.len(); + data.sections.push(CortSection { + title: "On Local Library".to_string(), + kind: "local".to_string(), + rows: track_rows, + has_more: rows.len() > shown, + }); + } + assign_flat_indices(data); +} + +/// Append the local ALBUM section to an IMMERSIVE cortinilla payload (immersive +/// shows albums ONLY — selecting one queues it per the configured action). Rows +/// are derived local albums tagged `kind = "album"` / `source = "local"`, +/// `kind`-tagged section `local-album`. No "View more" in immersive, so the +/// `has_more` flag is carried but unused by the UI. No-op when `rows` is empty. +fn append_immersive_local_albums( + data: &mut CortinillaData, + rows: &[qbz_library::LocalTrack], + cap: usize, +) { + if rows.is_empty() { + return; + } + let (album_rows, has_more) = derive_local_album_rows(rows, cap); + if album_rows.is_empty() { + return; + } data.sections.push(CortSection { - title: "On this device".to_string(), - kind: "local".to_string(), - rows: cort_rows, - has_more: total > shown, + title: "Albums on Local Library".to_string(), + kind: "local-album".to_string(), + rows: album_rows, + has_more, }); assign_flat_indices(data); } -/// Fetch up to [`CORTINILLA_LOCAL_LIMIT`] local-library tracks matching `query`, -/// off the UI thread (the rusqlite read is sync + blocking, so it runs inside -/// `spawn_blocking`). Returns an empty Vec when the module is disabled, the -/// library is empty, or no row matches — the caller then simply adds no section. +/// Fetch up to `limit` local-library tracks matching `query`, off the UI thread +/// (the rusqlite read is sync + blocking, so it runs inside `spawn_blocking`). +/// Returns an empty Vec when the module is gated off, the library is empty, or no +/// row matches — the caller then simply adds no local section. `gated` makes the +/// fetch respect the intelligent-search toggle (main cortinilla); the immersive +/// search passes `false` since it has its own enable. /// /// Independent of the Qobuz search: callers `tokio::join!` this with /// `core.search_all`, so an offline / slow Qobuz never blocks the on-device /// results (and vice-versa). -pub async fn load_cortinilla_local(query: &str) -> Vec { - // Gate: only touch the DB when the intelligent-search module is enabled. - if !crate::search_service::is_enabled() { +pub async fn load_cortinilla_local( + query: &str, + limit: u64, + gated: bool, +) -> Vec { + // Gate: the MAIN cortinilla only touches the DB when the intelligent-search + // module is enabled (`gated = true`). The immersive search is governed by its + // own "search action" enable instead, so it passes `gated = false`. + if gated && !crate::search_service::is_enabled() { + log::info!("[qbz-slint] cortinilla local: gated off (intelligent-search disabled)"); return Vec::new(); } let q = query.trim().to_string(); @@ -776,20 +957,43 @@ pub async fn load_cortinilla_local(query: &str) -> Vec return Vec::new(); } let exclude_network = crate::local_library::exclude_network_folders_now(); - tokio::task::spawn_blocking(move || { - crate::library_db::with_db(|db| { - db.search_with_filter_page(q.trim(), 0, CORTINILLA_LOCAL_LIMIT, true, exclude_network) + // Plex is part of the user's Local Library (the Artists/Tracks tabs union it), + // so the cortinilla must include it too. `db.search` only hits `local_tracks`; + // the Plex cache is a separate bounded set merged here (same shape as the + // LocalLibrary Tracks tab, see local_library::fetch_tracks_page). + let plex_enabled = crate::plex_settings::get().enabled; + let q_log = q.clone(); + let rows: Vec = tokio::task::spawn_blocking(move || { + let mut rows = crate::library_db::with_db(|db| { + db.search_with_filter_page(q.trim(), 0, limit, true, exclude_network) }) - .unwrap_or_default() + .unwrap_or_default(); + if plex_enabled { + if let Ok(plex_rows) = + qbz_plex::plex_cache_search_tracks(q.trim().to_string(), None) + { + // Map Plex rows into the LocalTrack shape (source=plex, file_path= + // rating_key, plex:album: group keys) and PREPEND so Plex content + // is visible without scrolling past a full local page. + let mut merged: Vec = plex_rows + .into_iter() + .map(crate::local_library::map_plex_cached_to_local_track) + .collect(); + merged.append(&mut rows); + rows = merged; + } + } + rows }) .await - .unwrap_or_default() + .unwrap_or_default(); + log::debug!( + "[qbz-slint] cortinilla local: query={q_log:?} limit={limit} plex={plex_enabled} -> {} rows", + rows.len() + ); + rows } -/// How many local rows the cortinilla fetches (a small over-fetch beyond the 3 -/// shown so `has_more` is accurate and the "View more" affordance is honest). -const CORTINILLA_LOCAL_LIMIT: u64 = 6; - /// (Re)assign `flat_index` across a cortinilla payload: top-result = 0, then /// each section's rows in declaration order, 1..N. Called after the local /// section is appended too, so indices stay contiguous. @@ -848,6 +1052,7 @@ where pub async fn load_cortinilla( runtime: &Arc>, query: &str, + expand_local: bool, ) -> Result<(CortinillaData, Vec), String> where A: FrontendAdapter + Send + Sync + 'static, @@ -857,13 +1062,18 @@ where } else { std::collections::HashSet::new() }; + // Offline / not-signed-in → the dropdown is local-only, so widen the local + // section caps (and the raw fetch that feeds the derived album/artist groups). + let caps = LocalCaps::for_session(expand_local); let core = runtime.core(); // Fire the Qobuz search and the local-library search CONCURRENTLY. The local // query is independent — if Qobuz is slow/offline the on-device rows still // fill in (a Qobuz error falls into the local-only branch below instead of // discarding everything; the local rows are already resolved by then). - let (results, local_rows) = - tokio::join!(core.search_all(query, &blacklist), load_cortinilla_local(query)); + let (results, local_rows) = tokio::join!( + core.search_all(query, &blacklist), + load_cortinilla_local(query, caps.fetch_limit(), true) + ); let mut data = match results { Ok(results) => { // Persist the live page so a later keystroke (or restart) can paint @@ -885,9 +1095,10 @@ where } } }; - // Append the "On this device" section LAST (after every Qobuz category) and - // re-run flat-index assignment so the local rows get contiguous indices. - append_local_section(&mut data, &local_rows); + // Append the local "on this device" sections LAST (after every Qobuz + // category) and re-run flat-index assignment so the local rows get + // contiguous indices. + append_local_sections(&mut data, &local_rows, caps); Ok((data, local_rows)) } @@ -901,6 +1112,7 @@ where pub async fn load_immersive_search( runtime: &Arc>, query: &str, + expand_local: bool, ) -> Result where A: FrontendAdapter + Send + Sync + 'static, @@ -910,12 +1122,31 @@ where } else { std::collections::HashSet::new() }; + let caps = LocalCaps::for_session(expand_local); let core = runtime.core(); - let results = core - .search_all(query, &blacklist) - .await - .map_err(|e| e.to_string())?; - Ok(map_search_all_to_immersive(query, &results)) + // Qobuz catalog + local albums CONCURRENTLY. Local is ungated (immersive + // search has its own "search action" enable, independent of the main + // cortinilla's intelligent-search toggle). + let (results, local_rows) = tokio::join!( + core.search_all(query, &blacklist), + load_cortinilla_local(query, caps.fetch_limit(), false) + ); + // A Qobuz error (offline / not signed in) still yields a local-only dropdown + // rather than discarding everything — the local albums are already resolved. + let mut data = match results { + Ok(results) => map_search_all_to_immersive(query, &results), + Err(e) => { + log::debug!("[qbz-slint] immersive search: qobuz failed ({e}); local-only"); + CortinillaData { + query: query.to_string(), + top: None, + sections: Vec::new(), + } + } + }; + // Immersive shows albums ONLY; selecting one queues it per the action. + append_immersive_local_albums(&mut data, &local_rows, caps.albums); + Ok(data) } // ==================== Apply (Slint event loop) ==================== diff --git a/crates/qbz-slint/ui/immersive/ImmersiveView.slint b/crates/qbz-slint/ui/immersive/ImmersiveView.slint index e31cb8680..88f3483cd 100644 --- a/crates/qbz-slint/ui/immersive/ImmersiveView.slint +++ b/crates/qbz-slint/ui/immersive/ImmersiveView.slint @@ -824,6 +824,11 @@ component ImmersiveSearchPlaceholder inherits Rectangle { vertical-alignment: center; horizontal-alignment: center; single-line: true; + // Two-way bound to a DEDICATED raw-text property so the controller can + // clear the field after a result is activated (consistency with the + // main cortinilla). Separate from the trimmed `search-query`. Typing + // still flows through `edited`. + text <=> ImmersiveState.search-input-text; accepted => { search-scope.on-enter(); } edited => { ImmersiveSearchActions.live(self.text); } // On focus-IN: route focus to the wrapping scope (so its key-pressed diff --git a/crates/qbz-slint/ui/shell/HeaderBar.slint b/crates/qbz-slint/ui/shell/HeaderBar.slint index 45813c4e0..08e6563de 100644 --- a/crates/qbz-slint/ui/shell/HeaderBar.slint +++ b/crates/qbz-slint/ui/shell/HeaderBar.slint @@ -632,6 +632,10 @@ export component HeaderBar inherits Rectangle { vertical-alignment: center; horizontal-alignment: center; single-line: true; + // Two-way bound so the controller can clear the field after a + // cortinilla element is activated (stops the focus-bounce + // re-invocation). Typing still flows through `edited` below. + text <=> SearchState.header-search-text; // Enter is handled by the FocusScope (cortinilla-aware); keep // `accepted` as a fallback for the rare case the input owns the // event directly (e.g. focus routed straight to it). diff --git a/crates/qbz-slint/ui/state.slint b/crates/qbz-slint/ui/state.slint index f5cb083df..ff27dfb9a 100644 --- a/crates/qbz-slint/ui/state.slint +++ b/crates/qbz-slint/ui/state.slint @@ -3380,7 +3380,14 @@ export global ImmersiveState { // search-open is true the HUD must NOT auto-hide. See the immersive-search // design spec (qbz-nix-docs/specs/2026-06-20-immersive-search-design.md). in-out property search-open: false; + // The TRIMMED query the cortinilla reflects (controller-set, display only). in property search-query; + // The raw immersive search TextInput text, two-way bound to the field (in-out) + // so the controller can CLEAR it after the user activates a result — + // consistency with the main header cortinilla. Kept SEPARATE from the trimmed + // `search-query` so the controller writing the trimmed value never fights the + // user's in-progress text (e.g. trailing spaces). + in-out property search-input-text: ""; in property search-loading: false; in property <[CortinillaSection]> search-sections: []; in-out property search-selected-index: -1; @@ -4128,6 +4135,13 @@ export global SearchState { // The controller owns the index -> API-value mapping. in property filter-index: 0; + // The live header search-box text, two-way bound to the TextInput in + // HeaderBar. Owned here (not internal to the TextInput) so the controller + // can CLEAR it after the user activates a cortinilla element (row click / + // "View more" / Enter) — lingering text would otherwise re-invoke the + // dropdown when focus bounces back to the field after any UI interaction. + in-out property header-search-text: ""; + // ---- Cortinilla (live as-you-type dropdown under the header search) ---- // Whether the cortinilla overlay is currently shown. The overlay is a // LAST child of AppShell, visibility-gated on this flag.