feat(slint): post-lyrics UI polish sweep + correctness fixes

- TrackRow: Korean/CJK titles render via layout-assigned width+height
  (SongCard parity, never femtovg-measured); explicit "E" badge hugs the
  title text; duration + position number dropped to 13px so they read
  smaller than the 14px title.
- AlbumView: label/awards rail 214->160px with smaller card/icon/padding
  and centered headings in the compact rail; removed the dark right gutter
  (full-width Flickable, content clears the scrollbar via the 32px page
  padding); column headers homologated to Playlist casing (Title/Duration/
  Quality), same in LocalAlbumView.
- ArtistView: network sidebar auto-collapses on ShellState.content-
  constrained (the AlbumView signal) and no longer re-opens on artist->
  artist navigation (reset_network_sidebar respects the constraint).
- Hero titles homologated to Typography.section (18px) across MyQBZ detail,
  Musician, Label releases, Artists-by-location, Offline Manager.
- Lyrics: Qobuz || LRCLIB parallel fetch, next-track prefetch, source
  footer, asymmetric line fade.

cc
This commit is contained in:
vicrodh committed 2026-06-11 22:03:46 -06:00
1 parent 67a0e39841
commit 999ded11ff
32 files changed
+1512 -406

No files matched your search

+179 -18
View File
@@ -10,7 +10,7 @@ use std::sync::Arc;
use qbz_app::shell::AppRuntime;
use qbz_core::FrontendAdapter;
use qbz_models::{Album, Track};
use slint::{ComponentHandle, ModelRc, VecModel};
use slint::{ComponentHandle, Model, ModelRc, VecModel};
use crate::{AlbumState, TrackItem, AppWindow};
@@ -19,6 +19,11 @@ thread_local! {
/// track search can filter against it without a re-fetch. UI thread
/// only, hence `thread_local`.
static FULL_TRACKS: RefCell<Vec<TrackItem>> = RefCell::new(Vec::new());
/// The current album's RAW catalog tracks (qbz_models::Track), kept so
/// the multi-select bulk actions (enqueue / cache) can resolve the
/// selected rows to full Track objects without a re-fetch — mirrors the
/// `play` Vec the favorites tab keeps. UI thread only.
static PLAY_TRACKS: RefCell<Vec<Track>> = RefCell::new(Vec::new());
}
/// Plain, `Send` album data produced on the worker thread.
@@ -29,6 +34,11 @@ pub struct AlbumData {
pub artist_id: String,
/// Pre-formatted "year • label • genre • N tracks • duration".
pub info_line: String,
/// Meta-line segment BEFORE the label (the year) — rendered with the
/// label as a clickable link in the header.
pub meta_pre: String,
/// Meta-line segment AFTER the label (genre • N tracks • duration).
pub meta_post: String,
pub quality_tier: String,
/// "24-bit / 96 kHz" — the quality-badge detail line.
pub quality_detail: String,
@@ -36,6 +46,8 @@ pub struct AlbumData {
pub description: String,
/// Short, truncated description for the header (full text in a modal).
pub description_short: String,
/// Half-length truncation used when the content area is space-constrained.
pub description_shorter: String,
pub artwork_url: String,
/// Record label name, for the sidebar (empty when unknown).
pub label: String,
@@ -44,7 +56,12 @@ pub struct AlbumData {
pub label_id: String,
/// Editorial award names, for the sidebar.
pub awards: Vec<String>,
/// True when the album bundles a downloadable booklet/liner-notes PDF
/// (Qobuz goodies) — gates the header booklet button.
pub has_booklet: bool,
pub tracks: Vec<TrackData>,
/// Raw catalog tracks, kept for the multi-select bulk actions.
pub raw_tracks: Vec<Track>,
}
pub struct TrackData {
@@ -89,23 +106,49 @@ fn map_album(album: Album) -> AlbumData {
.unwrap_or("")
.to_string();
let mut parts: Vec<String> = Vec::new();
// Meta line, split around the label so the header can render the label
// as a clickable link (Tauri's `date • [label] • genre • N tracks •
// duration`). `meta_pre` = the segment before the label (the year);
// `meta_post` = everything after (genre / tracks / duration). The full
// `info_line` (label inlined as plain text) stays the fallback for when
// there is no label id to navigate to.
let label_name = album
.label
.as_ref()
.filter(|l| !l.name.is_empty())
.map(|l| l.name.clone());
let genre_str = album
.genre
.as_ref()
.filter(|g| !g.name.is_empty())
.map(|g| g.name.clone());
let tracks_str = album.tracks_count.map(|count| format!("{count} tracks"));
let duration_str = album.duration.map(format_duration);
let mut pre_parts: Vec<String> = Vec::new();
if !year.is_empty() {
parts.push(year);
pre_parts.push(year.clone());
}
if let Some(label) = album.label.as_ref().filter(|l| !l.name.is_empty()) {
parts.push(label.name.clone());
let mut post_parts: Vec<String> = Vec::new();
if let Some(g) = &genre_str {
post_parts.push(g.clone());
}
if let Some(genre) = album.genre.as_ref().filter(|g| !g.name.is_empty()) {
parts.push(genre.name.clone());
if let Some(tc) = &tracks_str {
post_parts.push(tc.clone());
}
if let Some(count) = album.tracks_count {
parts.push(format!("{count} tracks"));
if let Some(d) = &duration_str {
post_parts.push(d.clone());
}
if let Some(duration) = album.duration {
parts.push(format_duration(duration));
let meta_pre = pre_parts.join(" • ");
let meta_post = post_parts.join(" • ");
let mut all_parts = pre_parts.clone();
if let Some(l) = &label_name {
all_parts.push(l.clone());
}
let info_line = parts.join(" • ");
all_parts.extend(post_parts.clone());
let info_line = all_parts.join(" • ");
let quality_tier = tier(album.maximum_bit_depth).to_string();
let quality_detail = crate::quality::detail(album.maximum_bit_depth, album.maximum_sampling_rate);
@@ -118,6 +161,8 @@ fn map_album(album: Album) -> AlbumData {
// artwork, so a longer truncation keeps it from looking like a thin
// strip; the Read more modal still holds the complete text.
let description_short = truncate_words(&description, 360);
// Half the cutoff for the space-constrained layout (tracks get priority).
let description_shorter = truncate_words(&description, 180);
let artwork_url = album.image.best().cloned().unwrap_or_default();
let label = album
.label
@@ -137,13 +182,17 @@ fn map_album(album: Album) -> AlbumData {
.map(|a| a.name.clone())
.filter(|n| !n.is_empty())
.collect();
let tracks = album
// Booklet present when the album carries any goody with a usable URL.
let has_booklet = album
.goodies
.as_deref()
.map(|goodies| goodies.iter().any(|g| !g.url.is_empty()))
.unwrap_or(false);
let raw_tracks: Vec<Track> = album
.tracks
.map(|container| container.items)
.unwrap_or_default()
.into_iter()
.map(map_track)
.collect();
.unwrap_or_default();
let tracks = raw_tracks.iter().cloned().map(map_track).collect();
AlbumData {
id: album.id,
@@ -151,15 +200,20 @@ fn map_album(album: Album) -> AlbumData {
artist,
artist_id,
info_line,
meta_pre,
meta_post,
quality_tier,
quality_detail,
description,
description_short,
description_shorter,
artwork_url,
label,
label_id,
awards,
has_booklet,
tracks,
raw_tracks,
}
}
@@ -282,16 +336,34 @@ pub fn apply_album(window: &AppWindow, data: AlbumData) {
state.set_artist(data.artist.into());
state.set_artist_id(data.artist_id.into());
state.set_info_line(data.info_line.into());
state.set_meta_pre(data.meta_pre.into());
state.set_meta_post(data.meta_post.into());
state.set_quality_tier(data.quality_tier.into());
state.set_quality_detail(data.quality_detail.into());
state.set_description(data.description.into());
state.set_description_short(data.description_short.into());
state.set_description_shorter(data.description_shorter.into());
state.set_label(data.label.into());
state.set_label_id(data.label_id.into());
state.set_awards(ModelRc::new(VecModel::from(awards)));
state.set_has_booklet(data.has_booklet);
// Fully cached = every track already has a ready (3) offline copy. Kept
// live afterwards by set_row_cache_status as downloads complete.
let album_fully_cached =
!tracks.is_empty() && tracks.iter().all(|t| t.cache_status == 3);
state.set_album_fully_cached(album_fully_cached);
// Seed the header heart from the favorite-album cache (kept in sync with
// the server at login + on every toggle).
state.set_is_favorite(crate::fav_cache::is_album_favorite(album_id.as_str()));
state.set_favorite_loading(false);
// Keep the unfiltered list for the track search, then show it all.
// Keep the unfiltered list for the track search + the raw tracks for the
// multi-select bulk actions, then show them all.
FULL_TRACKS.with(|cell| *cell.borrow_mut() = tracks.clone());
PLAY_TRACKS.with(|cell| *cell.borrow_mut() = data.raw_tracks);
// A freshly loaded album starts out of select mode with nothing selected.
state.set_multi_select(false);
state.set_selected_count(0);
state.set_tracks(ModelRc::new(VecModel::from(tracks)));
}
@@ -320,14 +392,103 @@ pub fn filter_tracks(window: &AppWindow, query: &str) {
/// album so the previous one does not flash).
pub fn reset_album(window: &AppWindow) {
FULL_TRACKS.with(|cell| cell.borrow_mut().clear());
PLAY_TRACKS.with(|cell| cell.borrow_mut().clear());
let state = window.global::<AlbumState>();
state.set_multi_select(false);
state.set_selected_count(0);
state.set_tracks(ModelRc::new(VecModel::from(Vec::<TrackItem>::new())));
state.set_artwork(slint::Image::default());
// Clear the booklet gate so the previous album's value doesn't linger.
state.set_has_booklet(false);
state.set_album_fully_cached(false);
state.set_is_favorite(false);
state.set_favorite_loading(false);
// Default to a Qobuz album; the local-album loader opts in.
state.set_is_local(false);
state.set_loading(true);
}
// ==================== Multi-select (track selection) ====================
/// Toggle multi-select mode on the album track list. Leaving the mode
/// clears any current selection.
pub fn set_multi_select(window: &AppWindow, on: bool) {
let state = window.global::<AlbumState>();
state.set_multi_select(on);
if !on {
clear_selection(window);
}
}
/// Recompute the "N selected" count from the track rows.
pub fn recount_selected(window: &AppWindow) {
let state = window.global::<AlbumState>();
let model = state.get_tracks();
let count = (0..model.row_count())
.filter(|&i| model.row_data(i).map(|t| t.selected).unwrap_or(false))
.count();
state.set_selected_count(count as i32);
}
/// Select every row, or clear if all are already selected (the toggle the
/// "Select all" bulk button drives — same semantics as the favorites bar).
pub fn select_all(window: &AppWindow) {
let model = window.global::<AlbumState>().get_tracks();
let total = model.row_count();
let selected = (0..total)
.filter(|&i| model.row_data(i).map(|t| t.selected).unwrap_or(false))
.count();
let target = selected != total;
for i in 0..total {
if let Some(mut item) = model.row_data(i) {
if item.selected != target {
item.selected = target;
model.set_row_data(i, item);
}
}
}
recount_selected(window);
}
/// Clear the selection (uncheck all), keeping multi-select mode on.
pub fn clear_selection(window: &AppWindow) {
let model = window.global::<AlbumState>().get_tracks();
for i in 0..model.row_count() {
if let Some(mut item) = model.row_data(i) {
if item.selected {
item.selected = false;
model.set_row_data(i, item);
}
}
}
window.global::<AlbumState>().set_selected_count(0);
}
/// The catalog ids of the currently selected rows (for add-to-playlist /
/// add-to-favorites — Qobuz catalog ids only).
pub fn selected_ids(window: &AppWindow) -> Vec<String> {
let model = window.global::<AlbumState>().get_tracks();
(0..model.row_count())
.filter_map(|i| model.row_data(i))
.filter(|t| t.selected)
.map(|t| t.id.to_string())
.filter(|s| s.parse::<u64>().is_ok())
.collect()
}
/// The full catalog Track objects for the selected rows (for enqueue /
/// cache), resolved from the stashed raw album tracks by id.
pub fn selected_play_tracks(window: &AppWindow) -> Vec<Track> {
let ids: std::collections::HashSet<String> = selected_ids(window).into_iter().collect();
PLAY_TRACKS.with(|cell| {
cell.borrow()
.iter()
.filter(|t| ids.contains(&t.id.to_string()))
.cloned()
.collect()
})
}
/// Apply decoded header artwork pixels. Runs on the Slint event loop.
pub fn apply_artwork(window: &AppWindow, pixels: &[u8], width: u32, height: u32) {
let mut buffer = slint::SharedPixelBuffer::<slint::Rgba8Pixel>::new(width, height);
+96 -7
View File
@@ -20,7 +20,7 @@ use crate::home::CardData;
use crate::{
AlbumCardItem, TrackItem, AppWindow, ArtistState, DiscoverSection, DiscoveryArtist,
JumpNavTab, LabelEntry, MbOriginData, MbRelationship, MbRelationshipsData,
NetworkSidebarState, SimilarEntry,
NetworkSidebarState, ShellState, SimilarEntry,
};
/// Plain, `Send` artist data produced on the worker thread.
@@ -697,9 +697,87 @@ pub fn reset_artist(window: &AppWindow) {
state.set_name("".into());
state.set_bio("".into());
state.set_bio_source("".into());
state.set_top_tracks_multi_select(false);
state.set_top_tracks_selected_count(0);
state.set_loading(true);
}
// ============== Popular Tracks multi-select (mirrors AlbumState) ==========
/// Toggle Popular Tracks multi-select; leaving the mode clears the selection.
pub fn set_multi_select(window: &AppWindow, on: bool) {
let state = window.global::<ArtistState>();
state.set_top_tracks_multi_select(on);
if !on {
clear_selection(window);
}
}
/// Recompute the "N selected" count from the Popular Tracks rows.
pub fn recount_selected(window: &AppWindow) {
let state = window.global::<ArtistState>();
let model = state.get_top_tracks();
let count = (0..model.row_count())
.filter(|&i| model.row_data(i).map(|t| t.selected).unwrap_or(false))
.count();
state.set_top_tracks_selected_count(count as i32);
}
/// Select every row, or clear if all are already selected.
pub fn select_all(window: &AppWindow) {
let model = window.global::<ArtistState>().get_top_tracks();
let total = model.row_count();
let selected = (0..total)
.filter(|&i| model.row_data(i).map(|t| t.selected).unwrap_or(false))
.count();
let target = selected != total;
for i in 0..total {
if let Some(mut item) = model.row_data(i) {
if item.selected != target {
item.selected = target;
model.set_row_data(i, item);
}
}
}
recount_selected(window);
}
/// Clear the selection (uncheck all), keeping multi-select mode on.
pub fn clear_selection(window: &AppWindow) {
let model = window.global::<ArtistState>().get_top_tracks();
for i in 0..model.row_count() {
if let Some(mut item) = model.row_data(i) {
if item.selected {
item.selected = false;
model.set_row_data(i, item);
}
}
}
window.global::<ArtistState>().set_top_tracks_selected_count(0);
}
/// Catalog ids of the selected Popular Tracks rows (Qobuz ids only).
pub fn selected_ids(window: &AppWindow) -> Vec<String> {
let model = window.global::<ArtistState>().get_top_tracks();
(0..model.row_count())
.filter_map(|i| model.row_data(i))
.filter(|t| t.selected)
.map(|t| t.id.to_string())
.filter(|s| s.parse::<u64>().is_ok())
.collect()
}
/// Catalog ids of ALL Popular Tracks rows (for the section "more" menu's
/// all-tracks actions).
pub fn all_top_track_ids(window: &AppWindow) -> Vec<String> {
let model = window.global::<ArtistState>().get_top_tracks();
(0..model.row_count())
.filter_map(|i| model.row_data(i))
.map(|t| t.id.to_string())
.filter(|s| s.parse::<u64>().is_ok())
.collect()
}
/// Apply decoded portrait artwork. Runs on the Slint event loop.
pub fn apply_artwork(window: &AppWindow, pixels: &[u8], width: u32, height: u32) {
let mut buffer = slint::SharedPixelBuffer::<slint::Rgba8Pixel>::new(width, height);
@@ -732,19 +810,30 @@ pub struct MbOrigin {
pub location_clickable: bool,
}
/// Reset the network sidebar's MB-driven state and force-open the
/// panel. Called when the artist changes so a stale Origin /
/// Relationships / Discovery never bleeds across artists, and so the
/// sidebar always starts open on every artist visit (per user policy
/// — close is per-session, never persisted).
/// Reset the network sidebar's MB-driven state and (re)apply the open
/// state on artist change so a stale Origin / Relationships / Discovery
/// never bleeds across artists. The sidebar opens fresh on every artist
/// visit (per user policy — close is per-session, never persisted)
/// EXCEPT when the content area is space-constrained (a Queue / Lyrics
/// right panel is open on a non-wide window). In that case it stays
/// collapsed so the Popular Tracks list keeps priority — mirroring the
/// `!net-cramped` rule the ArtistPageView Slint handlers use. Reading
/// the constraint here (instead of unconditionally force-opening) is
/// what fixes the artist->artist navigation case: when a panel was
/// already open, navigating to a new artist no longer re-opens the
/// sidebar over the Slint handler.
pub fn reset_network_sidebar(window: &AppWindow) {
// Drop the previous artist's cached location params so a stale
// scene-view click can't fire for the wrong artist.
if let Ok(mut guard) = LOCATION_PARAMS.lock() {
*guard = None;
}
// Open only when there's room — mirror ShellState.content-constrained
// (the same signal AlbumView + the ArtistPageView `net-cramped`
// handlers use). Constrained => keep collapsed.
let constrained = window.global::<ShellState>().get_content_constrained();
let state = window.global::<NetworkSidebarState>();
state.set_open(true);
state.set_open(!constrained);
state.set_mb_available(true);
state.set_mb_mbid("".into());
state.set_origin_loading(false);
+22 -2
View File
@@ -587,11 +587,31 @@ fn apply_artwork(
}
}
ArtworkTarget::SearchArtist { idx } => {
let model = window.global::<SearchState>().get_artists();
let state = window.global::<SearchState>();
let model = state.get_artists();
let mut artist_id = None;
if let Some(mut item) = model.row_data(idx) {
item.artwork = image;
artist_id = Some(item.id.clone());
item.artwork = image.clone();
model.set_row_data(idx, item);
}
// The All-tab carousel is a SEPARATE model (`artists_carousel`,
// built as a clone with the hero dup dropped), so the artwork
// pipeline never reaches it. Mirror the cover into the matching
// carousel row by id (indices differ when the artist hero drops
// the first entry) so the carousel cards show their images.
if let Some(aid) = artist_id {
let carousel = state.get_artists_carousel();
for i in 0..carousel.row_count() {
if let Some(mut c) = carousel.row_data(i) {
if c.id == aid {
c.artwork = image.clone();
carousel.set_row_data(i, c);
break;
}
}
}
}
}
ArtworkTarget::SearchPlaylistCover { idx, slot } => {
let model = window.global::<SearchState>().get_playlists();
+75
View File
@@ -21,6 +21,13 @@ use qbz_app::settings::favorites_cache::FavoritesCacheStore;
static FAVORITES: LazyLock<RwLock<HashSet<u64>>> =
LazyLock::new(|| RwLock::new(HashSet::new()));
/// Process-wide set of the user's favorite ALBUM ids (string catalog ids).
/// Same disk-first + network-refresh lifecycle as [`FAVORITES`], so the
/// album header heart renders the right state from first paint and stays
/// live across toggles. Mirrors Tauri's `albumFavoritesStore`.
static FAV_ALBUMS: LazyLock<RwLock<HashSet<String>>> =
LazyLock::new(|| RwLock::new(HashSet::new()));
/// Per-user persistent ID store. `None` until a session (online or offline)
/// is activated; pure in-memory behavior in that window.
static STORE: Mutex<Option<FavoritesCacheStore>> = Mutex::new(None);
@@ -54,6 +61,19 @@ pub fn init_for_user(base_dir: &Path) {
}
Err(e) => log::warn!("[qbz-slint] favorites cache disk seed failed: {e}"),
}
match store.get_favorite_album_ids() {
Ok(ids) => {
let set: HashSet<String> = ids.into_iter().collect();
log::info!(
"[qbz-slint] favorites cache: {} album ids seeded from disk",
set.len()
);
if let Ok(mut guard) = FAV_ALBUMS.write() {
*guard = set;
}
}
Err(e) => log::warn!("[qbz-slint] favorites cache album disk seed failed: {e}"),
}
if let Ok(mut guard) = STORE.lock() {
*guard = Some(store);
}
@@ -67,6 +87,9 @@ pub fn teardown() {
if let Ok(mut guard) = FAVORITES.write() {
guard.clear();
}
if let Ok(mut guard) = FAV_ALBUMS.write() {
guard.clear();
}
}
/// Replace the cache with a freshly-fetched set and mirror it to the
@@ -135,3 +158,55 @@ pub fn set(track_id: u64, favorite: bool) {
}
}
}
// ==================== Favorite albums ====================
/// True when the album catalog id is in the user's favorite-album set.
pub fn is_album_favorite(album_id: &str) -> bool {
FAV_ALBUMS
.read()
.map(|g| g.contains(album_id))
.unwrap_or(false)
}
/// Replace the favorite-album set with a freshly-fetched id list and mirror
/// it to the per-user store (full replace — Tauri's
/// `v2_sync_cached_favorite_albums`). Blocking disk write; call off the UI
/// thread.
pub fn set_all_albums(ids: HashSet<String>) {
if let Ok(guard) = STORE.lock() {
if let Some(store) = guard.as_ref() {
let disk: Vec<String> = ids.iter().cloned().collect();
if let Err(e) = store.sync_favorite_albums(&disk) {
log::warn!("[qbz-slint] favorites cache album sync failed: {e}");
}
}
}
if let Ok(mut guard) = FAV_ALBUMS.write() {
*guard = ids;
}
}
/// Insert / remove a single album id (optimistic toggle) and mirror the
/// change to the per-user store so the heart survives a restart.
pub fn set_album(album_id: &str, favorite: bool) {
if let Ok(mut guard) = FAV_ALBUMS.write() {
if favorite {
guard.insert(album_id.to_string());
} else {
guard.remove(album_id);
}
}
if let Ok(guard) = STORE.lock() {
if let Some(store) = guard.as_ref() {
let res = if favorite {
store.add_favorite_album(album_id)
} else {
store.remove_favorite_album(album_id)
};
if let Err(e) = res {
log::warn!("[qbz-slint] favorites cache album disk update failed: {e}");
}
}
}
}
+57
View File
@@ -141,6 +141,63 @@ pub struct LabelCard {
pub image_url: String,
}
/// Fetch the full set of favorite ALBUM ids from the server (paginated),
/// for seeding `fav_cache` at login so the album header heart is correct
/// without first visiting the Favorites view. Mirrors Tauri's
/// `albumFavoritesStore.syncFromApi`.
pub async fn favorite_album_ids<A>(
runtime: &Arc<AppRuntime<A>>,
) -> std::collections::HashSet<String>
where
A: FrontendAdapter + Send + Sync + 'static,
{
let mut ids: std::collections::HashSet<String> = std::collections::HashSet::new();
let mut offset = 0u32;
loop {
let value = match runtime.core().get_favorites("albums", PAGE_SIZE, offset).await {
Ok(v) => v,
Err(e) => {
log::warn!("[qbz-slint] favorite album ids fetch failed: {e}");
break;
}
};
let branch = value.get("albums");
let total = branch
.and_then(|b| b.get("total"))
.and_then(|t| t.as_u64())
.unwrap_or(0) as usize;
let page: Vec<serde_json::Value> = branch
.and_then(|b| b.get("items"))
.and_then(|i| i.as_array())
.cloned()
.unwrap_or_default();
let page_len = page.len();
for item in &page {
match item.get("id") {
Some(v) if v.is_string() => {
if let Some(s) = v.as_str() {
ids.insert(s.to_string());
}
}
Some(v) if v.is_u64() => {
if let Some(n) = v.as_u64() {
ids.insert(n.to_string());
}
}
_ => {}
}
}
offset += page_len as u32;
let exhausted = page_len < PAGE_SIZE as usize
|| (total > 0 && offset as usize >= total)
|| ids.len() >= MAX_ITEMS;
if exhausted {
break;
}
}
ids
}
/// Fetch + parse one favorites tab.
pub async fn load_favorites<A>(
runtime: &Arc<AppRuntime<A>>,
+29
View File
@@ -278,6 +278,35 @@ fn provider_label(provider: LyricsProvider) -> &'static str {
/// panel-open path for the current track. Fire-and-forget: pushes the
/// loading state immediately, resolves through the engine off-loop, and
/// commits the response only if the track is still current (F2).
/// Resolve + CACHE lyrics for a track in the BACKGROUND without touching the
/// UI — warms the lyrics cache for an upcoming queued track so the panel is
/// instant when that track becomes current (the user's "prefetch the next
/// track's lyrics" request; Tauri only fetches the current one). Fire-and-
/// forget; skipped offline so we never spend network warming ahead.
pub fn prefetch_lyrics(track: &QueueTrack) {
let Some(service) = SERVICE.get().cloned() else {
return;
};
if crate::offline_mode::engine().is_offline() {
return;
}
let source = source_kind(track);
let request = LyricsRequest {
track_id: (source == LyricsSourceKind::Qobuz).then_some(track.id),
source,
title: track.title.clone(),
artist: track.artist.clone(),
album: (!track.album.is_empty()).then(|| track.album.clone()),
duration_secs: (track.duration_secs > 0).then_some(track.duration_secs),
offline: false,
};
tokio::spawn(async move {
// Resolution upserts into lyrics.db; the result is discarded (no UI).
// On advance, on_track_changed hits this warm cache instantly.
let _ = service.get(request).await;
});
}
pub fn on_track_changed(weak: slint::Weak<AppWindow>, track: &QueueTrack) {
let Some(service) = SERVICE.get().cloned() else {
log::debug!("[qbz-slint] lyrics fetch skipped: service not installed");
+93
View File
@@ -1371,6 +1371,12 @@ pub(crate) async fn refresh_now_playing_meta(runtime: &Runtime, weak: &slint::We
// peer's track (Q7). Fire-and-forget; the stale-response guard (F2)
// lives in `lyrics::on_track_changed`.
crate::lyrics::on_track_changed(weak.clone(), &track);
// Warm the NEXT queued track's lyrics in the background so the panel is
// instant when it becomes current (cache-only; no UI). Generated here
// because Tauri only ever fetches the CURRENT track.
if let Some(next) = runtime.core().queue().read().await.peek_next() {
crate::lyrics::prefetch_lyrics(&next);
}
let notify_meta = qbz_media_controls::NotificationMeta {
title: title.clone(),
artist: artist.clone(),
@@ -1740,6 +1746,93 @@ pub fn play_artist_top_tracks(
});
}
/// Enqueue (play-next or append) a subset of the artist's Popular tracks,
/// identified by catalog id. Re-fetches the page (like the play-all path),
/// filters to `ids`, preserves the page order, and queues — QConnect-aware
/// (mirrors `enqueue_queue_tracks`). Drives both the bulk bar (selection)
/// and the section "more" menu (all ids).
pub fn enqueue_artist_top_selected(
runtime: Runtime,
weak: slint::Weak<AppWindow>,
handle: tokio::runtime::Handle,
artist_id: String,
ids: Vec<String>,
next: bool,
) {
if ids.is_empty() {
return;
}
handle.spawn(async move {
let Some(all) = fetch_artist_top_for_play(&runtime, &weak, &artist_id).await else {
return;
};
let want: std::collections::HashSet<u64> =
ids.iter().filter_map(|s| s.parse::<u64>().ok()).collect();
let tracks: Vec<QueueTrack> =
all.into_iter().filter(|qt| want.contains(&qt.id)).collect();
if tracks.is_empty() {
return;
}
if let Some(svc) = crate::qconnect_service::service() {
let routed: Vec<(u64, Option<String>)> =
tracks.iter().map(|qt| (qt.id, qt.source.clone())).collect();
let handled = if next {
svc.play_next_batch_on_peer_if_active(&routed).await
} else {
svc.add_to_queue_batch_on_peer_if_active(&routed).await
};
if handled {
return;
}
}
if next {
for track in tracks.into_iter().rev() {
runtime.core().add_track_next(track).await;
}
} else {
runtime.core().add_tracks(tracks).await;
}
refresh_sidebar(false);
crate::toast::success_weak(&weak, if next { "Playing next" } else { "Added to queue" });
});
}
/// Shuffle-play ALL of the artist's Popular tracks (section "more" menu).
/// Re-fetches, xorshift-shuffles (same seedless mix as `play_album_shuffled`),
/// and replaces the queue.
pub fn play_artist_top_shuffled(
runtime: Runtime,
weak: slint::Weak<AppWindow>,
handle: tokio::runtime::Handle,
artist_id: String,
) {
handle.spawn(async move {
let Some(mut tracks) = fetch_artist_top_for_play(&runtime, &weak, &artist_id).await else {
return;
};
if tracks.is_empty() {
return;
}
let mut seed = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos() as u64)
.unwrap_or(1)
| 1;
for i in (1..tracks.len()).rev() {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
let j = (seed % (i as u64 + 1)) as usize;
tracks.swap(i, j);
}
let start_track_id = tracks[0].id;
set_now_playing_context(&weak, "artist", &artist_id);
runtime.core().set_queue(tracks, Some(0)).await;
after_track_change(&runtime, &weak, start_track_id).await;
refresh_sidebar(true);
});
}
/// Play the artist's Popular tracks starting at the clicked track id (queues
/// the tracks that follow it). `visible_ids` is the Popular-tracks VISIBLE row
/// order — the queue is reordered/filtered to match, so the in-page search
+7
View File
@@ -11,6 +11,13 @@ pub fn qobuz_playlist_url(playlist_id: &str) -> String {
format!("https://play.qobuz.com/playlist/{playlist_id}")
}
/// Qobuz web-player album URL (matches Tauri's `shareAlbumQobuzLink`,
/// `https://play.qobuz.com/album/{id}`). Also the source URL fed to
/// Song.link for the album-level "Album.link".
pub fn qobuz_album_url(album_id: &str) -> String {
format!("https://play.qobuz.com/album/{album_id}")
}
/// Copy `text` to the system clipboard. Runs on a blocking thread —
/// clipboard backends (X11/Wayland) can block, and arboard keeps an
/// owner thread alive so the contents persist after this returns.