//! Application state. Lives on the UI thread; background work reports back //! through `slint::invoke_from_event_loop` + `with_app`. use std::cell::RefCell; use std::collections::{HashMap, HashSet}; use std::future::Future; use std::num::NonZeroUsize; use std::path::PathBuf; use std::rc::Rc; use std::sync::Arc; use std::time::{Duration, Instant}; use anyhow::Result; use lru::LruCache; use slint::{Color, ComponentHandle, Image, ModelRc, Rgb8Pixel, SharedPixelBuffer, SharedString, Timer, VecModel}; use tokio::runtime::Handle; use tokio::sync::Semaphore; use crate::config::{self, Config, Settings}; use crate::palette::{Lab, Palette, Role, Tone}; use crate::player::{Player, PlayerEvent}; use crate::prompts::{self, Control, Family, Prompts}; use crate::subsonic::{self, Album, Artist, Client, Playlist, SearchResult, Song}; use crate::{Action, AppWindow, Area, Header, Hint, Item, Screen, Theme}; thread_local! { static APP: RefCell> = const { RefCell::new(None) }; } /// Runs `f` against the app. If the app is already borrowed (a callback fired /// while we were updating the UI), retries on the next event loop turn. pub fn with_app(f: impl FnOnce(&mut App) + 'static) { APP.with(|cell| match cell.try_borrow_mut() { Ok(mut guard) => { if let Some(app) = guard.as_mut() { f(app); } } Err(_) => Timer::single_shot(Duration::ZERO, move || with_app(f)), }); } pub fn install(ui: &AppWindow, rt: Handle) { let app = App::new(ui.clone_strong(), rt); APP.with(|cell| *cell.borrow_mut() = Some(app)); ui.on_action(|a| with_app(move |app| app.key_action(a))); ui.on_item_clicked(|i| with_app(move |app| app.item_clicked(i.max(0) as usize))); ui.on_wheel(|d| with_app(move |app| app.wheel(d))); ui.on_sidebar_clicked(|i| with_app(move |app| app.sidebar_clicked(i.max(0) as usize))); ui.on_queue_clicked(|i| with_app(move |app| app.queue_clicked(i.max(0) as usize))); ui.on_queue_wheel(|d| with_app(move |app| app.move_queue_sel(-d as isize * 3))); ui.on_search_accepted(|q| with_app(move |app| app.run_search(q.to_string()))); ui.on_login_submit(|| with_app(|app| app.login_submit())); ui.on_login_field_clicked(|i| with_app(move |app| app.set_login_focus(i))); ui.on_layout_changed(|| with_app(|app| app.sync_items(true))); with_app(|app| app.start()); } /// Drops the app, which stops playback. pub fn shutdown() { let app = APP.with(|cell| cell.borrow_mut().take()); drop(app); } #[derive(Clone, Copy, PartialEq, Eq, Debug)] enum Section { Recent, Random, Albums, Artists, Playlists, Search, Settings, } const SECTIONS: [Section; 7] = [ Section::Recent, Section::Random, Section::Albums, Section::Artists, Section::Playlists, Section::Search, Section::Settings, ]; impl Section { fn label(self) -> &'static str { match self { Section::Recent => "Recently added", Section::Random => "Random", Section::Albums => "Albums", Section::Artists => "Artists", Section::Playlists => "Playlists", Section::Search => "Search", Section::Settings => "Settings", } } } #[derive(Clone, Debug)] enum Target { Album(String), Artist(String), Playlist(String), /// Index into the page's `songs`. Song(usize), Setting(Setting), } #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Setting { AlbumArtColours, } /// How long the UI takes to change from one palette to the next. const FADE: Duration = Duration::from_millis(800); /// The palette on screen and the one it is fading towards. struct Fade { from: Palette, to: Palette, shown: Palette, started: Instant, timer: Timer, } #[derive(Clone, Debug)] struct Entry { title: String, subtitle: String, detail: String, number: String, cover: Option, round: bool, show_art: bool, target: Target, } #[derive(Clone, Debug, Default)] struct HeaderInfo { kind: &'static str, title: String, subtitle: String, info: String, cover: Option, round: bool, } #[derive(Clone, Debug)] enum Source { Section(Section), Album(String), Artist(String), Playlist(String), Search(String), } /// What a load returns, applied to the page that asked for it. #[derive(Default)] struct PageData { entries: Vec, songs: Vec, header: Option, } struct Page { id: u64, title: String, list: bool, header: Option, entries: Vec, songs: Vec, sel: usize, loading: bool, error: Option, /// Automatic retries after a failed load, for the backoff. retries: u32, source: Source, } type CoverKey = (String, u32); struct Covers { images: LruCache, /// Per cover id, whatever size it was decoded at. None for a cover with /// too little colour to base a palette on. tones: LruCache>, pending: HashSet, failed: HashSet, limit: Arc, dir: Option, } pub struct App { ui: AppWindow, rt: Handle, client: Option, player: Option, screen: Screen, area: Area, section: usize, stacks: Vec>, next_id: u64, items: Rc>, items_range: (usize, usize), queue_items: Rc>, queue_range: (usize, usize), covers: Covers, queue: Vec, current: Option, queue_sel: usize, position: f64, duration: f64, paused: bool, scrobbled: bool, login_focus: i32, toast_timer: Timer, /// Keyboard keys or the buttons of the controller used last. prompts: Prompts, /// Decoded hint icons, so a selection move does not parse SVG again. icons: RefCell>>, settings: Settings, fade: Fade, } impl App { fn new(ui: AppWindow, rt: Handle) -> App { let items = Rc::new(VecModel::default()); let queue_items = Rc::new(VecModel::default()); ui.set_items(ModelRc::from(items.clone())); ui.set_queue_items(ModelRc::from(queue_items.clone())); let dir = config::cache_dir().map(|d| d.join("covers")); if let Some(d) = &dir && let Err(e) = std::fs::create_dir_all(d) { log::warn!("cover cache disabled, cannot create {}: {e}", d.display()); } App { ui, rt, client: None, player: None, screen: Screen::Login, area: Area::Content, section: 0, stacks: SECTIONS.iter().map(|_| Vec::new()).collect(), next_id: 1, items, items_range: (0, 0), queue_items, queue_range: (0, 0), covers: Covers { images: LruCache::new(NonZeroUsize::new(400).unwrap()), tones: LruCache::new(NonZeroUsize::new(400).unwrap()), pending: HashSet::new(), failed: HashSet::new(), limit: Arc::new(Semaphore::new(6)), dir, }, queue: Vec::new(), current: None, queue_sel: 0, position: 0.0, duration: 0.0, paused: false, scrobbled: false, login_focus: 0, toast_timer: Timer::default(), prompts: Prompts::Keyboard, icons: RefCell::default(), settings: config::load_settings(), fade: Fade { from: Palette::brand(), to: Palette::brand(), shown: Palette::brand(), started: Instant::now(), timer: Timer::default(), }, } } fn start(&mut self) { let labels: Vec = SECTIONS.iter().map(|s| s.label().into()).collect(); self.ui.set_sections(ModelRc::new(VecModel::from(labels))); match Player::spawn(|ev| { let _ = slint::invoke_from_event_loop(move || with_app(move |app| app.player_event(ev))); }) { Ok(p) => self.player = Some(p), Err(e) => { log::error!("{e:#}"); self.toast(format!("Playback unavailable: {e:#}")); } } match config::load() { Ok(Some(cfg)) => { log::info!("using saved login for {} on {}", cfg.username, cfg.url); self.ui.set_login_server(cfg.url.clone().into()); self.ui.set_login_username(cfg.username.clone().into()); self.enter_browse(cfg.client()); } Ok(None) => { log::info!("no saved login, showing the login screen"); self.show_login(); } Err(e) => { log::error!("could not read the saved login: {e:#}"); self.ui.set_login_error(format!("{e:#}").into()); self.show_login(); } } self.render_player(); } fn spawn(&self, fut: F, done: D) where T: Send + 'static, F: Future> + Send + 'static, D: FnOnce(&mut App, Result) + Send + 'static, { self.rt.spawn(async move { let r = fut.await; let _ = slint::invoke_from_event_loop(move || with_app(move |app| done(app, r))); }); } // ---------------------------------------------------------------- login fn show_login(&mut self) { self.screen = Screen::Login; self.ui.set_screen(Screen::Login); self.set_login_focus(0); } fn set_login_focus(&mut self, i: i32) { self.login_focus = i.clamp(0, 3); self.ui.set_login_focus(self.login_focus); self.ui.invoke_focus_login(self.login_focus); self.render_hints(); } fn login_action(&mut self, a: Action) { match a { Action::Up | Action::SectionPrev => self.set_login_focus(self.login_focus - 1), Action::Down | Action::SectionNext => self.set_login_focus(self.login_focus + 1), Action::Activate if self.login_focus < 2 => self.set_login_focus(self.login_focus + 1), Action::Activate => self.login_submit(), _ => {} } } /// Fills in the login form and submits it, for scripted runs. pub fn dev_login(&mut self, url: &str, user: &str, password: &str) { self.ui.set_login_server(url.into()); self.ui.set_login_username(user.into()); self.ui.set_login_password(password.into()); self.login_submit(); } fn login_submit(&mut self) { if self.ui.get_login_busy() { return; } let url = self.ui.get_login_server().trim().to_string(); let user = self.ui.get_login_username().trim().to_string(); let password = self.ui.get_login_password().to_string(); if url.is_empty() || user.is_empty() { self.ui.set_login_error("Enter a server address and a username.".into()); return; } self.ui.set_login_error("".into()); self.ui.set_login_busy(true); self.spawn( async move { Client::login(&url, &user, &password).await }, move |app, r| { app.ui.set_login_busy(false); match r { Ok(client) => { app.ui.set_login_password("".into()); if let Err(e) = config::save(&Config::from_client(&client)) { app.toast(format!("Could not save settings: {e:#}")); } app.enter_browse(client); } Err(e) => app.ui.set_login_error(login_error(&e).into()), } }, ); } fn enter_browse(&mut self, client: Client) { let host = client.base().split("://").nth(1).unwrap_or(client.base()).to_string(); self.ui .set_server_label(format!("{} on {}", client.user(), host).into()); self.client = Some(client); self.covers.images.clear(); self.covers.tones.clear(); self.covers.pending.clear(); self.covers.failed.clear(); for stack in &mut self.stacks { stack.clear(); } self.screen = Screen::Browse; self.ui.set_screen(Screen::Browse); self.section = usize::MAX; self.select_section(0); self.set_area(Area::Content); } // ---------------------------------------------------------------- input /// A key pressed in the window. pub fn key_action(&mut self, a: Action) { self.set_prompts(Prompts::Keyboard); self.action(a); } /// A button pressed on a controller of this family. pub fn pad_action(&mut self, a: Action, family: Family) { self.set_prompts(Prompts::Pad(family)); self.action(a); } /// A controller connected (its family) or the last one disconnected. pub fn pad_present(&mut self, family: Option) { self.set_prompts(family.map_or(Prompts::Keyboard, Prompts::Pad)); } fn set_prompts(&mut self, prompts: Prompts) { if prompts != self.prompts { self.prompts = prompts; self.render_hints(); } } pub fn action(&mut self, a: Action) { match a { Action::Quit => { let _ = slint::quit_event_loop(); return; } Action::ToggleFullscreen => { let w = self.ui.window(); w.set_fullscreen(!w.is_fullscreen()); return; } _ => {} } match self.screen { Screen::Login => self.login_action(a), Screen::Browse => self.browse_action(a), Screen::NowPlaying => self.now_playing_action(a), } } /// Playback and screen-switching actions that work the same everywhere /// once logged in. Returns whether `a` was one of them. fn global_action(&mut self, a: Action) -> bool { match a { Action::PlayPause => { if self.current.is_none() { self.toast("Nothing is playing".into()); } else if let Some(p) = &self.player { p.toggle_pause(); } } Action::Next => { if let Some(p) = &self.player { p.next(); } } Action::Prev => { if let Some(p) = &self.player { p.prev(); } } Action::SeekForward => self.seek(10.0), Action::SeekBack => self.seek(-10.0), Action::NowPlaying => { if self.screen == Screen::NowPlaying { self.close_now_playing(); } else { self.open_now_playing(); } } Action::Search => self.open_search(), _ => return false, } true } fn seek(&self, seconds: f64) { if self.current.is_some() && let Some(p) = &self.player { p.seek(seconds); } } fn browse_action(&mut self, a: Action) { if self.global_action(a) { return; } match self.area { Area::Sidebar => match a { Action::Up | Action::SectionPrev => self.select_section(self.section.saturating_sub(1)), Action::Down | Action::SectionNext => self.select_section((self.section + 1).min(SECTIONS.len() - 1)), Action::Activate if SECTIONS[self.section] == Section::Random => { self.reload_root(); self.enter_content(); } Action::Right | Action::Activate => self.enter_content(), _ => {} }, Area::Content => match a { Action::Up | Action::Down | Action::Left | Action::Right | Action::PageUp | Action::PageDown => { self.move_sel(a) } Action::Activate => self.activate(), Action::Back => self.back(), Action::Queue => self.enqueue_selected(), Action::SectionNext => self.select_section((self.section + 1).min(SECTIONS.len() - 1)), Action::SectionPrev => self.select_section(self.section.saturating_sub(1)), _ => {} }, Area::Search => match a { Action::Down => { if self.current_page().is_some_and(|p| !p.entries.is_empty()) { self.set_area(Area::Content); } } Action::Activate => { let q = self.ui.get_search_text().to_string(); self.run_search(q); } Action::Back | Action::Left => self.set_area(Area::Sidebar), Action::SectionNext => self.select_section((self.section + 1).min(SECTIONS.len() - 1)), Action::SectionPrev => self.select_section(self.section.saturating_sub(1)), _ => {} }, } } fn set_area(&mut self, area: Area) { self.area = area; self.ui.set_area(area); if area == Area::Search { self.ui.invoke_focus_search(); } else { self.ui.invoke_focus_main(); } self.render_hints(); } /// Moves focus from the sidebar into the page, or into the search box when /// the search page has nothing to select yet. fn enter_content(&mut self) { let is_search = matches!( self.current_page().map(|p| &p.source), Some(Source::Search(_)) | Some(Source::Section(Section::Search)) ); let empty = self.current_page().is_none_or(|p| p.entries.is_empty()); if is_search && empty { self.set_area(Area::Search); } else { self.set_area(Area::Content); } } fn item_clicked(&mut self, index: usize) { if self.screen != Screen::Browse { return; } if let Some(page) = self.current_page_mut() { page.sel = index; } self.ui.set_selected(index as i32); self.set_area(Area::Content); self.activate(); } fn wheel(&mut self, rows: i32) { let a = if rows > 0 { Action::Down } else { Action::Up }; if self.area != Area::Content { self.set_area(Area::Content); } self.move_sel(a); } fn sidebar_clicked(&mut self, index: usize) { self.select_section(index); self.enter_content(); } // ---------------------------------------------------------------- pages fn current_page(&self) -> Option<&Page> { self.stacks.get(self.section)?.last() } fn current_page_mut(&mut self) -> Option<&mut Page> { self.stacks.get_mut(self.section)?.last_mut() } fn find_page_mut(&mut self, id: u64) -> Option<&mut Page> { self.stacks.iter_mut().flat_map(|s| s.iter_mut()).find(|p| p.id == id) } fn is_current(&self, id: u64) -> bool { self.current_page().is_some_and(|p| p.id == id) } fn new_page(&mut self, source: Source, title: String, list: bool, header: Option) -> Page { let id = self.next_id; self.next_id += 1; Page { id, title, list, header, entries: Vec::new(), songs: Vec::new(), sel: 0, loading: true, error: None, retries: 0, source, } } fn select_section(&mut self, index: usize) { if index == self.section { return; } self.section = index; self.ui.set_section(index as i32); if self.stacks[index].is_empty() { let section = SECTIONS[index]; let list = matches!(section, Section::Artists | Section::Search | Section::Settings); let mut page = self.new_page(Source::Section(section), section.label().to_string(), list, None); if section == Section::Search { page.loading = false; } let id = page.id; self.stacks[index].push(page); self.load(id, Source::Section(section)); } if self.area == Area::Search { self.area = Area::Content; self.ui.set_area(Area::Content); self.ui.invoke_focus_main(); } self.render_page(); } fn reload_root(&mut self) { let Some(stack) = self.stacks.get_mut(self.section) else { return; }; stack.truncate(1); let Some(page) = stack.first_mut() else { return }; if matches!(page.source, Source::Section(Section::Search)) { return; } page.entries.clear(); page.songs.clear(); page.sel = 0; page.loading = true; page.error = None; let (id, source) = (page.id, page.source.clone()); self.load(id, source); self.render_page(); } fn push_page(&mut self, source: Source, title: String, list: bool, header: HeaderInfo) { let page = self.new_page(source.clone(), title, list, Some(header)); let id = page.id; self.stacks[self.section].push(page); self.load(id, source); self.render_page(); } fn back(&mut self) { let stack = &mut self.stacks[self.section]; if stack.len() > 1 { stack.pop(); self.render_page(); } else { self.set_area(Area::Sidebar); } } fn columns(&self) -> usize { match self.current_page() { Some(p) if !p.list => self.ui.get_grid_columns().max(1) as usize, _ => 1, } } fn move_sel(&mut self, a: Action) { let cols = self.columns(); let Some(page) = self.current_page() else { return }; let is_search = matches!(page.source, Source::Search(_) | Source::Section(Section::Search)); let n = page.entries.len(); let s = page.sel; let rows_per_page = if page.list { 8 } else { 3 }; enum Move { To(usize), Sidebar, SearchBox, Stay, } let mv = if n == 0 { match a { Action::Left => Move::Sidebar, Action::Up if is_search => Move::SearchBox, _ => Move::Stay, } } else { match a { Action::Left if s % cols == 0 => Move::Sidebar, Action::Left => Move::To(s - 1), Action::Right if (s + 1) % cols != 0 && s + 1 < n => Move::To(s + 1), Action::Up if s >= cols => Move::To(s - cols), Action::Up if is_search => Move::SearchBox, Action::Down if s + cols < n => Move::To(s + cols), Action::Down if s / cols < (n - 1) / cols => Move::To(n - 1), Action::PageDown => Move::To((s + cols * rows_per_page).min(n - 1)), Action::PageUp => Move::To(s.saturating_sub(cols * rows_per_page)), _ => Move::Stay, } }; match mv { Move::To(new) => { if let Some(page) = self.current_page_mut() { page.sel = new; } self.ui.set_selected(new as i32); self.sync_items(false); self.render_hints(); } Move::Sidebar => self.set_area(Area::Sidebar), Move::SearchBox => self.set_area(Area::Search), Move::Stay => {} } } fn activate(&mut self) { let Some(page) = self.current_page() else { return }; if page.entries.is_empty() { if page.error.is_some() { let (id, source) = (page.id, page.source.clone()); if let Some(p) = self.current_page_mut() { p.error = None; p.loading = true; } self.load(id, source); self.render_page(); } return; } let Some(entry) = page.entries.get(page.sel).cloned() else { return; }; let header = HeaderInfo { kind: "", title: entry.title.clone(), subtitle: entry.subtitle.clone(), info: String::new(), cover: entry.cover.clone(), round: entry.round, }; match entry.target { Target::Album(id) => self.push_page( Source::Album(id), entry.title, true, HeaderInfo { kind: "ALBUM", ..header }, ), Target::Artist(id) => self.push_page( Source::Artist(id), entry.title, false, HeaderInfo { kind: "ARTIST", subtitle: String::new(), ..header }, ), Target::Playlist(id) => self.push_page( Source::Playlist(id), entry.title, true, HeaderInfo { kind: "PLAYLIST", ..header }, ), Target::Song(index) => { let songs = page.songs.clone(); self.play_songs(songs, index); } Target::Setting(s) => self.toggle_setting(s), } } // ---------------------------------------------------------------- settings fn toggle_setting(&mut self, setting: Setting) { match setting { Setting::AlbumArtColours => self.settings.album_art_colours = !self.settings.album_art_colours, } if let Err(e) = config::save_settings(&self.settings) { self.toast(format!("Could not save settings: {e:#}")); } let entries = settings_data(&self.settings).entries; let index = SECTIONS.iter().position(|s| *s == Section::Settings).unwrap_or(0); if let Some(page) = self.stacks[index].first_mut() { page.entries = entries; if self.section == index { self.sync_items(true); } } self.update_theme(); } // ---------------------------------------------------------------- theme /// The palette the UI should show: from the playing track's cover when /// that setting is on, else the brand palette. None while the cover is /// still loading, to keep the current palette rather than flash the brand. fn wanted_palette(&mut self) -> Option { if !self.settings.album_art_colours { return Some(Palette::brand()); } let Some(id) = self .current .and_then(|i| self.queue.get(i)) .and_then(|s| s.cover_art.clone()) else { return Some(Palette::brand()); }; match self.covers.tones.get(&id) { Some(Some(tone)) => Some(Palette::from_tone(*tone)), Some(None) => Some(Palette::brand()), None if self.covers.failed.iter().any(|(f, _)| *f == id) => Some(Palette::brand()), None => None, } } fn update_theme(&mut self) { let Some(target) = self.wanted_palette() else { return }; if target == self.fade.to { return; } log::debug!( "fading to a new palette, accent {:?}", target.get(Role::Accent).to_rgb() ); // From whatever is on screen, so a fade cut short by a skip carries on // from where it got to instead of jumping. self.fade.from = self.fade.shown; self.fade.to = target; self.fade.started = Instant::now(); if !self.fade.timer.running() { self.fade .timer .start(slint::TimerMode::Repeated, Duration::from_millis(16), || { with_app(|app| app.fade_step()) }); } } fn fade_step(&mut self) { let t = (self.fade.started.elapsed().as_secs_f32() / FADE.as_secs_f32()).min(1.0); let eased = t * t * (3.0 - 2.0 * t); self.fade.shown = self.fade.from.mix(&self.fade.to, eased); self.apply_palette(); if t >= 1.0 { self.fade.timer.stop(); } } fn apply_palette(&self) { let theme = self.ui.global::(); for role in Role::ALL { let c = color(self.fade.shown.get(role)); match role { Role::Bg => theme.set_bg(c), Role::Panel => theme.set_panel(c), Role::Raised => theme.set_raised(c), Role::Line => theme.set_line(c), Role::Text => theme.set_text(c), Role::Muted => theme.set_muted(c), Role::Faint => theme.set_faint(c), Role::Accent => theme.set_accent(c), Role::OnAccent => theme.set_on_accent(c), Role::Highlight => theme.set_highlight(c), Role::Focus => theme.set_focus(c), Role::Glow => theme.set_glow(c), Role::LoginGlow => theme.set_login_glow(c), } } } fn open_search(&mut self) { if self.screen != Screen::Browse { self.close_now_playing(); } let index = SECTIONS.iter().position(|s| *s == Section::Search).unwrap_or(0); self.select_section(index); self.stacks[index].truncate(1); self.render_page(); self.set_area(Area::Search); } fn run_search(&mut self, query: String) { let query = query.trim().to_string(); if query.is_empty() { return; } let Some(page) = self.current_page_mut() else { return }; if !matches!(page.source, Source::Search(_) | Source::Section(Section::Search)) { return; } page.source = Source::Search(query.clone()); page.title = format!("Results for \u{201c}{query}\u{201d}"); page.entries.clear(); page.songs.clear(); page.sel = 0; page.loading = true; page.error = None; let id = page.id; self.load(id, Source::Search(query)); self.set_area(Area::Content); self.render_page(); } // ---------------------------------------------------------------- loading fn load(&mut self, page_id: u64, source: Source) { if matches!(source, Source::Section(Section::Settings)) { let data = settings_data(&self.settings); self.page_loaded(page_id, Ok(data), true); return; } let Some(client) = self.client.clone() else { return }; match source { Source::Section(Section::Recent) => self.spawn( async move { Ok(albums_data(client.album_list("newest", 180, 0).await?)) }, move |app, r| app.page_loaded(page_id, r, true), ), Source::Section(Section::Random) => self.spawn( async move { Ok(albums_data(client.album_list("random", 120, 0).await?)) }, move |app, r| app.page_loaded(page_id, r, true), ), Source::Section(Section::Albums) => { // The full library, a page at a time, shown as it arrives. self.rt.spawn(async move { const BATCH: u32 = 500; let mut offset = 0; loop { let r = client.album_list("alphabeticalByName", BATCH, offset).await; let done = r.as_ref().map_or(true, |a| (a.len() as u32) < BATCH); offset += r.as_ref().map_or(0, |a| a.len() as u32); let data = r.map(albums_data); let _ = slint::invoke_from_event_loop(move || { with_app(move |app| app.page_loaded(page_id, data, done)) }); if done { break; } } }); } Source::Section(Section::Artists) => self.spawn( async move { Ok(artists_data(client.artists().await?)) }, move |app, r| app.page_loaded(page_id, r, true), ), Source::Section(Section::Playlists) => self.spawn( async move { Ok(playlists_data(client.playlists().await?)) }, move |app, r| app.page_loaded(page_id, r, true), ), Source::Section(Section::Search | Section::Settings) => {} Source::Search(q) => self.spawn( async move { Ok(search_data(client.search(&q).await?)) }, move |app, r| app.page_loaded(page_id, r, true), ), Source::Album(id) => self.spawn( async move { let album = client.album(&id).await?; let multi_disc = album.song.iter().any(|s| s.disc_number.unwrap_or(1) > 1); let album_artist = album.artist.clone().unwrap_or_default(); let entries = album .song .iter() .enumerate() .map(|(i, s)| { let artist = s.artist.clone().unwrap_or_default(); let number = match (s.track, multi_disc) { (Some(t), true) => format!("{}.{t:02}", s.disc_number.unwrap_or(1)), (Some(t), false) => t.to_string(), (None, _) => (i + 1).to_string(), }; Entry { title: s.title.clone(), subtitle: if artist != album_artist { artist } else { String::new() }, detail: s.duration.map(|d| fmt_time(d as f64)).unwrap_or_default(), number, cover: s.cover_art.clone(), round: false, show_art: false, target: Target::Song(i), } }) .collect(); let total = album .duration .unwrap_or_else(|| album.song.iter().filter_map(|s| s.duration).sum()); let info = join_dot([ album.year.map(|y| y.to_string()), Some(plural(album.song.len(), "track")), (total > 0).then(|| fmt_total(total)), ]); Ok(PageData { entries, header: Some(HeaderInfo { kind: "ALBUM", title: album.name, subtitle: album_artist, info, cover: album.cover_art, round: false, }), songs: album.song, }) }, move |app, r| app.page_loaded(page_id, r, true), ), Source::Artist(id) => self.spawn( async move { let artist = client.artist(&id).await?; let mut albums = artist.album; albums.sort_by_key(|a| std::cmp::Reverse(a.year.unwrap_or(0))); let cover = albums.first().and_then(|a| a.cover_art.clone()); let info = plural(albums.len(), "album"); let mut data = albums_data(albums); for e in &mut data.entries { // On an artist page the year is more useful than the artist again. e.subtitle = e.detail.clone(); } data.header = Some(HeaderInfo { kind: "ARTIST", title: artist.name, subtitle: String::new(), info, cover, round: true, }); Ok(data) }, move |app, r| app.page_loaded(page_id, r, true), ), Source::Playlist(id) => self.spawn( async move { let pl = client.playlist(&id).await?; let total = pl .duration .unwrap_or_else(|| pl.entry.iter().filter_map(|s| s.duration).sum()); let info = join_dot([ Some(plural(pl.entry.len(), "track")), (total > 0).then(|| fmt_total(total)), ]); let mut data = songs_data(pl.entry); data.header = Some(HeaderInfo { kind: "PLAYLIST", title: pl.name, subtitle: String::new(), info, cover: pl.cover_art, round: false, }); Ok(data) }, move |app, r| app.page_loaded(page_id, r, true), ), } } /// Appends a load result to the page. `done` is false while more batches follow. fn page_loaded(&mut self, page_id: u64, result: Result, done: bool) { let Some(page) = self.find_page_mut(page_id) else { return; }; match result { Ok(data) => { let offset = page.songs.len(); page.entries.extend(data.entries.into_iter().map(|mut e| { if let Target::Song(i) = &mut e.target { *i += offset; } e })); page.songs.extend(data.songs); if data.header.is_some() { page.header = data.header; } page.loading = !done; page.retries = 0; } Err(e) => { log::warn!("load failed: {e:#}"); page.error = Some(format!("{e:#}")); page.loading = false; // An empty page retries on its own, so a library opened before // the network is up (right after boot) fills in once it is. // A partial one does not: reloading would duplicate entries. if page.entries.is_empty() { let delay = Duration::from_secs(2u64.saturating_pow(page.retries + 1).min(30)); page.retries += 1; Timer::single_shot(delay, move || with_app(move |app| app.retry_page(page_id))); } } } if self.is_current(page_id) { self.render_page(); } } fn retry_page(&mut self, page_id: u64) { let Some(page) = self.find_page_mut(page_id) else { return; }; if page.error.is_none() || !page.entries.is_empty() { return; } page.error = None; page.loading = true; let source = page.source.clone(); self.load(page_id, source); if self.is_current(page_id) { self.render_page(); } } // ---------------------------------------------------------------- render fn render_page(&mut self) { let Some(page) = self.current_page() else { return }; let status = if !page.entries.is_empty() { String::new() } else if page.loading { "Loading…".to_string() } else if let Some(e) = &page.error { format!("Could not reach the server. Retrying on its own, or press A to try now.\n\n{e}") } else { match page.source { Source::Section(Section::Search) => "Search your library by artist, album or song title.".to_string(), Source::Search(_) => "No results.".to_string(), _ => "Nothing here.".to_string(), } }; let title = page.title.clone(); let loading = page.loading; let list = page.list; let count = page.entries.len(); let sel = page.sel.min(count.saturating_sub(1)); let is_search = matches!(page.source, Source::Search(_) | Source::Section(Section::Search)); let header = page.header.clone(); self.ui.set_page_title(title.into()); self.ui.set_page_loading(loading); self.ui.set_list_mode(list); self.ui.set_is_search(is_search); self.ui.set_item_count(count as i32); self.ui.set_selected(sel as i32); self.ui.set_status(status.into()); let header = match header { Some(h) => { let px = self.header_px(); let cover = h.cover.as_deref().and_then(|id| self.cover(id, px)); Header { visible: true, kind: h.kind.into(), letter: initial(&h.title).into(), tint: tint(&h.title), has_cover: cover.is_some(), cover: cover.unwrap_or_default(), title: h.title.into(), subtitle: h.subtitle.into(), info: h.info.into(), round: h.round, } } None => Header::default(), }; self.ui.set_header(header); self.sync_items(true); self.render_hints(); } /// Fills the item model with a window of entries around the selection. /// Rebuilds only when the selection nears the window's edge, unless forced. fn sync_items(&mut self, force: bool) { let cols = self.columns(); let (count, sel, list) = match self.current_page() { Some(p) => (p.entries.len(), p.sel, p.list), None => (0, 0, true), }; let (lo, hi) = window(count, sel, cols, list); let margin = if list { 12 } else { 3 * cols }; let (cur_lo, cur_hi) = self.items_range; let covered = cur_lo <= sel.saturating_sub(margin) && (sel + margin).min(count) <= cur_hi; if !force && covered { return; } let px = if list { self.thumb_px() } else { self.grid_px() }; let items: Vec = (lo..hi).filter_map(|i| self.make_item(i, px)).collect(); self.items.set_vec(items); self.items_range = (lo, hi); } fn playing_id(&self) -> Option<&str> { self.current.and_then(|i| self.queue.get(i)).map(|s| s.id.as_str()) } fn make_item(&mut self, index: usize, px: u32) -> Option { let page = self.current_page()?; let entry = page.entries.get(index)?.clone(); let playing = match entry.target { Target::Song(i) => page.songs.get(i).map(|s| s.id.as_str()) == self.playing_id(), _ => false, }; let cover = entry.cover.as_deref().and_then(|id| self.cover(id, px)); Some(Item { index: index as i32, letter: initial(&entry.title).into(), tint: tint(&entry.title), title: entry.title.into(), subtitle: entry.subtitle.into(), detail: entry.detail.into(), number: entry.number.into(), has_cover: cover.is_some(), cover: cover.unwrap_or_default(), round: entry.round, show_art: entry.show_art, playing, }) } fn render_hints(&self) { let mut hints = Vec::new(); let mut h = |c: Control, l: &str| { let icons = self.hint_icons(c); // Nothing to press for it with this input, such as Steam + X on a keyboard. if !icons.is_empty() { hints.push(Hint { icons: ModelRc::new(VecModel::from(icons)), label: l.into(), }); } }; match self.screen { Screen::Login => { h(Control::Activate, if self.login_focus < 2 { "Next" } else { "Connect" }); } Screen::Browse => match self.area { Area::Sidebar => { h(Control::Activate, "Open"); h(Control::PlayPause, "Play / Pause"); h(Control::Search, "Search"); h(Control::NowPlaying, "Now playing"); } Area::Search => { h(Control::Activate, "Search"); h(Control::Back, "Back"); h(Control::OnScreenKeyboard, "Keyboard"); } _ => { let target = self .current_page() .and_then(|p| p.entries.get(p.sel)) .map(|e| &e.target); match target { Some(Target::Song(_)) => h(Control::Activate, "Play"), Some(Target::Setting(_)) => h(Control::Activate, "Change"), Some(_) => h(Control::Activate, "Open"), None if self.current_page().is_some_and(|p| p.error.is_some()) => { h(Control::Activate, "Try again") } None => {} } h(Control::Back, "Back"); if matches!(target, Some(Target::Song(_) | Target::Album(_) | Target::Playlist(_))) { h(Control::Queue, "Add to queue"); } h(Control::PlayPause, "Play / Pause"); h(Control::Sections, "Sections"); h(Control::NowPlaying, "Now playing"); } }, Screen::NowPlaying => { h(Control::Activate, "Play selected"); h(Control::Back, "Back"); h(Control::PlayPause, "Play / Pause"); h(Control::Skip, "Skip"); h(Control::Seek, "Seek"); } } self.ui.set_hints(ModelRc::new(VecModel::from(hints))); } fn hint_icons(&self, control: Control) -> Vec { self.icons .borrow_mut() .entry((self.prompts, control)) .or_insert_with(|| { prompts::icons(self.prompts, control) .iter() .filter_map(|svg| match Image::load_from_svg_data(svg) { Ok(img) => Some(img), Err(e) => { log::warn!("hint icon for {control:?}: {e:?}"); None } }) .collect() }) .clone() } fn toast(&mut self, text: String) { self.ui.set_toast(text.into()); self.toast_timer .start(slint::TimerMode::SingleShot, Duration::from_millis(2500), || { with_app(|app| app.ui.set_toast("".into())) }); } // ---------------------------------------------------------------- covers fn scale(&self) -> f32 { self.ui.global::().get_s() * self.ui.window().scale_factor() } fn grid_px(&self) -> u32 { bucket(self.ui.get_grid_art() * self.ui.window().scale_factor()) } fn thumb_px(&self) -> u32 { bucket(46.0 * self.scale()) } fn header_px(&self) -> u32 { bucket(176.0 * self.scale()) } fn now_playing_px(&self) -> u32 { bucket(self.ui.get_np_art_size().max(300.0) * self.ui.window().scale_factor()) } /// Returns the cover if cached, otherwise starts loading it and returns None. fn cover(&mut self, id: &str, px: u32) -> Option { let key: CoverKey = (id.to_string(), px); if let Some(img) = self.covers.images.get(&key) { return Some(img.clone()); } if self.covers.pending.contains(&key) || self.covers.failed.contains(&key) { return None; } let client = self.client.clone()?; self.covers.pending.insert(key.clone()); let limit = self.covers.limit.clone(); let path = self .covers .dir .as_ref() .map(|d| d.join(format!("{}_{px}", sanitize(id)))); let id = id.to_string(); self.spawn( async move { let _permit = limit.acquire_owned().await?; let cached = path.as_ref().and_then(|p| std::fs::read(p).ok()); let bytes = match cached { Some(b) => b, None => { let b = client.cover_art(&id, px).await?; if let Some(p) = &path { let _ = std::fs::write(p, &b); } b } }; let decoded = tokio::task::spawn_blocking(move || decode_cover(&bytes, px)).await??; Ok(decoded) }, move |app, r| app.cover_loaded(key, r), ); None } fn cover_loaded(&mut self, key: CoverKey, result: Result<(SharedPixelBuffer, Option)>) { self.covers.pending.remove(&key); match result { Ok((buf, tone)) => { self.covers.images.put(key.clone(), Image::from_rgb8(buf)); // The first size decoded decides: other sizes give a tone that // differs in the last digits, which would restart the fade. if !self.covers.tones.contains(&key.0) { log::debug!("cover {} tone {tone:?}", key.0); self.covers.tones.put(key.0.clone(), tone); } } Err(e) => { log::debug!("cover {} failed: {e:#}", key.0); self.covers.failed.insert(key); // The playing track's cover failing means the brand palette. self.update_theme(); return; } } let id = key.0.as_str(); // Refresh whatever shows this cover. let (lo, hi) = self.items_range; let rows: Vec = match self.current_page() { Some(p) => (lo..hi.min(p.entries.len())) .filter(|&i| p.entries[i].cover.as_deref() == Some(id)) .collect(), None => Vec::new(), }; if !rows.is_empty() { let px = if self.current_page().is_some_and(|p| p.list) { self.thumb_px() } else { self.grid_px() }; for i in rows { if let Some(item) = self.make_item(i, px) { slint::Model::set_row_data(&*self.items, i - lo, item); } } } if self .current_page() .and_then(|p| p.header.as_ref()) .and_then(|h| h.cover.as_deref()) == Some(id) { self.render_page_header(); } if self .current .and_then(|i| self.queue.get(i)) .and_then(|s| s.cover_art.as_deref()) == Some(id) { self.render_player(); } let (qlo, qhi) = self.queue_range; let qrows: Vec = (qlo..qhi.min(self.queue.len())) .filter(|&i| self.queue[i].cover_art.as_deref() == Some(id)) .collect(); let qpx = self.thumb_px(); for i in qrows { let item = self.make_queue_item(i, qpx); slint::Model::set_row_data(&*self.queue_items, i - qlo, item); } } fn render_page_header(&mut self) { let Some(h) = self.current_page().and_then(|p| p.header.clone()) else { return; }; let px = self.header_px(); let cover = h.cover.as_deref().and_then(|id| self.cover(id, px)); let mut header = self.ui.get_header(); header.has_cover = cover.is_some(); header.cover = cover.unwrap_or_default(); self.ui.set_header(header); } // ---------------------------------------------------------------- playback fn play_songs(&mut self, songs: Vec, start: usize) { let Some(client) = &self.client else { return }; let Some(player) = &self.player else { self.toast("Playback is unavailable: GStreamer could not start".into()); return; }; let urls: Vec = songs.iter().map(|s| client.stream_url(&s.id)).collect(); player.play_list(&urls, start); self.queue = songs; self.current = None; self.queue_sel = start; self.sync_queue(true); } fn enqueue(&mut self, songs: Vec, what: String) { let Some(client) = &self.client else { return }; let Some(player) = &self.player else { self.toast("Playback is unavailable: GStreamer could not start".into()); return; }; if songs.is_empty() { return; } for s in &songs { player.append(&client.stream_url(&s.id)); } let n = songs.len(); self.queue.extend(songs); self.sync_queue(true); self.toast(if n == 1 { format!("Queued {what}") } else { format!("Queued {what} ({n} tracks)") }); } fn enqueue_selected(&mut self) { let Some(page) = self.current_page() else { return }; let Some(entry) = page.entries.get(page.sel) else { return; }; let Some(client) = self.client.clone() else { return }; let title = entry.title.clone(); match entry.target.clone() { Target::Song(i) => { if let Some(song) = page.songs.get(i).cloned() { self.enqueue(vec![song], title); } } Target::Album(id) => self.spawn( async move { Ok(client.album(&id).await?.song) }, move |app, r| match r { Ok(songs) => app.enqueue(songs, title), Err(e) => app.toast(format!("Could not queue: {e:#}")), }, ), Target::Playlist(id) => { self.spawn( async move { Ok(client.playlist(&id).await?.entry) }, move |app, r| match r { Ok(songs) => app.enqueue(songs, title), Err(e) => app.toast(format!("Could not queue: {e:#}")), }, ) } Target::Artist(_) => self.toast("Open the artist to queue one of their albums".into()), Target::Setting(_) => {} } } fn player_event(&mut self, ev: PlayerEvent) { match ev { PlayerEvent::Position(p) => { self.position = p; self.render_progress(); self.maybe_scrobble(); } PlayerEvent::Duration(d) => { self.duration = d; self.render_progress(); } PlayerEvent::Paused(p) => { self.paused = p; self.ui.set_np_paused(p); } PlayerEvent::Track(t) => { // Reported once per track started, so the same index again is a // new play: another queue started there, or the track replayed. let t = t.filter(|&i| i < self.queue.len()); self.current = t; self.position = 0.0; self.scrobbled = false; if let (Some(song), Some(client)) = (t.and_then(|i| self.queue.get(i)), self.client.clone()) { let id = song.id.clone(); self.spawn(async move { client.scrobble(&id, false).await }, |_, r| { if let Err(e) = r { log::debug!("now-playing update failed: {e:#}"); } }); } if let Some(i) = t && self.screen == Screen::NowPlaying { self.queue_sel = i; } self.render_player(); self.sync_items(true); self.sync_queue(true); } } } /// Submits a play once half the track (or four minutes) has been heard, /// the usual scrobbling rule. fn maybe_scrobble(&mut self) { if self.scrobbled || self.duration < 30.0 { return; } if self.position < (self.duration / 2.0).min(240.0) { return; } self.scrobbled = true; let (Some(song), Some(client)) = (self.current.and_then(|i| self.queue.get(i)), self.client.clone()) else { return; }; let id = song.id.clone(); self.spawn(async move { client.scrobble(&id, true).await }, |_, r| { if let Err(e) = r { log::warn!("scrobble failed: {e:#}"); } }); } fn render_progress(&self) { let progress = if self.duration > 0.0 { (self.position / self.duration).clamp(0.0, 1.0) } else { 0.0 }; self.ui.set_np_progress(progress as f32); self.ui.set_np_position(fmt_time(self.position).into()); self.ui.set_np_duration(fmt_time(self.duration).into()); } fn render_player(&mut self) { let song = self.current.and_then(|i| self.queue.get(i)).cloned(); self.ui.set_np_has_track(song.is_some()); self.ui.set_np_paused(self.paused); match song { Some(s) => { let px = self.now_playing_px(); let cover = s.cover_art.as_deref().and_then(|id| self.cover(id, px)); self.ui .set_np_letter(initial(s.album.as_deref().unwrap_or(&s.title)).into()); self.ui.set_np_tint(tint(s.album.as_deref().unwrap_or(&s.title))); self.ui.set_np_has_cover(cover.is_some()); self.ui.set_np_cover(cover.unwrap_or_default()); self.ui.set_np_title(s.title.into()); self.ui.set_np_artist(s.artist.unwrap_or_default().into()); self.ui.set_np_album(s.album.unwrap_or_default().into()); } None => { self.ui.set_np_has_cover(false); self.ui.set_np_cover(Image::default()); self.ui.set_np_letter("".into()); self.ui.set_np_title("".into()); self.ui.set_np_artist("".into()); self.ui.set_np_album("".into()); } } self.render_progress(); self.update_theme(); } // ---------------------------------------------------------------- now playing fn open_now_playing(&mut self) { self.screen = Screen::NowPlaying; self.ui.set_screen(Screen::NowPlaying); self.queue_sel = self.current.unwrap_or(0); self.ui.invoke_focus_main(); self.sync_queue(true); // The art is larger here than in the bar, so ask again at this size. self.render_player(); self.render_hints(); } fn close_now_playing(&mut self) { self.screen = Screen::Browse; self.ui.set_screen(Screen::Browse); let area = self.area; self.set_area(area); } fn now_playing_action(&mut self, a: Action) { if self.global_action(a) { return; } match a { Action::Back => self.close_now_playing(), Action::Up => self.move_queue_sel(-1), Action::Down => self.move_queue_sel(1), Action::PageUp => self.move_queue_sel(-8), Action::PageDown => self.move_queue_sel(8), Action::Left => self.seek(-10.0), Action::Right => self.seek(10.0), Action::Activate => { if self.queue_sel < self.queue.len() && let Some(p) = &self.player { p.play_index(self.queue_sel); } } _ => {} } } fn queue_clicked(&mut self, index: usize) { self.queue_sel = index; self.ui.set_queue_selected(index as i32); if let Some(p) = &self.player { p.play_index(index); } } fn move_queue_sel(&mut self, delta: isize) { if self.queue.is_empty() { return; } let max = self.queue.len() as isize - 1; self.queue_sel = (self.queue_sel as isize + delta).clamp(0, max) as usize; self.ui.set_queue_selected(self.queue_sel as i32); self.sync_queue(false); } fn sync_queue(&mut self, force: bool) { let count = self.queue.len(); let sel = self.queue_sel.min(count.saturating_sub(1)); self.ui.set_queue_count(count as i32); self.ui.set_queue_selected(sel as i32); let (lo, hi) = window(count, sel, 1, true); let (cur_lo, cur_hi) = self.queue_range; let covered = cur_lo <= sel.saturating_sub(12) && (sel + 12).min(count) <= cur_hi; if !force && covered { return; } let px = self.thumb_px(); let items: Vec = (lo..hi).map(|i| self.make_queue_item(i, px)).collect(); self.queue_items.set_vec(items); self.queue_range = (lo, hi); } fn make_queue_item(&mut self, index: usize, px: u32) -> Item { let s = self.queue[index].clone(); let cover = s.cover_art.as_deref().and_then(|id| self.cover(id, px)); let album = s.album.clone().unwrap_or_default(); Item { index: index as i32, letter: initial(&album).into(), tint: tint(&album), title: s.title.into(), subtitle: join_dot([s.artist, s.album]).into(), detail: s.duration.map(|d| fmt_time(d as f64)).unwrap_or_default().into(), number: (index + 1).to_string().into(), has_cover: cover.is_some(), cover: cover.unwrap_or_default(), round: false, show_art: true, playing: Some(index) == self.current, } } } // -------------------------------------------------------------------- data shaping fn albums_data(albums: Vec) -> PageData { PageData { entries: albums .into_iter() .map(|a| Entry { subtitle: a.artist.unwrap_or_default(), detail: a.year.map(|y| y.to_string()).unwrap_or_default(), title: a.name, number: String::new(), cover: a.cover_art, round: false, show_art: true, target: Target::Album(a.id), }) .collect(), ..Default::default() } } fn artists_data(artists: Vec) -> PageData { PageData { entries: artists.into_iter().map(artist_entry).collect(), ..Default::default() } } fn artist_entry(a: Artist) -> Entry { Entry { subtitle: a.album_count.map(|n| plural(n as usize, "album")).unwrap_or_default(), title: a.name, detail: String::new(), number: String::new(), cover: a.cover_art, round: true, show_art: true, target: Target::Artist(a.id), } } fn playlists_data(playlists: Vec) -> PageData { PageData { entries: playlists .into_iter() .map(|p| Entry { subtitle: join_dot([p.song_count.map(|n| plural(n as usize, "track")), p.owner]), detail: String::new(), title: p.name, number: String::new(), cover: p.cover_art, round: false, show_art: true, target: Target::Playlist(p.id), }) .collect(), ..Default::default() } } fn songs_data(songs: Vec) -> PageData { PageData { entries: songs.iter().enumerate().map(|(i, s)| song_entry(s, i)).collect(), songs, header: None, } } fn song_entry(s: &Song, index: usize) -> Entry { Entry { title: s.title.clone(), subtitle: join_dot([s.artist.clone(), s.album.clone()]), detail: s.duration.map(|d| fmt_time(d as f64)).unwrap_or_default(), number: (index + 1).to_string(), cover: s.cover_art.clone(), round: false, show_art: true, target: Target::Song(index), } } fn settings_data(s: &Settings) -> PageData { let on_off = |on: bool| if on { "On" } else { "Off" }.to_string(); PageData { entries: vec![Entry { title: "Colours from album art".to_string(), subtitle: "Tint the interface with the cover of the playing track".to_string(), detail: on_off(s.album_art_colours), number: String::new(), cover: None, round: false, show_art: false, target: Target::Setting(Setting::AlbumArtColours), }], ..Default::default() } } fn search_data(r: SearchResult) -> PageData { let mut entries: Vec = r.artist.into_iter().map(artist_entry).collect(); entries.extend(r.album.into_iter().map(|a| Entry { subtitle: join_dot([Some("Album".to_string()), a.artist]), detail: a.year.map(|y| y.to_string()).unwrap_or_default(), title: a.name, number: String::new(), cover: a.cover_art, round: false, show_art: true, target: Target::Album(a.id), })); entries.extend(r.song.iter().enumerate().map(|(i, s)| song_entry(s, i))); PageData { entries, songs: r.song, header: None, } } // -------------------------------------------------------------------- helpers /// The range of entries to instantiate around `sel`. fn window(count: usize, sel: usize, cols: usize, list: bool) -> (usize, usize) { if list { (sel.saturating_sub(40), (sel + 40).min(count)) } else { let row = sel / cols; (row.saturating_sub(10) * cols, ((row + 11) * cols).min(count)) } } /// Rounds a pixel size up to a fixed set so the server and disk caches get reused. fn bucket(px: f32) -> u32 { const SIZES: [u32; 8] = [128, 192, 256, 384, 512, 768, 1024, 1536]; SIZES.into_iter().find(|&s| px <= s as f32).unwrap_or(1536) } /// Decodes a cover at `px` and works out its tone for the album art palette. fn decode_cover(bytes: &[u8], px: u32) -> Result<(SharedPixelBuffer, Option)> { let img = image::load_from_memory(bytes)?; let img = if img.width() > px || img.height() > px { img.resize(px, px, image::imageops::FilterType::Triangle) } else { img }; // A small copy is plenty to find the dominant hue. let small = img .resize_exact(24, 24, image::imageops::FilterType::Triangle) .to_rgb8(); let tone = crate::palette::tone(small.as_raw()); let rgb = img.to_rgb8(); let buf = SharedPixelBuffer::clone_from_slice(rgb.as_raw(), rgb.width(), rgb.height()); Ok((buf, tone)) } fn color(lab: Lab) -> Color { let [r, g, b] = lab.to_rgb(); Color::from_rgb_u8(r, g, b) } fn sanitize(id: &str) -> String { id.chars() .map(|c| { if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' } }) .collect() } fn initial(s: &str) -> String { s.chars() .find(|c| c.is_alphanumeric()) .map(|c| c.to_uppercase().collect()) .unwrap_or_default() } /// A stable, muted colour per title, used behind missing or loading art. fn tint(seed: &str) -> Color { let h = seed .bytes() .fold(7u32, |a, b| a.wrapping_mul(31).wrapping_add(b as u32)) % 360; let (s, v) = (0.42f32, 0.40f32); let c = v * s; let x = c * (1.0 - ((h as f32 / 60.0) % 2.0 - 1.0).abs()); let (r, g, b) = match h / 60 { 0 => (c, x, 0.0), 1 => (x, c, 0.0), 2 => (0.0, c, x), 3 => (0.0, x, c), 4 => (x, 0.0, c), _ => (c, 0.0, x), }; let m = v - c; let to = |f: f32| ((f + m) * 255.0) as u8; Color::from_rgb_u8(to(r), to(g), to(b)) } /// The message for a failed login, with a pointer to the fix where the /// server's own message does not give one. fn login_error(e: &anyhow::Error) -> String { let msg = format!("{e:#}"); match subsonic::api_error(e) { Some(a) if a.code == subsonic::WRONG_CREDENTIALS && a.server .as_deref() .is_some_and(|s| s.to_lowercase().contains("nextcloud")) => { format!( "{msg}. Nextcloud Music needs the API password generated in its own \ settings, not your Nextcloud login password." ) } _ => msg, } } fn fmt_time(secs: f64) -> String { let t = secs.max(0.0) as u64; let (h, m, s) = (t / 3600, (t / 60) % 60, t % 60); if h > 0 { format!("{h}:{m:02}:{s:02}") } else { format!("{m}:{s:02}") } } fn fmt_total(secs: u32) -> String { let m = (secs + 30) / 60; if m >= 60 { format!("{} h {} min", m / 60, m % 60) } else { format!("{m} min") } } fn plural(n: usize, word: &str) -> String { if n == 1 { format!("1 {word}") } else { format!("{n} {word}s") } } fn join_dot>>(parts: I) -> String { parts .into_iter() .flatten() .filter(|s| !s.is_empty()) .collect::>() .join(" · ") } #[cfg(test)] mod tests { use super::*; #[test] fn grid_window_is_row_aligned() { assert_eq!(window(1000, 0, 5, false), (0, 55)); assert_eq!(window(1000, 503, 5, false), (450, 555)); assert_eq!(window(30, 29, 5, false), (0, 30)); } #[test] fn list_window_is_clamped() { assert_eq!(window(10, 5, 1, true), (0, 10)); assert_eq!(window(500, 100, 1, true), (60, 140)); } #[test] fn buckets_round_up() { assert_eq!(bucket(100.0), 128); assert_eq!(bucket(257.0), 384); assert_eq!(bucket(5000.0), 1536); } #[test] fn nextcloud_wrong_password_points_at_the_api_password() { let err = |server: &str| { anyhow::Error::from(subsonic::ApiError { code: subsonic::WRONG_CREDENTIALS, message: "Wrong username or password".into(), server: Some(server.into()), }) }; assert!(login_error(&err("nextcloud music")).contains("API password")); assert_eq!(login_error(&err("navidrome")), "Wrong username or password"); } #[test] fn formatting() { assert_eq!(fmt_time(61.9), "1:01"); assert_eq!(fmt_time(3725.0), "1:02:05"); assert_eq!(fmt_total(2900), "48 min"); assert_eq!(fmt_total(4320), "1 h 12 min"); assert_eq!( join_dot([Some("a".into()), None, Some("".into()), Some("b".into())]), "a · b" ); assert_eq!(initial(" (the) Band"), "T"); } }