Browses a Subsonic library and plays it through mpv, driven by a gamepad or keyboard. The UI scales from the window's physical height rather than the compositor's scale factor, so it keeps its proportions on a Steam Deck and on a 4K TV, where other players open small or scale badly.
1786 lines
60 KiB
Rust
1786 lines
60 KiB
Rust
//! 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::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;
|
|
|
|
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};
|
|
use crate::player::{Player, PlayerEvent};
|
|
use crate::subsonic::{Album, Artist, Client, Playlist, SearchResult, Song};
|
|
use crate::{Action, AppWindow, Area, Header, Hint, Item, Screen, Theme};
|
|
|
|
thread_local! {
|
|
static APP: RefCell<Option<App>> = 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.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 mpv.
|
|
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,
|
|
}
|
|
|
|
const SECTIONS: [Section; 6] = [
|
|
Section::Recent,
|
|
Section::Random,
|
|
Section::Albums,
|
|
Section::Artists,
|
|
Section::Playlists,
|
|
Section::Search,
|
|
];
|
|
|
|
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",
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Debug)]
|
|
enum Target {
|
|
Album(String),
|
|
Artist(String),
|
|
Playlist(String),
|
|
/// Index into the page's `songs`.
|
|
Song(usize),
|
|
}
|
|
|
|
#[derive(Clone, Debug)]
|
|
struct Entry {
|
|
title: String,
|
|
subtitle: String,
|
|
detail: String,
|
|
number: String,
|
|
cover: Option<String>,
|
|
round: bool,
|
|
show_art: bool,
|
|
target: Target,
|
|
}
|
|
|
|
#[derive(Clone, Debug, Default)]
|
|
struct HeaderInfo {
|
|
kind: &'static str,
|
|
title: String,
|
|
subtitle: String,
|
|
info: String,
|
|
cover: Option<String>,
|
|
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<Entry>,
|
|
songs: Vec<Song>,
|
|
header: Option<HeaderInfo>,
|
|
}
|
|
|
|
struct Page {
|
|
id: u64,
|
|
title: String,
|
|
list: bool,
|
|
header: Option<HeaderInfo>,
|
|
entries: Vec<Entry>,
|
|
songs: Vec<Song>,
|
|
sel: usize,
|
|
loading: bool,
|
|
error: Option<String>,
|
|
source: Source,
|
|
}
|
|
|
|
type CoverKey = (String, u32);
|
|
|
|
struct Covers {
|
|
images: LruCache<CoverKey, Image>,
|
|
pending: HashSet<CoverKey>,
|
|
failed: HashSet<CoverKey>,
|
|
limit: Arc<Semaphore>,
|
|
dir: Option<PathBuf>,
|
|
}
|
|
|
|
pub struct App {
|
|
ui: AppWindow,
|
|
rt: Handle,
|
|
client: Option<Client>,
|
|
player: Option<Player>,
|
|
screen: Screen,
|
|
area: Area,
|
|
section: usize,
|
|
stacks: Vec<Vec<Page>>,
|
|
next_id: u64,
|
|
items: Rc<VecModel<Item>>,
|
|
items_range: (usize, usize),
|
|
queue_items: Rc<VecModel<Item>>,
|
|
queue_range: (usize, usize),
|
|
covers: Covers,
|
|
queue: Vec<Song>,
|
|
current: Option<usize>,
|
|
queue_sel: usize,
|
|
position: f64,
|
|
duration: f64,
|
|
paused: bool,
|
|
scrobbled: bool,
|
|
login_focus: i32,
|
|
toast_timer: Timer,
|
|
}
|
|
|
|
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()),
|
|
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(),
|
|
}
|
|
}
|
|
|
|
fn start(&mut self) {
|
|
let labels: Vec<SharedString> = 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(Client::new(&cfg.url, &cfg.username, &cfg.salt, &cfg.token));
|
|
}
|
|
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<T, F, D>(&self, fut: F, done: D)
|
|
where
|
|
T: Send + 'static,
|
|
F: Future<Output = Result<T>> + Send + 'static,
|
|
D: FnOnce(&mut App, Result<T>) + 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);
|
|
let client = Client::from_password(&url, &user, &password);
|
|
let probe = client.clone();
|
|
self.spawn(async move { probe.ping().await }, move |app, r| {
|
|
app.ui.set_login_busy(false);
|
|
match r {
|
|
Ok(()) => {
|
|
app.ui.set_login_password("".into());
|
|
let cfg = Config {
|
|
url: client.base().to_string(),
|
|
username: client.user().to_string(),
|
|
salt: client.salt().to_string(),
|
|
token: client.token().to_string(),
|
|
};
|
|
if let Err(e) = config::save(&cfg) {
|
|
app.toast(format!("Could not save settings: {e:#}"));
|
|
}
|
|
app.enter_browse(client);
|
|
}
|
|
Err(e) => app.ui.set_login_error(format!("{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.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
|
|
|
|
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<HeaderInfo>) -> 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,
|
|
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);
|
|
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);
|
|
}
|
|
}
|
|
}
|
|
|
|
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) {
|
|
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) => {}
|
|
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<PageData>, 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;
|
|
}
|
|
Err(e) => {
|
|
log::warn!("load failed: {e:#}");
|
|
page.error = Some(format!("{e:#}"));
|
|
page.loading = false;
|
|
}
|
|
}
|
|
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 load this page.\n{e}\n\nPress A to try again.")
|
|
} 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<Item> = (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<Item> {
|
|
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 h = |k: &str, l: &str| Hint {
|
|
key: k.into(),
|
|
label: l.into(),
|
|
};
|
|
let mut hints = Vec::new();
|
|
match self.screen {
|
|
Screen::Login => {
|
|
hints.push(h("A", if self.login_focus < 2 { "Next" } else { "Connect" }));
|
|
}
|
|
Screen::Browse => match self.area {
|
|
Area::Sidebar => {
|
|
hints.push(h("A", "Open"));
|
|
hints.push(h("X", "Play / Pause"));
|
|
hints.push(h("VIEW", "Search"));
|
|
hints.push(h("MENU", "Now playing"));
|
|
}
|
|
Area::Search => {
|
|
hints.push(h("A", "Search"));
|
|
hints.push(h("B", "Back"));
|
|
hints.push(h("STEAM + X", "Keyboard"));
|
|
}
|
|
_ => {
|
|
let target = self
|
|
.current_page()
|
|
.and_then(|p| p.entries.get(p.sel))
|
|
.map(|e| &e.target);
|
|
match target {
|
|
Some(Target::Song(_)) => hints.push(h("A", "Play")),
|
|
Some(_) => hints.push(h("A", "Open")),
|
|
None if self.current_page().is_some_and(|p| p.error.is_some()) => {
|
|
hints.push(h("A", "Try again"))
|
|
}
|
|
None => {}
|
|
}
|
|
hints.push(h("B", "Back"));
|
|
if matches!(target, Some(Target::Song(_) | Target::Album(_) | Target::Playlist(_))) {
|
|
hints.push(h("Y", "Add to queue"));
|
|
}
|
|
hints.push(h("X", "Play / Pause"));
|
|
hints.push(h("LT RT", "Sections"));
|
|
hints.push(h("MENU", "Now playing"));
|
|
}
|
|
},
|
|
Screen::NowPlaying => {
|
|
hints.push(h("A", "Play selected"));
|
|
hints.push(h("B", "Back"));
|
|
hints.push(h("X", "Play / Pause"));
|
|
hints.push(h("LB RB", "Skip"));
|
|
hints.push(h("◀ ▶", "Seek"));
|
|
}
|
|
}
|
|
self.ui.set_hints(ModelRc::new(VecModel::from(hints)));
|
|
}
|
|
|
|
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::<Theme>().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<Image> {
|
|
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 buf = tokio::task::spawn_blocking(move || decode_cover(&bytes, px)).await??;
|
|
Ok(buf)
|
|
},
|
|
move |app, r| app.cover_loaded(key, r),
|
|
);
|
|
None
|
|
}
|
|
|
|
fn cover_loaded(&mut self, key: CoverKey, result: Result<SharedPixelBuffer<Rgb8Pixel>>) {
|
|
self.covers.pending.remove(&key);
|
|
match result {
|
|
Ok(buf) => {
|
|
self.covers.images.put(key.clone(), Image::from_rgb8(buf));
|
|
}
|
|
Err(e) => {
|
|
log::debug!("cover {} failed: {e:#}", key.0);
|
|
self.covers.failed.insert(key);
|
|
return;
|
|
}
|
|
}
|
|
let id = key.0.as_str();
|
|
|
|
// Refresh whatever shows this cover.
|
|
let (lo, hi) = self.items_range;
|
|
let rows: Vec<usize> = 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<usize> = (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<Song>, start: usize) {
|
|
let Some(client) = &self.client else { return };
|
|
let Some(player) = &self.player else {
|
|
self.toast("Playback is unavailable: mpv is not running".into());
|
|
return;
|
|
};
|
|
let urls: Vec<String> = 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<Song>, what: String) {
|
|
let Some(client) = &self.client else { return };
|
|
let Some(player) = &self.player else {
|
|
self.toast("Playback is unavailable: mpv is not running".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()),
|
|
}
|
|
}
|
|
|
|
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) => {
|
|
let t = t.filter(|&i| i < self.queue.len());
|
|
if t == self.current {
|
|
return;
|
|
}
|
|
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);
|
|
}
|
|
PlayerEvent::Exited => {
|
|
self.player = None;
|
|
self.toast("Playback stopped: mpv exited".into());
|
|
}
|
|
}
|
|
}
|
|
|
|
/// 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();
|
|
}
|
|
|
|
// ---------------------------------------------------------------- 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<Item> = (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<Album>) -> 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<Artist>) -> 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<Playlist>) -> 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<Song>) -> 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 search_data(r: SearchResult) -> PageData {
|
|
let mut entries: Vec<Entry> = 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)
|
|
}
|
|
|
|
fn decode_cover(bytes: &[u8], px: u32) -> Result<SharedPixelBuffer<Rgb8Pixel>> {
|
|
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
|
|
};
|
|
let rgb = img.to_rgb8();
|
|
Ok(SharedPixelBuffer::clone_from_slice(
|
|
rgb.as_raw(),
|
|
rgb.width(),
|
|
rgb.height(),
|
|
))
|
|
}
|
|
|
|
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))
|
|
}
|
|
|
|
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<I: IntoIterator<Item = Option<String>>>(parts: I) -> String {
|
|
parts
|
|
.into_iter()
|
|
.flatten()
|
|
.filter(|s| !s.is_empty())
|
|
.collect::<Vec<_>>()
|
|
.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 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");
|
|
}
|
|
}
|