feat(slint): port Awards pages (landing + albums listing + follow)

Port Tauri's AwardView/AwardAlbumsView to Slint: the award landing
(hero + acclaimed-releases preview grid + other-awards rail + follow
heart), the paginated albums listing with client-side search, and
clickable album-sidebar laurels that open the award page (resolving the
award id by name when /album/get omits it).

- AwardState/AwardActions globals + AwardEntry; AlbumState.awards now
  carries award ids
- award controller (src/award.rs): /award/page hero (never page.releases),
  /award/getAlbums grid, /award/explore other-awards + name->id resolver;
  follow via the shared favorite_awards cache (plural-read/singular-write
  favType, skip-if-remote, login seed)
- nav registration: NavEntry::Award/AwardAlbums, ContentView arms,
  navigate_award/navigate_award_albums, AppShell mounts, app.slint exports
- ArtworkTarget::AwardAlbum/AwardOther

cc
This commit is contained in:
vicrodh committed 2026-06-19 02:41:12 -06:00
1 parent c48c938bb9
commit 9ccfbd3845
12 files changed
+1933 -10

No files matched your search

+18 -6
View File
@@ -54,8 +54,10 @@ pub struct AlbumData {
/// Record label id, so the sidebar label card can navigate to the label
/// page ("" when unknown).
pub label_id: String,
/// Editorial award names, for the sidebar.
pub awards: Vec<String>,
/// Editorial awards for the sidebar, as `(id, name)` pairs. `id` may be
/// "" — some /album/get entries omit it; the award controller then
/// resolves it by name on click. Mirrors Tauri's `AlbumAward { id?, name }`.
pub awards: Vec<(String, String)>,
/// True when the album bundles a downloadable booklet/liner-notes PDF
/// (Qobuz goodies) — gates the header booklet button.
pub has_booklet: bool,
@@ -183,8 +185,8 @@ fn map_album(album: Album) -> AlbumData {
.as_deref()
.unwrap_or_default()
.iter()
.map(|a| a.name.clone())
.filter(|n| !n.is_empty())
.map(|a| (a.id.clone().unwrap_or_default(), a.name.clone()))
.filter(|(_, n)| !n.is_empty())
.collect();
// Booklet present when the album carries any goody with a usable URL.
let has_booklet = album
@@ -380,8 +382,18 @@ pub fn apply_album(window: &AppWindow, data: AlbumData) {
})
.collect();
let awards: Vec<slint::SharedString> =
data.awards.into_iter().map(Into::into).collect();
// Seed the award name->id resolver from this album's awards (the same
// harvesting Tauri's awardCatalogStore.rememberAwardsFromAlbums does), so
// a sidebar laurel whose id Qobuz omitted can still resolve on click.
crate::award::remember_awards(&data.awards);
let awards: Vec<crate::AwardEntry> = data
.awards
.into_iter()
.map(|(id, name)| crate::AwardEntry {
id: id.into(),
name: name.into(),
})
.collect();
let has_custom_cover = crate::custom_artwork::album_cover(&data.id).is_some();
let artwork_url = data.artwork_url.clone();
+19
View File
@@ -82,6 +82,11 @@ pub enum ArtworkTarget {
LabelArtist { index: usize },
/// A card in LabelState.more-labels[index] (landing).
LabelMoreLabel { index: usize },
/// A card in AwardState.albums[index] (landing preview grid AND the
/// full AwardAlbums listing — both source the `albums` model).
AwardAlbum { index: usize },
/// A card in AwardState.other-awards[index] (landing carousel).
AwardOther { index: usize },
/// A card in LocationViewState.artists[index].
LocationArtist { index: usize },
/// A row in FavoritesState.tracks[index].
@@ -852,6 +857,20 @@ fn apply_artwork(
model.set_row_data(index, item);
}
}
ArtworkTarget::AwardAlbum { index } => {
let model = window.global::<crate::AwardState>().get_albums();
if let Some(mut item) = model.row_data(index) {
item.artwork = image;
model.set_row_data(index, item);
}
}
ArtworkTarget::AwardOther { index } => {
let model = window.global::<crate::AwardState>().get_other_awards();
if let Some(mut item) = model.row_data(index) {
item.artwork = image;
model.set_row_data(index, item);
}
}
ArtworkTarget::LocationArtist { index } => {
let model = window.global::<crate::LocationViewState>().get_artists();
if let Some(mut item) = model.row_data(index) {
+639
View File
@@ -0,0 +1,639 @@
//! Award pages controller — the AwardView landing (hero + award-winning
//! releases preview + "Other awards" carousel + follow heart) and the
//! AwardAlbumsView listing (paginated album grid + client-side search).
//!
//! Mirrors Tauri's AwardView.svelte / AwardAlbumsView.svelte. Two hard
//! rules carried from the Tauri review:
//! * the album grid is ALWAYS sourced from `/award/getAlbums`, never
//! `/award/page.releases` (that endpoint is user-scoped and is used
//! only for the hero name/image/magazine);
//! * the favorite split is plural-read / singular-write — reads use
//! `get_favorites("awards", ..)`, writes use `add/remove_favorite("award", ..)`.
//!
//! The name->id resolver (`resolve_award_id_by_name`) replaces Tauri's
//! sessionStorage `awardCatalogStore`: a process-local normalized cache,
//! harvested from album awards as they load (`remember_awards`), with an
//! `/award/explore` crawl fallback.
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, Mutex, OnceLock};
use qbz_app::shell::AppRuntime;
use qbz_core::FrontendAdapter;
use serde_json::Value;
use slint::{ComponentHandle, Model, ModelRc, VecModel};
use crate::album_map::{map_album, to_item, AlbumCard};
use crate::artwork::{ArtworkJob, ArtworkTarget};
use crate::{AlbumCardItem, AppWindow, AwardState, SlimItem};
/// Landing preview grid page size (Tauri AwardView PAGE_SIZE).
pub const PREVIEW_PAGE_SIZE: u32 = 20;
/// Full-listing page size (Tauri AwardAlbumsView PAGE_SIZE).
pub const LIST_PAGE_SIZE: u32 = 50;
/// "Other awards" carousel size (Tauri AwardView loadOtherAwards limit).
const OTHER_AWARDS_LIMIT: u32 = 30;
/// /award/explore crawl page size + cap (Tauri awardCatalogStore).
const EXPLORE_PAGE_SIZE: u32 = 100;
const EXPLORE_MAX_PAGES: u32 = 40;
// ======================================================================
// Name -> id resolver (process-local, harvested + explore-crawl)
// ======================================================================
/// Normalized award-name -> stringified-id map. Seeded by `remember_awards`
/// (from album awards + explore crawl); read by `resolve_award_id_by_name`.
fn catalog() -> &'static Mutex<HashMap<String, String>> {
static CATALOG: OnceLock<Mutex<HashMap<String, String>>> = OnceLock::new();
CATALOG.get_or_init(|| Mutex::new(HashMap::new()))
}
/// Lowercase + trim + collapse-whitespace. Both the harvested names and the
/// to-resolve names come from the same Qobuz field, so this consistent
/// normalization is sufficient for self-matching (Tauri additionally strips
/// diacritics, which is moot here since both sides share the source string).
fn normalize(name: &str) -> String {
name.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
.to_lowercase()
}
/// Remember `(id, name)` award pairs (the harvesting Tauri's
/// `rememberAwardsFromAlbums` does). No-op for empty id/name. Called on the
/// UI thread from album/award applies — cheap, lock-guarded.
pub fn remember_awards(pairs: &[(String, String)]) {
if pairs.is_empty() {
return;
}
if let Ok(mut map) = catalog().lock() {
for (id, name) in pairs {
if id.is_empty() || name.is_empty() {
continue;
}
map.entry(normalize(name)).or_insert_with(|| id.clone());
}
}
}
fn lookup_cached(name: &str) -> Option<String> {
catalog()
.lock()
.ok()
.and_then(|m| m.get(&normalize(name)).cloned())
}
/// Resolve an award id from its name. Cache-first; on a miss, crawl
/// `/award/explore` (remembering every pair) until found or exhausted.
/// Returns `None` when unresolvable (the caller toasts awardUnavailable).
pub async fn resolve_award_id_by_name<A>(
runtime: &Arc<AppRuntime<A>>,
name: &str,
) -> Option<String>
where
A: FrontendAdapter + Send + Sync + 'static,
{
if name.trim().is_empty() {
return None;
}
if let Some(id) = lookup_cached(name) {
return Some(id);
}
let target = normalize(name);
let mut offset = 0u32;
let mut seen: HashSet<String> = HashSet::new();
for _ in 0..EXPLORE_MAX_PAGES {
let resp = match runtime
.core()
.get_award_explore(EXPLORE_PAGE_SIZE, offset)
.await
{
Ok(v) => v,
Err(e) => {
log::warn!("[qbz-slint] award explore crawl failed: {e}");
break;
}
};
let items = resp
.get("items")
.and_then(|v| v.as_array())
.cloned()
.unwrap_or_default();
if items.is_empty() {
break;
}
let mut new_ids = 0usize;
let mut found: Option<String> = None;
let pairs: Vec<(String, String)> = items
.iter()
.filter_map(|it| {
let id = it.get("id").map(value_to_string)?;
let nm = it.get("name").and_then(|v| v.as_str())?.to_string();
if id.is_empty() || nm.is_empty() {
return None;
}
if seen.insert(id.clone()) {
new_ids += 1;
}
if normalize(&nm) == target {
found = Some(id.clone());
}
Some((id, nm))
})
.collect();
remember_awards(&pairs);
if let Some(id) = found {
return Some(id);
}
let has_more = resp
.get("has_more")
.and_then(|v| v.as_bool())
.unwrap_or(false);
offset += items.len() as u32;
if !has_more || new_ids == 0 {
break;
}
}
log::warn!("[qbz-slint] award id unresolved for name: {name}");
None
}
// ======================================================================
// Landing page (AwardView)
// ======================================================================
#[derive(Clone)]
pub struct OtherAward {
pub id: String,
pub name: String,
pub magazine: String,
pub image_url: String,
}
pub struct AwardPagePayload {
pub id: String,
pub name: String,
pub image_url: String,
pub magazine_name: String,
pub is_following: bool,
pub albums: Vec<AlbumCard>,
pub total: usize,
pub has_more: bool,
/// True when the /award/getAlbums grid load failed (drives the
/// error+retry branch, distinct from a genuinely empty award).
pub albums_failed: bool,
pub other_awards: Vec<OtherAward>,
}
/// Fetch the award landing: hero (best-effort `/award/page`), the first
/// `/award/getAlbums` preview page, and the `/award/explore` other-awards
/// rail. The hero never blocks the grid (mirrors Tauri's independent loads).
pub async fn load_award_page<A>(
runtime: &Arc<AppRuntime<A>>,
award_id: &str,
fallback_name: &str,
) -> AwardPagePayload
where
A: FrontendAdapter + Send + Sync + 'static,
{
// Hero — best-effort; on failure fall back to the passed name + no image.
let (mut name, mut image_url, mut magazine_name) =
(fallback_name.to_string(), String::new(), String::new());
match runtime.core().get_award_page(award_id).await {
Ok(page) => {
if let Some(n) = page.name.filter(|s| !s.is_empty()) {
name = n;
}
image_url = page.image.unwrap_or_default();
if let Some(mag) = page.magazine {
if image_url.is_empty() {
image_url = mag.image.clone().unwrap_or_default();
}
magazine_name = mag.name.unwrap_or_default();
}
}
Err(e) => log::warn!("[qbz-slint] award page hero failed: {e}"),
}
// Album grid — ALWAYS from /award/getAlbums (never page.releases).
let (albums, total, has_more, albums_failed) =
match runtime.core().get_award_albums(award_id, PREVIEW_PAGE_SIZE, 0).await {
Ok(page) => {
let loaded = page.items.len();
let total = page.total as usize;
let albums: Vec<AlbumCard> = page.items.into_iter().map(map_album).collect();
// D2: trust the real has_more (total is the client's hint =
// loaded + has_more), so an exactly-full page still offers
// "See all" only when more genuinely remain.
(albums, total.max(loaded), total > loaded, false)
}
Err(e) => {
log::error!("[qbz-slint] award albums (preview) failed: {e}");
(Vec::new(), 0, false, true)
}
};
let other_awards = load_other_awards(runtime, award_id).await;
let is_following = crate::fav_cache::is_award_favorite(award_id);
AwardPagePayload {
id: award_id.to_string(),
name,
image_url,
magazine_name,
is_following,
albums,
total,
has_more,
albums_failed,
other_awards,
}
}
/// The "Other awards" rail — `/award/explore` minus the current award.
async fn load_other_awards<A>(
runtime: &Arc<AppRuntime<A>>,
current_id: &str,
) -> Vec<OtherAward>
where
A: FrontendAdapter + Send + Sync + 'static,
{
let resp = match runtime
.core()
.get_award_explore(OTHER_AWARDS_LIMIT, 0)
.await
{
Ok(v) => v,
Err(e) => {
log::warn!("[qbz-slint] award explore (other-awards) failed: {e}");
return Vec::new();
}
};
let items = resp
.get("items")
.and_then(|v| v.as_array())
.cloned()
.unwrap_or_default();
// Harvest the pairs while we're here (feeds the resolver).
let pairs: Vec<(String, String)> = items
.iter()
.filter_map(|it| {
let id = it.get("id").map(value_to_string)?;
let nm = it.get("name").and_then(|v| v.as_str())?.to_string();
(!id.is_empty() && !nm.is_empty()).then_some((id, nm))
})
.collect();
remember_awards(&pairs);
items
.iter()
.filter_map(|it| {
let id = it.get("id").map(value_to_string).filter(|s| !s.is_empty())?;
if id == current_id {
return None;
}
let name = it.get("name").and_then(|v| v.as_str())?.to_string();
if name.is_empty() {
return None;
}
let magazine = it
.get("magazine")
.and_then(|m| m.get("name"))
.and_then(|v| v.as_str())
.unwrap_or_default()
.to_string();
let image_url = it.get("image").map(parse_image_value).unwrap_or_default();
Some(OtherAward {
id,
name,
magazine,
image_url,
})
})
.collect()
}
fn other_to_item(o: &OtherAward) -> SlimItem {
SlimItem {
id: o.id.clone().into(),
title: o.name.clone().into(),
subtitle: o.magazine.clone().into(),
rank: "".into(),
artwork_url: o.image_url.clone().into(),
artwork: slint::Image::default(),
following: false,
}
}
/// Apply the landing payload to `AwardState`. Runs on the Slint event loop.
pub fn apply_award_page(window: &AppWindow, payload: AwardPagePayload) {
let albums: Vec<AlbumCardItem> = payload.albums.into_iter().map(to_item).collect();
let other: Vec<SlimItem> = payload.other_awards.iter().map(other_to_item).collect();
let state = window.global::<AwardState>();
state.set_id(payload.id.into());
state.set_name(payload.name.into());
state.set_image_url(payload.image_url.into());
state.set_magazine_name(payload.magazine_name.into());
state.set_is_following(payload.is_following);
state.set_following_toggling(false);
state.set_albums(ModelRc::new(VecModel::from(albums)));
state.set_total(payload.total as i32);
state.set_has_more(payload.has_more);
state.set_other_awards(ModelRc::new(VecModel::from(other)));
state.set_load_error(payload.albums_failed);
state.set_loading(false);
state.set_page_loaded(true);
}
/// Artwork jobs for the landing (preview grid covers + other-awards images).
pub fn page_artwork_jobs(payload: &AwardPagePayload) -> Vec<ArtworkJob> {
let mut jobs = Vec::new();
for (i, a) in payload.albums.iter().enumerate() {
if !a.artwork_url.is_empty() {
jobs.push(ArtworkJob {
url: a.artwork_url.clone(),
target: ArtworkTarget::AwardAlbum { index: i },
});
}
}
for (i, o) in payload.other_awards.iter().enumerate() {
if !o.image_url.is_empty() {
jobs.push(ArtworkJob {
url: o.image_url.clone(),
target: ArtworkTarget::AwardOther { index: i },
});
}
}
jobs
}
/// Apply the decoded award hero image. Runs on the Slint event loop.
pub fn apply_image(window: &AppWindow, pixels: &[u8], width: u32, height: u32) {
let mut buffer = slint::SharedPixelBuffer::<slint::Rgba8Pixel>::new(width, height);
let dst = buffer.make_mut_bytes();
if dst.len() != pixels.len() {
return;
}
dst.copy_from_slice(pixels);
window
.global::<AwardState>()
.set_image(slint::Image::from_rgba8(buffer));
}
/// Clear the landing state before loading a new award. Unlike Tauri's
/// effect reset, this also clears `other-awards` (D2) so an award->award
/// jump never flashes the previous award's carousel.
pub fn reset_award_page(window: &AppWindow) {
let state = window.global::<AwardState>();
state.set_name("".into());
state.set_image_url("".into());
state.set_image(slint::Image::default());
state.set_magazine_name("".into());
state.set_is_following(false);
state.set_following_toggling(false);
state.set_albums(ModelRc::new(VecModel::from(Vec::<AlbumCardItem>::new())));
state.set_visible(ModelRc::new(VecModel::from(Vec::<AlbumCardItem>::new())));
state.set_other_awards(ModelRc::new(VecModel::from(Vec::<SlimItem>::new())));
state.set_total(0);
state.set_has_more(false);
state.set_load_error(false);
state.set_loading(true);
state.set_load_more_loading(false);
state.set_page_loaded(false);
state.set_search_query("".into());
state.set_shown(0);
}
// ======================================================================
// Albums listing (AwardAlbumsView)
// ======================================================================
pub struct AwardAlbumsPayload {
pub id: String,
pub name: String,
pub albums: Vec<AlbumCard>,
pub total: usize,
pub has_more: bool,
}
/// Fetch the first full-listing page (`/award/getAlbums`, limit 50). The
/// listing has no hero — the kicker uses the passed fallback name (1:1 with
/// Tauri's AwardAlbumsView, which never calls /award/page).
pub async fn load_award_albums<A>(
runtime: &Arc<AppRuntime<A>>,
award_id: &str,
fallback_name: &str,
) -> Result<AwardAlbumsPayload, String>
where
A: FrontendAdapter + Send + Sync + 'static,
{
let page = runtime
.core()
.get_award_albums(award_id, LIST_PAGE_SIZE, 0)
.await
.map_err(|e| e.to_string())?;
let loaded = page.items.len();
let total = page.total as usize;
let albums = page.items.into_iter().map(map_album).collect();
Ok(AwardAlbumsPayload {
id: award_id.to_string(),
name: fallback_name.to_string(),
albums,
total: total.max(loaded),
has_more: total > loaded,
})
}
/// Fetch one more listing page for load-more.
pub async fn load_more_award_albums<A>(
runtime: &Arc<AppRuntime<A>>,
award_id: &str,
offset: u32,
) -> Result<(Vec<AlbumCard>, usize, bool), String>
where
A: FrontendAdapter + Send + Sync + 'static,
{
let page = runtime
.core()
.get_award_albums(award_id, LIST_PAGE_SIZE, offset)
.await
.map_err(|e| e.to_string())?;
let loaded = offset as usize + page.items.len();
let total = page.total as usize;
let albums = page.items.into_iter().map(map_album).collect();
Ok((albums, total.max(loaded), total > loaded))
}
/// Apply the first listing page to `AwardState`.
pub fn apply_award_albums(window: &AppWindow, payload: AwardAlbumsPayload) {
let items: Vec<AlbumCardItem> = payload.albums.into_iter().map(to_item).collect();
let state = window.global::<AwardState>();
state.set_id(payload.id.into());
state.set_name(payload.name.into());
state.set_albums(ModelRc::new(VecModel::from(items)));
state.set_total(payload.total as i32);
state.set_has_more(payload.has_more);
state.set_load_error(false);
state.set_loading(false);
derive_award_albums(window);
}
/// Append the next listing page (load-more).
pub fn append_award_albums(
window: &AppWindow,
albums: Vec<AlbumCard>,
total: usize,
has_more: bool,
) {
let state = window.global::<AwardState>();
let model = state.get_albums();
let mut combined: Vec<AlbumCardItem> = (0..model.row_count())
.filter_map(|i| model.row_data(i))
.collect();
combined.extend(albums.into_iter().map(to_item));
state.set_albums(ModelRc::new(VecModel::from(combined)));
state.set_total(total as i32);
state.set_has_more(has_more);
state.set_load_more_loading(false);
derive_award_albums(window);
}
/// Re-derive the listing's rendered `visible` model from the loaded catalog
/// + the search query (client-side title/artist filter). The no-search fast
/// path shares the `albums` model so artwork keeps updating in place.
pub fn derive_award_albums(window: &AppWindow) {
let state = window.global::<AwardState>();
let albums = state.get_albums();
let query_owned = state.get_search_query().to_lowercase();
let query = query_owned.trim();
if query.is_empty() {
state.set_visible(albums.clone());
state.set_shown(albums.row_count() as i32);
return;
}
let filtered: Vec<AlbumCardItem> = (0..albums.row_count())
.filter_map(|i| albums.row_data(i))
.filter(|a| {
a.title.to_lowercase().contains(query) || a.artist.to_lowercase().contains(query)
})
.collect();
let shown = filtered.len();
state.set_visible(ModelRc::new(VecModel::from(filtered)));
state.set_shown(shown as i32);
}
/// Artwork jobs for the listing grid (AwardState.albums).
pub fn albums_artwork_jobs(albums: &[AlbumCard], offset: usize) -> Vec<ArtworkJob> {
albums
.iter()
.enumerate()
.filter(|(_, a)| !a.artwork_url.is_empty())
.map(|(i, a)| ArtworkJob {
url: a.artwork_url.clone(),
target: ArtworkTarget::AwardAlbum { index: offset + i },
})
.collect()
}
/// Clear the listing state before loading a new award's albums.
pub fn reset_award_albums(window: &AppWindow) {
let state = window.global::<AwardState>();
state.set_name("".into());
state.set_albums(ModelRc::new(VecModel::from(Vec::<AlbumCardItem>::new())));
state.set_visible(ModelRc::new(VecModel::from(Vec::<AlbumCardItem>::new())));
state.set_total(0);
state.set_has_more(false);
state.set_load_error(false);
state.set_loading(true);
state.set_load_more_loading(false);
state.set_search_query("".into());
state.set_shown(0);
}
// ======================================================================
// Follow heart helpers
// ======================================================================
/// The user's followed-award ids from the network (`/favorite/getUserFavorites`
/// type=awards — the PLURAL read). Best-effort: an error yields an empty set.
/// Seeds `fav_cache` at login so the AwardView heart is correct on first open.
pub async fn favorite_award_ids<A>(runtime: &Arc<AppRuntime<A>>) -> HashSet<String>
where
A: FrontendAdapter + Send + Sync + 'static,
{
match runtime.core().get_favorites("awards", 500, 0).await {
Ok(v) => v
.get("awards")
.and_then(|a| a.get("items"))
.and_then(|i| i.as_array())
.map(|arr| {
arr.iter()
.filter_map(|it| it.get("id").map(value_to_string))
.filter(|s| !s.is_empty())
.collect()
})
.unwrap_or_default(),
Err(_) => HashSet::new(),
}
}
/// Current follow state for `award_id` — the header when it's the open
/// award, else the cache.
pub fn following_state(window: &AppWindow, award_id: &str) -> bool {
let state = window.global::<AwardState>();
if state.get_id().as_str() == award_id {
return state.get_is_following();
}
crate::fav_cache::is_award_favorite(award_id)
}
/// Optimistically reflect a follow toggle on the header (when it's the open
/// award) and set the toggling flag.
pub fn mark_following(window: &AppWindow, award_id: &str, following: bool, toggling: bool) {
let state = window.global::<AwardState>();
if state.get_id().as_str() == award_id {
state.set_is_following(following);
state.set_following_toggling(toggling);
}
}
/// Name of an "Other awards" card by id (nav-history fallback for a click).
pub fn other_award_name(window: &AppWindow, award_id: &str) -> String {
let model = window.global::<AwardState>().get_other_awards();
for i in 0..model.row_count() {
if let Some(item) = model.row_data(i) {
if item.id.as_str() == award_id {
return item.title.to_string();
}
}
}
String::new()
}
// ======================================================================
// Value helpers
// ======================================================================
/// String for an id-ish Value (string verbatim, number stringified).
fn value_to_string(v: &Value) -> String {
match v {
Value::String(s) => s.clone(),
Value::Number(n) => n.to_string(),
_ => String::new(),
}
}
/// Best URL out of an award/magazine `image` Value (string or object).
fn parse_image_value(v: &Value) -> String {
if let Some(s) = v.as_str() {
return s.to_string();
}
for key in ["large", "extralarge", "mega", "medium", "thumbnail", "small"] {
if let Some(s) = v.get(key).and_then(|x| x.as_str()) {
return s.to_string();
}
}
String::new()
}
+76
View File
@@ -28,6 +28,14 @@ static FAVORITES: LazyLock<RwLock<HashSet<u64>>> =
static FAV_ALBUMS: LazyLock<RwLock<HashSet<String>>> =
LazyLock::new(|| RwLock::new(HashSet::new()));
/// Process-wide set of the user's followed AWARD ids (string ids — Qobuz
/// types them inconsistently, stored TEXT). Same disk-first + network-refresh
/// lifecycle as the album set, so the AwardView follow heart renders the
/// right state from first paint and stays live across toggles. Mirrors
/// Tauri's `awardFavoritesStore`.
static FAV_AWARDS: 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);
@@ -74,6 +82,19 @@ pub fn init_for_user(base_dir: &Path) {
}
Err(e) => log::warn!("[qbz-slint] favorites cache album disk seed failed: {e}"),
}
match store.get_favorite_award_ids() {
Ok(ids) => {
let set: HashSet<String> = ids.into_iter().collect();
log::info!(
"[qbz-slint] favorites cache: {} award ids seeded from disk",
set.len()
);
if let Ok(mut guard) = FAV_AWARDS.write() {
*guard = set;
}
}
Err(e) => log::warn!("[qbz-slint] favorites cache award disk seed failed: {e}"),
}
if let Ok(mut guard) = STORE.lock() {
*guard = Some(store);
}
@@ -90,6 +111,9 @@ pub fn teardown() {
if let Ok(mut guard) = FAV_ALBUMS.write() {
guard.clear();
}
if let Ok(mut guard) = FAV_AWARDS.write() {
guard.clear();
}
}
/// Replace the cache with a freshly-fetched set and mirror it to the
@@ -210,3 +234,55 @@ pub fn set_album(album_id: &str, favorite: bool) {
}
}
}
// ==================== Followed awards ====================
/// True when the award id is in the user's followed-award set.
pub fn is_award_favorite(award_id: &str) -> bool {
FAV_AWARDS
.read()
.map(|g| g.contains(award_id))
.unwrap_or(false)
}
/// Replace the followed-award set with a freshly-fetched id list and mirror
/// it to the per-user store (full replace — Tauri's
/// `v2_sync_cached_favorite_awards`). Blocking disk write; call off the UI
/// thread.
pub fn set_all_awards(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_awards(&disk) {
log::warn!("[qbz-slint] favorites cache award sync failed: {e}");
}
}
}
if let Ok(mut guard) = FAV_AWARDS.write() {
*guard = ids;
}
}
/// Insert / remove a single award id (optimistic toggle) and mirror the
/// change to the per-user store so the follow survives a restart.
pub fn set_award(award_id: &str, favorite: bool) {
if let Ok(mut guard) = FAV_AWARDS.write() {
if favorite {
guard.insert(award_id.to_string());
} else {
guard.remove(award_id);
}
}
if let Ok(guard) = STORE.lock() {
if let Some(store) = guard.as_ref() {
let res = if favorite {
store.add_favorite_award(award_id)
} else {
store.remove_favorite_award(award_id)
};
if let Err(e) = res {
log::warn!("[qbz-slint] favorites cache award disk update failed: {e}");
}
}
}
}
+369
View File
@@ -21,6 +21,7 @@ mod artist;
mod artist_blacklist;
mod artwork;
mod auth;
mod award;
mod blacklist_manager;
mod commands;
mod custom_artwork;
@@ -336,6 +337,19 @@ async fn enter_shell(
});
}
// Same for followed AWARDS — seeds fav_cache so the AwardView follow heart
// is correct from first open (Tauri's loadAwardFavorites, plural read).
{
let runtime = runtime.clone();
tokio::spawn(async move {
if crate::offline_mode::engine().is_offline() {
return;
}
let ids = award::favorite_award_ids(&runtime).await;
let _ = tokio::task::spawn_blocking(move || fav_cache::set_all_awards(ids)).await;
});
}
// Load Audio + Playback settings into the Settings page in the
// background — store reads and device enumeration are blocking.
spawn_settings_snapshot_load(runtime.clone(), weak.clone(), settings_ctx.clone());
@@ -1290,6 +1304,8 @@ fn scope_for(entry: &nav::NavEntry) -> String {
nav::NavEntry::Musician { .. } => "musician".into(),
nav::NavEntry::Label { .. } => "label".into(),
nav::NavEntry::LabelReleases { .. } => "label-releases".into(),
nav::NavEntry::Award { .. } => "award".into(),
nav::NavEntry::AwardAlbums { .. } => "award-albums".into(),
nav::NavEntry::Location { .. } => "location".into(),
}
}
@@ -1396,6 +1412,19 @@ fn apply_entry(
name,
);
}
nav::NavEntry::Award { id, name } => {
navigate_award(runtime.clone(), weak.clone(), handle, image_cache.clone(), id, name);
}
nav::NavEntry::AwardAlbums { id, name } => {
navigate_award_albums(
runtime.clone(),
weak.clone(),
handle,
image_cache.clone(),
id,
name,
);
}
nav::NavEntry::DiscoverBrowse { endpoint, title } => {
discover_browse::navigate(
runtime.clone(),
@@ -1612,6 +1641,75 @@ fn navigate_label_releases(
});
}
/// Open the AwardView landing for `award_id`: hero + first /award/getAlbums
/// preview page + other-awards rail, then the header image.
fn navigate_award(
runtime: Arc<AppRuntime<SlintAdapter>>,
weak: slint::Weak<AppWindow>,
handle: &tokio::runtime::Handle,
image_cache: artwork::ImageCache,
award_id: String,
name: String,
) {
handle.spawn(async move {
let _ = weak.upgrade_in_event_loop(|w| {
award::reset_award_page(&w);
w.global::<NavState>().set_view(ContentView::Award);
});
let payload = award::load_award_page(&runtime, &award_id, &name).await;
let jobs = award::page_artwork_jobs(&payload);
let image_url = payload.image_url.clone();
let _ = weak.upgrade_in_event_loop(move |w| {
award::apply_award_page(&w, payload);
});
artwork::spawn_loads(jobs, weak.clone(), image_cache.clone());
if !image_url.is_empty() {
if let Some((pixels, width, height)) =
artwork::fetch_and_decode(&image_url, &image_cache, 240).await
{
let _ = weak.upgrade_in_event_loop(move |w| {
award::apply_image(&w, &pixels, width, height);
});
}
}
});
}
/// Open the full AwardAlbumsView listing for `award_id` (paginated grid +
/// client-side search). No hero — the kicker uses the passed name (1:1 Tauri).
fn navigate_award_albums(
runtime: Arc<AppRuntime<SlintAdapter>>,
weak: slint::Weak<AppWindow>,
handle: &tokio::runtime::Handle,
image_cache: artwork::ImageCache,
award_id: String,
name: String,
) {
handle.spawn(async move {
let _ = weak.upgrade_in_event_loop(|w| {
award::reset_award_albums(&w);
w.global::<NavState>().set_view(ContentView::AwardAlbums);
});
match award::load_award_albums(&runtime, &award_id, &name).await {
Ok(payload) => {
let jobs = award::albums_artwork_jobs(&payload.albums, 0);
let _ = weak.upgrade_in_event_loop(move |w| {
award::apply_award_albums(&w, payload);
});
artwork::spawn_loads(jobs, weak.clone(), image_cache.clone());
}
Err(e) => {
log::error!("[qbz-slint] award albums load failed: {e}");
let _ = weak.upgrade_in_event_loop(|w| {
let s = w.global::<AwardState>();
s.set_loading(false);
s.set_load_error(true);
});
}
}
});
}
/// Open Library > Favorites on `tab` and lazy-load that tab's data.
/// Switching the active tab also routes here so each tab fetches on
/// first view (Tauri's loadTabIfNeeded).
@@ -6028,6 +6126,64 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
update_nav_flags(&w);
}
}
// Album sidebar laurel (id present) -> open the award page.
("award", "open") => {
if !id.is_empty() {
let name = weak
.upgrade()
.map(|w| award::other_award_name(&w, &id))
.unwrap_or_default();
nav::record(nav::NavEntry::Award {
id: id.clone(),
name: name.clone(),
});
navigate_award(
runtime.clone(),
weak.clone(),
&handle,
image_cache.clone(),
id.clone(),
name,
);
if let Some(w) = weak.upgrade() {
update_nav_flags(&w);
}
}
}
// Album sidebar laurel WITHOUT an id -> `id` carries the award
// NAME; resolve it to an id (cache / explore crawl) then open,
// or toast awardUnavailable on a miss (1:1 Tauri handleAwardClick).
("award", "resolve-open") => {
let name = id.clone();
let runtime = runtime.clone();
let weak = weak.clone();
let image_cache = image_cache.clone();
let handle_inner = handle.clone();
handle.spawn(async move {
match award::resolve_award_id_by_name(&runtime, &name).await {
Some(award_id) => {
let runtime2 = runtime.clone();
let ic = image_cache.clone();
let h = handle_inner.clone();
let name2 = name.clone();
let _ = weak.upgrade_in_event_loop(move |w| {
nav::record(nav::NavEntry::Award {
id: award_id.clone(),
name: name2.clone(),
});
navigate_award(runtime2, w.as_weak(), &h, ic, award_id, name2);
update_nav_flags(&w);
});
}
None => {
crate::toast::info_weak(
&weak,
"Award detail not available for this entry.",
);
}
}
});
}
("track", "toggle-select") => {
// Flip `selected` on the matching row, in whichever
// multi-select surface is showing: the playlist detail,
@@ -7922,6 +8078,219 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
});
}
// Award pages actions (AwardView landing + AwardAlbumsView listing).
{
// Header follow heart — optimistic flip + three-state toggling, then
// the API write (singular favType "award") + local cache mirror. On
// error, revert. skip_if_remote: a remote Qobuz Connect session must
// not fire favorite I/O while controlling another device.
let runtime = app_runtime.clone();
let weak = window.as_weak();
let handle = tokio_rt.handle().clone();
window
.global::<AwardActions>()
.on_toggle_follow(move |award_id| {
let award_id = award_id.to_string();
if award_id.is_empty() {
return;
}
let runtime = runtime.clone();
let weak = weak.clone();
handle.spawn(async move {
// skip-if-remote: never fire favorite I/O while a remote
// QConnect renderer is being controlled (Tauri's skipIfRemote).
if let Some(svc) = crate::qconnect_service::service() {
if svc.is_peer_active().await {
return;
}
}
// Committed state is the local cache (mirrored on success).
// The heart is disabled while toggling, so no double-toggle.
let make = !crate::fav_cache::is_award_favorite(&award_id);
{
let award_id = award_id.clone();
let _ = weak.upgrade_in_event_loop(move |w| {
award::mark_following(&w, &award_id, make, true);
});
}
// Write API first (singular "award" -> award_ids), then
// mirror the local cache, then clear the toggling flag.
let res = if make {
runtime.core().add_favorite("award", &award_id).await
} else {
runtime.core().remove_favorite("award", &award_id).await
};
match res {
Ok(_) => {
crate::fav_cache::set_award(&award_id, make);
let _ = weak.upgrade_in_event_loop(move |w| {
award::mark_following(&w, &award_id, make, false);
});
}
Err(e) => {
log::error!("[qbz-slint] toggle award favorite failed: {e}");
let _ = weak.upgrade_in_event_loop(move |w| {
award::mark_following(&w, &award_id, !make, false);
});
}
}
});
});
}
{
// Landing "See all" -> the full albums listing for the open award.
let runtime = app_runtime.clone();
let weak = window.as_weak();
let handle = tokio_rt.handle().clone();
let image_cache = image_cache.clone();
window.global::<AwardActions>().on_open_albums(move || {
let Some(w) = weak.upgrade() else {
return;
};
let state = w.global::<AwardState>();
let id = state.get_id().to_string();
let name = state.get_name().to_string();
if id.is_empty() {
return;
}
nav::record(nav::NavEntry::AwardAlbums {
id: id.clone(),
name: name.clone(),
});
navigate_award_albums(
runtime.clone(),
weak.clone(),
&handle,
image_cache.clone(),
id,
name,
);
update_nav_flags(&w);
});
}
{
// "Other awards" card -> open that award's landing.
let runtime = app_runtime.clone();
let weak = window.as_weak();
let handle = tokio_rt.handle().clone();
let image_cache = image_cache.clone();
window
.global::<AwardActions>()
.on_open_award(move |award_id, name| {
let award_id = award_id.to_string();
let mut name = name.to_string();
if award_id.is_empty() {
return;
}
// The other-awards carousel emits only the id; recover the
// name from the card for a good history/back-forward label.
if name.is_empty() {
if let Some(w) = weak.upgrade() {
name = award::other_award_name(&w, &award_id);
}
}
nav::record(nav::NavEntry::Award {
id: award_id.clone(),
name: name.clone(),
});
navigate_award(
runtime.clone(),
weak.clone(),
&handle,
image_cache.clone(),
award_id,
name,
);
if let Some(w) = weak.upgrade() {
update_nav_flags(&w);
}
});
}
{
// AwardAlbumsView load-more — append the next /award/getAlbums page.
let runtime = app_runtime.clone();
let weak = window.as_weak();
let handle = tokio_rt.handle().clone();
let image_cache = image_cache.clone();
window.global::<AwardActions>().on_load_more(move || {
let Some(w) = weak.upgrade() else {
return;
};
let state = w.global::<AwardState>();
let award_id = state.get_id().to_string();
if award_id.is_empty() {
return;
}
let offset = state.get_albums().row_count() as u32;
state.set_load_more_loading(true);
let runtime = runtime.clone();
let weak = weak.clone();
let image_cache = image_cache.clone();
handle.spawn(async move {
match award::load_more_award_albums(&runtime, &award_id, offset).await {
Ok((data, total, has_more)) => {
let jobs = award::albums_artwork_jobs(&data, offset as usize);
let _ = weak.upgrade_in_event_loop(move |w| {
award::append_award_albums(&w, data, total, has_more);
});
artwork::spawn_loads(jobs, weak, image_cache);
}
Err(e) => {
log::error!("[qbz-slint] award load-more failed: {e}");
let _ = weak.upgrade_in_event_loop(|w| {
w.global::<AwardState>().set_load_more_loading(false);
});
}
}
});
});
}
{
// AwardAlbumsView client-side search — re-derive `visible` (UI thread).
let weak = window.as_weak();
window.global::<AwardActions>().on_search(move |_| {
if let Some(w) = weak.upgrade() {
award::derive_award_albums(&w);
}
});
}
{
// Error branch retry — reload whichever award surface is showing.
let runtime = app_runtime.clone();
let weak = window.as_weak();
let handle = tokio_rt.handle().clone();
let image_cache = image_cache.clone();
window.global::<AwardActions>().on_retry(move || {
let Some(w) = weak.upgrade() else {
return;
};
let state = w.global::<AwardState>();
let id = state.get_id().to_string();
let name = state.get_name().to_string();
if id.is_empty() {
return;
}
match w.global::<NavState>().get_view() {
ContentView::AwardAlbums => navigate_award_albums(
runtime.clone(),
weak.clone(),
&handle,
image_cache.clone(),
id,
name,
),
_ => navigate_award(
runtime.clone(),
weak.clone(),
&handle,
image_cache.clone(),
id,
name,
),
}
});
}
// Artist Blacklist Manager actions (Task 11). Mutations are synchronous
// (in-memory set + single SQLite ops via the artist_blacklist wrapper), so
// no tokio handle is needed; each callback runs on the event-loop thread.
+15
View File
@@ -112,6 +112,21 @@ pub enum NavEntry {
id: u64,
name: String,
},
/// AwardView landing — the award detail page (hero + award-winning
/// releases preview + "Other awards" carousel + follow heart). Reached
/// from an album's sidebar laurel or another award's "Other awards"
/// card. Carries the award id (string — Qobuz types it inconsistently)
/// + name fallback (history restores the id only; name is best-effort).
Award {
id: String,
name: String,
},
/// AwardAlbumsView — the "See all" paginated listing reached from the
/// AwardView landing. Carries the award id + name fallback.
AwardAlbums {
id: String,
name: String,
},
/// ArtistsByLocationView — opened by the Origin section's
/// location link. Carries the full scene-discovery payload.
Location {