Musyx Mobile: Android TV player for Yandex Music
Kotlin, Compose for TV and Media3 port of the desktop Musyx, with device-code sign-in, Home, My Wave, search, collection, detail pages, Now Playing with queue and lyrics, and settings for streaming quality, appearance, font size (small, medium, large) and language. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
46610d95fa
217 files changed
+26144
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,297 @@
|
||||
//! Changing things: likes, dislikes, playlist edits, plus lyrics and the
|
||||
//! server-side queue. Every change is shown at once and undone if Yandex refuses.
|
||||
|
||||
use crate::i18n::{tr, trf};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use iced::Task;
|
||||
use ym_api::{Error, PlaylistId};
|
||||
|
||||
use super::{App, Message};
|
||||
use crate::player;
|
||||
use crate::route::Route;
|
||||
use crate::screens::Loadable;
|
||||
use crate::screens::collection::Liked;
|
||||
use crate::widgets::sheet::Sheet;
|
||||
|
||||
/// How long a status message stays up.
|
||||
const TOAST: Duration = Duration::from_secs(4);
|
||||
|
||||
/// What to reload after an edit lands.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Refresh {
|
||||
Playlist(PlaylistId),
|
||||
Playlists,
|
||||
Liked,
|
||||
LikedIds,
|
||||
}
|
||||
|
||||
/// The outcome of a change sent to Yandex.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Edited {
|
||||
pub result: Result<(), Error>,
|
||||
/// Shown when it worked.
|
||||
pub done: String,
|
||||
/// Shown when it didn't.
|
||||
pub failed: String,
|
||||
pub refresh: Vec<Refresh>,
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub(super) fn toast(&mut self, text: impl Into<String>) {
|
||||
self.toast = Some((text.into(), Instant::now()));
|
||||
}
|
||||
|
||||
/// Sends a change, then reports and refreshes through [`Message::Edited`].
|
||||
fn send_edit<F>(&self, change: F, done: String, failed: String, refresh: Vec<Refresh>) -> Task<Message>
|
||||
where
|
||||
F: std::future::Future<Output = Result<(), Error>> + Send + 'static,
|
||||
{
|
||||
Task::future(change).map(move |result| {
|
||||
Message::Edited(Box::new(Edited { result, done: done.clone(), failed: failed.clone(), refresh: refresh.clone() }))
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn update_edit(&mut self, message: Message) -> Task<Message> {
|
||||
let Some(client) = self.client().cloned() else { return Task::none() };
|
||||
match message {
|
||||
Message::LikeTrack(track, on) => {
|
||||
self.library.liked = self.library.liked.with(&track, on);
|
||||
if on {
|
||||
self.likes.disliked_tracks.remove(&track.id);
|
||||
}
|
||||
let id = track.full_id();
|
||||
let c = client.clone();
|
||||
self.send_edit(
|
||||
async move { c.set_track_liked(&id, on).await },
|
||||
if on { tr("Added to Liked tracks") } else { tr("Removed from Liked tracks") }.into(),
|
||||
tr("Couldn't change the like. Try again.").into(),
|
||||
vec![],
|
||||
)
|
||||
}
|
||||
Message::DislikeTrack(track, on) => {
|
||||
if on {
|
||||
self.likes.disliked_tracks.insert(track.id.clone());
|
||||
self.library.liked = self.library.liked.with(&track, false);
|
||||
} else {
|
||||
self.likes.disliked_tracks.remove(&track.id);
|
||||
}
|
||||
// Not hearing it again starts now.
|
||||
let skip = if on && self.player.track().is_some_and(|t| t.id == track.id) {
|
||||
self.update(Message::Player(player::Msg::Next))
|
||||
} else {
|
||||
Task::none()
|
||||
};
|
||||
let id = track.full_id();
|
||||
let c = client.clone();
|
||||
Task::batch([
|
||||
skip,
|
||||
self.send_edit(
|
||||
async move { c.set_track_disliked(&id, on).await },
|
||||
if on { tr("You won't be recommended this track") } else { tr("Recommendations for this track restored") }.into(),
|
||||
tr("Couldn't change that. Try again.").into(),
|
||||
vec![],
|
||||
),
|
||||
])
|
||||
}
|
||||
Message::LikeAlbum(id, on) => {
|
||||
toggle(&mut self.likes.albums, id, on);
|
||||
self.library.albums = Loadable::NotLoaded;
|
||||
self.send_edit(
|
||||
async move { client.set_album_liked(id, on).await },
|
||||
if on { tr("Album added to your collection") } else { tr("Album removed from your collection") }.into(),
|
||||
tr("Couldn't change the like. Try again.").into(),
|
||||
vec![Refresh::LikedIds],
|
||||
)
|
||||
}
|
||||
Message::LikeArtist(id, on) => {
|
||||
toggle(&mut self.likes.artists, id, on);
|
||||
self.library.artists = Loadable::NotLoaded;
|
||||
self.send_edit(
|
||||
async move { client.set_artist_liked(id, on).await },
|
||||
if on { tr("Artist added to your collection") } else { tr("Artist removed from your collection") }.into(),
|
||||
tr("Couldn't change the like. Try again.").into(),
|
||||
vec![Refresh::LikedIds],
|
||||
)
|
||||
}
|
||||
Message::LikePlaylist(id, on) => {
|
||||
toggle(&mut self.likes.playlists, id, on);
|
||||
self.send_edit(
|
||||
async move { client.set_playlist_liked(id, on).await },
|
||||
if on { tr("Playlist added to your collection") } else { tr("Playlist removed from your collection") }.into(),
|
||||
tr("Couldn't change the like. Try again.").into(),
|
||||
vec![Refresh::Playlists, Refresh::LikedIds],
|
||||
)
|
||||
}
|
||||
Message::LikeClip(clip, on) => {
|
||||
toggle(&mut self.likes.clips, clip.id, on);
|
||||
if let Loadable::Loaded(clips) = &mut self.library.clips {
|
||||
clips.retain(|c| c.id != clip.id);
|
||||
if on {
|
||||
clips.insert(0, clip.clone());
|
||||
}
|
||||
}
|
||||
self.send_edit(
|
||||
async move { client.set_clip_liked(clip.id, on).await },
|
||||
if on { tr("Clip added to your collection") } else { tr("Clip removed from your collection") }.into(),
|
||||
tr("Couldn't change the like. Try again.").into(),
|
||||
vec![],
|
||||
)
|
||||
}
|
||||
Message::AddToPlaylist(id, track) => {
|
||||
self.sheet = None;
|
||||
let title = self.playlist_title(id);
|
||||
self.send_edit(
|
||||
async move { client.add_to_playlist(id, &track).await },
|
||||
trf("Added to “{}”", &[&title]),
|
||||
trf("Couldn't add to “{}”. Try again.", &[&title]),
|
||||
vec![Refresh::Playlist(id), Refresh::Playlists],
|
||||
)
|
||||
}
|
||||
Message::CreatePlaylist => {
|
||||
let Some(Sheet::NewPlaylist { name, add }) = self.sheet.take() else { return Task::none() };
|
||||
let name = name.trim().to_owned();
|
||||
if name.is_empty() {
|
||||
return Task::none();
|
||||
}
|
||||
let done = match &add {
|
||||
Some(_) => trf("Created “{}” with the track", &[&name]),
|
||||
None => trf("Created “{}”", &[&name]),
|
||||
};
|
||||
self.send_edit(
|
||||
async move {
|
||||
let created = client.create_playlist(&name, false).await?;
|
||||
if let Some(track) = add {
|
||||
client.add_to_playlist(created.id, &track).await?;
|
||||
}
|
||||
Ok(())
|
||||
},
|
||||
done,
|
||||
tr("Couldn't create the playlist. Try again.").into(),
|
||||
vec![Refresh::Playlists],
|
||||
)
|
||||
}
|
||||
Message::RenamePlaylist => {
|
||||
let Some(Sheet::Rename { id, name }) = self.sheet.take() else { return Task::none() };
|
||||
let name = name.trim().to_owned();
|
||||
if name.is_empty() {
|
||||
return Task::none();
|
||||
}
|
||||
let done = trf("Renamed to “{}”", &[&name]);
|
||||
self.send_edit(
|
||||
async move { client.rename_playlist(id, &name).await },
|
||||
done,
|
||||
tr("Couldn't rename the playlist. Try again.").into(),
|
||||
vec![Refresh::Playlist(id), Refresh::Playlists],
|
||||
)
|
||||
}
|
||||
Message::SetPlaylistPublic(id, public) => self.send_edit(
|
||||
async move { client.set_playlist_public(id, public).await },
|
||||
if public { tr("Anyone with the link can now see this playlist") } else { tr("Only you can see this playlist now") }.into(),
|
||||
tr("Couldn't change who can see it. Try again.").into(),
|
||||
vec![Refresh::Playlist(id), Refresh::Playlists],
|
||||
),
|
||||
Message::DeletePlaylist(id) => {
|
||||
self.sheet = None;
|
||||
let title = self.playlist_title(id);
|
||||
if self.nav.current() == Route::Playlist(id) {
|
||||
self.nav.back();
|
||||
}
|
||||
self.pages.remove(&Route::Playlist(id));
|
||||
self.send_edit(
|
||||
async move { client.delete_playlist(id).await },
|
||||
trf("Deleted “{}”", &[&title]),
|
||||
trf("Couldn't delete “{}”. Try again.", &[&title]),
|
||||
vec![Refresh::Playlists],
|
||||
)
|
||||
}
|
||||
Message::RemoveFromPlaylist(id, index) => {
|
||||
self.sheet = None;
|
||||
self.send_edit(
|
||||
async move { client.remove_from_playlist(id, index).await },
|
||||
tr("Removed from the playlist").into(),
|
||||
tr("Couldn't remove the track. Try again.").into(),
|
||||
vec![Refresh::Playlist(id), Refresh::Playlists],
|
||||
)
|
||||
}
|
||||
Message::MovePlaylistTrack { id, track, from, to } => {
|
||||
self.sheet = None;
|
||||
self.send_edit(
|
||||
async move { client.move_in_playlist(id, &track, from, to).await },
|
||||
tr("Moved").into(),
|
||||
tr("Couldn't move the track. Try again.").into(),
|
||||
vec![Refresh::Playlist(id)],
|
||||
)
|
||||
}
|
||||
Message::Edited(edited) => {
|
||||
let Edited { result, done, failed, refresh } = *edited;
|
||||
match result {
|
||||
Ok(()) => {
|
||||
self.toast(done);
|
||||
Task::batch(refresh.into_iter().map(|r| self.refresh(r)))
|
||||
}
|
||||
Err(e) => {
|
||||
if let Some(task) = self.failed("edit", &e) {
|
||||
return task;
|
||||
}
|
||||
self.toast(failed);
|
||||
// The optimistic change may be wrong now; re-read the truth.
|
||||
Task::batch([self.refresh(Refresh::Liked), self.refresh(Refresh::LikedIds)])
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => Task::none(),
|
||||
}
|
||||
}
|
||||
|
||||
fn playlist_title(&self, id: PlaylistId) -> String {
|
||||
self.library
|
||||
.playlists
|
||||
.get()
|
||||
.and_then(|p| p.own.iter().chain(&p.liked).find(|pl| pl.id == id))
|
||||
.map_or_else(|| tr("the playlist").to_owned(), |p| p.title.clone())
|
||||
}
|
||||
|
||||
pub(super) fn refresh(&mut self, what: Refresh) -> Task<Message> {
|
||||
match what {
|
||||
Refresh::Playlist(id) => {
|
||||
let route = Route::Playlist(id);
|
||||
self.pages.remove(&route);
|
||||
if self.nav.current() == route { self.on_enter(route) } else { Task::none() }
|
||||
}
|
||||
Refresh::Playlists => self.update(Message::LoadLibrary(crate::screens::collection::Tab::Playlists)),
|
||||
Refresh::Liked => {
|
||||
self.library.liked = Liked::NotLoaded;
|
||||
self.update(Message::LoadLiked)
|
||||
}
|
||||
Refresh::LikedIds => self.update(Message::LoadLikedIds),
|
||||
}
|
||||
}
|
||||
|
||||
/// Lyrics for the playing track, fetched once per track while the panel is open.
|
||||
pub(super) fn want_lyrics(&mut self) -> Task<Message> {
|
||||
let (Some(client), Some(track)) = (self.client().cloned(), self.player.track()) else { return Task::none() };
|
||||
if self.drawer != Some(crate::widgets::drawer::Panel::Lyrics) || self.lyrics.contains_key(&track.id) {
|
||||
return Task::none();
|
||||
}
|
||||
let id = track.id.clone();
|
||||
self.lyrics.insert(id.clone(), Loadable::Loading);
|
||||
Task::future(async move {
|
||||
let result = client.lyrics(&id).await.map(|l| l.map(Arc::new));
|
||||
Message::LyricsLoaded(id, result)
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn toast_expired(&self) -> bool {
|
||||
self.toast.as_ref().is_some_and(|(_, at)| at.elapsed() >= TOAST)
|
||||
}
|
||||
}
|
||||
|
||||
fn toggle<T: std::hash::Hash + Eq>(set: &mut std::collections::HashSet<T>, item: T, on: bool) {
|
||||
if on {
|
||||
set.insert(item);
|
||||
} else {
|
||||
set.remove(&item);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
//! Cover art: fetched when a cover scrolls into view, kept in memory for the
|
||||
//! session and on disk across sessions.
|
||||
//!
|
||||
//! Views never wait for images. A missing cover renders its placeholder inside
|
||||
//! a `sensor`, and showing it sends [`Message::CoverWanted`].
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use iced::widget::{container, image, sensor, space};
|
||||
use iced::{Element, Task};
|
||||
use tokio::sync::Semaphore;
|
||||
use ym_api::YmClient;
|
||||
|
||||
use crate::app::Message;
|
||||
use crate::ui::theme;
|
||||
|
||||
/// Pixel sizes requested from Yandex. Rows and the player bar use `SMALL`,
|
||||
/// cards and page headers `LARGE`; both cover 2× displays.
|
||||
pub const SMALL: u32 = 100;
|
||||
pub const LARGE: u32 = 400;
|
||||
|
||||
/// Downloads in flight at once.
|
||||
const PARALLEL: usize = 8;
|
||||
|
||||
pub struct Covers {
|
||||
images: HashMap<String, image::Handle>,
|
||||
pending: HashSet<String>,
|
||||
failed: HashSet<String>,
|
||||
/// Bumped (debounced) when images arrive, so cached lists rebuild.
|
||||
version: u64,
|
||||
dirty: bool,
|
||||
dir: Option<PathBuf>,
|
||||
gate: Arc<Semaphore>,
|
||||
}
|
||||
|
||||
impl Default for Covers {
|
||||
fn default() -> Self {
|
||||
let dir = directories::ProjectDirs::from("", "", "Musyx").map(|d| d.cache_dir().join("covers"));
|
||||
Self {
|
||||
images: HashMap::new(),
|
||||
pending: HashSet::new(),
|
||||
failed: HashSet::new(),
|
||||
version: 0,
|
||||
dirty: false,
|
||||
dir,
|
||||
gate: Arc::new(Semaphore::new(PARALLEL)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Covers {
|
||||
pub fn get(&self, url: &str) -> Option<image::Handle> {
|
||||
self.images.get(url).cloned()
|
||||
}
|
||||
|
||||
pub fn version(&self) -> u64 {
|
||||
self.version
|
||||
}
|
||||
|
||||
/// Whether arrivals are waiting to be shown; the app ticks [`Covers::flush`] meanwhile.
|
||||
pub fn dirty(&self) -> bool {
|
||||
self.dirty
|
||||
}
|
||||
|
||||
pub fn flush(&mut self) {
|
||||
if self.dirty {
|
||||
self.version += 1;
|
||||
self.dirty = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts fetching `url` unless it is known, in flight, or failed before.
|
||||
pub fn want(&mut self, url: String, client: &YmClient) -> Task<Message> {
|
||||
if self.images.contains_key(&url) || self.pending.contains(&url) || self.failed.contains(&url) {
|
||||
return Task::none();
|
||||
}
|
||||
self.pending.insert(url.clone());
|
||||
let (client, dir, gate) = (client.clone(), self.dir.clone(), self.gate.clone());
|
||||
Task::future(async move {
|
||||
let bytes = load(&client, &url, dir, &gate).await;
|
||||
Message::CoverLoaded(url, bytes)
|
||||
})
|
||||
}
|
||||
|
||||
/// Deletes the on-disk cache and forgets failures; images in memory stay for this session.
|
||||
pub fn clear_disk(&mut self) -> Task<Result<(), String>> {
|
||||
self.failed.clear();
|
||||
let Some(dir) = self.dir.clone() else { return Task::done(Ok(())) };
|
||||
Task::future(async move {
|
||||
match tokio::fs::remove_dir_all(&dir).await {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||
Err(e) => Err(e.to_string()),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn loaded(&mut self, url: String, bytes: Option<Arc<[u8]>>) {
|
||||
self.pending.remove(&url);
|
||||
match bytes {
|
||||
Some(bytes) => {
|
||||
self.images.insert(url, image::Handle::from_bytes(bytes.to_vec()));
|
||||
self.dirty = true;
|
||||
}
|
||||
None => {
|
||||
self.failed.insert(url);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn load(client: &YmClient, url: &str, dir: Option<PathBuf>, gate: &Semaphore) -> Option<Arc<[u8]>> {
|
||||
let path = dir.as_ref().map(|d| d.join(file_name(url)));
|
||||
if let Some(path) = &path
|
||||
&& let Ok(bytes) = tokio::fs::read(path).await
|
||||
{
|
||||
return Some(bytes.into());
|
||||
}
|
||||
|
||||
let _permit = gate.acquire().await.ok()?;
|
||||
let bytes = match client.image(url).await {
|
||||
Ok(bytes) if !bytes.is_empty() => bytes,
|
||||
Ok(_) => return None,
|
||||
Err(e) => {
|
||||
eprintln!("cover {url}: {e}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
if let (Some(dir), Some(path)) = (&dir, &path) {
|
||||
// A failed cache write only costs a re-download next time.
|
||||
let _ = tokio::fs::create_dir_all(dir).await;
|
||||
let _ = tokio::fs::write(path, &bytes).await;
|
||||
}
|
||||
Some(bytes.into())
|
||||
}
|
||||
|
||||
/// A stable, filesystem-safe name for a URL (64-bit FNV-1a).
|
||||
fn file_name(url: &str) -> String {
|
||||
let hash = url.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3));
|
||||
format!("{hash:016x}.img")
|
||||
}
|
||||
|
||||
/// A square cover: the image when cached, otherwise placeholder art that asks
|
||||
/// for the image once it is (nearly) on screen.
|
||||
pub fn view(
|
||||
covers: &Covers,
|
||||
url: Option<String>,
|
||||
hues: (f32, f32),
|
||||
size: f32,
|
||||
corner: f32,
|
||||
) -> Element<'static, Message> {
|
||||
if let Some(handle) = url.as_deref().and_then(|u| covers.get(u)) {
|
||||
return image(handle).width(size).height(size).border_radius(corner).into();
|
||||
}
|
||||
let placeholder = container(space()).width(size).height(size).style(theme::cover(hues.0, hues.1, corner));
|
||||
match url {
|
||||
Some(url) => sensor(placeholder)
|
||||
.on_show(move |_| Message::CoverWanted(url.clone()))
|
||||
.anticipate(300)
|
||||
.into(),
|
||||
None => placeholder.into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn file_names_are_stable_and_distinct() {
|
||||
let a = file_name("https://avatars.yandex.net/get-music-content/1/100x100");
|
||||
assert_eq!(a, file_name("https://avatars.yandex.net/get-music-content/1/100x100"));
|
||||
assert_ne!(a, file_name("https://avatars.yandex.net/get-music-content/1/400x400"));
|
||||
assert!(a.ends_with(".img") && a.len() == 20);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrivals_bump_version_only_on_flush() {
|
||||
let mut covers = Covers { dir: None, ..Covers::default() };
|
||||
covers.pending.insert("u".into());
|
||||
covers.loaded("u".into(), Some(Arc::from(vec![1u8, 2, 3])));
|
||||
assert!(covers.dirty());
|
||||
assert_eq!(covers.version(), 0);
|
||||
covers.flush();
|
||||
assert_eq!(covers.version(), 1);
|
||||
assert!(covers.get("u").is_some());
|
||||
covers.loaded("bad".into(), None);
|
||||
assert!(covers.failed.contains("bad"));
|
||||
covers.flush();
|
||||
assert_eq!(covers.version(), 1, "a failure changes nothing on screen");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
//! Interface language. Strings are written in English where they're used and
|
||||
//! looked up here; Russian falls back to English for anything missing (a test
|
||||
//! scans the sources so nothing is).
|
||||
|
||||
use std::fmt::Display;
|
||||
|
||||
mod ru;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
|
||||
pub enum Lang {
|
||||
#[default]
|
||||
En,
|
||||
Ru,
|
||||
}
|
||||
|
||||
impl Lang {
|
||||
/// From a BCP 47 tag such as `ru-RU` or `en-US`.
|
||||
pub fn from_tag(tag: &str) -> Lang {
|
||||
let primary = tag.split(['-', '_']).next().unwrap_or_default();
|
||||
if primary.eq_ignore_ascii_case("ru") { Lang::Ru } else { Lang::En }
|
||||
}
|
||||
|
||||
/// The first language the system prefers.
|
||||
pub fn system() -> Lang {
|
||||
sys_locale::get_locale().map_or(Lang::En, |tag| Lang::from_tag(&tag))
|
||||
}
|
||||
|
||||
/// What Yandex should write its own titles in (genres, Home blocks, station names).
|
||||
pub fn content(self) -> ym_api::ContentLanguage {
|
||||
match self {
|
||||
Lang::En => ym_api::ContentLanguage::English,
|
||||
Lang::Ru => ym_api::ContentLanguage::Russian,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The app's state lives on the main thread, but tests run in parallel threads,
|
||||
// so there each thread keeps its own language.
|
||||
#[cfg(not(test))]
|
||||
static RUSSIAN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
static RUSSIAN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
pub fn set(lang: Lang) {
|
||||
#[cfg(not(test))]
|
||||
RUSSIAN.store(lang == Lang::Ru, std::sync::atomic::Ordering::Relaxed);
|
||||
#[cfg(test)]
|
||||
RUSSIAN.set(lang == Lang::Ru);
|
||||
}
|
||||
|
||||
pub fn lang() -> Lang {
|
||||
#[cfg(not(test))]
|
||||
let russian = RUSSIAN.load(std::sync::atomic::Ordering::Relaxed);
|
||||
#[cfg(test)]
|
||||
let russian = RUSSIAN.get();
|
||||
if russian { Lang::Ru } else { Lang::En }
|
||||
}
|
||||
|
||||
/// `english` in the interface language.
|
||||
pub fn tr(english: &str) -> &str {
|
||||
match lang() {
|
||||
Lang::En => english,
|
||||
Lang::Ru => ru::get(english).unwrap_or(english),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`tr`] with each `{}` in the template filled from `args`, in order.
|
||||
pub fn trf(template: &str, args: &[&dyn Display]) -> String {
|
||||
let mut out = String::with_capacity(template.len() + 16);
|
||||
let mut args = args.iter();
|
||||
let mut pieces = tr(template).split("{}");
|
||||
out.push_str(pieces.next().unwrap_or_default());
|
||||
for piece in pieces {
|
||||
if let Some(arg) = args.next() {
|
||||
out.push_str(&arg.to_string());
|
||||
}
|
||||
out.push_str(piece);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The word that goes with `n`: `en` is [one, other], `ru` is [one, few, many].
|
||||
pub fn plural<'a>(n: u64, en: [&'a str; 2], ru: [&'a str; 3]) -> &'a str {
|
||||
match lang() {
|
||||
Lang::En => en[usize::from(n != 1)],
|
||||
Lang::Ru => ru[ru_form(n)],
|
||||
}
|
||||
}
|
||||
|
||||
/// "1 track" / "5 tracks", "1 трек" / "3 трека" / "5 треков".
|
||||
pub fn count(n: u64, en: [&str; 2], ru: [&str; 3]) -> String {
|
||||
format!("{n} {}", plural(n, en, ru))
|
||||
}
|
||||
|
||||
/// Russian plural form: 0 for 1, 21, 101…; 1 for 2–4, 22–24…; 2 for the rest.
|
||||
fn ru_form(n: u64) -> usize {
|
||||
match (n % 10, n % 100) {
|
||||
(1, r) if r != 11 => 0,
|
||||
(2..=4, r) if !(12..=14).contains(&r) => 1,
|
||||
_ => 2,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn russian_lookups_fall_back_to_english() {
|
||||
set(Lang::Ru);
|
||||
assert_eq!(tr("Settings"), "Настройки");
|
||||
assert_eq!(tr("not a key"), "not a key");
|
||||
assert_eq!(trf("Added “{}” to the queue", &[&"Хочешь?"]), "«Хочешь?» добавлен в очередь");
|
||||
set(Lang::En);
|
||||
assert_eq!(tr("Settings"), "Settings");
|
||||
assert_eq!(trf("Added “{}” to the queue", &[&"Hm"]), "Added “Hm” to the queue");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plural_forms() {
|
||||
let forms = ([("track"), "tracks"], ["трек", "трека", "треков"]);
|
||||
set(Lang::Ru);
|
||||
let ru: Vec<String> = [1, 2, 5, 11, 12, 21, 22, 25, 101, 111].map(|n| count(n, forms.0, forms.1)).into();
|
||||
assert_eq!(ru, ["1 трек", "2 трека", "5 треков", "11 треков", "12 треков", "21 трек", "22 трека", "25 треков", "101 трек", "111 треков"]);
|
||||
set(Lang::En);
|
||||
assert_eq!(count(1, forms.0, forms.1), "1 track");
|
||||
assert_eq!(count(0, forms.0, forms.1), "0 tracks");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn system_tags() {
|
||||
assert_eq!(Lang::from_tag("ru-RU"), Lang::Ru);
|
||||
assert_eq!(Lang::from_tag("ru"), Lang::Ru);
|
||||
assert_eq!(Lang::from_tag("en-US"), Lang::En);
|
||||
assert_eq!(Lang::from_tag("kk_KZ"), Lang::En);
|
||||
}
|
||||
|
||||
/// Every `tr("…")` and `trf("…"` literal in the sources has a Russian entry,
|
||||
/// and so does every label that reaches `tr` from ym-api.
|
||||
#[test]
|
||||
fn every_string_has_a_russian_translation() {
|
||||
fn walk(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
|
||||
for entry in std::fs::read_dir(dir).unwrap().flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
walk(&path, out);
|
||||
} else if path.extension().is_some_and(|e| e == "rs") {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut files = Vec::new();
|
||||
walk(&std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"), &mut files);
|
||||
let mut missing = Vec::new();
|
||||
let mut seen = 0;
|
||||
// This file's own examples aren't interface strings.
|
||||
for file in files.into_iter().filter(|f| !f.ends_with("i18n.rs")) {
|
||||
let source = std::fs::read_to_string(&file).unwrap();
|
||||
// The scan reads a literal up to its closing quote, so it can't follow a
|
||||
// string continued with a backslash; keep interface strings on one line.
|
||||
let name = file.file_name().unwrap().to_string_lossy().into_owned();
|
||||
let code = source.split("#[cfg(test)]").next().unwrap_or_default();
|
||||
for (n, line) in code.lines().enumerate() {
|
||||
if line.trim_end().ends_with('\\') && line.contains('"') {
|
||||
missing.push(format!("{name}:{}: string continues on the next line", n + 1));
|
||||
}
|
||||
}
|
||||
for call in ["tr(\"", "trf(\""] {
|
||||
for (at, _) in source.match_indices(call) {
|
||||
// Skip `ustr(`, `attr(` and the like.
|
||||
if source[..at].ends_with(|c: char| c.is_alphanumeric() || c == '_') {
|
||||
continue;
|
||||
}
|
||||
let rest = &source[at + call.len()..];
|
||||
let end = rest.find('"').unwrap();
|
||||
let key = rest[..end].replace("\\n", "\n");
|
||||
seen += 1;
|
||||
if ru::get(&key).is_none() {
|
||||
missing.push(format!("{}: {key}", file.file_name().unwrap().to_string_lossy()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
use ym_api::{AlbumKind, Character, Language, Mood, SearchKind};
|
||||
let labels = Mood::ALL.iter().map(|m| m.label())
|
||||
.chain(Character::ALL.iter().map(|c| c.label()))
|
||||
.chain(Language::ALL.iter().map(|l| l.label()))
|
||||
.chain(SearchKind::ALL.iter().map(|k| k.label()))
|
||||
.chain(AlbumKind::ALL.iter().map(|k| k.label()));
|
||||
missing.extend(labels.filter(|l| ru::get(l).is_none()).map(|l| format!("ym-api label: {l}")));
|
||||
missing.sort();
|
||||
missing.dedup();
|
||||
assert!(seen > 200, "found only {seen} strings; is the scan broken?");
|
||||
assert!(missing.is_empty(), "{} strings have no Russian:\n{}", missing.len(), missing.join("\n"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,361 @@
|
||||
//! Russian strings, keyed by the English text in the code. Terms follow the
|
||||
//! Yandex Music apps ("Моя волна", "Мне нравится", "Чарт").
|
||||
|
||||
pub fn get(english: &str) -> Option<&'static str> {
|
||||
Some(match english {
|
||||
// Navigation and pages
|
||||
"Home" => "Главная",
|
||||
"My Wave" => "Моя волна",
|
||||
"Search" => "Поиск",
|
||||
"Collection" => "Коллекция",
|
||||
"Podcasts" => "Подкасты",
|
||||
"Settings" => "Настройки",
|
||||
"Album" => "Альбом",
|
||||
"Artist" => "Исполнитель",
|
||||
"Playlist" => "Плейлист",
|
||||
"Chart" => "Чарт",
|
||||
"Genre" => "Жанр",
|
||||
"Browse" => "Обзор",
|
||||
"Search artists, tracks, podcasts" => "Исполнители, треки, подкасты",
|
||||
"Playlists" => "Плейлисты",
|
||||
"Playlists you make or like show up here." => "Здесь появятся ваши плейлисты и те, что вам понравились.",
|
||||
"Loading playlists…" => "Загружаем плейлисты…",
|
||||
"Plus subscription" => "Подписка Плюс",
|
||||
"No Plus: 30-second previews" => "Без Плюса: фрагменты по 30 секунд",
|
||||
|
||||
// Home, chart, genres, podcasts
|
||||
"Recently played" => "Вы недавно слушали",
|
||||
"Made for you" => "Собрано для вас",
|
||||
"Show all" => "Показать все",
|
||||
"Show all {}" => "Показать все {}",
|
||||
"New releases" => "Новые релизы",
|
||||
"New playlists" => "Новые плейлисты",
|
||||
"Loading your picks…" => "Подбираем музыку для вас…",
|
||||
"The most played tracks on Yandex Music today" => "Самые популярные треки Яндекс Музыки сегодня",
|
||||
"The chart is empty right now." => "Чарт сейчас пуст.",
|
||||
"Loading the chart…" => "Загружаем чарт…",
|
||||
"Genres" => "Жанры",
|
||||
"Loading genres…" => "Загружаем жанры…",
|
||||
"This genre isn't available any more." => "Этот жанр больше недоступен.",
|
||||
"Play radio" => "Включить радио",
|
||||
"No playlists in this genre yet." => "В этом жанре пока нет плейлистов.",
|
||||
"Podcasts and books" => "Подкасты и книги",
|
||||
"Yours" => "Ваши",
|
||||
"Featured" => "Рекомендуем",
|
||||
"Loading podcasts…" => "Загружаем подкасты…",
|
||||
|
||||
// Loading and failures; the {} is an object in the accusative
|
||||
"Loading {}…" => "Загружаем {}…",
|
||||
"Loading…" => "Загрузка…",
|
||||
"Couldn't load {}. Check your connection and try again." => {
|
||||
"Не удалось загрузить {}. Проверьте подключение и попробуйте ещё раз."
|
||||
}
|
||||
"Couldn't load {}. Try again in a moment." => "Не удалось загрузить {}. Попробуйте чуть позже.",
|
||||
"Try again" => "Повторить",
|
||||
"your albums" => "ваши альбомы",
|
||||
"your artists" => "ваших исполнителей",
|
||||
"your clips" => "ваши клипы",
|
||||
"your home page" => "главную страницу",
|
||||
"your liked tracks" => "ваши любимые треки",
|
||||
"your playlists" => "ваши плейлисты",
|
||||
"your station settings" => "настройки волны",
|
||||
"genres" => "жанры",
|
||||
"podcasts" => "подкасты",
|
||||
"stations" => "станции",
|
||||
"the album" => "альбом",
|
||||
"the artist" => "исполнителя",
|
||||
"the chart" => "чарт",
|
||||
"the playlist" => "плейлист",
|
||||
"the playlists" => "плейлисты",
|
||||
"the results" => "результаты",
|
||||
|
||||
// Collection
|
||||
"Liked tracks" => "Мне нравится",
|
||||
"Albums" => "Альбомы",
|
||||
"Artists" => "Исполнители",
|
||||
"Clips" => "Клипы",
|
||||
"Your playlists" => "Ваши плейлисты",
|
||||
"Liked playlists" => "Понравившиеся плейлисты",
|
||||
"Play" => "Слушать",
|
||||
"Shuffle" => "Вперемешку",
|
||||
"Loading your liked tracks…" => "Загружаем ваши любимые треки…",
|
||||
"No liked albums yet. Like an album and it lands here." => {
|
||||
"Понравившихся альбомов пока нет. Отметьте альбом сердечком, и он появится здесь."
|
||||
}
|
||||
"No liked artists yet. Like an artist and they land here." => {
|
||||
"Понравившихся исполнителей пока нет. Отметьте исполнителя сердечком, и он появится здесь."
|
||||
}
|
||||
"No liked clips yet. Like a clip on an artist's page and it lands here." => {
|
||||
"Понравившихся клипов пока нет. Отметьте клип на странице исполнителя, и он появится здесь."
|
||||
}
|
||||
"No liked tracks yet. Tap the heart on any track and it lands here." => {
|
||||
"Любимых треков пока нет. Нажмите на сердечко у любого трека, и он появится здесь."
|
||||
}
|
||||
"No playlists yet. Playlists you make or like show up here." => {
|
||||
"Плейлистов пока нет. Здесь появятся ваши плейлисты и те, что вам понравились."
|
||||
}
|
||||
|
||||
// Album, artist and playlist pages
|
||||
"Loading the album…" => "Загружаем альбом…",
|
||||
"Loading the artist…" => "Загружаем исполнителя…",
|
||||
"Loading the playlist…" => "Загружаем плейлист…",
|
||||
"This album isn't available on Yandex Music any more." => "Этого альбома больше нет в Яндекс Музыке.",
|
||||
"This artist isn't available on Yandex Music any more." => "Этого исполнителя больше нет в Яндекс Музыке.",
|
||||
"This playlist isn't available on Yandex Music any more." => "Этого плейлиста больше нет в Яндекс Музыке.",
|
||||
"Artist · {}" => "Исполнитель · {}",
|
||||
"Popular tracks" => "Популярные треки",
|
||||
"Appears on" => "Участвует в",
|
||||
"Similar artists" => "Похожие исполнители",
|
||||
"Playlist · {}" => "Плейлист · {}",
|
||||
"Public" => "Открытый",
|
||||
"Private" => "Закрытый",
|
||||
"Rename" => "Переименовать",
|
||||
"Make private" => "Сделать закрытым",
|
||||
"Make public" => "Сделать открытым",
|
||||
"Delete" => "Удалить",
|
||||
"This playlist is empty." => "В этом плейлисте пока пусто.",
|
||||
"Single" => "Сингл",
|
||||
"Compilation" => "Сборник",
|
||||
"Podcast" => "Подкаст",
|
||||
"Audiobook" => "Аудиокнига",
|
||||
|
||||
// Search
|
||||
"All" => "Всё",
|
||||
"Tracks" => "Треки",
|
||||
"Results for “{}”" => "Результаты по запросу «{}»",
|
||||
"Nothing found for “{}”. Check the spelling or try fewer words." => {
|
||||
"По запросу «{}» ничего не нашлось. Проверьте написание или сократите запрос."
|
||||
}
|
||||
"Searching…" => "Ищем…",
|
||||
"Showing results for “{}”" => "Показаны результаты по запросу «{}»",
|
||||
"Show more" => "Показать ещё",
|
||||
"Track · {}" => "Трек · {}",
|
||||
"Top result" => "Лучшее совпадение",
|
||||
|
||||
// My Wave
|
||||
"Tuned to: {} mood, {} tracks, {} language." => "Настроено: настроение — {}, характер — {}, язык — {}.",
|
||||
"An endless stream picked from what you play, like and skip." => {
|
||||
"Бесконечный поток музыки, который подстраивается под то, что вы слушаете, лайкаете и пропускаете."
|
||||
}
|
||||
"Pause" => "Пауза",
|
||||
"Resume" => "Продолжить",
|
||||
"Play My Wave" => "Слушать Мою волну",
|
||||
"Mood" => "Настроение",
|
||||
"Character" => "Характер",
|
||||
"Language" => "Язык",
|
||||
"Any" => "Не важно",
|
||||
"Energetic" => "Бодрое",
|
||||
"Cheerful" => "Весёлое",
|
||||
"Calm" => "Спокойное",
|
||||
"Sad" => "Грустное",
|
||||
"Favourite" => "Любимое",
|
||||
"Unfamiliar" => "Незнакомое",
|
||||
"Popular" => "Популярное",
|
||||
"Russian" => "Русский",
|
||||
"Foreign" => "Иностранный",
|
||||
"Loading your settings…" => "Загружаем настройки…",
|
||||
"No other stations suggested right now." => "Других станций сейчас не предлагается.",
|
||||
"Loading stations…" => "Загружаем станции…",
|
||||
"Stations" => "Станции",
|
||||
|
||||
// Settings
|
||||
"Streaming quality" => "Качество звука",
|
||||
"Lossless" => "Без потерь",
|
||||
"Best" => "Лучшее",
|
||||
"Balanced" => "Оптимальное",
|
||||
"Data saver" => "Экономия трафика",
|
||||
"FLAC when Yandex offers it for your subscription and region, otherwise the best it allows. About 3–5 times the data of MP3, and tracks take longer to start." => {
|
||||
"FLAC, если Яндекс даёт его для вашей подписки и региона, иначе лучшее из доступного. Трафика в 3–5 раз больше, чем у MP3, и треки дольше запускаются."
|
||||
}
|
||||
"Highest MP3 bitrate Yandex offers, up to 320 kbps." => "Самый высокий битрейт MP3, который даёт Яндекс, до 320 кбит/с.",
|
||||
"Up to 192 kbps. About 40% less data." => "До 192 кбит/с. Примерно на 40% меньше трафика.",
|
||||
"Up to 128 kbps, for slow or metered connections." => "До 128 кбит/с, для медленного или платного интернета.",
|
||||
"Streaming quality: {}. Applies from the next track." => "Качество звука: {}. Применится со следующего трека.",
|
||||
"Appearance" => "Оформление",
|
||||
"Match system" => "Как в системе",
|
||||
"Light" => "Светлое",
|
||||
"Dark" => "Тёмное",
|
||||
"Storage" => "Хранилище",
|
||||
"Covers are kept on disk so pages open instantly next time. Clearing them frees the space; they download again as you browse." => {
|
||||
"Обложки хранятся на диске, чтобы страницы открывались мгновенно. Очистка освободит место, а обложки снова загрузятся по мере просмотра."
|
||||
}
|
||||
"Clear cover cache" => "Очистить кеш обложек",
|
||||
"Cover cache cleared" => "Кеш обложек очищен",
|
||||
"Couldn't clear the cover cache." => "Не удалось очистить кеш обложек.",
|
||||
"Couldn't save your settings. They'll apply until Musyx quits." => {
|
||||
"Не удалось сохранить настройки. Они будут действовать, пока Musyx открыт."
|
||||
}
|
||||
"Musyx {} · unofficial Yandex Music client" => "Musyx {} · неофициальный клиент Яндекс Музыки",
|
||||
|
||||
// Account
|
||||
"Yandex Plus" => "Яндекс Плюс",
|
||||
"Yandex Plus until {}" => "Яндекс Плюс до {}",
|
||||
"No Plus subscription. Tracks play as 30-second previews." => {
|
||||
"Нет подписки Плюс. Треки играют фрагментами по 30 секунд."
|
||||
}
|
||||
"Sign out" => "Выйти",
|
||||
"Can't reach Yandex Music" => "Яндекс Музыка недоступна",
|
||||
"You're still signed in. Check your internet connection, then try again." => {
|
||||
"Вы по-прежнему в аккаунте. Проверьте подключение к интернету и попробуйте ещё раз."
|
||||
}
|
||||
"Checking your sign-in…" => "Проверяем вход…",
|
||||
"Signing in…" => "Входим…",
|
||||
|
||||
// Sign-in
|
||||
"Musyx plays your Yandex Music library, My Wave and playlists. You confirm sign-in on Yandex's own page, so your password never passes through this app." => {
|
||||
"Musyx играет вашу коллекцию Яндекс Музыки, Мою волну и плейлисты. Вход подтверждается на странице самого Яндекса, поэтому пароль никогда не проходит через это приложение."
|
||||
}
|
||||
"Musyx is an unofficial client and isn't affiliated with Yandex. Your sign-in token is kept in the system keychain." => {
|
||||
"Musyx — неофициальный клиент, не связанный с Яндексом. Токен входа хранится в системной связке ключей."
|
||||
}
|
||||
"Sign in with your Yandex account" => "Войдите с аккаунтом Яндекса",
|
||||
"Get sign-in code" => "Получить код для входа",
|
||||
"Getting a code…" => "Получаем код…",
|
||||
"Copy code" => "Скопировать код",
|
||||
"Copied" => "Скопировано",
|
||||
"Waiting for confirmation · code expires in {}" => "Ждём подтверждения · код действует ещё {}",
|
||||
"Cancel" => "Отмена",
|
||||
"Open {}" => "Откройте {}",
|
||||
"On this computer or your phone. You can also scan the QR code." => {
|
||||
"На этом компьютере или на телефоне. Можно и отсканировать QR-код."
|
||||
}
|
||||
"Open in browser" => "Открыть в браузере",
|
||||
"Enter this code" => "Введите этот код",
|
||||
"Come back here" => "Вернитесь сюда",
|
||||
"Musyx signs you in as soon as you allow access." => "Musyx войдёт, как только вы разрешите доступ.",
|
||||
"Hide token sign-in" => "Скрыть вход по токену",
|
||||
"Sign in with an existing token instead" => "Войти с готовым токеном",
|
||||
"Paste OAuth token" => "Вставьте OAuth-токен",
|
||||
"Sign in" => "Войти",
|
||||
"Scan to open the sign-in page" => "Отсканируйте, чтобы открыть страницу входа",
|
||||
"A QR code appears with your sign-in code" => "QR-код появится вместе с кодом для входа",
|
||||
"Couldn't open your browser. Go to {} yourself." => "Не удалось открыть браузер. Откройте {} сами.",
|
||||
"Yandex didn't accept that token. Check it and paste it again." => {
|
||||
"Яндекс не принял этот токен. Проверьте его и вставьте ещё раз."
|
||||
}
|
||||
"The code expired before it was confirmed. Get a new code to try again." => {
|
||||
"Срок действия кода истёк до подтверждения. Получите новый код и попробуйте снова."
|
||||
}
|
||||
"Access was declined on Yandex's page. Get a new code if that was a mistake." => {
|
||||
"Доступ отклонён на странице Яндекса. Если это ошибка, получите новый код."
|
||||
}
|
||||
"Can't reach Yandex. Check your connection and try again." => {
|
||||
"Яндекс недоступен. Проверьте подключение и попробуйте ещё раз."
|
||||
}
|
||||
"Yandex didn't accept the sign-in. Get a new code to try again." => {
|
||||
"Яндекс не принял вход. Получите новый код и попробуйте снова."
|
||||
}
|
||||
"Yandex sent an unexpected answer. Try again in a moment." => {
|
||||
"Яндекс прислал неожиданный ответ. Попробуйте чуть позже."
|
||||
}
|
||||
|
||||
// Player bar, queue and lyrics
|
||||
"Can't play" => "Не удаётся воспроизвести",
|
||||
"Nothing playing" => "Ничего не играет",
|
||||
"Pick a track to start" => "Выберите трек",
|
||||
"Preview" => "Фрагмент",
|
||||
"Queue" => "Очередь",
|
||||
"Lyrics" => "Текст",
|
||||
"Now playing" => "Сейчас играет",
|
||||
"Nothing after this" => "Дальше ничего нет",
|
||||
"Next up · {}" => "Далее · {}",
|
||||
"and {} more" => "и ещё {}",
|
||||
"Nothing queued yet. Tracks you play, and the ones lined up after them, show up here." => {
|
||||
"Очередь пока пуста. Здесь появятся треки, которые вы включите, и те, что за ними."
|
||||
}
|
||||
"Play a track to see its lyrics." => "Включите трек, чтобы увидеть его текст.",
|
||||
"Yandex Music has no lyrics for this track." => "У Яндекс Музыки нет текста этого трека.",
|
||||
"Couldn't load the lyrics. Check your connection and try again." => {
|
||||
"Не удалось загрузить текст. Проверьте подключение и попробуйте ещё раз."
|
||||
}
|
||||
"Loading lyrics…" => "Загружаем текст…",
|
||||
"Written by {}" => "Авторы: {}",
|
||||
"No sound output found. Connect speakers or headphones and playback picks up." => {
|
||||
"Не найдено устройство вывода звука. Подключите колонки или наушники, и воспроизведение продолжится."
|
||||
}
|
||||
"Couldn't load more of this station. Check your connection and try again." => {
|
||||
"Не удалось загрузить продолжение станции. Проверьте подключение и попробуйте ещё раз."
|
||||
}
|
||||
"Several tracks in a row couldn't be played. Check your connection and try again." => {
|
||||
"Несколько треков подряд не удалось воспроизвести. Проверьте подключение и попробуйте ещё раз."
|
||||
}
|
||||
"Couldn't play “{}”, so it was skipped." => "Не удалось воспроизвести «{}», трек пропущен.",
|
||||
"Title" => "Название",
|
||||
|
||||
// Track menu
|
||||
"Next track" => "Следующий трек",
|
||||
"Previous track" => "Предыдущий трек",
|
||||
"Play next" => "Играть следующим",
|
||||
"Add to queue" => "Добавить в очередь",
|
||||
"Add to Liked tracks" => "Добавить в «Мне нравится»",
|
||||
"Remove from Liked tracks" => "Убрать из «Мне нравится»",
|
||||
"Add to playlist…" => "Добавить в плейлист…",
|
||||
"Add to playlist" => "Добавить в плейлист",
|
||||
"Play similar tracks" => "Слушать похожие",
|
||||
"Go to album" => "Перейти к альбому",
|
||||
"Go to artist" => "Перейти к исполнителю",
|
||||
"Don't recommend this track" => "Не рекомендовать этот трек",
|
||||
"Recommend this track again" => "Снова рекомендовать этот трек",
|
||||
"Move up" => "Переместить выше",
|
||||
"Move down" => "Переместить ниже",
|
||||
"Remove from this playlist" => "Удалить из этого плейлиста",
|
||||
"New playlist…" => "Новый плейлист…",
|
||||
"New playlist" => "Новый плейлист",
|
||||
"Rename playlist" => "Переименовать плейлист",
|
||||
"Playlist name" => "Название плейлиста",
|
||||
"Create" => "Создать",
|
||||
"The track goes in once it's created." => "Трек добавится, как только плейлист будет создан.",
|
||||
"Only you can see it until you make it public." => "Его видите только вы, пока не сделаете его открытым.",
|
||||
"Delete “{}”?" => "Удалить «{}»?",
|
||||
"The playlist and its track order go away for good. The tracks stay in Yandex Music." => {
|
||||
"Плейлист и порядок треков удалятся навсегда. Сами треки останутся в Яндекс Музыке."
|
||||
}
|
||||
|
||||
// Toasts
|
||||
"“{}” is already playing" => "«{}» уже играет",
|
||||
"“{}” plays next" => "«{}» зазвучит следующим",
|
||||
"Added “{}” to the queue" => "«{}» добавлен в очередь",
|
||||
"Finding tracks like “{}”…" => "Ищем треки в духе «{}»…",
|
||||
"Yandex has no similar tracks for “{}”" => "У Яндекса нет похожих треков для «{}»",
|
||||
"Playing {} like “{}”" => "Играем {} в духе «{}»",
|
||||
"Couldn't find similar tracks. Try again." => "Не удалось найти похожие треки. Попробуйте ещё раз.",
|
||||
"Opening “{}” in your browser" => "Открываем «{}» в браузере",
|
||||
"Couldn't open your browser." => "Не удалось открыть браузер.",
|
||||
"Added to Liked tracks" => "Добавлено в «Мне нравится»",
|
||||
"Removed from Liked tracks" => "Убрано из «Мне нравится»",
|
||||
"Couldn't change the like. Try again." => "Не удалось изменить отметку. Попробуйте ещё раз.",
|
||||
"You won't be recommended this track" => "Этот трек больше не будет попадаться в рекомендациях",
|
||||
"Recommendations for this track restored" => "Трек снова может попадаться в рекомендациях",
|
||||
"Couldn't change that. Try again." => "Не удалось это изменить. Попробуйте ещё раз.",
|
||||
"Album added to your collection" => "Альбом добавлен в коллекцию",
|
||||
"Album removed from your collection" => "Альбом убран из коллекции",
|
||||
"Artist added to your collection" => "Исполнитель добавлен в коллекцию",
|
||||
"Artist removed from your collection" => "Исполнитель убран из коллекции",
|
||||
"Playlist added to your collection" => "Плейлист добавлен в коллекцию",
|
||||
"Playlist removed from your collection" => "Плейлист убран из коллекции",
|
||||
"Clip added to your collection" => "Клип добавлен в коллекцию",
|
||||
"Clip removed from your collection" => "Клип убран из коллекции",
|
||||
"Added to “{}”" => "Добавлено в «{}»",
|
||||
"Couldn't add to “{}”. Try again." => "Не удалось добавить в «{}». Попробуйте ещё раз.",
|
||||
"Created “{}”" => "Плейлист «{}» создан",
|
||||
"Created “{}” with the track" => "Плейлист «{}» создан, трек добавлен",
|
||||
"Couldn't create the playlist. Try again." => "Не удалось создать плейлист. Попробуйте ещё раз.",
|
||||
"Renamed to “{}”" => "Плейлист переименован в «{}»",
|
||||
"Couldn't rename the playlist. Try again." => "Не удалось переименовать плейлист. Попробуйте ещё раз.",
|
||||
"Anyone with the link can now see this playlist" => "Теперь плейлист видят все, у кого есть ссылка",
|
||||
"Only you can see this playlist now" => "Теперь плейлист видите только вы",
|
||||
"Couldn't change who can see it. Try again." => "Не удалось изменить доступ. Попробуйте ещё раз.",
|
||||
"Deleted “{}”" => "Плейлист «{}» удалён",
|
||||
"Couldn't delete “{}”. Try again." => "Не удалось удалить «{}». Попробуйте ещё раз.",
|
||||
"Removed from the playlist" => "Удалено из плейлиста",
|
||||
"Couldn't remove the track. Try again." => "Не удалось удалить трек. Попробуйте ещё раз.",
|
||||
"Moved" => "Перемещено",
|
||||
"Couldn't move the track. Try again." => "Не удалось переместить трек. Попробуйте ещё раз.",
|
||||
|
||||
// Units
|
||||
"{} h {} min" => "{} ч {} мин",
|
||||
"{} min" => "{} мин",
|
||||
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
mod app;
|
||||
mod covers;
|
||||
mod i18n;
|
||||
mod media;
|
||||
mod menubar;
|
||||
mod player;
|
||||
mod route;
|
||||
mod screens;
|
||||
mod session;
|
||||
mod store;
|
||||
#[cfg(feature = "snapshot")]
|
||||
mod snapshot;
|
||||
mod ui;
|
||||
mod widgets;
|
||||
|
||||
use iced::{Size, window};
|
||||
|
||||
use app::App;
|
||||
use ui::theme;
|
||||
|
||||
/// The Linux application id: the window's Wayland app id / X11 class and the `.desktop` name.
|
||||
#[cfg(target_os = "linux")]
|
||||
const APP_ID: &str = "it.panov.musyx.desktop";
|
||||
|
||||
fn main() -> iced::Result {
|
||||
let app = iced::application(App::new, App::update, App::view)
|
||||
.title(App::title)
|
||||
.theme(App::theme)
|
||||
.subscription(App::subscription)
|
||||
.default_font(theme::BODY)
|
||||
.window(window::Settings {
|
||||
size: Size::new(1280.0, 800.0),
|
||||
min_size: Some(Size::new(960.0, 620.0)),
|
||||
icon: window::icon::from_file_data(include_bytes!("../assets/icon/musyx.png"), None).ok(),
|
||||
// Matches the installed `it.panov.musyx.desktop.desktop`, so the shell shows its name and icon.
|
||||
#[cfg(target_os = "linux")]
|
||||
platform_specific: window::settings::PlatformSpecific {
|
||||
application_id: APP_ID.to_owned(),
|
||||
..Default::default()
|
||||
},
|
||||
..window::Settings::default()
|
||||
})
|
||||
.centered();
|
||||
|
||||
theme::FONTS.into_iter().fold(app, |app, font| app.font(font)).run()
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
//! Media keys and the system's Now Playing widget (macOS Control Center,
|
||||
//! Windows media overlay, Linux MPRIS), through `souvlaki`.
|
||||
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
use std::time::Duration;
|
||||
|
||||
use iced::Subscription;
|
||||
use iced::futures::{SinkExt, Stream};
|
||||
use souvlaki::{MediaControlEvent, MediaControls, MediaMetadata, MediaPlayback, MediaPosition, PlatformConfig};
|
||||
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
|
||||
use ym_api::Track;
|
||||
|
||||
use crate::covers;
|
||||
use crate::player::Status;
|
||||
|
||||
/// What the media keys asked for, in player terms.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Command {
|
||||
Play,
|
||||
Pause,
|
||||
Toggle,
|
||||
Next,
|
||||
Previous,
|
||||
SeekTo(Duration),
|
||||
SeekBy { forward: bool, by: Duration },
|
||||
}
|
||||
|
||||
/// Without an amount, a seek key jumps this far.
|
||||
const SEEK_STEP: Duration = Duration::from_secs(10);
|
||||
|
||||
impl Command {
|
||||
fn from_event(event: MediaControlEvent) -> Option<Self> {
|
||||
use souvlaki::SeekDirection::Forward;
|
||||
Some(match event {
|
||||
MediaControlEvent::Play => Command::Play,
|
||||
MediaControlEvent::Pause | MediaControlEvent::Stop => Command::Pause,
|
||||
MediaControlEvent::Toggle => Command::Toggle,
|
||||
MediaControlEvent::Next => Command::Next,
|
||||
MediaControlEvent::Previous => Command::Previous,
|
||||
MediaControlEvent::SetPosition(MediaPosition(at)) => Command::SeekTo(at),
|
||||
MediaControlEvent::Seek(dir) => Command::SeekBy { forward: dir == Forward, by: SEEK_STEP },
|
||||
MediaControlEvent::SeekBy(dir, by) => Command::SeekBy { forward: dir == Forward, by },
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The OS calls back on its own thread; this hands commands to the subscription.
|
||||
static INBOX: Mutex<Option<UnboundedReceiver<Command>>> = Mutex::new(None);
|
||||
static OUTBOX: OnceLock<UnboundedSender<Command>> = OnceLock::new();
|
||||
|
||||
/// Queues a command as if a media key sent it (the menu bar mini player uses this).
|
||||
pub fn send(command: Command) {
|
||||
if let Some(tx) = OUTBOX.get() {
|
||||
let _ = tx.send(command);
|
||||
}
|
||||
}
|
||||
|
||||
/// Owns the OS integration. Created on the main thread at startup.
|
||||
pub struct Media {
|
||||
controls: Option<MediaControls>,
|
||||
/// What was last published, so unchanged state isn't sent again.
|
||||
shown: Option<(String, Status)>,
|
||||
}
|
||||
|
||||
impl Media {
|
||||
pub fn new() -> Self {
|
||||
let (tx, rx): (UnboundedSender<Command>, _) = unbounded_channel();
|
||||
if OUTBOX.set(tx).is_ok()
|
||||
&& let Ok(mut inbox) = INBOX.lock()
|
||||
{
|
||||
*inbox = Some(rx);
|
||||
}
|
||||
let controls = MediaControls::new(PlatformConfig { display_name: "Musyx", dbus_name: "musyx", hwnd: None })
|
||||
.and_then(|mut c| {
|
||||
c.attach(|event| {
|
||||
if let Some(command) = Command::from_event(event) {
|
||||
send(command);
|
||||
}
|
||||
})?;
|
||||
Ok(c)
|
||||
});
|
||||
match controls {
|
||||
Ok(c) => Self { controls: Some(c), shown: None },
|
||||
Err(e) => {
|
||||
eprintln!("media controls unavailable: {e:?}");
|
||||
Self { controls: None, shown: None }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Publishes the track and play state; `force` resends the position after a seek.
|
||||
pub fn update(&mut self, track: Option<&Track>, status: Status, position: Duration, force: bool) {
|
||||
let Some(controls) = &mut self.controls else { return };
|
||||
let Some(track) = track else {
|
||||
if self.shown.take().is_some() {
|
||||
let _ = controls.set_playback(MediaPlayback::Stopped);
|
||||
}
|
||||
return;
|
||||
};
|
||||
let new_track = self.shown.as_ref().is_none_or(|(id, _)| *id != track.id);
|
||||
let new_status = self.shown.as_ref().is_none_or(|(_, s)| *s != status);
|
||||
if !new_track && !new_status && !force {
|
||||
return;
|
||||
}
|
||||
if new_track {
|
||||
let title = track.full_title();
|
||||
let artist = track.artist_line();
|
||||
let album = track.album.as_ref().map(|a| a.title.clone());
|
||||
let cover = track.cover_url(covers::LARGE);
|
||||
let _ = controls.set_metadata(MediaMetadata {
|
||||
title: Some(&title),
|
||||
artist: Some(&artist),
|
||||
album: album.as_deref(),
|
||||
cover_url: cover.as_deref(),
|
||||
duration: Some(track.duration),
|
||||
});
|
||||
}
|
||||
let progress = Some(MediaPosition(position));
|
||||
let _ = controls.set_playback(match status {
|
||||
Status::Playing | Status::Loading => MediaPlayback::Playing { progress },
|
||||
Status::Paused | Status::Ended => MediaPlayback::Paused { progress },
|
||||
});
|
||||
self.shown = Some((track.id.clone(), status));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn subscription() -> Subscription<Command> {
|
||||
Subscription::run(commands)
|
||||
}
|
||||
|
||||
fn commands() -> impl Stream<Item = Command> {
|
||||
iced::stream::channel(16, async |mut output| {
|
||||
let inbox = INBOX.lock().ok().and_then(|mut i| i.take());
|
||||
let Some(mut inbox) = inbox else {
|
||||
// Already taken by an earlier run: stay pending rather than ending the subscription.
|
||||
std::future::pending::<()>().await;
|
||||
return;
|
||||
};
|
||||
while let Some(command) = inbox.recv().await {
|
||||
if output.send(command).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use souvlaki::SeekDirection;
|
||||
|
||||
#[test]
|
||||
fn os_events_map_to_player_commands() {
|
||||
assert_eq!(Command::from_event(MediaControlEvent::Toggle), Some(Command::Toggle));
|
||||
assert_eq!(Command::from_event(MediaControlEvent::Stop), Some(Command::Pause));
|
||||
assert_eq!(
|
||||
Command::from_event(MediaControlEvent::SetPosition(MediaPosition(Duration::from_secs(42)))),
|
||||
Some(Command::SeekTo(Duration::from_secs(42)))
|
||||
);
|
||||
assert_eq!(
|
||||
Command::from_event(MediaControlEvent::Seek(SeekDirection::Backward)),
|
||||
Some(Command::SeekBy { forward: false, by: SEEK_STEP })
|
||||
);
|
||||
assert_eq!(Command::from_event(MediaControlEvent::Raise), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
//! A monochrome mini player in the macOS menu bar, shown while the window is
|
||||
//! minimised: previous, play/pause and next, then the track. Clicking the track
|
||||
//! brings the window back. The glyphs are template SF Symbols and the text uses
|
||||
//! the label colour, so the menu bar tints both to match itself.
|
||||
|
||||
use ym_api::Track;
|
||||
|
||||
use crate::player::Status;
|
||||
|
||||
/// What the menu bar shows, so unchanged state isn't redrawn on every tick.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
struct NowPlaying {
|
||||
title: String,
|
||||
artist: String,
|
||||
playing: bool,
|
||||
}
|
||||
|
||||
impl NowPlaying {
|
||||
fn new(track: Option<&Track>, status: Status) -> Option<Self> {
|
||||
track.map(|t| Self {
|
||||
title: t.full_title(),
|
||||
artist: t.artist_line(),
|
||||
playing: matches!(status, Status::Playing | Status::Loading),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "macos", test))]
|
||||
fn line(&self) -> String {
|
||||
if self.artist.is_empty() { self.title.clone() } else { format!("{} — {}", self.title, self.artist) }
|
||||
}
|
||||
}
|
||||
|
||||
/// The app's handle on the mini player. Created on the main thread at startup.
|
||||
pub struct MiniPlayer {
|
||||
shown: Option<NowPlaying>,
|
||||
}
|
||||
|
||||
impl MiniPlayer {
|
||||
pub fn new() -> Self {
|
||||
#[cfg(target_os = "macos")]
|
||||
mac::install();
|
||||
Self { shown: None }
|
||||
}
|
||||
|
||||
/// Hands the mini player the current track and play state.
|
||||
pub fn update(&mut self, track: Option<&Track>, status: Status) {
|
||||
let now = NowPlaying::new(track, status);
|
||||
if now == self.shown {
|
||||
return;
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
mac::set_now_playing(now.clone());
|
||||
self.shown = now;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod mac {
|
||||
use std::cell::RefCell;
|
||||
use std::ptr::NonNull;
|
||||
|
||||
use block2::RcBlock;
|
||||
use objc2::rc::Retained;
|
||||
use objc2::runtime::{AnyObject, NSObjectProtocol, ProtocolObject, Sel};
|
||||
use objc2::{MainThreadMarker, MainThreadOnly, define_class, msg_send, sel};
|
||||
use objc2_app_kit::{
|
||||
NSApplication, NSButton, NSCellImagePosition, NSFont, NSFontWeightRegular, NSImage,
|
||||
NSImageSymbolConfiguration, NSLineBreakMode, NSStatusBar, NSStatusItem, NSTextField,
|
||||
NSVariableStatusItemLength, NSWindowDidDeminiaturizeNotification, NSWindowDidMiniaturizeNotification,
|
||||
};
|
||||
use objc2_foundation::{NSNotification, NSNotificationCenter, NSObject, NSPoint, NSRect, NSSize, NSString};
|
||||
|
||||
use super::NowPlaying;
|
||||
use crate::i18n::tr;
|
||||
use crate::media::{self, Command};
|
||||
|
||||
/// Width of each transport button, in points.
|
||||
const KEY: f64 = 22.0;
|
||||
/// Space at the ends and between the buttons and the text.
|
||||
const PAD: f64 = 4.0;
|
||||
/// Longer titles are cut with an ellipsis.
|
||||
const MAX_TEXT: f64 = 220.0;
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
now: Option<NowPlaying>,
|
||||
minimised: bool,
|
||||
bar: Option<Bar>,
|
||||
/// Kept so the window notifications keep arriving.
|
||||
observers: Vec<Retained<ProtocolObject<dyn NSObjectProtocol>>>,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static STATE: RefCell<State> = RefCell::default();
|
||||
}
|
||||
|
||||
/// Watches the window being minimised and restored. Off the main thread
|
||||
/// (in tests) there's no menu bar, so this does nothing.
|
||||
pub fn install() {
|
||||
if MainThreadMarker::new().is_none() {
|
||||
return;
|
||||
}
|
||||
let center = NSNotificationCenter::defaultCenter();
|
||||
// SAFETY: the notification names are AppKit constants, read on the main thread.
|
||||
let names = unsafe { [(NSWindowDidMiniaturizeNotification, true), (NSWindowDidDeminiaturizeNotification, false)] };
|
||||
let observers = names.map(|(name, minimised)| {
|
||||
let block = RcBlock::new(move |_: NonNull<NSNotification>| {
|
||||
STATE.with_borrow_mut(|s| {
|
||||
s.minimised = minimised;
|
||||
sync(s);
|
||||
});
|
||||
});
|
||||
// SAFETY: with no queue, AppKit runs the block on the thread that posts,
|
||||
// which for window notifications is the main thread.
|
||||
unsafe { center.addObserverForName_object_queue_usingBlock(Some(name), None, None, &block) }
|
||||
});
|
||||
STATE.with_borrow_mut(|s| s.observers.extend(observers));
|
||||
}
|
||||
|
||||
pub fn set_now_playing(now: Option<NowPlaying>) {
|
||||
STATE.with_borrow_mut(|s| {
|
||||
s.now = now;
|
||||
sync(s);
|
||||
});
|
||||
}
|
||||
|
||||
/// Adds, refreshes or removes the status item to match the state.
|
||||
fn sync(state: &mut State) {
|
||||
let Some(mtm) = MainThreadMarker::new() else { return };
|
||||
let now = state.now.as_ref().filter(|_| state.minimised);
|
||||
match (now, &state.bar) {
|
||||
(None, Some(_)) => {
|
||||
if let Some(bar) = state.bar.take() {
|
||||
NSStatusBar::systemStatusBar().removeStatusItem(&bar.item);
|
||||
}
|
||||
}
|
||||
(Some(now), None) => state.bar = Bar::new(mtm).inspect(|bar| bar.show(now)),
|
||||
(Some(now), Some(bar)) => bar.show(now),
|
||||
(None, None) => {}
|
||||
}
|
||||
}
|
||||
|
||||
struct Bar {
|
||||
item: Retained<NSStatusItem>,
|
||||
keys: [Retained<NSButton>; 3],
|
||||
label: Retained<NSTextField>,
|
||||
/// Receives the clicks; the buttons hold it only weakly.
|
||||
_target: Retained<Target>,
|
||||
}
|
||||
|
||||
impl Bar {
|
||||
fn new(mtm: MainThreadMarker) -> Option<Self> {
|
||||
let item = NSStatusBar::systemStatusBar().statusItemWithLength(NSVariableStatusItemLength);
|
||||
let button = item.button(mtm)?;
|
||||
let target = Target::new(mtm);
|
||||
let receiver: &AnyObject = ⌖
|
||||
// SAFETY: `Target` implements every action named here and outlives the buttons.
|
||||
unsafe {
|
||||
button.setTarget(Some(receiver));
|
||||
button.setAction(Some(sel!(restore:)));
|
||||
}
|
||||
let keys = [
|
||||
key("backward.fill", tr("Previous track"), sel!(previous:), receiver, mtm),
|
||||
key("play.fill", tr("Play"), sel!(toggle:), receiver, mtm),
|
||||
key("forward.fill", tr("Next track"), sel!(next:), receiver, mtm),
|
||||
];
|
||||
let label = NSTextField::labelWithString(&NSString::new(), mtm);
|
||||
label.setFont(Some(&NSFont::menuBarFontOfSize(0.0)));
|
||||
label.setLineBreakMode(NSLineBreakMode::ByTruncatingTail);
|
||||
for key in &keys {
|
||||
button.addSubview(key);
|
||||
}
|
||||
button.addSubview(&label);
|
||||
Some(Self { item, keys, label, _target: target })
|
||||
}
|
||||
|
||||
fn show(&self, now: &NowPlaying) {
|
||||
let (symbol, description) = if now.playing { ("pause.fill", tr("Pause")) } else { ("play.fill", tr("Play")) };
|
||||
if let Some(image) = symbol_image(symbol, description) {
|
||||
self.keys[1].setImage(Some(&image));
|
||||
}
|
||||
let line = NSString::from_str(&now.line());
|
||||
self.label.setStringValue(&line);
|
||||
self.label.sizeToFit();
|
||||
|
||||
let height = NSStatusBar::systemStatusBar().thickness();
|
||||
let mut x = PAD;
|
||||
for key in &self.keys {
|
||||
key.setFrame(NSRect::new(NSPoint::new(x, 0.0), NSSize::new(KEY, height)));
|
||||
x += KEY;
|
||||
}
|
||||
x += PAD;
|
||||
let text = self.label.frame().size;
|
||||
let width = text.width.min(MAX_TEXT).ceil();
|
||||
self.label.setFrame(NSRect::new(
|
||||
NSPoint::new(x, ((height - text.height) / 2.0).round()),
|
||||
NSSize::new(width, text.height),
|
||||
));
|
||||
self.item.setLength(x + width + PAD + 2.0);
|
||||
if let Some(button) = self.item.button(MainThreadMarker::from(&*self.label)) {
|
||||
button.setToolTip(Some(&line));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A borderless transport button showing one template SF Symbol.
|
||||
fn key(symbol: &str, description: &str, action: Sel, target: &AnyObject, mtm: MainThreadMarker) -> Retained<NSButton> {
|
||||
let button = NSButton::new(mtm);
|
||||
if let Some(image) = symbol_image(symbol, description) {
|
||||
button.setImage(Some(&image));
|
||||
}
|
||||
button.setBordered(false);
|
||||
button.setImagePosition(NSCellImagePosition::ImageOnly);
|
||||
button.setToolTip(Some(&NSString::from_str(description)));
|
||||
// SAFETY: `target` is the `Target` that implements `action`, kept alive by `Bar`.
|
||||
unsafe {
|
||||
button.setTarget(Some(target));
|
||||
button.setAction(Some(action));
|
||||
}
|
||||
button
|
||||
}
|
||||
|
||||
fn symbol_image(symbol: &str, description: &str) -> Option<Retained<NSImage>> {
|
||||
let image = NSImage::imageWithSystemSymbolName_accessibilityDescription(
|
||||
&NSString::from_str(symbol),
|
||||
Some(&NSString::from_str(description)),
|
||||
)?;
|
||||
// SAFETY: an AppKit constant.
|
||||
let weight = unsafe { NSFontWeightRegular };
|
||||
let config = NSImageSymbolConfiguration::configurationWithPointSize_weight(12.0, weight);
|
||||
let image = image.imageWithSymbolConfiguration(&config).unwrap_or(image);
|
||||
image.setTemplate(true);
|
||||
Some(image)
|
||||
}
|
||||
|
||||
/// Deminiaturises the app's windows and brings it to the front.
|
||||
fn restore(mtm: MainThreadMarker) {
|
||||
let app = NSApplication::sharedApplication(mtm);
|
||||
for window in app.windows() {
|
||||
if window.isMiniaturized() {
|
||||
window.deminiaturize(None);
|
||||
}
|
||||
}
|
||||
#[allow(deprecated)] // `activate` needs macOS 14.
|
||||
app.activateIgnoringOtherApps(true);
|
||||
}
|
||||
|
||||
define_class!(
|
||||
// SAFETY: NSObject has no subclassing requirements, and `Target` has no `Drop`.
|
||||
#[unsafe(super(NSObject))]
|
||||
#[thread_kind = MainThreadOnly]
|
||||
#[name = "MusyxMiniPlayerTarget"]
|
||||
struct Target;
|
||||
|
||||
impl Target {
|
||||
#[unsafe(method(previous:))]
|
||||
fn previous(&self, _sender: Option<&AnyObject>) {
|
||||
media::send(Command::Previous);
|
||||
}
|
||||
|
||||
#[unsafe(method(toggle:))]
|
||||
fn toggle(&self, _sender: Option<&AnyObject>) {
|
||||
media::send(Command::Toggle);
|
||||
}
|
||||
|
||||
#[unsafe(method(next:))]
|
||||
fn next(&self, _sender: Option<&AnyObject>) {
|
||||
media::send(Command::Next);
|
||||
}
|
||||
|
||||
#[unsafe(method(restore:))]
|
||||
fn restore(&self, _sender: Option<&AnyObject>) {
|
||||
restore(self.mtm());
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
impl Target {
|
||||
fn new(mtm: MainThreadMarker) -> Retained<Self> {
|
||||
let this = Self::alloc(mtm).set_ivars(());
|
||||
// SAFETY: plain NSObject initialisation.
|
||||
unsafe { msg_send![super(this), init] }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn line_joins_title_and_artist() {
|
||||
let now = NowPlaying { title: "Song".into(), artist: "Band".into(), playing: true };
|
||||
assert_eq!(now.line(), "Song — Band");
|
||||
let now = NowPlaying { artist: String::new(), ..now };
|
||||
assert_eq!(now.line(), "Song");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
//! The audio thread. It owns the output device and a rodio `Player`, takes
|
||||
//! [`Command`]s over a channel and reports [`Event`]s through an iced subscription.
|
||||
//!
|
||||
//! Everything here is about one loaded item at a time; the queue and fetching
|
||||
//! live in the UI state. Each load carries a `generation` so stale events from a
|
||||
//! previous track can be told apart.
|
||||
|
||||
use std::io::Cursor;
|
||||
use std::sync::Arc;
|
||||
use std::sync::mpsc::{self, RecvTimeoutError};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use iced::Subscription;
|
||||
use iced::futures::{SinkExt, Stream};
|
||||
use rodio::{Decoder, DeviceSinkBuilder, MixerDeviceSink, Player, Source};
|
||||
|
||||
/// How often position is reported while playing.
|
||||
const TICK: Duration = Duration::from_millis(250);
|
||||
|
||||
pub enum Command {
|
||||
Load { generation: u64, bytes: Arc<[u8]>, hint: String, play: bool },
|
||||
Play,
|
||||
Pause,
|
||||
Seek(Duration),
|
||||
Volume(f32),
|
||||
Stop,
|
||||
/// The output device failed or changed; sent by the audio stream's error callback.
|
||||
Reopen,
|
||||
}
|
||||
|
||||
/// A cheap handle the UI keeps to send commands.
|
||||
#[derive(Clone)]
|
||||
pub struct Handle(mpsc::Sender<Command>);
|
||||
|
||||
impl std::fmt::Debug for Handle {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("engine::Handle")
|
||||
}
|
||||
}
|
||||
|
||||
impl Handle {
|
||||
pub fn send(&self, command: Command) {
|
||||
// The thread only stops with the subscription, i.e. when the app exits.
|
||||
let _ = self.0.send(command);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Event {
|
||||
Ready(Handle),
|
||||
Loaded { generation: u64, duration: Option<Duration> },
|
||||
Position { generation: u64, position: Duration },
|
||||
Ended { generation: u64 },
|
||||
/// The bytes didn't decode (corrupt download, unsupported codec).
|
||||
DecodeFailed { generation: u64, reason: String },
|
||||
/// No output device, or it went away. Musyx keeps trying to reopen one.
|
||||
NoOutput(String),
|
||||
/// Sound is going to a device again after [`Event::NoOutput`].
|
||||
OutputReady,
|
||||
}
|
||||
|
||||
pub fn subscription() -> Subscription<Event> {
|
||||
Subscription::run(events)
|
||||
}
|
||||
|
||||
fn events() -> impl Stream<Item = Event> {
|
||||
iced::stream::channel(64, async |mut output| {
|
||||
let (commands, inbox) = mpsc::channel();
|
||||
let (events, mut outbox) = tokio::sync::mpsc::unbounded_channel();
|
||||
let own = commands.clone();
|
||||
std::thread::Builder::new()
|
||||
.name("musyx-audio".into())
|
||||
.spawn(move || run(inbox, own, events))
|
||||
.expect("spawn audio thread");
|
||||
|
||||
let _ = output.send(Event::Ready(Handle(commands))).await;
|
||||
while let Some(event) = outbox.recv().await {
|
||||
if output.send(event).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Opens the system's default output device.
|
||||
///
|
||||
/// rodio's own `open_default_sink` asks for a 50 ms buffer (2048 frames at
|
||||
/// 44.1 kHz), which Bluetooth headphones that cap at 1024 frames reject, and its
|
||||
/// fallback then filters out every macOS device. So pick the buffer here,
|
||||
/// clamped to what the device says it supports.
|
||||
fn open_output(on_error: impl FnMut(rodio::cpal::Error) + Send + Clone + 'static) -> Result<MixerDeviceSink, String> {
|
||||
use rodio::cpal::traits::{DeviceTrait, HostTrait};
|
||||
use rodio::cpal::{BufferSize, SupportedBufferSize};
|
||||
|
||||
let device = rodio::cpal::default_host()
|
||||
.default_output_device()
|
||||
.ok_or_else(|| "no default output device".to_owned())?;
|
||||
let config = device.default_output_config().map_err(|e| e.to_string())?;
|
||||
let buffer = match config.buffer_size() {
|
||||
SupportedBufferSize::Range { min, max } => {
|
||||
BufferSize::Fixed(buffer_frames(config.sample_rate(), *min, *max))
|
||||
}
|
||||
SupportedBufferSize::Unknown => BufferSize::Default,
|
||||
};
|
||||
DeviceSinkBuilder::default()
|
||||
.with_device(device)
|
||||
.with_supported_config(&config)
|
||||
.with_buffer_size(buffer)
|
||||
.with_error_callback(on_error)
|
||||
.open_stream()
|
||||
.or_else(|first| DeviceSinkBuilder::open_default_sink().map_err(|_| first.to_string()))
|
||||
}
|
||||
|
||||
/// About 50 ms of audio, rounded to a power of two, within the device's limits.
|
||||
fn buffer_frames(sample_rate: u32, min: u32, max: u32) -> u32 {
|
||||
(sample_rate / 20).next_power_of_two().clamp(min, max.max(min))
|
||||
}
|
||||
|
||||
/// An open device and the player feeding it. The sink must outlive the player:
|
||||
/// dropping it silences everything.
|
||||
struct Output {
|
||||
_sink: MixerDeviceSink,
|
||||
player: Player,
|
||||
}
|
||||
|
||||
/// The track loaded now, kept so it can be reloaded on a new device.
|
||||
struct Current {
|
||||
generation: u64,
|
||||
bytes: Arc<[u8]>,
|
||||
hint: String,
|
||||
}
|
||||
|
||||
/// Wait after a device change before reopening; macOS needs a moment to settle.
|
||||
const SETTLE: Duration = Duration::from_millis(400);
|
||||
/// How often to look for a device when there is none.
|
||||
const RETRY: Duration = Duration::from_secs(3);
|
||||
|
||||
fn open(commands: &mpsc::Sender<Command>) -> Result<Output, String> {
|
||||
let tx = commands.clone();
|
||||
let on_error = move |e: rodio::cpal::Error| {
|
||||
use rodio::cpal::ErrorKind;
|
||||
// Underruns are momentary glitches; only a lost or switched device needs a new stream.
|
||||
if matches!(e.kind(), ErrorKind::DeviceChanged | ErrorKind::DeviceNotAvailable) {
|
||||
let _ = tx.send(Command::Reopen);
|
||||
} else if !matches!(e.kind(), ErrorKind::Xrun) {
|
||||
eprintln!("audio stream error: {e}");
|
||||
}
|
||||
};
|
||||
let mut sink = open_output(on_error)?;
|
||||
sink.log_on_drop(false);
|
||||
let player = Player::connect_new(sink.mixer());
|
||||
Ok(Output { _sink: sink, player })
|
||||
}
|
||||
|
||||
fn decode(current: &Current) -> Result<Decoder<Cursor<Arc<[u8]>>>, String> {
|
||||
let len = current.bytes.len() as u64;
|
||||
Decoder::builder()
|
||||
.with_data(Cursor::new(current.bytes.clone()))
|
||||
.with_byte_len(len)
|
||||
.with_hint(¤t.hint)
|
||||
.with_seekable(true)
|
||||
.with_gapless(true)
|
||||
.build()
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn run(inbox: mpsc::Receiver<Command>, commands: mpsc::Sender<Command>, events: tokio::sync::mpsc::UnboundedSender<Event>) {
|
||||
let emit = |e: Event| {
|
||||
let _ = events.send(e);
|
||||
};
|
||||
|
||||
let mut output = match open(&commands) {
|
||||
Ok(o) => Some(o),
|
||||
Err(e) => {
|
||||
emit(Event::NoOutput(e));
|
||||
None
|
||||
}
|
||||
};
|
||||
let mut volume = 1.0_f32;
|
||||
let mut playing = false;
|
||||
let mut current: Option<Current> = None;
|
||||
let mut ended_sent = false;
|
||||
let mut last_reported = None;
|
||||
let mut last_attempt = Instant::now();
|
||||
|
||||
loop {
|
||||
match inbox.recv_timeout(TICK) {
|
||||
Ok(Command::Load { generation, bytes, hint, play }) => {
|
||||
let next = Current { generation, bytes, hint };
|
||||
match decode(&next) {
|
||||
Ok(source) => {
|
||||
let duration = source.total_duration();
|
||||
if let Some(o) = &output {
|
||||
o.player.clear();
|
||||
o.player.append(source);
|
||||
if play {
|
||||
o.player.play();
|
||||
}
|
||||
}
|
||||
playing = play;
|
||||
current = Some(next);
|
||||
ended_sent = false;
|
||||
last_reported = None;
|
||||
emit(Event::Loaded { generation, duration });
|
||||
}
|
||||
Err(reason) => {
|
||||
current = None;
|
||||
emit(Event::DecodeFailed { generation, reason });
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Command::Play) => {
|
||||
playing = true;
|
||||
if let Some(o) = &output {
|
||||
o.player.play();
|
||||
}
|
||||
}
|
||||
Ok(Command::Pause) => {
|
||||
playing = false;
|
||||
if let Some(o) = &output {
|
||||
o.player.pause();
|
||||
}
|
||||
}
|
||||
Ok(Command::Seek(to)) => {
|
||||
if let (Some(o), Some(c)) = (&output, ¤t)
|
||||
// A failed seek leaves playback where it was; the next tick reports that.
|
||||
&& o.player.try_seek(to).is_ok()
|
||||
{
|
||||
emit(Event::Position { generation: c.generation, position: o.player.get_pos() });
|
||||
}
|
||||
}
|
||||
Ok(Command::Volume(v)) => {
|
||||
volume = v.clamp(0.0, 1.0);
|
||||
if let Some(o) = &output {
|
||||
o.player.set_volume(volume);
|
||||
}
|
||||
}
|
||||
Ok(Command::Stop) => {
|
||||
if let Some(o) = &output {
|
||||
o.player.clear();
|
||||
}
|
||||
current = None;
|
||||
playing = false;
|
||||
}
|
||||
Ok(Command::Reopen) => {
|
||||
// Several errors arrive per change; one reopen covers them all.
|
||||
while let Ok(Command::Reopen) = inbox.try_recv() {}
|
||||
if last_attempt.elapsed() >= SETTLE {
|
||||
std::thread::sleep(SETTLE);
|
||||
while let Ok(Command::Reopen) = inbox.try_recv() {}
|
||||
output = reopen(output.take(), &commands, ¤t, volume, playing, &emit);
|
||||
last_attempt = Instant::now();
|
||||
}
|
||||
}
|
||||
Err(RecvTimeoutError::Timeout) => {}
|
||||
Err(RecvTimeoutError::Disconnected) => break,
|
||||
}
|
||||
|
||||
// No device yet: look again now and then (headphones plugged in later).
|
||||
if output.is_none() && last_attempt.elapsed() >= RETRY {
|
||||
last_attempt = Instant::now();
|
||||
output = reopen(None, &commands, ¤t, volume, playing, &emit);
|
||||
}
|
||||
|
||||
let (Some(o), Some(c)) = (&output, ¤t) else { continue };
|
||||
if o.player.empty() {
|
||||
if !ended_sent {
|
||||
ended_sent = true;
|
||||
emit(Event::Ended { generation: c.generation });
|
||||
}
|
||||
} else if !o.player.is_paused() {
|
||||
let position = o.player.get_pos();
|
||||
// Whole-tick resolution is plenty for a progress bar.
|
||||
let bucket = position.as_millis() / TICK.as_millis();
|
||||
if last_reported != Some(bucket) {
|
||||
last_reported = Some(bucket);
|
||||
emit(Event::Position { generation: c.generation, position });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens the current default device and puts the loaded track back where it was.
|
||||
fn reopen(
|
||||
old: Option<Output>,
|
||||
commands: &mpsc::Sender<Command>,
|
||||
current: &Option<Current>,
|
||||
volume: f32,
|
||||
playing: bool,
|
||||
emit: &impl Fn(Event),
|
||||
) -> Option<Output> {
|
||||
let position = old.as_ref().map(|o| o.player.get_pos());
|
||||
let had_output = old.is_some();
|
||||
drop(old);
|
||||
let output = match open(commands) {
|
||||
Ok(o) => o,
|
||||
Err(e) => {
|
||||
if had_output {
|
||||
emit(Event::NoOutput(e));
|
||||
}
|
||||
return None;
|
||||
}
|
||||
};
|
||||
output.player.set_volume(volume);
|
||||
if let Some(c) = current
|
||||
&& let Ok(source) = decode(c)
|
||||
{
|
||||
output.player.append(source);
|
||||
if let Some(at) = position {
|
||||
let _ = output.player.try_seek(at);
|
||||
}
|
||||
if playing {
|
||||
output.player.play();
|
||||
} else {
|
||||
output.player.pause();
|
||||
}
|
||||
}
|
||||
if !had_output {
|
||||
emit(Event::OutputReady);
|
||||
}
|
||||
Some(output)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::buffer_frames;
|
||||
|
||||
#[test]
|
||||
fn buffer_fits_bluetooth_limits() {
|
||||
assert_eq!(buffer_frames(44_100, 14, 1024), 1024);
|
||||
assert_eq!(buffer_frames(48_000, 15, 4096), 4096);
|
||||
assert_eq!(buffer_frames(8_000, 512, 4096), 512);
|
||||
assert_eq!(buffer_frames(44_100, 100, 50), 100, "a bogus range still yields the minimum");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,944 @@
|
||||
//! Playback state: the queue, what's loaded, and the rules for moving between
|
||||
//! tracks. Network work is described as [`Effect`]s for the app to run, so this
|
||||
//! module stays free of the API client and can be tested on its own.
|
||||
|
||||
pub mod engine;
|
||||
pub mod queue;
|
||||
|
||||
use crate::i18n::{tr, trf};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use ym_api::{Error, PlayReport, Stream, Track, WaveBatch, WaveEvent};
|
||||
|
||||
use engine::{Command, Event};
|
||||
pub use queue::{Queue, Repeat};
|
||||
|
||||
/// Give up after this many unplayable tracks in a row instead of skipping forever.
|
||||
const MAX_SKIPS: u8 = 3;
|
||||
/// "Previous" restarts the current track once it has played this long.
|
||||
const RESTART_AFTER: Duration = Duration::from_secs(3);
|
||||
/// Ask a station for more once this few tracks are left.
|
||||
const WAVE_LOW_WATER: usize = 2;
|
||||
/// Recent tracks sent with a request for more, so the station knows the context.
|
||||
const WAVE_CONTEXT: usize = 5;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Status {
|
||||
Loading,
|
||||
Playing,
|
||||
Paused,
|
||||
/// The queue ran out with repeat off. Play starts the last track again.
|
||||
Ended,
|
||||
}
|
||||
|
||||
/// Audio for one track, ready to hand to the engine.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Audio {
|
||||
pub stream: Stream,
|
||||
pub bytes: Arc<[u8]>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Msg {
|
||||
Engine(Event),
|
||||
/// Replace the queue. `shuffle` sets shuffle first; with it on, `start` is ignored.
|
||||
Play { tracks: Arc<[Track]>, start: usize, shuffle: Option<bool> },
|
||||
Toggle,
|
||||
Next,
|
||||
Previous,
|
||||
ToggleShuffle,
|
||||
CycleRepeat,
|
||||
/// The seek bar is being dragged; only the bar moves.
|
||||
SeekPreview(f32),
|
||||
SeekCommit,
|
||||
SetVolume(f32),
|
||||
ToggleMute,
|
||||
JumpTo(usize),
|
||||
Fetched { generation: u64, result: Result<Audio, Error> },
|
||||
Prefetched { track_id: String, result: Result<Audio, Error> },
|
||||
/// Start a station (`type:tag`).
|
||||
PlayWave { station: String },
|
||||
WaveBatch { station: String, result: Result<WaveBatch, Error> },
|
||||
/// The station's settings changed: replace what's queued after the current track.
|
||||
WaveRestart,
|
||||
/// Queue a track right after the current one (or play it if nothing is queued).
|
||||
PlayNext(Track),
|
||||
/// Queue a track at the end.
|
||||
Append(Track),
|
||||
Seek(Duration),
|
||||
}
|
||||
|
||||
/// Work the app has to do on the player's behalf.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Effect {
|
||||
Fetch { generation: u64, track_id: String },
|
||||
Prefetch { track_id: String },
|
||||
/// The token stopped working mid-session.
|
||||
SignedOut,
|
||||
/// Start a session (`session_id: None`) or continue one; `queue` is recent `full_id`s.
|
||||
WaveFetch { station: String, session_id: Option<String>, queue: Vec<String> },
|
||||
WaveFeedback { session_id: String, event: WaveEvent, batch_id: Option<String> },
|
||||
Report(PlayReport),
|
||||
}
|
||||
|
||||
/// A station being played, endlessly topped up.
|
||||
#[derive(Debug, Clone)]
|
||||
struct Wave {
|
||||
station: String,
|
||||
/// Set by the first batch; feedback can't be sent before it.
|
||||
session_id: Option<String>,
|
||||
/// The batch each queued track came in; feedback must name the track's own batch.
|
||||
batches: std::collections::HashMap<String, String>,
|
||||
fetching: bool,
|
||||
/// The queue ran out before the next batch came; advance when it does.
|
||||
waiting: bool,
|
||||
}
|
||||
|
||||
pub struct Player {
|
||||
engine: Option<engine::Handle>,
|
||||
queue: Option<Queue<Track>>,
|
||||
pub repeat: Repeat,
|
||||
shuffle: bool,
|
||||
pub volume: f32,
|
||||
pub muted: bool,
|
||||
generation: u64,
|
||||
status: Status,
|
||||
position: Duration,
|
||||
duration: Duration,
|
||||
current: Option<Audio>,
|
||||
/// Which track `current` holds, so a replay can reuse it.
|
||||
current_track_id: Option<String>,
|
||||
prefetched: Option<(String, Audio)>,
|
||||
skips: u8,
|
||||
seeking: Option<f32>,
|
||||
/// One line for the player bar when something went wrong.
|
||||
pub notice: Option<String>,
|
||||
wave: Option<Wave>,
|
||||
/// The track that started playing and hasn't been reported yet.
|
||||
started: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for Player {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
engine: None,
|
||||
queue: None,
|
||||
repeat: Repeat::Off,
|
||||
shuffle: false,
|
||||
volume: 0.7,
|
||||
muted: false,
|
||||
generation: 0,
|
||||
status: Status::Paused,
|
||||
position: Duration::ZERO,
|
||||
duration: Duration::ZERO,
|
||||
current: None,
|
||||
current_track_id: None,
|
||||
prefetched: None,
|
||||
skips: 0,
|
||||
seeking: None,
|
||||
notice: None,
|
||||
wave: None,
|
||||
started: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Player {
|
||||
/// Stops playback and forgets the queue (sign-out). The device and volume stay.
|
||||
pub fn reset(&mut self) {
|
||||
// No reports: the session they'd go to is ending.
|
||||
self.send(Command::Stop);
|
||||
*self = Self { engine: self.engine.take(), volume: self.volume, muted: self.muted, ..Self::default() };
|
||||
}
|
||||
|
||||
pub fn track(&self) -> Option<&Track> {
|
||||
self.queue.as_ref().map(Queue::current)
|
||||
}
|
||||
|
||||
pub fn queue(&self) -> Option<&Queue<Track>> {
|
||||
self.queue.as_ref()
|
||||
}
|
||||
|
||||
pub fn status(&self) -> Status {
|
||||
self.status
|
||||
}
|
||||
|
||||
pub fn shuffle(&self) -> bool {
|
||||
self.shuffle
|
||||
}
|
||||
|
||||
/// The station playing, if the queue is a wave.
|
||||
pub fn wave_station(&self) -> Option<&str> {
|
||||
self.wave.as_ref().map(|w| w.station.as_str())
|
||||
}
|
||||
|
||||
/// Where the seek bar should sit: the drag position while dragging.
|
||||
pub fn position(&self) -> Duration {
|
||||
self.seeking.map_or(self.position, Duration::from_secs_f32)
|
||||
}
|
||||
|
||||
pub fn duration(&self) -> Duration {
|
||||
self.duration
|
||||
}
|
||||
|
||||
pub fn stream(&self) -> Option<&Stream> {
|
||||
self.current.as_ref().map(|a| &a.stream)
|
||||
}
|
||||
|
||||
fn send(&self, command: Command) {
|
||||
if let Some(engine) = &self.engine {
|
||||
engine.send(command);
|
||||
}
|
||||
}
|
||||
|
||||
fn effective_volume(&self) -> f32 {
|
||||
if self.muted { 0.0 } else { self.volume }
|
||||
}
|
||||
|
||||
pub fn update(&mut self, msg: Msg) -> Vec<Effect> {
|
||||
match msg {
|
||||
Msg::Engine(event) => return self.on_engine(event),
|
||||
Msg::Play { tracks, start, shuffle } => {
|
||||
if let Some(on) = shuffle {
|
||||
self.shuffle = on;
|
||||
}
|
||||
let start = if shuffle == Some(true) && !tracks.is_empty() {
|
||||
rand::random_range(0..tracks.len())
|
||||
} else {
|
||||
start
|
||||
};
|
||||
let mut effects = self.leave(false);
|
||||
self.wave = None;
|
||||
self.queue = Queue::new(tracks.to_vec(), start, self.shuffle);
|
||||
self.skips = 0;
|
||||
self.notice = None;
|
||||
effects.extend(self.load_current());
|
||||
return effects;
|
||||
}
|
||||
Msg::PlayNext(track) | Msg::Append(track) if self.queue.is_none() => {
|
||||
return self.update(Msg::Play { tracks: Arc::from(vec![track]), start: 0, shuffle: None });
|
||||
}
|
||||
Msg::PlayNext(track) => {
|
||||
if let Some(queue) = &mut self.queue
|
||||
&& queue.insert_next(track, |a, b| a.id == b.id)
|
||||
{
|
||||
return self.prefetch_next();
|
||||
}
|
||||
}
|
||||
Msg::Append(track) => {
|
||||
if let Some(queue) = &mut self.queue {
|
||||
queue.extend([track]);
|
||||
}
|
||||
return self.prefetch_next();
|
||||
}
|
||||
Msg::Seek(to) => self.seek(to),
|
||||
Msg::PlayWave { station } => {
|
||||
let mut effects = self.leave(false);
|
||||
self.queue = None;
|
||||
self.current = None;
|
||||
self.skips = 0;
|
||||
self.notice = None;
|
||||
self.status = Status::Loading;
|
||||
self.send(Command::Stop);
|
||||
self.wave = Some(Wave {
|
||||
station: station.clone(),
|
||||
session_id: None,
|
||||
batches: Default::default(),
|
||||
fetching: true,
|
||||
waiting: true,
|
||||
});
|
||||
effects.push(Effect::WaveFetch { station, session_id: None, queue: Vec::new() });
|
||||
return effects;
|
||||
}
|
||||
Msg::WaveBatch { station, result } => return self.on_batch(station, result),
|
||||
Msg::WaveRestart => {
|
||||
// Settings are seeds of a session, so new settings mean a new session.
|
||||
let queue: Vec<String> = self.track().map(Track::full_id).into_iter().collect();
|
||||
let Some(wave) = &mut self.wave else { return vec![] };
|
||||
if let Some(q) = &mut self.queue {
|
||||
q.clear_upcoming();
|
||||
}
|
||||
self.prefetched = None;
|
||||
wave.session_id = None;
|
||||
wave.fetching = true;
|
||||
return vec![Effect::WaveFetch { station: wave.station.clone(), session_id: None, queue }];
|
||||
}
|
||||
Msg::Toggle => match self.status {
|
||||
Status::Playing => {
|
||||
self.send(Command::Pause);
|
||||
self.status = Status::Paused;
|
||||
}
|
||||
Status::Paused if self.current.is_some() => {
|
||||
self.send(Command::Play);
|
||||
self.status = Status::Playing;
|
||||
}
|
||||
Status::Paused if self.queue.is_some() => return self.load_current(),
|
||||
Status::Ended => return self.load_current(),
|
||||
Status::Paused | Status::Loading => {}
|
||||
},
|
||||
Msg::Next => return self.step(true, false),
|
||||
Msg::Previous => {
|
||||
if self.position >= RESTART_AFTER || !self.can_go_back() {
|
||||
self.seek(Duration::ZERO);
|
||||
} else {
|
||||
let mut effects = self.leave(false);
|
||||
if let Some(queue) = &mut self.queue {
|
||||
queue.back(self.repeat);
|
||||
effects.extend(self.load_current());
|
||||
}
|
||||
return effects;
|
||||
}
|
||||
}
|
||||
// A station decides its own order.
|
||||
Msg::ToggleShuffle if self.wave.is_some() => {}
|
||||
Msg::ToggleShuffle => {
|
||||
self.shuffle = !self.shuffle;
|
||||
if let Some(queue) = &mut self.queue {
|
||||
queue.set_shuffle(self.shuffle);
|
||||
}
|
||||
return self.prefetch_next();
|
||||
}
|
||||
Msg::CycleRepeat => {
|
||||
self.repeat = self.repeat.next();
|
||||
return self.prefetch_next();
|
||||
}
|
||||
Msg::SeekPreview(secs) => self.seeking = Some(secs),
|
||||
Msg::SeekCommit => {
|
||||
if let Some(secs) = self.seeking.take() {
|
||||
self.seek(Duration::from_secs_f32(secs.max(0.0)));
|
||||
}
|
||||
}
|
||||
Msg::SetVolume(v) => {
|
||||
self.volume = v.clamp(0.0, 1.0);
|
||||
self.muted = self.volume == 0.0;
|
||||
self.send(Command::Volume(self.effective_volume()));
|
||||
}
|
||||
Msg::ToggleMute => {
|
||||
self.muted = !self.muted;
|
||||
if !self.muted && self.volume == 0.0 {
|
||||
self.volume = 0.5;
|
||||
}
|
||||
self.send(Command::Volume(self.effective_volume()));
|
||||
}
|
||||
Msg::JumpTo(pos) => {
|
||||
let mut effects = self.leave(false);
|
||||
if let Some(queue) = &mut self.queue {
|
||||
queue.jump(pos);
|
||||
effects.extend(self.load_current());
|
||||
}
|
||||
return effects;
|
||||
}
|
||||
Msg::Fetched { generation, result } => {
|
||||
if generation != self.generation {
|
||||
return vec![];
|
||||
}
|
||||
match result {
|
||||
Ok(audio) => self.start(audio),
|
||||
Err(Error::Unauthorized(_)) => return vec![Effect::SignedOut],
|
||||
Err(e) => {
|
||||
eprintln!("fetch: {e}");
|
||||
return self.skip_unplayable();
|
||||
}
|
||||
}
|
||||
}
|
||||
Msg::Prefetched { track_id, result } => match result {
|
||||
Ok(audio) => self.prefetched = Some((track_id, audio)),
|
||||
Err(e) => eprintln!("prefetch {track_id}: {e}"),
|
||||
},
|
||||
}
|
||||
vec![]
|
||||
}
|
||||
|
||||
fn on_engine(&mut self, event: Event) -> Vec<Effect> {
|
||||
match event {
|
||||
Event::Ready(handle) => {
|
||||
handle.send(Command::Volume(self.effective_volume()));
|
||||
self.engine = Some(handle);
|
||||
}
|
||||
Event::NoOutput(reason) => {
|
||||
eprintln!("audio output: {reason}");
|
||||
self.notice = Some(
|
||||
tr("No sound output found. Connect speakers or headphones and playback picks up.").into(),
|
||||
);
|
||||
}
|
||||
Event::OutputReady => self.notice = None,
|
||||
Event::Loaded { generation, duration } if generation == self.generation => {
|
||||
if let Some(d) = duration.filter(|d| !d.is_zero()) {
|
||||
self.duration = d;
|
||||
}
|
||||
self.status = Status::Playing;
|
||||
self.skips = 0;
|
||||
let mut effects = Vec::new();
|
||||
if let Some((id, full_id)) = self.track().map(|t| (t.id.clone(), t.full_id())) {
|
||||
if let Some(wave) = &self.wave
|
||||
&& let Some(session_id) = wave.session_id.clone()
|
||||
{
|
||||
effects.push(Effect::WaveFeedback {
|
||||
session_id,
|
||||
event: WaveEvent::TrackStarted { track_id: full_id },
|
||||
batch_id: wave.batches.get(&id).cloned(),
|
||||
});
|
||||
}
|
||||
self.started = Some(id);
|
||||
}
|
||||
effects.extend(self.prefetch_next());
|
||||
effects.extend(self.top_up());
|
||||
return effects;
|
||||
}
|
||||
Event::Position { generation, position } if generation == self.generation => {
|
||||
self.position = position;
|
||||
}
|
||||
Event::Ended { generation } if generation == self.generation => {
|
||||
return self.step(false, true);
|
||||
}
|
||||
Event::DecodeFailed { generation, reason } if generation == self.generation => {
|
||||
eprintln!("decode: {reason}");
|
||||
return self.skip_unplayable();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
vec![]
|
||||
}
|
||||
|
||||
fn can_go_back(&self) -> bool {
|
||||
self.queue.as_ref().is_some_and(|q| q.len() > 1)
|
||||
}
|
||||
|
||||
fn seek(&mut self, to: Duration) {
|
||||
let to = to.min(self.duration);
|
||||
self.position = to;
|
||||
if self.status == Status::Ended {
|
||||
// The player is empty after the end; reload and play from `to`.
|
||||
if let Some(audio) = self.current.clone() {
|
||||
self.load_audio(audio, true);
|
||||
self.send(Command::Seek(to));
|
||||
}
|
||||
} else {
|
||||
self.send(Command::Seek(to));
|
||||
}
|
||||
}
|
||||
|
||||
/// Next track. `finished` distinguishes a natural end (repeat-one replays)
|
||||
/// from a skip; `user` skips always move on.
|
||||
fn step(&mut self, user: bool, finished: bool) -> Vec<Effect> {
|
||||
let mut effects = self.leave(finished && !user);
|
||||
let Some(queue) = &mut self.queue else { return effects };
|
||||
if queue.advance(self.repeat, finished && !user) {
|
||||
effects.extend(self.load_current());
|
||||
} else if let Some(wave) = &mut self.wave {
|
||||
// The batch ran dry; carry on as soon as the next one lands.
|
||||
wave.waiting = true;
|
||||
self.status = Status::Loading;
|
||||
effects.extend(self.top_up());
|
||||
} else {
|
||||
self.status = Status::Ended;
|
||||
self.position = self.duration;
|
||||
}
|
||||
effects
|
||||
}
|
||||
|
||||
/// Reports the track being left: to the listening history always, and to the
|
||||
/// station when it's a wave. `finished` means it played to the end.
|
||||
fn leave(&mut self, finished: bool) -> Vec<Effect> {
|
||||
let Some(id) = self.started.take() else { return vec![] };
|
||||
let Some(track) = self.track().filter(|t| t.id == id) else { return vec![] };
|
||||
let played = if finished { self.duration } else { self.position.min(self.duration) };
|
||||
let mut effects = vec![Effect::Report(PlayReport {
|
||||
track_id: id.clone(),
|
||||
album_id: track.album.as_ref().map(|a| a.id),
|
||||
length: self.duration,
|
||||
played,
|
||||
end_position: played,
|
||||
from: if self.wave.is_some() { "musyx-wave".into() } else { "musyx-desktop".into() },
|
||||
})];
|
||||
if let Some(wave) = &self.wave
|
||||
&& let Some(session_id) = wave.session_id.clone()
|
||||
{
|
||||
let batch_id = wave.batches.get(&id).cloned();
|
||||
let track_id = track.full_id();
|
||||
let event = if finished {
|
||||
WaveEvent::TrackFinished { track_id, played }
|
||||
} else {
|
||||
WaveEvent::Skipped { track_id, played }
|
||||
};
|
||||
effects.push(Effect::WaveFeedback { session_id, event, batch_id });
|
||||
}
|
||||
effects
|
||||
}
|
||||
|
||||
/// Asks the station for more when the queue runs low.
|
||||
fn top_up(&mut self) -> Vec<Effect> {
|
||||
let (Some(wave), Some(queue)) = (&mut self.wave, &self.queue) else { return vec![] };
|
||||
if wave.fetching || queue.upcoming().count() >= WAVE_LOW_WATER {
|
||||
return vec![];
|
||||
}
|
||||
wave.fetching = true;
|
||||
vec![Effect::WaveFetch {
|
||||
station: wave.station.clone(),
|
||||
session_id: wave.session_id.clone(),
|
||||
queue: queue.tail(WAVE_CONTEXT).map(Track::full_id).collect(),
|
||||
}]
|
||||
}
|
||||
|
||||
fn on_batch(&mut self, station: String, result: Result<WaveBatch, Error>) -> Vec<Effect> {
|
||||
let Some(wave) = self.wave.as_mut().filter(|w| w.station == station) else { return vec![] };
|
||||
wave.fetching = false;
|
||||
let batch = match result {
|
||||
Ok(batch) if !batch.tracks.is_empty() => batch,
|
||||
Ok(_) | Err(_) => {
|
||||
if let Err(Error::Unauthorized(_)) = result {
|
||||
return vec![Effect::SignedOut];
|
||||
}
|
||||
if let Err(e) = &result {
|
||||
eprintln!("wave batch: {e}");
|
||||
}
|
||||
if wave.waiting {
|
||||
wave.waiting = false;
|
||||
self.status = if self.queue.is_some() { Status::Ended } else { Status::Paused };
|
||||
self.notice = Some(tr("Couldn't load more of this station. Check your connection and try again.").into());
|
||||
}
|
||||
return vec![];
|
||||
}
|
||||
};
|
||||
if let Some(batch_id) = &batch.batch_id {
|
||||
for track in &batch.tracks {
|
||||
wave.batches.insert(track.id.clone(), batch_id.clone());
|
||||
}
|
||||
}
|
||||
// The first batch of a session opens it: tell the station the radio started.
|
||||
let mut effects = Vec::new();
|
||||
if wave.session_id.is_none()
|
||||
&& let Some(session_id) = batch.session_id.clone()
|
||||
{
|
||||
wave.session_id = Some(session_id.clone());
|
||||
effects.push(Effect::WaveFeedback {
|
||||
session_id,
|
||||
event: WaveEvent::Started,
|
||||
batch_id: batch.batch_id.clone(),
|
||||
});
|
||||
}
|
||||
let waiting = std::mem::replace(&mut wave.waiting, false);
|
||||
let next = match &mut self.queue {
|
||||
None => {
|
||||
self.queue = Queue::new(batch.tracks, 0, false);
|
||||
self.load_current()
|
||||
}
|
||||
Some(queue) => {
|
||||
queue.extend(batch.tracks);
|
||||
if waiting && queue.advance(Repeat::Off, false) {
|
||||
self.load_current()
|
||||
} else {
|
||||
self.prefetch_next()
|
||||
}
|
||||
}
|
||||
};
|
||||
effects.extend(next);
|
||||
effects
|
||||
}
|
||||
|
||||
fn load_current(&mut self) -> Vec<Effect> {
|
||||
let Some(track) = self.track().cloned() else { return vec![] };
|
||||
self.generation += 1;
|
||||
self.position = Duration::ZERO;
|
||||
self.duration = track.duration;
|
||||
self.seeking = None;
|
||||
|
||||
// Replaying the same track (repeat one, play after the end) reuses its bytes.
|
||||
let reuse = match (&self.current, self.prefetched.take()) {
|
||||
(_, Some((id, audio))) if id == track.id => Some(audio),
|
||||
(Some(audio), other) => {
|
||||
self.prefetched = other;
|
||||
self.current_is(&track).then(|| audio.clone())
|
||||
}
|
||||
(None, other) => {
|
||||
self.prefetched = other;
|
||||
None
|
||||
}
|
||||
};
|
||||
match reuse {
|
||||
Some(audio) => {
|
||||
self.start(audio);
|
||||
vec![]
|
||||
}
|
||||
None => {
|
||||
self.status = Status::Loading;
|
||||
self.current = None;
|
||||
vec![Effect::Fetch { generation: self.generation, track_id: track.id }]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn current_is(&self, track: &Track) -> bool {
|
||||
self.current_track_id.as_deref() == Some(track.id.as_str())
|
||||
}
|
||||
|
||||
fn start(&mut self, audio: Audio) {
|
||||
self.load_audio(audio, true);
|
||||
}
|
||||
|
||||
fn load_audio(&mut self, audio: Audio, play: bool) {
|
||||
self.current_track_id = self.track().map(|t| t.id.clone());
|
||||
self.status = Status::Loading;
|
||||
self.send(Command::Load {
|
||||
generation: self.generation,
|
||||
bytes: audio.bytes.clone(),
|
||||
hint: audio.stream.container().to_owned(),
|
||||
play,
|
||||
});
|
||||
self.current = Some(audio);
|
||||
}
|
||||
|
||||
fn prefetch_next(&mut self) -> Vec<Effect> {
|
||||
let Some(queue) = &self.queue else { return vec![] };
|
||||
let Some(next) = queue.peek_next(self.repeat) else { return vec![] };
|
||||
if self.current_is(next) {
|
||||
return vec![];
|
||||
}
|
||||
if self.prefetched.as_ref().is_some_and(|(id, _)| *id == next.id) {
|
||||
return vec![];
|
||||
}
|
||||
self.prefetched = None;
|
||||
vec![Effect::Prefetch { track_id: next.id.clone() }]
|
||||
}
|
||||
|
||||
fn skip_unplayable(&mut self) -> Vec<Effect> {
|
||||
let title = self.track().map(Track::full_title).unwrap_or_default();
|
||||
self.skips += 1;
|
||||
self.current = None;
|
||||
if self.skips >= MAX_SKIPS {
|
||||
self.status = Status::Paused;
|
||||
self.notice = Some(tr("Several tracks in a row couldn't be played. Check your connection and try again.").into());
|
||||
return vec![];
|
||||
}
|
||||
self.notice = Some(trf("Couldn't play “{}”, so it was skipped.", &[&title]));
|
||||
self.step(true, false)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn track(id: &str, secs: u64) -> Track {
|
||||
let json = format!(r#"{{"id":"{id}","title":"T{id}","durationMs":{}}}"#, secs * 1000);
|
||||
Track::from_json(&json).unwrap()
|
||||
}
|
||||
|
||||
fn audio() -> Audio {
|
||||
Audio {
|
||||
stream: Stream { urls: vec!["u".into()], codec: "mp3".into(), bitrate_kbps: 320, preview: false, key: None },
|
||||
bytes: Arc::from(vec![0u8; 4]),
|
||||
}
|
||||
}
|
||||
|
||||
fn fetch_generation(effects: &[Effect]) -> Option<u64> {
|
||||
effects.iter().find_map(|e| match e {
|
||||
Effect::Fetch { generation, .. } => Some(*generation),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn playing(n: usize, start: usize) -> Player {
|
||||
let mut p = Player::default();
|
||||
let tracks: Arc<[Track]> = (0..n).map(|i| track(&i.to_string(), 100)).collect();
|
||||
let effects = p.update(Msg::Play { tracks, start, shuffle: None });
|
||||
let Some(generation) = fetch_generation(&effects) else {
|
||||
panic!("expected fetch, got {effects:?}");
|
||||
};
|
||||
p.update(Msg::Fetched { generation, result: Ok(audio()) });
|
||||
p.update(Msg::Engine(Event::Loaded { generation, duration: None }));
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn play_fetches_then_plays_and_prefetches_next() {
|
||||
let mut p = Player::default();
|
||||
let tracks: Arc<[Track]> = vec![track("a", 10), track("b", 20)].into();
|
||||
let effects = p.update(Msg::Play { tracks, start: 0, shuffle: None });
|
||||
assert!(effects.contains(&Effect::Fetch { generation: 1, track_id: "a".into() }), "{effects:?}");
|
||||
assert_eq!(effects.iter().filter(|e| matches!(e, Effect::Fetch { .. })).count(), 1);
|
||||
assert_eq!(p.status(), Status::Loading);
|
||||
assert!(p.update(Msg::Fetched { generation: 1, result: Ok(audio()) }).is_empty());
|
||||
let effects = p.update(Msg::Engine(Event::Loaded { generation: 1, duration: None }));
|
||||
assert_eq!(p.status(), Status::Playing);
|
||||
assert_eq!(p.duration(), Duration::from_secs(10));
|
||||
assert_eq!(effects, vec![Effect::Prefetch { track_id: "b".into() }]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prefetched_audio_is_used_without_another_fetch() {
|
||||
let mut p = playing(3, 0);
|
||||
p.update(Msg::Prefetched { track_id: "1".into(), result: Ok(audio()) });
|
||||
let generation = p.generation;
|
||||
let effects = p.update(Msg::Engine(Event::Ended { generation }));
|
||||
assert!(!effects.iter().any(|e| matches!(e, Effect::Fetch { .. })), "{effects:?}");
|
||||
assert_eq!(p.track().unwrap().id, "1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_events_are_ignored() {
|
||||
let mut p = playing(3, 0);
|
||||
let old = p.generation;
|
||||
p.update(Msg::Next);
|
||||
p.update(Msg::Engine(Event::Position { generation: old, position: Duration::from_secs(50) }));
|
||||
assert_eq!(p.position(), Duration::ZERO);
|
||||
assert!(p.update(Msg::Fetched { generation: old, result: Ok(audio()) }).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn end_of_queue_stops_and_play_restarts_last_track() {
|
||||
let mut p = playing(1, 0);
|
||||
let generation = p.generation;
|
||||
let effects = p.update(Msg::Engine(Event::Ended { generation }));
|
||||
assert!(
|
||||
matches!(effects.as_slice(), [Effect::Report(r)] if r.played == Duration::from_secs(100) && r.from == "musyx-desktop"),
|
||||
"a finished track is reported once: {effects:?}"
|
||||
);
|
||||
assert_eq!(p.status(), Status::Ended);
|
||||
let effects = p.update(Msg::Toggle);
|
||||
assert!(fetch_generation(&effects).is_none(), "replay comes from memory: {effects:?}");
|
||||
assert_eq!(p.status(), Status::Loading);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeat_one_replays_from_memory() {
|
||||
let mut p = playing(3, 1);
|
||||
p.update(Msg::CycleRepeat);
|
||||
p.update(Msg::CycleRepeat);
|
||||
assert_eq!(p.repeat, Repeat::One);
|
||||
let generation = p.generation;
|
||||
let effects = p.update(Msg::Engine(Event::Ended { generation }));
|
||||
assert!(!effects.iter().any(|e| matches!(e, Effect::Fetch { .. })), "{effects:?}");
|
||||
assert_eq!(p.track().unwrap().id, "1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn previous_restarts_after_three_seconds() {
|
||||
let mut p = playing(3, 1);
|
||||
let generation = p.generation;
|
||||
p.update(Msg::Engine(Event::Position { generation, position: Duration::from_secs(10) }));
|
||||
p.update(Msg::Previous);
|
||||
assert_eq!(p.track().unwrap().id, "1");
|
||||
assert_eq!(p.position(), Duration::ZERO);
|
||||
p.update(Msg::Previous);
|
||||
assert_eq!(p.track().unwrap().id, "0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unplayable_tracks_are_skipped_then_given_up_on() {
|
||||
let mut p = playing(5, 0);
|
||||
for expected_skips in 1..MAX_SKIPS {
|
||||
p.update(Msg::Next);
|
||||
let generation = p.generation;
|
||||
p.update(Msg::Fetched { generation, result: Err(Error::Api("gone".into())) });
|
||||
assert_eq!(p.skips, expected_skips);
|
||||
assert!(p.notice.as_deref().unwrap().contains("skipped"));
|
||||
}
|
||||
let generation = p.generation;
|
||||
let effects = p.update(Msg::Fetched { generation, result: Err(Error::Api("gone".into())) });
|
||||
assert!(effects.is_empty());
|
||||
assert!(p.notice.as_deref().unwrap().contains("Several tracks"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expired_token_signs_out() {
|
||||
let mut p = Player::default();
|
||||
let tracks: Arc<[Track]> = vec![track("a", 10)].into();
|
||||
p.update(Msg::Play { tracks, start: 0, shuffle: None });
|
||||
let effects =
|
||||
p.update(Msg::Fetched { generation: 1, result: Err(Error::Unauthorized("401".into())) });
|
||||
assert_eq!(effects, vec![Effect::SignedOut]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seek_preview_moves_bar_until_commit() {
|
||||
let mut p = playing(1, 0);
|
||||
p.update(Msg::SeekPreview(42.0));
|
||||
assert_eq!(p.position(), Duration::from_secs(42));
|
||||
p.update(Msg::SeekCommit);
|
||||
assert_eq!(p.position(), Duration::from_secs(42));
|
||||
assert!(p.seeking.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shuffle_play_turns_shuffle_on() {
|
||||
let mut p = Player::default();
|
||||
let tracks: Arc<[Track]> = (0..20).map(|i| track(&i.to_string(), 10)).collect();
|
||||
p.update(Msg::Play { tracks, start: 0, shuffle: Some(true) });
|
||||
assert!(p.shuffle());
|
||||
assert_eq!(p.queue().unwrap().upcoming().count(), 19);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_keeps_volume_but_drops_queue() {
|
||||
let mut p = playing(3, 0);
|
||||
p.update(Msg::SetVolume(0.3));
|
||||
p.reset();
|
||||
assert!(p.track().is_none());
|
||||
assert_eq!(p.volume, 0.3);
|
||||
}
|
||||
|
||||
fn wave_with(n: usize) -> Player {
|
||||
let mut p = Player::default();
|
||||
let effects = p.update(Msg::PlayWave { station: "user:onyourwave".into() });
|
||||
assert!(matches!(effects.as_slice(), [Effect::WaveFetch { session_id: None, .. }]), "{effects:?}");
|
||||
let batch = WaveBatch {
|
||||
session_id: Some("s1".into()),
|
||||
tracks: (0..n).map(|i| track(&format!("w{i}"), 100)).collect(),
|
||||
batch_id: Some("b1".into()),
|
||||
};
|
||||
let effects = p.update(Msg::WaveBatch { station: "user:onyourwave".into(), result: Ok(batch) });
|
||||
assert!(matches!(&effects[0],
|
||||
Effect::WaveFeedback { session_id, event: WaveEvent::Started, batch_id: Some(b) } if session_id == "s1" && b == "b1"));
|
||||
let Some(Effect::Fetch { generation, .. }) = effects.get(1).cloned() else { panic!("{effects:?}") };
|
||||
p.update(Msg::Fetched { generation, result: Ok(audio()) });
|
||||
p
|
||||
}
|
||||
|
||||
fn loaded(p: &mut Player) -> Vec<Effect> {
|
||||
let generation = p.generation;
|
||||
p.update(Msg::Engine(Event::Loaded { generation, duration: None }))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wave_reports_start_and_tops_up_when_low() {
|
||||
let mut p = wave_with(3);
|
||||
let effects = loaded(&mut p);
|
||||
assert!(effects.iter().any(|e| matches!(e,
|
||||
Effect::WaveFeedback { event: WaveEvent::TrackStarted { track_id }, batch_id: Some(b), .. }
|
||||
if track_id == "w0" && b == "b1")));
|
||||
assert!(!effects.iter().any(|e| matches!(e, Effect::WaveFetch { .. })), "two still queued");
|
||||
|
||||
let generation = p.generation;
|
||||
p.update(Msg::Engine(Event::Position { generation, position: Duration::from_secs(20) }));
|
||||
let effects = p.update(Msg::Next);
|
||||
assert!(effects.iter().any(|e| matches!(e,
|
||||
Effect::WaveFeedback { event: WaveEvent::Skipped { track_id, played }, .. }
|
||||
if track_id == "w0" && *played == Duration::from_secs(20))));
|
||||
assert!(effects.iter().any(|e| matches!(e, Effect::Report(r) if r.from == "musyx-wave")));
|
||||
|
||||
let generation = p.generation;
|
||||
p.update(Msg::Fetched { generation, result: Ok(audio()) });
|
||||
let effects = loaded(&mut p);
|
||||
assert!(
|
||||
effects.iter().any(|e| matches!(e,
|
||||
Effect::WaveFetch { session_id: Some(s), queue, .. } if s == "s1" && queue.last().map(String::as_str) == Some("w2"))),
|
||||
"one left, so ask the session for more with recent tracks: {effects:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feedback_names_each_tracks_own_batch() {
|
||||
let mut p = wave_with(2);
|
||||
loaded(&mut p);
|
||||
let more = WaveBatch { session_id: Some("s1".into()), tracks: vec![track("n0", 10)], batch_id: Some("b2".into()) };
|
||||
p.update(Msg::WaveBatch { station: "user:onyourwave".into(), result: Ok(more) });
|
||||
let effects = p.update(Msg::Next);
|
||||
assert!(effects.iter().any(|e| matches!(e,
|
||||
Effect::WaveFeedback { event: WaveEvent::Skipped { .. }, batch_id: Some(b), .. } if b == "b1")),
|
||||
"w0 came in b1 even though b2 arrived since: {effects:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wave_waits_for_the_next_batch_when_dry() {
|
||||
let mut p = wave_with(1);
|
||||
loaded(&mut p);
|
||||
let generation = p.generation;
|
||||
let effects = p.update(Msg::Engine(Event::Ended { generation }));
|
||||
assert!(effects.iter().any(|e| matches!(e, Effect::WaveFeedback { event: WaveEvent::TrackFinished { .. }, .. })));
|
||||
assert_eq!(p.status(), Status::Loading, "a wave doesn't end");
|
||||
let batch = WaveBatch { session_id: Some("s1".into()), tracks: vec![track("w9", 50)], batch_id: Some("b2".into()) };
|
||||
let effects = p.update(Msg::WaveBatch { station: "user:onyourwave".into(), result: Ok(batch) });
|
||||
assert!(matches!(effects.first(), Some(Effect::Fetch { track_id, .. }) if track_id == "w9"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_settings_start_a_new_session() {
|
||||
let mut p = wave_with(3);
|
||||
loaded(&mut p);
|
||||
let effects = p.update(Msg::WaveRestart);
|
||||
assert!(matches!(effects.as_slice(), [Effect::WaveFetch { session_id: None, queue, .. }] if queue == &["w0"]));
|
||||
assert_eq!(p.queue().unwrap().upcoming().count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batches_for_another_station_are_ignored() {
|
||||
let mut p = wave_with(2);
|
||||
let batch = WaveBatch { session_id: None, tracks: vec![track("x", 10)], batch_id: None };
|
||||
assert!(p.update(Msg::WaveBatch { station: "genre:rock".into(), result: Ok(batch) }).is_empty());
|
||||
assert_eq!(p.queue().unwrap().len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn playing_a_list_leaves_wave_mode_and_shuffle_is_ignored_in_waves() {
|
||||
let mut p = wave_with(2);
|
||||
p.update(Msg::ToggleShuffle);
|
||||
assert!(!p.shuffle());
|
||||
let tracks: Arc<[Track]> = vec![track("a", 10)].into();
|
||||
p.update(Msg::Play { tracks, start: 0, shuffle: None });
|
||||
assert!(p.wave_station().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn play_next_and_append() {
|
||||
let mut p = playing(3, 0);
|
||||
p.update(Msg::PlayNext(track("n", 5)));
|
||||
p.update(Msg::Append(track("z", 5)));
|
||||
let upcoming: Vec<&str> = p.queue().unwrap().upcoming().map(|(_, t)| t.id.as_str()).collect();
|
||||
assert_eq!(upcoming, ["n", "1", "2", "z"]);
|
||||
|
||||
let mut empty = Player::default();
|
||||
let effects = empty.update(Msg::Append(track("solo", 5)));
|
||||
assert!(effects.iter().any(|e| matches!(e, Effect::Fetch { track_id, .. } if track_id == "solo")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn play_next_wins_over_an_already_prefetched_track() {
|
||||
let mut p = playing(3, 0);
|
||||
p.update(Msg::Prefetched { track_id: "1".into(), result: Ok(audio()) });
|
||||
let effects = p.update(Msg::PlayNext(track("n", 5)));
|
||||
assert!(effects.contains(&Effect::Prefetch { track_id: "n".into() }), "{effects:?}");
|
||||
let generation = p.generation;
|
||||
let effects = p.update(Msg::Engine(Event::Ended { generation }));
|
||||
assert_eq!(p.track().unwrap().id, "n", "{effects:?}");
|
||||
// A late prefetch for the old next track must not be played instead.
|
||||
p.update(Msg::Prefetched { track_id: "1".into(), result: Ok(audio()) });
|
||||
assert_eq!(p.track().unwrap().id, "n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn play_next_on_the_playing_track_changes_nothing() {
|
||||
let mut p = playing(3, 0);
|
||||
assert!(p.update(Msg::PlayNext(track("0", 100))).is_empty());
|
||||
p.update(Msg::Next);
|
||||
assert_eq!(p.track().unwrap().id, "1", "skip moves on instead of replaying");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn play_next_then_skip_plays_it() {
|
||||
let mut p = playing(3, 0);
|
||||
p.update(Msg::PlayNext(track("n", 5)));
|
||||
p.update(Msg::Next);
|
||||
assert_eq!(p.track().unwrap().id, "n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn play_next_in_a_wave() {
|
||||
let mut p = wave_with(3);
|
||||
loaded(&mut p);
|
||||
p.update(Msg::PlayNext(track("n", 5)));
|
||||
p.update(Msg::Next);
|
||||
assert_eq!(p.track().unwrap().id, "n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mute_and_volume() {
|
||||
let mut p = Player::default();
|
||||
p.update(Msg::SetVolume(0.0));
|
||||
assert!(p.muted);
|
||||
p.update(Msg::ToggleMute);
|
||||
assert!(!p.muted);
|
||||
assert_eq!(p.volume, 0.5);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
//! Play order over a fixed list of items: shuffle, repeat, next/previous.
|
||||
//!
|
||||
//! Generic so the rules can be tested with plain numbers; the app uses `Track`.
|
||||
|
||||
use rand::seq::SliceRandom;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum Repeat {
|
||||
#[default]
|
||||
Off,
|
||||
All,
|
||||
One,
|
||||
}
|
||||
|
||||
impl Repeat {
|
||||
pub fn next(self) -> Self {
|
||||
match self {
|
||||
Repeat::Off => Repeat::All,
|
||||
Repeat::All => Repeat::One,
|
||||
Repeat::One => Repeat::Off,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Queue<T> {
|
||||
items: Vec<T>,
|
||||
/// Indices into `items` in play order.
|
||||
order: Vec<usize>,
|
||||
/// Position in `order` of the current item.
|
||||
pos: usize,
|
||||
shuffle: bool,
|
||||
}
|
||||
|
||||
impl<T> Queue<T> {
|
||||
/// A queue over `items` starting at `start`. Returns `None` for an empty list.
|
||||
pub fn new(items: Vec<T>, start: usize, shuffle: bool) -> Option<Self> {
|
||||
if items.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let start = start.min(items.len() - 1);
|
||||
let mut queue = Self { order: (0..items.len()).collect(), items, pos: start, shuffle: false };
|
||||
if shuffle {
|
||||
queue.set_shuffle(true);
|
||||
}
|
||||
Some(queue)
|
||||
}
|
||||
|
||||
pub fn current(&self) -> &T {
|
||||
&self.items[self.order[self.pos]]
|
||||
}
|
||||
|
||||
/// Moves on after a track. `finished` is true when it played to the end, in
|
||||
/// which case `Repeat::One` replays it; a skip always advances. Returns
|
||||
/// `false` at the end of the queue with repeat off.
|
||||
pub fn advance(&mut self, repeat: Repeat, finished: bool) -> bool {
|
||||
if finished && repeat == Repeat::One {
|
||||
return true;
|
||||
}
|
||||
if self.pos + 1 < self.order.len() {
|
||||
self.pos += 1;
|
||||
true
|
||||
} else if repeat != Repeat::Off {
|
||||
self.pos = 0;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Steps back one item, wrapping when repeat is on. Returns `false` at the start.
|
||||
pub fn back(&mut self, repeat: Repeat) -> bool {
|
||||
if self.pos > 0 {
|
||||
self.pos -= 1;
|
||||
true
|
||||
} else if repeat != Repeat::Off {
|
||||
self.pos = self.order.len() - 1;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// The item that `advance(repeat, true)` would move to, without moving.
|
||||
pub fn peek_next(&self, repeat: Repeat) -> Option<&T> {
|
||||
match repeat {
|
||||
Repeat::One => Some(self.current()),
|
||||
_ if self.pos + 1 < self.order.len() => Some(&self.items[self.order[self.pos + 1]]),
|
||||
Repeat::All => Some(&self.items[self.order[0]]),
|
||||
Repeat::Off => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Items after the current one, in play order (no wrap-around).
|
||||
pub fn upcoming(&self) -> impl Iterator<Item = (usize, &T)> {
|
||||
self.order[self.pos + 1..].iter().enumerate().map(move |(i, &ix)| (self.pos + 1 + i, &self.items[ix]))
|
||||
}
|
||||
|
||||
/// Jumps to a play-order position from [`Queue::upcoming`].
|
||||
pub fn jump(&mut self, order_pos: usize) {
|
||||
if order_pos < self.order.len() {
|
||||
self.pos = order_pos;
|
||||
}
|
||||
}
|
||||
|
||||
/// Turning shuffle on keeps the current item and shuffles everything after it;
|
||||
/// turning it off restores list order at the current item.
|
||||
pub fn set_shuffle(&mut self, on: bool) {
|
||||
if on == self.shuffle {
|
||||
return;
|
||||
}
|
||||
let current = self.order[self.pos];
|
||||
if on {
|
||||
let mut rest: Vec<usize> = (0..self.items.len()).filter(|&i| i != current).collect();
|
||||
rest.shuffle(&mut rand::rng());
|
||||
self.order = std::iter::once(current).chain(rest).collect();
|
||||
self.pos = 0;
|
||||
} else {
|
||||
self.order = (0..self.items.len()).collect();
|
||||
self.pos = current;
|
||||
}
|
||||
self.shuffle = on;
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.items.len()
|
||||
}
|
||||
|
||||
/// The last `n` items of the play order, oldest first.
|
||||
pub fn tail(&self, n: usize) -> impl Iterator<Item = &T> {
|
||||
let start = self.order.len().saturating_sub(n);
|
||||
self.order[start..].iter().map(move |&i| &self.items[i])
|
||||
}
|
||||
|
||||
/// Adds items to the end of the play order (radio batches arriving).
|
||||
pub fn extend(&mut self, more: impl IntoIterator<Item = T>) {
|
||||
for item in more {
|
||||
self.order.push(self.items.len());
|
||||
self.items.push(item);
|
||||
}
|
||||
}
|
||||
|
||||
/// Puts an item right after the current one. If it's already coming up it moves
|
||||
/// there instead of being duplicated; if it *is* the current item nothing changes.
|
||||
/// Returns whether the queue changed.
|
||||
pub fn insert_next(&mut self, item: T, same: impl Fn(&T, &T) -> bool) -> bool {
|
||||
if same(self.current(), &item) {
|
||||
return false;
|
||||
}
|
||||
let later = self.order[self.pos + 1..].iter().position(|&i| same(&self.items[i], &item));
|
||||
match later {
|
||||
Some(offset) => {
|
||||
let index = self.order.remove(self.pos + 1 + offset);
|
||||
self.order.insert(self.pos + 1, index);
|
||||
}
|
||||
None => {
|
||||
self.items.push(item);
|
||||
self.order.insert(self.pos + 1, self.items.len() - 1);
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Drops everything after the current item, e.g. when a station's settings change.
|
||||
pub fn clear_upcoming(&mut self) {
|
||||
let keep: Vec<usize> = self.order[..=self.pos].to_vec();
|
||||
let items = std::mem::take(&mut self.items);
|
||||
let mut kept: Vec<Option<T>> = items.into_iter().map(Some).collect();
|
||||
self.items = keep.iter().map(|&i| kept[i].take().expect("each index once")).collect();
|
||||
self.order = (0..self.items.len()).collect();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn q(n: usize, start: usize) -> Queue<usize> {
|
||||
Queue::new((0..n).collect(), start, false).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_list_has_no_queue() {
|
||||
assert!(Queue::<u8>::new(vec![], 0, false).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn start_is_clamped() {
|
||||
assert_eq!(*q(3, 99).current(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn advance_stops_at_end_without_repeat() {
|
||||
let mut q = q(2, 0);
|
||||
assert!(q.advance(Repeat::Off, true));
|
||||
assert_eq!(*q.current(), 1);
|
||||
assert!(!q.advance(Repeat::Off, true));
|
||||
assert_eq!(*q.current(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeat_all_wraps_both_ways() {
|
||||
let mut q = q(3, 2);
|
||||
assert!(q.advance(Repeat::All, true));
|
||||
assert_eq!(*q.current(), 0);
|
||||
assert!(q.back(Repeat::All));
|
||||
assert_eq!(*q.current(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeat_one_replays_on_finish_but_skip_moves_on() {
|
||||
let mut q = q(3, 1);
|
||||
assert!(q.advance(Repeat::One, true));
|
||||
assert_eq!(*q.current(), 1);
|
||||
assert!(q.advance(Repeat::One, false));
|
||||
assert_eq!(*q.current(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn back_stops_at_start_without_repeat() {
|
||||
let mut q = q(3, 0);
|
||||
assert!(!q.back(Repeat::Off));
|
||||
assert_eq!(*q.current(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peek_matches_advance() {
|
||||
for repeat in [Repeat::Off, Repeat::All, Repeat::One] {
|
||||
for start in 0..3 {
|
||||
let mut q = q(3, start);
|
||||
let peeked = q.peek_next(repeat).copied();
|
||||
let moved = q.advance(repeat, true);
|
||||
assert_eq!(peeked, moved.then(|| *q.current()), "{repeat:?} from {start}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shuffle_keeps_current_and_covers_everything() {
|
||||
let mut q = q(50, 17);
|
||||
q.set_shuffle(true);
|
||||
assert_eq!(*q.current(), 17);
|
||||
let mut seen: Vec<usize> = std::iter::once(17).chain(q.upcoming().map(|(_, &x)| x)).collect();
|
||||
seen.sort_unstable();
|
||||
assert_eq!(seen, (0..50).collect::<Vec<_>>());
|
||||
q.advance(Repeat::Off, false);
|
||||
let now = *q.current();
|
||||
q.set_shuffle(false);
|
||||
assert_eq!(*q.current(), now, "unshuffling keeps the current item");
|
||||
assert_eq!(q.upcoming().count(), 49 - now);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extend_appends_after_everything() {
|
||||
let mut q = q(2, 1);
|
||||
assert!(!q.advance(Repeat::Off, true));
|
||||
q.extend([10, 11]);
|
||||
assert!(q.advance(Repeat::Off, true));
|
||||
assert_eq!(*q.current(), 10);
|
||||
assert_eq!(q.upcoming().map(|(_, &x)| x).collect::<Vec<_>>(), [11]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clear_upcoming_keeps_history_and_current() {
|
||||
let mut q = q(5, 0);
|
||||
q.set_shuffle(true);
|
||||
q.advance(Repeat::Off, false);
|
||||
let (first, now) = (q.order[0], *q.current());
|
||||
q.clear_upcoming();
|
||||
assert_eq!(q.len(), 2);
|
||||
assert_eq!(*q.current(), now);
|
||||
assert_eq!(q.upcoming().count(), 0);
|
||||
assert!(q.back(Repeat::Off));
|
||||
assert_eq!(*q.current(), first);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_next_plays_after_current_even_when_shuffled() {
|
||||
let mut q = q(4, 1);
|
||||
q.set_shuffle(true);
|
||||
assert!(q.insert_next(99, |a, b| a == b));
|
||||
assert_eq!(q.upcoming().next().map(|(_, &x)| x), Some(99));
|
||||
assert_eq!(*q.current(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_next_moves_instead_of_duplicating_and_ignores_current() {
|
||||
let mut q = q(5, 1);
|
||||
assert!(!q.insert_next(1, |a, b| a == b), "the current item stays put");
|
||||
assert_eq!(q.upcoming().map(|(_, &x)| x).collect::<Vec<_>>(), [2, 3, 4]);
|
||||
assert!(q.insert_next(4, |a, b| a == b));
|
||||
assert_eq!(q.upcoming().map(|(_, &x)| x).collect::<Vec<_>>(), [4, 2, 3]);
|
||||
assert_eq!(q.len(), 5, "moved, not added");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jump_moves_to_upcoming_position() {
|
||||
let mut q = q(5, 0);
|
||||
let (pos, &item) = q.upcoming().nth(2).unwrap();
|
||||
q.jump(pos);
|
||||
assert_eq!(*q.current(), item);
|
||||
q.jump(99);
|
||||
assert_eq!(*q.current(), item);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
//! Every place the content area can show. Detail pages (album, artist, playlist)
|
||||
//! join this enum once they carry ids from the API.
|
||||
|
||||
use crate::i18n::tr;
|
||||
use ym_api::PlaylistId;
|
||||
|
||||
use crate::ui::icons::Icon;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum Route {
|
||||
Home,
|
||||
Wave,
|
||||
Search,
|
||||
Collection,
|
||||
Podcasts,
|
||||
Settings,
|
||||
Album(i64),
|
||||
Artist(i64),
|
||||
Playlist(PlaylistId),
|
||||
Chart,
|
||||
/// Index into the app's flattened genre list.
|
||||
Genre(usize),
|
||||
}
|
||||
|
||||
impl Route {
|
||||
/// Sidebar order.
|
||||
pub const NAV: [Route; 5] =
|
||||
[Route::Home, Route::Wave, Route::Search, Route::Collection, Route::Podcasts];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Route::Home => tr("Home"),
|
||||
Route::Wave => tr("My Wave"),
|
||||
Route::Search => tr("Search"),
|
||||
Route::Collection => tr("Collection"),
|
||||
Route::Podcasts => tr("Podcasts"),
|
||||
Route::Settings => tr("Settings"),
|
||||
Route::Album(_) => tr("Album"),
|
||||
Route::Artist(_) => tr("Artist"),
|
||||
Route::Playlist(_) => tr("Playlist"),
|
||||
Route::Chart => tr("Chart"),
|
||||
Route::Genre(_) => tr("Genre"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn icon(self) -> Icon {
|
||||
match self {
|
||||
Route::Home => Icon::Home,
|
||||
Route::Wave => Icon::Wave,
|
||||
Route::Search => Icon::Search,
|
||||
Route::Collection => Icon::Library,
|
||||
Route::Podcasts => Icon::Podcast,
|
||||
Route::Settings => Icon::Settings,
|
||||
Route::Album(_) => Icon::Disc,
|
||||
Route::Artist(_) => Icon::Wave,
|
||||
Route::Playlist(_) => Icon::Queue,
|
||||
Route::Chart => Icon::Chart,
|
||||
Route::Genre(_) => Icon::Library,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Back-stack navigation: the sidebar pushes, the back button pops.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Navigator {
|
||||
current: Route,
|
||||
history: Vec<Route>,
|
||||
}
|
||||
|
||||
impl Navigator {
|
||||
const MAX_HISTORY: usize = 50;
|
||||
|
||||
pub fn new(start: Route) -> Self {
|
||||
Self { current: start, history: Vec::new() }
|
||||
}
|
||||
|
||||
pub fn current(&self) -> Route {
|
||||
self.current
|
||||
}
|
||||
|
||||
pub fn can_go_back(&self) -> bool {
|
||||
!self.history.is_empty()
|
||||
}
|
||||
|
||||
pub fn go(&mut self, route: Route) {
|
||||
if route == self.current {
|
||||
return;
|
||||
}
|
||||
if self.history.len() == Self::MAX_HISTORY {
|
||||
self.history.remove(0);
|
||||
}
|
||||
self.history.push(self.current);
|
||||
self.current = route;
|
||||
}
|
||||
|
||||
pub fn back(&mut self) {
|
||||
if let Some(previous) = self.history.pop() {
|
||||
self.current = previous;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn back_returns_to_previous_route() {
|
||||
let mut nav = Navigator::new(Route::Home);
|
||||
nav.go(Route::Search);
|
||||
nav.go(Route::Collection);
|
||||
nav.back();
|
||||
assert_eq!(nav.current(), Route::Search);
|
||||
nav.back();
|
||||
assert_eq!(nav.current(), Route::Home);
|
||||
assert!(!nav.can_go_back());
|
||||
nav.back();
|
||||
assert_eq!(nav.current(), Route::Home);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revisiting_current_route_does_not_grow_history() {
|
||||
let mut nav = Navigator::new(Route::Home);
|
||||
nav.go(Route::Home);
|
||||
assert!(!nav.can_go_back());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn history_is_bounded() {
|
||||
let mut nav = Navigator::new(Route::Home);
|
||||
for i in 0..200 {
|
||||
nav.go(if i % 2 == 0 { Route::Search } else { Route::Home });
|
||||
}
|
||||
assert_eq!(nav.history.len(), Navigator::MAX_HISTORY);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
//! Discovery: Home, the chart, genres and podcasts.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use iced::widget::{Row, button, column, container, row};
|
||||
use iced::{Alignment, Color, Element, Fill};
|
||||
use ym_api::{AlbumKind, AlbumSummary, ChartEntry, Genre, Home, PlaylistSummary, Track};
|
||||
|
||||
use super::Loadable;
|
||||
use super::collection::{LoadState, album_card, play_bar, playlist_card, section, status};
|
||||
use crate::app::Message;
|
||||
use crate::covers;
|
||||
use crate::route::Route;
|
||||
use crate::ui::theme::{self, Tokens, radius, size};
|
||||
use crate::ui::{line, para};
|
||||
use crate::widgets::card::{self, Card};
|
||||
use crate::widgets::track_list::{self, Env};
|
||||
use crate::widgets::track_row::Columns;
|
||||
use crate::i18n::{tr, trf};
|
||||
|
||||
/// Chart rows shown on Home before "Show all".
|
||||
const HOME_CHART: usize = 10;
|
||||
/// Cards per Home row.
|
||||
const HOME_CARDS: usize = 12;
|
||||
/// Tracks in Home's "Recently played".
|
||||
pub const RECENT: usize = 10;
|
||||
|
||||
/// Home data with the chart split out as a playable list.
|
||||
#[derive(Debug)]
|
||||
pub struct HomeData {
|
||||
pub home: Home,
|
||||
pub chart: Arc<[Track]>,
|
||||
pub shifts: Arc<[i32]>,
|
||||
/// The first rows of the chart for Home, built once so the cached list stays valid.
|
||||
top: Arc<[Track]>,
|
||||
top_shifts: Arc<[i32]>,
|
||||
}
|
||||
|
||||
impl HomeData {
|
||||
pub fn new(mut home: Home) -> Self {
|
||||
let entries = std::mem::take(&mut home.chart);
|
||||
let (chart, shifts): (Vec<Track>, Vec<i32>) =
|
||||
entries.into_iter().map(|ChartEntry { track, shift, .. }| (track, shift)).unzip();
|
||||
let top = chart.iter().take(HOME_CHART).cloned().collect();
|
||||
let top_shifts = shifts.iter().take(HOME_CHART).copied().collect();
|
||||
Self { home, chart: chart.into(), shifts: shifts.into(), top, top_shifts }
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything the discovery screens show. Each part loads on first visit.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Discover {
|
||||
pub home: Loadable<HomeData>,
|
||||
/// Top-level genres followed by their sub-genres, so a `Route::Genre` index finds either.
|
||||
pub genres: Loadable<Vec<Genre>>,
|
||||
pub podcasts: Loadable<Vec<AlbumSummary>>,
|
||||
/// The last tracks played on any device. Reloaded on every visit to Home.
|
||||
pub recent: Loadable<Arc<[Track]>>,
|
||||
}
|
||||
|
||||
/// Top-level genres first, then every sub-genre, each once.
|
||||
pub fn flatten(genres: Vec<Genre>) -> Vec<Genre> {
|
||||
let mut flat: Vec<Genre> = genres.clone();
|
||||
for g in genres {
|
||||
for sub in g.sub_genres {
|
||||
if !flat.iter().any(|f| f.id == sub.id) {
|
||||
flat.push(sub);
|
||||
}
|
||||
}
|
||||
}
|
||||
flat
|
||||
}
|
||||
|
||||
pub fn home<'a>(env: Env<'a>, discover: &'a Discover, hero: Element<'a, Message>) -> Element<'a, Message> {
|
||||
let t = env.t;
|
||||
let covers = env.covers;
|
||||
let mut page = column![hero].spacing(34);
|
||||
|
||||
// Only worth a section when it has something; a failure stays in the log.
|
||||
if let Loadable::Loaded(recent) = &discover.recent
|
||||
&& !recent.is_empty()
|
||||
{
|
||||
page = page.push(
|
||||
column![
|
||||
line(tr("Recently played"), theme::SEMIBOLD, size::SECTION, t.fg),
|
||||
track_list::view(env, recent, Columns::FULL),
|
||||
]
|
||||
.spacing(14)
|
||||
.width(Fill),
|
||||
);
|
||||
}
|
||||
|
||||
match &discover.home {
|
||||
Loadable::Loaded(data) => {
|
||||
let h = &data.home;
|
||||
if !h.personal.is_empty() {
|
||||
page = page.push(section(
|
||||
t,
|
||||
tr("Made for you"),
|
||||
h.personal.iter().map(|p| {
|
||||
card::view(t, covers, Card {
|
||||
title: p.playlist.title.clone(),
|
||||
subtitle: p.description.clone().unwrap_or_else(|| p.playlist.subtitle()),
|
||||
cover: p.playlist.cover_url(covers::LARGE),
|
||||
hues: p.playlist.hues(),
|
||||
round: false,
|
||||
on_press: Message::Navigate(Route::Playlist(p.playlist.id)),
|
||||
})
|
||||
}),
|
||||
));
|
||||
}
|
||||
if !data.chart.is_empty() {
|
||||
page = page.push(
|
||||
column![
|
||||
row![
|
||||
line(tr("Chart"), theme::SEMIBOLD, size::SECTION, t.fg).width(Fill),
|
||||
button(line(trf("Show all {}", &[&data.chart.len()]), theme::MEDIUM, size::META, t.muted))
|
||||
.padding(0)
|
||||
.style(theme::tab(false))
|
||||
.on_press(Message::Navigate(Route::Chart)),
|
||||
]
|
||||
.align_y(Alignment::Center),
|
||||
track_list::view_with(env, &data.top, Columns::CHART, Some(data.top_shifts.clone())),
|
||||
]
|
||||
.spacing(14),
|
||||
);
|
||||
}
|
||||
if !h.new_releases.is_empty() {
|
||||
page = page.push(section(
|
||||
t,
|
||||
tr("New releases"),
|
||||
h.new_releases.iter().take(HOME_CARDS).map(|a| album_card(t, covers, a)),
|
||||
));
|
||||
}
|
||||
if !h.new_playlists.is_empty() {
|
||||
page = page.push(section(
|
||||
t,
|
||||
tr("New playlists"),
|
||||
h.new_playlists.iter().take(HOME_CARDS).map(|p| playlist_card(t, covers, p)),
|
||||
));
|
||||
}
|
||||
}
|
||||
Loadable::Failed(e) => page = page.push(status(t, LoadState::Failed(e), tr("your home page"), Message::LoadHome)),
|
||||
_ => page = page.push(para(tr("Loading your picks…"), size::BODY, t.muted)),
|
||||
}
|
||||
|
||||
page.push(genres_section(env, &discover.genres)).into()
|
||||
}
|
||||
|
||||
pub fn chart<'a>(env: Env<'a>, discover: &'a Discover) -> Element<'a, Message> {
|
||||
let t = env.t;
|
||||
let body: Element<'a, Message> = match &discover.home {
|
||||
Loadable::Loaded(data) if !data.chart.is_empty() => column![
|
||||
play_bar(t, tr("The most played tracks on Yandex Music today").into(), &data.chart),
|
||||
track_list::view_with(env, &data.chart, Columns::CHART, Some(data.shifts.clone())),
|
||||
]
|
||||
.spacing(22)
|
||||
.into(),
|
||||
Loadable::Loaded(_) => para(tr("The chart is empty right now."), size::BODY, t.muted).into(),
|
||||
Loadable::Failed(e) => status(t, LoadState::Failed(e), tr("the chart"), Message::LoadHome),
|
||||
_ => para(tr("Loading the chart…"), size::BODY, t.muted).into(),
|
||||
};
|
||||
column![line(tr("Chart"), theme::DISPLAY, size::DISPLAY_S, t.fg), body].spacing(24).into()
|
||||
}
|
||||
|
||||
pub fn genres_section<'a>(env: Env<'a>, genres: &'a Loadable<Vec<Genre>>) -> Element<'a, Message> {
|
||||
let t = env.t;
|
||||
let body: Element<'a, Message> = match genres {
|
||||
// Sub-genres are reached from their parent's page.
|
||||
Loadable::Loaded(list) => {
|
||||
let top = list.iter().enumerate().filter(|(_, g)| !is_sub_genre(list, g));
|
||||
Row::with_children(top.map(|(i, g)| genre_tile(t, i, g))).spacing(12).wrap().vertical_spacing(12).into()
|
||||
}
|
||||
Loadable::Failed(e) => status(t, LoadState::Failed(e), tr("genres"), Message::LoadGenres),
|
||||
_ => para(tr("Loading genres…"), size::BODY, t.muted).into(),
|
||||
};
|
||||
column![line(tr("Genres"), theme::SEMIBOLD, size::SECTION, t.fg), body].spacing(14).into()
|
||||
}
|
||||
|
||||
fn is_sub_genre(all: &[Genre], g: &Genre) -> bool {
|
||||
all.iter().any(|parent| parent.sub_genres.iter().any(|s| s.id == g.id))
|
||||
}
|
||||
|
||||
fn genre_tile<'a>(t: &'static Tokens, index: usize, g: &Genre) -> Element<'a, Message> {
|
||||
let tint = g.color.as_deref().and_then(parse_hex).unwrap_or(t.raised);
|
||||
button(
|
||||
// Long names ("Nature Sounds and City Noise") wrap to a second line.
|
||||
container(
|
||||
iced::widget::text(g.title.clone())
|
||||
.font(theme::SEMIBOLD)
|
||||
.size(size::BODY)
|
||||
.line_height(1.2)
|
||||
.color(Color::WHITE),
|
||||
)
|
||||
.padding([0, 16])
|
||||
.align_y(iced::alignment::Vertical::Center)
|
||||
.height(72)
|
||||
.width(card::WIDTH)
|
||||
.clip(true),
|
||||
)
|
||||
.padding(0)
|
||||
.style(move |_, status| {
|
||||
let lift = matches!(status, button::Status::Hovered | button::Status::Pressed);
|
||||
button::Style {
|
||||
background: Some(iced::Background::Gradient(
|
||||
iced::gradient::Linear::new(std::f32::consts::FRAC_PI_4 * 3.0)
|
||||
.add_stop(0.0, if lift { theme::mix(tint, Color::WHITE, 0.12) } else { tint })
|
||||
.add_stop(1.0, theme::mix(tint, Color::BLACK, 0.45))
|
||||
.into(),
|
||||
)),
|
||||
text_color: Color::WHITE,
|
||||
border: iced::Border { radius: radius::COVER.into(), ..Default::default() },
|
||||
..Default::default()
|
||||
}
|
||||
})
|
||||
.on_press(Message::Navigate(Route::Genre(index)))
|
||||
.into()
|
||||
}
|
||||
|
||||
/// `#rrggbb` → colour.
|
||||
pub fn parse_hex(s: &str) -> Option<Color> {
|
||||
let h = s.strip_prefix('#')?;
|
||||
if h.len() != 6 {
|
||||
return None;
|
||||
}
|
||||
let n = u32::from_str_radix(h, 16).ok()?;
|
||||
Some(Color::from_rgb8((n >> 16) as u8, (n >> 8) as u8, n as u8))
|
||||
}
|
||||
|
||||
pub fn genre<'a>(
|
||||
env: Env<'a>,
|
||||
genres: &'a [Genre],
|
||||
index: usize,
|
||||
playlists: &'a Loadable<Vec<PlaylistSummary>>,
|
||||
) -> Element<'a, Message> {
|
||||
let t = env.t;
|
||||
let Some(g) = genres.get(index) else {
|
||||
return para(tr("This genre isn't available any more."), size::BODY, t.muted).into();
|
||||
};
|
||||
let radio = button(
|
||||
row![
|
||||
crate::ui::icons::icon(crate::ui::icons::Icon::Wave, t.accent_ink),
|
||||
line(tr("Play radio"), theme::SEMIBOLD, size::BODY, t.accent_ink),
|
||||
]
|
||||
.spacing(8)
|
||||
.align_y(Alignment::Center),
|
||||
)
|
||||
.padding([10, 18])
|
||||
.style(theme::primary)
|
||||
.on_press(Message::PlayWave(format!("genre:{}", g.id)));
|
||||
let mut page = column![
|
||||
row![line(g.title.clone(), theme::DISPLAY, size::DISPLAY_S, t.fg).width(Fill), radio]
|
||||
.align_y(Alignment::Center)
|
||||
]
|
||||
.spacing(24);
|
||||
|
||||
let subs: Vec<Element<'a, Message>> = g
|
||||
.sub_genres
|
||||
.iter()
|
||||
.filter_map(|s| genres.iter().position(|f| f.id == s.id).map(|i| (i, s)))
|
||||
.map(|(i, s)| {
|
||||
button(line(s.title.clone(), theme::MEDIUM, size::META, t.fg))
|
||||
.padding([7, 13])
|
||||
.style(theme::ghost)
|
||||
.on_press(Message::Navigate(Route::Genre(i)))
|
||||
.into()
|
||||
})
|
||||
.collect();
|
||||
if !subs.is_empty() {
|
||||
page = page.push(Row::with_children(subs).spacing(6).wrap().vertical_spacing(6));
|
||||
}
|
||||
|
||||
let body: Element<'a, Message> = match playlists {
|
||||
Loadable::Loaded(list) if list.is_empty() => {
|
||||
para(tr("No playlists in this genre yet."), size::BODY, t.muted).into()
|
||||
}
|
||||
Loadable::Loaded(list) => section(t, tr("Playlists"), list.iter().map(|p| playlist_card(t, env.covers, p))),
|
||||
Loadable::Failed(e) => status(t, LoadState::Failed(e), tr("the playlists"), Message::Navigate(Route::Genre(index))),
|
||||
_ => para(tr("Loading playlists…"), size::BODY, t.muted).into(),
|
||||
};
|
||||
page.push(body).into()
|
||||
}
|
||||
|
||||
pub fn podcasts<'a>(
|
||||
env: Env<'a>,
|
||||
discover: &'a Discover,
|
||||
liked: &'a Loadable<Vec<AlbumSummary>>,
|
||||
) -> Element<'a, Message> {
|
||||
let t = env.t;
|
||||
let covers = env.covers;
|
||||
let mut page = column![line(tr("Podcasts and books"), theme::DISPLAY, size::DISPLAY_S, t.fg)].spacing(34);
|
||||
|
||||
if let Loadable::Loaded(albums) = liked {
|
||||
let mine: Vec<&AlbumSummary> =
|
||||
albums.iter().filter(|a| matches!(a.kind, AlbumKind::Podcast | AlbumKind::Audiobook)).collect();
|
||||
if !mine.is_empty() {
|
||||
page = page.push(section(t, tr("Yours"), mine.into_iter().map(|a| album_card(t, covers, a))));
|
||||
}
|
||||
}
|
||||
|
||||
page.push(match &discover.podcasts {
|
||||
Loadable::Loaded(list) => section(t, tr("Featured"), list.iter().map(|a| album_card(t, covers, a))),
|
||||
Loadable::Failed(e) => status(t, LoadState::Failed(e), tr("podcasts"), Message::LoadPodcasts),
|
||||
_ => para(tr("Loading podcasts…"), size::BODY, t.muted).into(),
|
||||
})
|
||||
.into()
|
||||
}
|
||||
|
||||
/// The arrow beside a chart position.
|
||||
pub fn shift_marker(t: &'static Tokens, shift: i32) -> Element<'static, Message> {
|
||||
let (glyph, colour) = match shift {
|
||||
s if s > 0 => ("▲", t.ok),
|
||||
s if s < 0 => ("▼", t.like),
|
||||
_ => ("–", t.muted),
|
||||
};
|
||||
container(line(glyph, theme::DISPLAY, 9.0, colour)).width(14).center_x(14).into()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn genre(id: &str, subs: &[&str]) -> Genre {
|
||||
Genre {
|
||||
id: id.into(),
|
||||
title: id.into(),
|
||||
color: None,
|
||||
sub_genres: subs.iter().map(|s| genre(s, &[])).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flatten_appends_each_sub_genre_once() {
|
||||
let flat = flatten(vec![genre("rock", &["punk", "metal"]), genre("metal", &["doom"]), genre("pop", &["punk"])]);
|
||||
let ids: Vec<&str> = flat.iter().map(|g| g.id.as_str()).collect();
|
||||
assert_eq!(ids, ["rock", "metal", "pop", "punk", "doom"]);
|
||||
assert!(is_sub_genre(&flat, &flat[3]));
|
||||
assert!(!is_sub_genre(&flat, &flat[0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_colours() {
|
||||
assert_eq!(parse_hex("#ff8000"), Some(Color::from_rgb8(255, 128, 0)));
|
||||
assert_eq!(parse_hex("ff8000"), None);
|
||||
assert_eq!(parse_hex("#fff"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn home_data_splits_chart() {
|
||||
let track = |id: &str| Track::from_json(&format!(r#"{{"id":"{id}"}}"#)).unwrap();
|
||||
let home = Home {
|
||||
chart: vec![
|
||||
ChartEntry { position: 1, shift: 2, track: track("a") },
|
||||
ChartEntry { position: 2, shift: -1, track: track("b") },
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
let data = HomeData::new(home);
|
||||
assert_eq!(data.chart.len(), 2);
|
||||
assert_eq!(&*data.shifts, &[2, -1]);
|
||||
assert!(data.home.chart.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,408 @@
|
||||
//! Collection: liked tracks, albums, artists, playlists (own and liked) and clips.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use iced::widget::{button, column, container, row, space};
|
||||
use iced::{Alignment, Element, Fill};
|
||||
use ym_api::{AlbumSummary, ArtistSummary, Clip, Error, LibraryPlaylists, PlaylistSummary, Track};
|
||||
|
||||
use super::Loadable;
|
||||
use crate::app::Message;
|
||||
use crate::covers::{self, Covers};
|
||||
use crate::route::Route;
|
||||
use crate::ui::icons::{Icon, icon};
|
||||
use crate::ui::theme::{self, Tokens, size};
|
||||
use crate::ui::{duration_words, line, para, tracks_word};
|
||||
use crate::widgets::card::{self, Card};
|
||||
use crate::widgets::track_list::{self, Env};
|
||||
use crate::widgets::track_row::Columns;
|
||||
use crate::i18n::{tr, trf};
|
||||
|
||||
/// The liked-tracks list as the app holds it. Also answers "is this track liked?".
|
||||
#[derive(Debug, Default)]
|
||||
pub enum Liked {
|
||||
#[default]
|
||||
NotLoaded,
|
||||
Loading,
|
||||
Loaded {
|
||||
tracks: Arc<[Track]>,
|
||||
ids: HashSet<String>,
|
||||
/// Bumped on every reload so cached rows rebuild.
|
||||
version: u64,
|
||||
},
|
||||
Failed(Error),
|
||||
}
|
||||
|
||||
impl Liked {
|
||||
pub fn loaded(tracks: Vec<Track>, previous: &Liked) -> Self {
|
||||
let version = previous.version() + 1;
|
||||
let ids = tracks.iter().map(|t| t.id.clone()).collect();
|
||||
Liked::Loaded { tracks: tracks.into(), ids, version }
|
||||
}
|
||||
|
||||
/// A copy with `track` liked (at the top, like Yandex lists it) or unliked.
|
||||
/// Not loaded yet: unchanged, the next load has it.
|
||||
pub fn with(&self, track: &Track, liked: bool) -> Liked {
|
||||
let Liked::Loaded { tracks, ids, version } = self else {
|
||||
return match self {
|
||||
Liked::Failed(e) => Liked::Failed(e.clone()),
|
||||
Liked::Loading => Liked::Loading,
|
||||
_ => Liked::NotLoaded,
|
||||
};
|
||||
};
|
||||
if ids.contains(&track.id) == liked {
|
||||
return Liked::Loaded { tracks: tracks.clone(), ids: ids.clone(), version: *version };
|
||||
}
|
||||
let list: Vec<Track> = if liked {
|
||||
std::iter::once(track.clone()).chain(tracks.iter().cloned()).collect()
|
||||
} else {
|
||||
tracks.iter().filter(|t| t.id != track.id).cloned().collect()
|
||||
};
|
||||
let ids = list.iter().map(|t| t.id.clone()).collect();
|
||||
Liked::Loaded { tracks: list.into(), ids, version: version + 1 }
|
||||
}
|
||||
|
||||
pub fn contains(&self, track_id: &str) -> bool {
|
||||
matches!(self, Liked::Loaded { ids, .. } if ids.contains(track_id))
|
||||
}
|
||||
|
||||
pub fn tracks(&self) -> Option<&Arc<[Track]>> {
|
||||
match self {
|
||||
Liked::Loaded { tracks, .. } => Some(tracks),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn version(&self) -> u64 {
|
||||
match self {
|
||||
Liked::Loaded { version, .. } => *version,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum Tab {
|
||||
#[default]
|
||||
Tracks,
|
||||
Albums,
|
||||
Artists,
|
||||
Playlists,
|
||||
Clips,
|
||||
}
|
||||
|
||||
impl Tab {
|
||||
const ALL: [Tab; 5] = [Tab::Tracks, Tab::Albums, Tab::Artists, Tab::Playlists, Tab::Clips];
|
||||
|
||||
fn label(self) -> &'static str {
|
||||
match self {
|
||||
Tab::Tracks => tr("Liked tracks"),
|
||||
Tab::Albums => tr("Albums"),
|
||||
Tab::Artists => tr("Artists"),
|
||||
Tab::Playlists => tr("Playlists"),
|
||||
Tab::Clips => tr("Clips"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything Collection shows. Parts load on first visit to their tab.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Library {
|
||||
pub tab: Tab,
|
||||
pub liked: Liked,
|
||||
pub albums: Loadable<Vec<AlbumSummary>>,
|
||||
pub artists: Loadable<Vec<ArtistSummary>>,
|
||||
pub playlists: Loadable<LibraryPlaylists>,
|
||||
pub clips: Loadable<Vec<Clip>>,
|
||||
}
|
||||
|
||||
impl Library {
|
||||
fn count(&self, tab: Tab) -> Option<usize> {
|
||||
match tab {
|
||||
Tab::Tracks => self.liked.tracks().map(|t| t.len()),
|
||||
Tab::Albums => self.albums.get().map(Vec::len),
|
||||
Tab::Artists => self.artists.get().map(Vec::len),
|
||||
Tab::Playlists => self.playlists.get().map(|p| p.own.len() + p.liked.len()),
|
||||
Tab::Clips => self.clips.get().map(Vec::len),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn view<'a>(env: Env<'a>, library: &'a Library) -> Element<'a, Message> {
|
||||
let t = env.t;
|
||||
let tabs = row(Tab::ALL.map(|tab| tab_button(t, tab, library))).spacing(4);
|
||||
|
||||
let body: Element<'a, Message> = match library.tab {
|
||||
Tab::Tracks => liked_tracks(env, &library.liked),
|
||||
Tab::Albums => match &library.albums {
|
||||
Loadable::Loaded(albums) if albums.is_empty() => {
|
||||
empty(t, tr("No liked albums yet. Like an album and it lands here."))
|
||||
}
|
||||
Loadable::Loaded(albums) => card::grid(albums.iter().map(|a| album_card(t, env.covers, a))),
|
||||
other => status(t, other.state(), tr("your albums"), Message::LoadLibrary(Tab::Albums)),
|
||||
},
|
||||
Tab::Artists => match &library.artists {
|
||||
Loadable::Loaded(artists) if artists.is_empty() => {
|
||||
empty(t, tr("No liked artists yet. Like an artist and they land here."))
|
||||
}
|
||||
Loadable::Loaded(artists) => card::grid(artists.iter().map(|a| artist_card(t, env.covers, a))),
|
||||
other => status(t, other.state(), tr("your artists"), Message::LoadLibrary(Tab::Artists)),
|
||||
},
|
||||
Tab::Playlists => match &library.playlists {
|
||||
Loadable::Loaded(p) if p.own.is_empty() && p.liked.is_empty() => {
|
||||
empty(t, tr("No playlists yet. Playlists you make or like show up here."))
|
||||
}
|
||||
Loadable::Loaded(p) => {
|
||||
let mut sections = column![].spacing(28);
|
||||
if !p.own.is_empty() {
|
||||
sections = sections.push(section(
|
||||
t,
|
||||
tr("Your playlists"),
|
||||
p.own.iter().map(|pl| playlist_card(t, env.covers, pl)),
|
||||
));
|
||||
}
|
||||
if !p.liked.is_empty() {
|
||||
sections = sections.push(section(
|
||||
t,
|
||||
tr("Liked playlists"),
|
||||
p.liked.iter().map(|pl| playlist_card(t, env.covers, pl)),
|
||||
));
|
||||
}
|
||||
sections.into()
|
||||
}
|
||||
other => status(t, other.state(), tr("your playlists"), Message::LoadLibrary(Tab::Playlists)),
|
||||
},
|
||||
Tab::Clips => match &library.clips {
|
||||
Loadable::Loaded(clips) if clips.is_empty() => {
|
||||
empty(t, tr("No liked clips yet. Like a clip on an artist's page and it lands here."))
|
||||
}
|
||||
Loadable::Loaded(clips) => card::grid(clips.iter().map(|c| clip_card(env, c))),
|
||||
other => status(t, other.state(), tr("your clips"), Message::LoadLibrary(Tab::Clips)),
|
||||
},
|
||||
};
|
||||
|
||||
column![line(tr("Collection"), theme::DISPLAY, size::DISPLAY_S, t.fg), tabs, body]
|
||||
.spacing(24)
|
||||
.width(Fill)
|
||||
.into()
|
||||
}
|
||||
|
||||
fn tab_button<'a>(t: &'static Tokens, tab: Tab, library: &Library) -> Element<'a, Message> {
|
||||
let on = library.tab == tab;
|
||||
let mut label = row![line(tab.label(), theme::MEDIUM, size::BODY, if on { t.fg } else { t.muted })]
|
||||
.spacing(6)
|
||||
.align_y(Alignment::Center);
|
||||
if let Some(n) = library.count(tab) {
|
||||
label = label.push(line(n.to_string(), theme::BODY, size::SMALL, t.muted));
|
||||
}
|
||||
button(
|
||||
column![label, container(space()).width(Fill).height(2).style(theme::tab_underline(on))]
|
||||
.spacing(7)
|
||||
.width(iced::Shrink),
|
||||
)
|
||||
.padding([6, 10])
|
||||
.style(theme::tab(on))
|
||||
.on_press(Message::CollectionTab(tab))
|
||||
.into()
|
||||
}
|
||||
|
||||
fn liked_tracks<'a>(env: Env<'a>, liked: &'a Liked) -> Element<'a, Message> {
|
||||
let t = env.t;
|
||||
match liked {
|
||||
Liked::NotLoaded | Liked::Loading => para(tr("Loading your liked tracks…"), size::BODY, t.muted).into(),
|
||||
Liked::Failed(e) => status(t, LoadState::Failed(e), tr("your liked tracks"), Message::LoadLiked),
|
||||
Liked::Loaded { tracks, .. } if tracks.is_empty() => {
|
||||
empty(t, tr("No liked tracks yet. Tap the heart on any track and it lands here."))
|
||||
}
|
||||
Liked::Loaded { tracks, .. } => {
|
||||
let total = tracks.iter().map(|t| t.duration).sum();
|
||||
column![
|
||||
play_bar(t, format!("{} · {}", tracks_word(tracks.len()), duration_words(total)), tracks),
|
||||
track_list::view(env, tracks, Columns::FULL),
|
||||
]
|
||||
.spacing(22)
|
||||
.into()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Play and Shuffle buttons with a summary on the left. Shared by every page with tracks.
|
||||
pub fn play_bar<'a>(t: &'static Tokens, summary: String, tracks: &Arc<[Track]>) -> Element<'a, Message> {
|
||||
let has_tracks = !tracks.is_empty();
|
||||
let pill = |glyph: Icon,
|
||||
label: &'static str,
|
||||
ink,
|
||||
style: fn(&iced::Theme, button::Status) -> button::Style,
|
||||
msg| {
|
||||
button(
|
||||
row![icon(glyph, ink), line(label, theme::SEMIBOLD, size::BODY, ink)]
|
||||
.spacing(8)
|
||||
.align_y(Alignment::Center),
|
||||
)
|
||||
.padding([10, 18])
|
||||
.style(style)
|
||||
.on_press_maybe(has_tracks.then_some(msg))
|
||||
};
|
||||
row![
|
||||
container(line(summary, theme::BODY, size::META, t.muted)).width(Fill),
|
||||
pill(
|
||||
Icon::Play,
|
||||
tr("Play"),
|
||||
t.accent_ink,
|
||||
theme::primary,
|
||||
Message::PlayTracks { tracks: tracks.clone(), start: 0, shuffle: false },
|
||||
),
|
||||
pill(
|
||||
Icon::Shuffle,
|
||||
tr("Shuffle"),
|
||||
t.fg,
|
||||
theme::ghost,
|
||||
Message::PlayTracks { tracks: tracks.clone(), start: 0, shuffle: true },
|
||||
),
|
||||
]
|
||||
.spacing(10)
|
||||
.align_y(Alignment::Center)
|
||||
.into()
|
||||
}
|
||||
|
||||
pub fn album_card<'a>(t: &'static Tokens, covers: &Covers, a: &AlbumSummary) -> Element<'a, Message> {
|
||||
card::view(
|
||||
t,
|
||||
covers,
|
||||
Card {
|
||||
title: a.full_title(),
|
||||
subtitle: a.subtitle(),
|
||||
cover: a.cover_url(covers::LARGE),
|
||||
hues: a.hues(),
|
||||
round: false,
|
||||
on_press: Message::Navigate(Route::Album(a.id)),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub fn artist_card<'a>(t: &'static Tokens, covers: &Covers, a: &ArtistSummary) -> Element<'a, Message> {
|
||||
card::view(
|
||||
t,
|
||||
covers,
|
||||
Card {
|
||||
title: a.name.clone(),
|
||||
subtitle: a.genres.first().cloned().unwrap_or_else(|| tr("Artist").into()),
|
||||
cover: a.cover_url(covers::LARGE),
|
||||
hues: a.hues(),
|
||||
round: true,
|
||||
on_press: Message::Navigate(Route::Artist(a.id)),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub fn playlist_card<'a>(t: &'static Tokens, covers: &Covers, p: &PlaylistSummary) -> Element<'a, Message> {
|
||||
card::view(
|
||||
t,
|
||||
covers,
|
||||
Card {
|
||||
title: p.title.clone(),
|
||||
subtitle: p.subtitle(),
|
||||
cover: p.cover_url(covers::LARGE),
|
||||
hues: p.hues(),
|
||||
round: false,
|
||||
on_press: Message::Navigate(Route::Playlist(p.id)),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// A music video. It opens in the browser; the heart likes it.
|
||||
pub fn clip_card<'a>(env: Env<'_>, c: &Clip) -> Element<'a, Message> {
|
||||
let liked = env.likes.clips.contains(&c.id);
|
||||
let length = crate::widgets::player_bar::clock(c.duration.as_secs_f32());
|
||||
card::with_like(
|
||||
env.t,
|
||||
env.covers,
|
||||
Card {
|
||||
title: c.title.clone(),
|
||||
subtitle: format!("{} · {length}", c.artist_line()),
|
||||
cover: c.cover_url(covers::LARGE),
|
||||
hues: c.hues(),
|
||||
round: false,
|
||||
on_press: Message::OpenClip(c.clone()),
|
||||
},
|
||||
liked,
|
||||
Message::LikeClip(c.clone(), !liked),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn section<'a>(
|
||||
t: &'static Tokens,
|
||||
heading: &'a str,
|
||||
cards: impl IntoIterator<Item = Element<'a, Message>>,
|
||||
) -> Element<'a, Message> {
|
||||
column![line(heading, theme::SEMIBOLD, size::SECTION, t.fg), card::grid(cards)]
|
||||
.spacing(14)
|
||||
.into()
|
||||
}
|
||||
|
||||
pub enum LoadState<'a> {
|
||||
Loading,
|
||||
Failed(&'a Error),
|
||||
}
|
||||
|
||||
/// Loading text, or a failure with a retry button. `what` is the object of
|
||||
/// "Loading …" and "Couldn't load …", such as "your albums".
|
||||
pub fn status<'a>(t: &'static Tokens, state: LoadState<'_>, what: &str, retry: Message) -> Element<'a, Message> {
|
||||
match state {
|
||||
LoadState::Loading => para(trf("Loading {}…", &[&what]), size::BODY, t.muted).into(),
|
||||
LoadState::Failed(e) => column![
|
||||
para(
|
||||
match e {
|
||||
Error::Network(_) => {
|
||||
trf("Couldn't load {}. Check your connection and try again.", &[&what])
|
||||
}
|
||||
_ => trf("Couldn't load {}. Try again in a moment.", &[&what]),
|
||||
},
|
||||
size::BODY,
|
||||
t.muted,
|
||||
),
|
||||
button(line(tr("Try again"), theme::SEMIBOLD, size::BODY, t.accent_ink))
|
||||
.padding([11, 18])
|
||||
.style(theme::primary)
|
||||
.on_press(retry),
|
||||
]
|
||||
.spacing(16)
|
||||
.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn empty<'a>(t: &'static Tokens, text: &'static str) -> Element<'a, Message> {
|
||||
para(text, size::BODY, t.muted).into()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn track(id: &str) -> Track {
|
||||
Track::from_json(&format!(r#"{{"id":"{id}","title":"T"}}"#)).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reload_bumps_version_and_indexes_ids() {
|
||||
let first = Liked::loaded(vec![track("1"), track("2")], &Liked::Loading);
|
||||
assert!(first.contains("2") && !first.contains("3"));
|
||||
assert_eq!(first.version(), 1);
|
||||
let second = Liked::loaded(vec![track("3")], &first);
|
||||
assert_eq!(second.version(), 2);
|
||||
assert!(!Liked::Failed(Error::Denied).contains("1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_adds_on_top_and_removes() {
|
||||
let base = Liked::loaded(vec![track("1"), track("2")], &Liked::Loading);
|
||||
let added = base.with(&track("3"), true);
|
||||
assert_eq!(added.tracks().unwrap()[0].id, "3");
|
||||
assert!(added.version() > base.version());
|
||||
let removed = added.with(&track("1"), false);
|
||||
assert!(!removed.contains("1") && removed.contains("2"));
|
||||
assert_eq!(removed.with(&track("2"), true).version(), removed.version(), "no-op keeps the cache");
|
||||
assert!(matches!(Liked::NotLoaded.with(&track("9"), true), Liked::NotLoaded));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
//! Album, artist and playlist pages: a cover header, then tracks and cards.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use iced::widget::{Row, button, column, container, row, text};
|
||||
use iced::{Alignment, Element, Fill, Task};
|
||||
use ym_api::{AlbumPage, ArtistPage, ArtistRef, Error, PlaylistPage, Track, YmClient};
|
||||
|
||||
use super::Loadable;
|
||||
use super::collection::{LoadState, album_card, artist_card, clip_card, play_bar, section, status};
|
||||
use crate::app::Message;
|
||||
use crate::covers;
|
||||
use crate::route::Route;
|
||||
use crate::ui::theme::{self, size};
|
||||
use crate::ui::{counted, duration_words, line, para, tracks_word};
|
||||
use crate::widgets::track_list::{self, Env};
|
||||
use crate::widgets::sheet::Sheet;
|
||||
use crate::widgets::track_row::Columns;
|
||||
use crate::ui::icons::{Icon, icon};
|
||||
use crate::i18n::{tr, trf};
|
||||
|
||||
/// A loaded page. Tracks are split out as `Arc<[Track]>` so playing them shares the list.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Page {
|
||||
Album { info: AlbumPage, tracks: Arc<[Track]> },
|
||||
Artist { info: ArtistPage, popular: Arc<[Track]> },
|
||||
Playlist { info: PlaylistPage, tracks: Arc<[Track]> },
|
||||
}
|
||||
|
||||
/// Fetches whatever `route` shows. Non-detail routes load nothing.
|
||||
pub fn load(client: &YmClient, route: Route) -> Option<Task<Message>> {
|
||||
let client = client.clone();
|
||||
let task = match route {
|
||||
Route::Album(id) => Task::future(async move {
|
||||
client.album(id).await.map(|mut info| {
|
||||
let tracks = std::mem::take(&mut info.tracks).into();
|
||||
Page::Album { info, tracks }
|
||||
})
|
||||
}),
|
||||
Route::Artist(id) => Task::future(async move {
|
||||
client.artist(id).await.map(|mut info| {
|
||||
let popular = std::mem::take(&mut info.popular).into();
|
||||
Page::Artist { info, popular }
|
||||
})
|
||||
}),
|
||||
Route::Playlist(id) => Task::future(async move {
|
||||
client.playlist(id).await.map(|mut info| {
|
||||
let tracks = std::mem::take(&mut info.tracks).into();
|
||||
Page::Playlist { info, tracks }
|
||||
})
|
||||
}),
|
||||
_ => return None,
|
||||
};
|
||||
Some(task.map(move |result| Message::PageLoaded(route, result)))
|
||||
}
|
||||
|
||||
pub fn view<'a>(env: Env<'a>, route: Route, page: &'a Loadable<Page>) -> Element<'a, Message> {
|
||||
let t = env.t;
|
||||
let what = match route {
|
||||
Route::Album(_) => What { loading: tr("Loading the album…"), gone: tr("This album isn't available on Yandex Music any more."), retry: tr("the album") },
|
||||
Route::Artist(_) => What { loading: tr("Loading the artist…"), gone: tr("This artist isn't available on Yandex Music any more."), retry: tr("the artist") },
|
||||
_ => What { loading: tr("Loading the playlist…"), gone: tr("This playlist isn't available on Yandex Music any more."), retry: tr("the playlist") },
|
||||
};
|
||||
match page {
|
||||
Loadable::Loaded(Page::Album { info, tracks }) => album(env, info, tracks),
|
||||
Loadable::Loaded(Page::Artist { info, popular }) => artist(env, info, popular),
|
||||
Loadable::Loaded(Page::Playlist { info, tracks }) => playlist(env, info, tracks),
|
||||
Loadable::Failed(e) => not_found_or_retry(env, e, what, route),
|
||||
Loadable::NotLoaded | Loadable::Loading => {
|
||||
para(what.loading, size::BODY, t.muted).into()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How the page talks about what it's loading.
|
||||
struct What {
|
||||
loading: &'static str,
|
||||
gone: &'static str,
|
||||
retry: &'static str,
|
||||
}
|
||||
|
||||
fn not_found_or_retry<'a>(env: Env<'a>, e: &'a Error, what: What, route: Route) -> Element<'a, Message> {
|
||||
if let Error::Api(m) = e
|
||||
&& m.contains("not found")
|
||||
{
|
||||
return para(what.gone, size::BODY, env.t.muted).into();
|
||||
}
|
||||
status(env.t, LoadState::Failed(e), what.retry, Message::Navigate(route))
|
||||
}
|
||||
|
||||
struct Head<'a> {
|
||||
cover: Option<String>,
|
||||
hues: (f32, f32),
|
||||
round: bool,
|
||||
kind: String,
|
||||
title: String,
|
||||
by: Option<Element<'a, Message>>,
|
||||
meta: String,
|
||||
actions: Vec<Element<'a, Message>>,
|
||||
}
|
||||
|
||||
fn head<'a>(env: Env<'a>, h: Head<'a>) -> Element<'a, Message> {
|
||||
let t = env.t;
|
||||
let size_px = 200.0;
|
||||
let corner = if h.round { size_px / 2.0 } else { theme::radius::COVER };
|
||||
row![
|
||||
covers::view(env.covers, h.cover, h.hues, size_px, corner),
|
||||
column![
|
||||
line(h.kind, theme::BODY, size::META, t.muted),
|
||||
text(h.title).font(theme::DISPLAY).size(size::DISPLAY_L).line_height(1.08).color(t.fg),
|
||||
]
|
||||
.push(h.by)
|
||||
.push(line(h.meta, theme::BODY, size::META, t.muted))
|
||||
.push((!h.actions.is_empty()).then(|| Row::with_children(h.actions).spacing(8).align_y(Alignment::Center)))
|
||||
.spacing(8)
|
||||
.width(Fill),
|
||||
]
|
||||
.spacing(28)
|
||||
.align_y(Alignment::End)
|
||||
.into()
|
||||
}
|
||||
|
||||
/// A round heart that adds or removes something from the collection.
|
||||
fn like_button<'a>(t: &'static theme::Tokens, liked: bool, msg: Message) -> Element<'a, Message> {
|
||||
button(icon(if liked { Icon::HeartFilled } else { Icon::Heart }, if liked { t.like } else { t.fg }))
|
||||
.padding(10)
|
||||
.style(theme::ghost)
|
||||
.on_press(msg)
|
||||
.into()
|
||||
}
|
||||
|
||||
fn pill<'a>(t: &'static theme::Tokens, glyph: Icon, label: &'a str, msg: Message) -> Element<'a, Message> {
|
||||
button(row![icon(glyph, t.fg), line(label, theme::MEDIUM, size::META, t.fg)].spacing(6).align_y(Alignment::Center))
|
||||
.padding([8, 14])
|
||||
.style(theme::ghost)
|
||||
.on_press(msg)
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Artist names as links to their pages.
|
||||
fn artist_links<'a>(env: Env<'a>, artists: &[ArtistRef]) -> Element<'a, Message> {
|
||||
let t = env.t;
|
||||
Row::with_children(artists.iter().map(|a| {
|
||||
let label = line(a.name.clone(), theme::MEDIUM, size::BODY, t.fg);
|
||||
match a.id {
|
||||
Some(id) => button(label)
|
||||
.padding(0)
|
||||
.style(theme::tab(true))
|
||||
.on_press(Message::Navigate(Route::Artist(id)))
|
||||
.into(),
|
||||
None => label.into(),
|
||||
}
|
||||
}))
|
||||
.spacing(12)
|
||||
.into()
|
||||
}
|
||||
|
||||
fn album<'a>(env: Env<'a>, info: &'a AlbumPage, tracks: &'a Arc<[Track]>) -> Element<'a, Message> {
|
||||
let a = &info.album;
|
||||
let kind = match a.year {
|
||||
Some(year) => format!("{} · {year}", tr(a.kind.label())),
|
||||
None => tr(a.kind.label()).to_owned(),
|
||||
};
|
||||
// `info.tracks` was moved into `tracks`, so measure the list itself.
|
||||
let length = format!("{} · {}", tracks_word(tracks.len()), duration_words(tracks.iter().map(|tr| tr.duration).sum()));
|
||||
let meta = match &info.label {
|
||||
Some(label) => format!("{length} · {label}"),
|
||||
None => length,
|
||||
};
|
||||
column![
|
||||
head(env, Head {
|
||||
cover: a.cover_url(covers::LARGE),
|
||||
hues: a.hues(),
|
||||
round: false,
|
||||
kind,
|
||||
title: a.full_title(),
|
||||
by: Some(artist_links(env, &a.artists)),
|
||||
meta,
|
||||
actions: vec![like_button(env.t, env.likes.albums.contains(&a.id), Message::LikeAlbum(a.id, !env.likes.albums.contains(&a.id)))],
|
||||
}),
|
||||
play_bar(env.t, String::new(), tracks),
|
||||
track_list::view(env, tracks, Columns::ALBUM_PAGE),
|
||||
]
|
||||
.spacing(28)
|
||||
.into()
|
||||
}
|
||||
|
||||
fn artist<'a>(env: Env<'a>, info: &'a ArtistPage, popular: &'a Arc<[Track]>) -> Element<'a, Message> {
|
||||
let t = env.t;
|
||||
let a = &info.artist;
|
||||
let kind = if a.genres.is_empty() { tr("Artist").to_owned() } else { trf("Artist · {}", &[&a.genres.join(", ")]) };
|
||||
let meta = info
|
||||
.monthly_listeners
|
||||
.map(|n| counted(n, ["listener a month", "listeners a month"], ["слушатель в месяц", "слушателя в месяц", "слушателей в месяц"]))
|
||||
.or_else(|| a.likes.map(|n| counted(n, ["like", "likes"], ["лайк", "лайка", "лайков"])))
|
||||
.unwrap_or_default();
|
||||
|
||||
let mut page = column![
|
||||
head(env, Head {
|
||||
cover: a.cover_url(covers::LARGE),
|
||||
hues: a.hues(),
|
||||
round: true,
|
||||
kind,
|
||||
title: a.name.clone(),
|
||||
by: None,
|
||||
meta,
|
||||
actions: vec![like_button(t, env.likes.artists.contains(&a.id), Message::LikeArtist(a.id, !env.likes.artists.contains(&a.id)))],
|
||||
}),
|
||||
]
|
||||
.spacing(34);
|
||||
|
||||
if !popular.is_empty() {
|
||||
page = page.push(
|
||||
column![
|
||||
line(tr("Popular tracks"), theme::SEMIBOLD, size::SECTION, t.fg),
|
||||
play_bar(t, String::new(), popular),
|
||||
track_list::view(env, popular, Columns::FULL),
|
||||
]
|
||||
.spacing(14),
|
||||
);
|
||||
}
|
||||
if !info.albums.is_empty() {
|
||||
page = page.push(section(t, tr("Albums"), info.albums.iter().map(|al| album_card(t, env.covers, al))));
|
||||
}
|
||||
if !info.also_albums.is_empty() {
|
||||
page = page.push(section(t, tr("Appears on"), info.also_albums.iter().map(|al| album_card(t, env.covers, al))));
|
||||
}
|
||||
if !info.clips.is_empty() {
|
||||
page = page.push(section(t, tr("Clips"), info.clips.iter().map(|c| clip_card(env, c))));
|
||||
}
|
||||
if !info.similar.is_empty() {
|
||||
page = page.push(section(t, tr("Similar artists"), info.similar.iter().map(|ar| artist_card(t, env.covers, ar))));
|
||||
}
|
||||
page.into()
|
||||
}
|
||||
|
||||
fn playlist<'a>(env: Env<'a>, info: &'a PlaylistPage, tracks: &'a Arc<[Track]>) -> Element<'a, Message> {
|
||||
let t = env.t;
|
||||
let p = &info.playlist;
|
||||
let own = p.id.owner == env.me;
|
||||
let total = tracks.iter().map(|tr| tr.duration).sum();
|
||||
let mut page = column![
|
||||
head(env, Head {
|
||||
cover: p.cover_url(covers::LARGE),
|
||||
hues: p.hues(),
|
||||
round: false,
|
||||
kind: trf("Playlist · {}", &[&if p.public { tr("Public") } else { tr("Private") }]),
|
||||
title: p.title.clone(),
|
||||
by: Some(line(p.owner_name.clone(), theme::MEDIUM, size::BODY, t.fg).into()),
|
||||
meta: format!("{} · {}", tracks_word(tracks.len()), duration_words(total)),
|
||||
actions: if own {
|
||||
vec![
|
||||
pill(t, Icon::Pencil, tr("Rename"), Message::OpenSheet(Sheet::Rename { id: p.id, name: p.title.clone() })),
|
||||
pill(
|
||||
t,
|
||||
if p.public { Icon::Lock } else { Icon::Globe },
|
||||
if p.public { tr("Make private") } else { tr("Make public") },
|
||||
Message::SetPlaylistPublic(p.id, !p.public),
|
||||
),
|
||||
pill(t, Icon::Trash, tr("Delete"), Message::OpenSheet(Sheet::ConfirmDelete { id: p.id, title: p.title.clone() })),
|
||||
]
|
||||
} else {
|
||||
vec![like_button(t, env.likes.playlists.contains(&p.id), Message::LikePlaylist(p.id, !env.likes.playlists.contains(&p.id)))]
|
||||
},
|
||||
}),
|
||||
]
|
||||
.spacing(28);
|
||||
if let Some(description) = &info.description {
|
||||
page = page.push(container(para(description.clone(), size::BODY, t.muted)).max_width(640));
|
||||
}
|
||||
if tracks.is_empty() {
|
||||
return page.push(para(tr("This playlist is empty."), size::BODY, t.muted)).into();
|
||||
}
|
||||
let list = if own {
|
||||
track_list::view_own_playlist(env, tracks, p.id)
|
||||
} else {
|
||||
track_list::view(env, tracks, Columns::FULL)
|
||||
};
|
||||
page.push(play_bar(t, String::new(), tracks)).push(list).into()
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
//! Content for each route, plus the full-window screens shown outside a session.
|
||||
|
||||
pub mod browse;
|
||||
pub mod collection;
|
||||
pub mod detail;
|
||||
pub mod search;
|
||||
pub mod settings;
|
||||
pub mod sign_in;
|
||||
pub mod wave;
|
||||
|
||||
use iced::widget::{Column, button, column, container, row, space};
|
||||
use iced::{Alignment, Element, Fill, Padding};
|
||||
use std::collections::HashMap;
|
||||
|
||||
use ym_api::{Account, Error, PlaylistSummary};
|
||||
|
||||
use crate::app::Message;
|
||||
use crate::route::Route;
|
||||
use crate::ui::icons::{Icon, icon};
|
||||
use crate::ui::theme::{self, Tokens, size, space as sp};
|
||||
use crate::ui::{line, para};
|
||||
use crate::widgets::sidebar;
|
||||
use crate::widgets::track_list::Env;
|
||||
use crate::i18n::{tr, trf};
|
||||
|
||||
/// Something fetched from the API: not asked for yet, on its way, here, or failed.
|
||||
#[derive(Debug, Default)]
|
||||
pub enum Loadable<T> {
|
||||
#[default]
|
||||
NotLoaded,
|
||||
Loading,
|
||||
Loaded(T),
|
||||
Failed(Error),
|
||||
}
|
||||
|
||||
impl<T> Loadable<T> {
|
||||
pub fn get(&self) -> Option<&T> {
|
||||
match self {
|
||||
Loadable::Loaded(v) => Some(v),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Not loaded yet, or failed: worth (re)requesting.
|
||||
pub fn needs_load(&self) -> bool {
|
||||
matches!(self, Loadable::NotLoaded | Loadable::Failed(_))
|
||||
}
|
||||
|
||||
pub fn state(&self) -> collection::LoadState<'_> {
|
||||
match self {
|
||||
Loadable::Failed(e) => collection::LoadState::Failed(e),
|
||||
_ => collection::LoadState::Loading,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_result(result: Result<T, Error>) -> Self {
|
||||
match result {
|
||||
Ok(v) => Loadable::Loaded(v),
|
||||
Err(e) => Loadable::Failed(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything a routed screen may need from app state.
|
||||
pub struct Ctx<'a> {
|
||||
pub env: Env<'a>,
|
||||
pub route: Route,
|
||||
pub search: &'a search::Search,
|
||||
pub me: &'a Account,
|
||||
pub library: &'a collection::Library,
|
||||
pub pages: &'a HashMap<Route, Loadable<detail::Page>>,
|
||||
pub discover: &'a browse::Discover,
|
||||
pub genre_playlists: &'a HashMap<usize, Loadable<Vec<PlaylistSummary>>>,
|
||||
pub player: &'a crate::player::Player,
|
||||
pub wave: &'a wave::WaveScreen,
|
||||
pub wave_phase: f32,
|
||||
pub settings: &'a crate::store::Settings,
|
||||
}
|
||||
|
||||
pub fn view<'a>(ctx: Ctx<'a>) -> Element<'a, Message> {
|
||||
let Ctx { env, route, search, me, library, pages, discover, genre_playlists, player, wave, wave_phase, settings } = ctx;
|
||||
let t = env.t;
|
||||
let content: Column<'a, Message> = match route {
|
||||
Route::Home => {
|
||||
column![browse::home(env, discover, wave::hero(t, player, wave_phase, wave.shown(), false))]
|
||||
}
|
||||
Route::Wave => column![wave::view(
|
||||
t,
|
||||
env.covers,
|
||||
wave,
|
||||
wave::hero(t, player, wave_phase, wave.shown(), true),
|
||||
)],
|
||||
Route::Search => column![search::view(env, search, browse::genres_section(env, &discover.genres))],
|
||||
Route::Chart => column![browse::chart(env, discover)],
|
||||
Route::Genre(i) => column![browse::genre(
|
||||
env,
|
||||
discover.genres.get().map_or(&[][..], Vec::as_slice),
|
||||
i,
|
||||
genre_playlists.get(&i).unwrap_or(&Loadable::Loading),
|
||||
)],
|
||||
Route::Collection => column![collection::view(env, library)],
|
||||
Route::Album(_) | Route::Artist(_) | Route::Playlist(_) => {
|
||||
column![detail::view(env, route, pages.get(&route).unwrap_or(&Loadable::Loading))]
|
||||
}
|
||||
Route::Podcasts => column![browse::podcasts(env, discover, &library.albums)],
|
||||
Route::Settings => column![settings::view(t, settings, account_card(t, me))],
|
||||
};
|
||||
|
||||
content
|
||||
.spacing(sp::SECTION)
|
||||
.padding(Padding::default().top(6).bottom(40).left(sp::GUTTER).right(sp::GUTTER))
|
||||
.width(Fill)
|
||||
.into()
|
||||
}
|
||||
|
||||
fn account_card<'a>(t: &'static Tokens, me: &'a Account) -> Element<'a, Message> {
|
||||
let avatar = container(line(me.initial().to_string(), theme::SEMIBOLD, 22.0, iced::Color::from_rgb8(0x1C, 0x1A, 0x22)))
|
||||
.center(56)
|
||||
.style(theme::avatar);
|
||||
|
||||
let plan = match (me.has_plus, me.subscription_end.as_deref().and_then(human_date)) {
|
||||
(true, Some(end)) => trf("Yandex Plus until {}", &[&end]),
|
||||
(true, None) => tr("Yandex Plus").to_owned(),
|
||||
(false, _) => tr("No Plus subscription. Tracks play as 30-second previews.").to_owned(),
|
||||
};
|
||||
|
||||
container(
|
||||
row![
|
||||
avatar,
|
||||
column![
|
||||
line(&me.name, theme::SEMIBOLD, size::SECTION, t.fg),
|
||||
line(&me.login, theme::BODY, size::BODY, t.muted),
|
||||
line(plan, theme::MEDIUM, size::META, if me.has_plus { t.ok } else { t.muted }),
|
||||
]
|
||||
.spacing(4)
|
||||
.width(Fill),
|
||||
button(
|
||||
row![icon(Icon::LogOut, t.fg), line(tr("Sign out"), theme::MEDIUM, size::BODY, t.fg)]
|
||||
.spacing(8)
|
||||
.align_y(Alignment::Center),
|
||||
)
|
||||
.padding([9, 16])
|
||||
.style(theme::ghost)
|
||||
.on_press(Message::SignOut),
|
||||
]
|
||||
.spacing(18)
|
||||
.align_y(Alignment::Center),
|
||||
)
|
||||
.padding(24)
|
||||
.width(Fill)
|
||||
.style(theme::card)
|
||||
.into()
|
||||
}
|
||||
|
||||
/// `2027-01-05T00:00:00+03:00` → `5 January 2027` (`5 января 2027`).
|
||||
pub fn human_date(iso: &str) -> Option<String> {
|
||||
const MONTHS: [&str; 12] = [
|
||||
"January", "February", "March", "April", "May", "June", "July", "August", "September",
|
||||
"October", "November", "December",
|
||||
];
|
||||
// Genitive, as Russian dates need.
|
||||
const MONTHS_RU: [&str; 12] = [
|
||||
"января", "февраля", "марта", "апреля", "мая", "июня", "июля", "августа", "сентября",
|
||||
"октября", "ноября", "декабря",
|
||||
];
|
||||
let months = match crate::i18n::lang() {
|
||||
crate::i18n::Lang::En => MONTHS,
|
||||
crate::i18n::Lang::Ru => MONTHS_RU,
|
||||
};
|
||||
let date = iso.get(..10)?;
|
||||
let mut parts = date.split('-');
|
||||
let (y, m, d) = (parts.next()?, parts.next()?, parts.next()?);
|
||||
let month = months.get(m.parse::<usize>().ok()?.checked_sub(1)?)?;
|
||||
let day: u32 = d.parse().ok()?;
|
||||
y.parse::<u32>().ok()?;
|
||||
Some(format!("{day} {month} {y}"))
|
||||
}
|
||||
|
||||
/// Full-window holding screen while the stored session is checked or a new one connects.
|
||||
pub fn connecting<'a>(t: &'static Tokens, label: &'a str) -> Element<'a, Message> {
|
||||
container(
|
||||
column![
|
||||
sidebar::wordmark(t),
|
||||
line(label, theme::BODY, size::BODY, t.muted),
|
||||
]
|
||||
.spacing(14)
|
||||
.align_x(Alignment::Center),
|
||||
)
|
||||
.center(Fill)
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Full-window screen when stored credentials exist but Yandex can't be reached.
|
||||
pub fn unreachable<'a>(t: &'static Tokens) -> Element<'a, Message> {
|
||||
container(
|
||||
column![
|
||||
sidebar::wordmark(t),
|
||||
line(tr("Can't reach Yandex Music"), theme::DISPLAY, size::DISPLAY_S, t.fg),
|
||||
container(para(
|
||||
tr("You're still signed in. Check your internet connection, then try again."),
|
||||
15.0,
|
||||
t.muted,
|
||||
))
|
||||
.max_width(440),
|
||||
row![
|
||||
button(line(tr("Try again"), theme::SEMIBOLD, size::BODY, t.accent_ink))
|
||||
.padding([11, 18])
|
||||
.style(theme::primary)
|
||||
.on_press(Message::Restore),
|
||||
button(line(tr("Sign out"), theme::MEDIUM, size::BODY, t.fg))
|
||||
.padding([11, 18])
|
||||
.style(theme::ghost)
|
||||
.on_press(Message::SignOut),
|
||||
]
|
||||
.spacing(10),
|
||||
space().height(40),
|
||||
]
|
||||
.spacing(18)
|
||||
.align_x(Alignment::Center),
|
||||
)
|
||||
.center(Fill)
|
||||
.into()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::human_date;
|
||||
|
||||
#[test]
|
||||
fn dates_read_naturally() {
|
||||
assert_eq!(human_date("2027-01-05T00:00:00+03:00").as_deref(), Some("5 January 2027"));
|
||||
assert_eq!(human_date("2026-12-31").as_deref(), Some("31 December 2026"));
|
||||
assert_eq!(human_date("2026-13-01"), None);
|
||||
crate::i18n::set(crate::i18n::Lang::Ru);
|
||||
assert_eq!(human_date("2027-01-05T00:00:00+03:00").as_deref(), Some("5 января 2027"));
|
||||
crate::i18n::set(crate::i18n::Lang::En);
|
||||
assert_eq!(human_date("soon"), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,467 @@
|
||||
//! Search: suggestions while typing, results by kind, more pages on request.
|
||||
//! With no query it shows genres to browse.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use iced::widget::{button, column, container, row};
|
||||
use iced::{Alignment, Element, Fill, Task};
|
||||
use ym_api::{BestMatch, Error, SearchKind, SearchResults, Track, YmClient};
|
||||
|
||||
use super::collection::{
|
||||
LoadState, album_card, artist_card, play_bar, playlist_card, section, status,
|
||||
};
|
||||
use super::Loadable;
|
||||
use crate::app::Message;
|
||||
use crate::covers;
|
||||
use crate::route::Route;
|
||||
use crate::ui::icons::{Icon, icon};
|
||||
use crate::ui::theme::{self, radius, size};
|
||||
use crate::ui::{compact, line, para};
|
||||
use crate::widgets::card;
|
||||
use crate::widgets::track_list::{self, Env};
|
||||
use crate::widgets::track_row::Columns;
|
||||
use crate::i18n::{tr, trf};
|
||||
|
||||
/// Wait this long after the last keystroke before asking for suggestions.
|
||||
const DEBOUNCE: Duration = Duration::from_millis(250);
|
||||
/// Tracks shown in the "All" tab before "Show all".
|
||||
const ALL_TAB_TRACKS: usize = 5;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Msg {
|
||||
Changed(String),
|
||||
/// The debounce timer for this text ran out.
|
||||
Settled(String),
|
||||
Suggestions(String, Result<Vec<String>, Error>),
|
||||
Pick(String),
|
||||
Submit,
|
||||
CloseSuggestions,
|
||||
Tab(SearchKind),
|
||||
Loaded { query: String, kind: SearchKind, page: u32, result: Box<Result<SearchResults, Error>> },
|
||||
More,
|
||||
}
|
||||
|
||||
/// Results for one query and kind, with the tracks as a playable list.
|
||||
#[derive(Debug)]
|
||||
pub struct Results {
|
||||
pub data: SearchResults,
|
||||
pub tracks: Arc<[Track]>,
|
||||
/// The first few tracks for the "All" tab, built once so the cached list stays valid.
|
||||
top: Arc<[Track]>,
|
||||
pub page: u32,
|
||||
loading_more: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Search {
|
||||
pub text: String,
|
||||
/// The query the results are for; `text` may have moved on since.
|
||||
query: String,
|
||||
kind: SearchKind,
|
||||
results: Loadable<Results>,
|
||||
suggestions: Vec<String>,
|
||||
show_suggestions: bool,
|
||||
}
|
||||
|
||||
/// What the app should do after a search message besides running the task.
|
||||
pub enum After {
|
||||
Nothing,
|
||||
ShowResults,
|
||||
}
|
||||
|
||||
impl Search {
|
||||
pub fn suggestions(&self) -> Option<&[String]> {
|
||||
(self.show_suggestions && !self.suggestions.is_empty()).then_some(&self.suggestions)
|
||||
}
|
||||
|
||||
pub fn update(&mut self, msg: Msg, client: Option<&YmClient>) -> (Task<Message>, After) {
|
||||
match msg {
|
||||
Msg::Changed(text) => {
|
||||
self.text = text.clone();
|
||||
self.show_suggestions = !text.trim().is_empty();
|
||||
if text.trim().is_empty() {
|
||||
self.suggestions.clear();
|
||||
return (Task::none(), After::Nothing);
|
||||
}
|
||||
let task = Task::future(async move {
|
||||
tokio::time::sleep(DEBOUNCE).await;
|
||||
text
|
||||
})
|
||||
.map(|t| Message::Search(Msg::Settled(t)));
|
||||
return (task, After::Nothing);
|
||||
}
|
||||
Msg::Settled(text) => {
|
||||
// Only the last keystroke's timer asks.
|
||||
if text != self.text {
|
||||
return (Task::none(), After::Nothing);
|
||||
}
|
||||
let Some(client) = client.cloned() else { return (Task::none(), After::Nothing) };
|
||||
let part = text.clone();
|
||||
let task = Task::future(async move { client.suggest(&part).await })
|
||||
.map(move |r| Message::Search(Msg::Suggestions(text.clone(), r)));
|
||||
return (task, After::Nothing);
|
||||
}
|
||||
Msg::Suggestions(text, Ok(list)) if text == self.text => self.suggestions = list,
|
||||
Msg::Suggestions(_, Err(e)) => eprintln!("suggest: {e}"),
|
||||
Msg::Suggestions(..) => {}
|
||||
Msg::Pick(text) => {
|
||||
self.text = text;
|
||||
return self.update(Msg::Submit, client);
|
||||
}
|
||||
Msg::Submit => {
|
||||
self.show_suggestions = false;
|
||||
let query = self.text.trim().to_owned();
|
||||
if query.is_empty() {
|
||||
return (Task::none(), After::ShowResults);
|
||||
}
|
||||
if query != self.query || self.results.needs_load() {
|
||||
self.query = query;
|
||||
return (self.fetch(client, 0), After::ShowResults);
|
||||
}
|
||||
return (Task::none(), After::ShowResults);
|
||||
}
|
||||
Msg::CloseSuggestions => self.show_suggestions = false,
|
||||
Msg::Tab(kind) => {
|
||||
if kind != self.kind {
|
||||
self.kind = kind;
|
||||
if !self.query.is_empty() {
|
||||
return (self.fetch(client, 0), After::Nothing);
|
||||
}
|
||||
}
|
||||
}
|
||||
Msg::Loaded { query, kind, page, result } => {
|
||||
if query != self.query || kind != self.kind {
|
||||
return (Task::none(), After::Nothing);
|
||||
}
|
||||
match (*result, &mut self.results) {
|
||||
(Ok(more), Loadable::Loaded(current)) if page > 0 => {
|
||||
current.data.tracks.extend(more.tracks);
|
||||
current.data.albums.extend(more.albums);
|
||||
current.data.artists.extend(more.artists);
|
||||
current.data.playlists.extend(more.playlists);
|
||||
current.data.podcasts.extend(more.podcasts);
|
||||
current.tracks = current.data.tracks.clone().into();
|
||||
current.top = top_of(¤t.tracks);
|
||||
current.page = page;
|
||||
current.loading_more = false;
|
||||
}
|
||||
(Ok(data), _) => {
|
||||
let tracks: Arc<[Track]> = data.tracks.clone().into();
|
||||
let top = top_of(&tracks);
|
||||
self.results = Loadable::Loaded(Results { data, tracks, top, page, loading_more: false });
|
||||
}
|
||||
(Err(e), Loadable::Loaded(current)) if page > 0 => {
|
||||
eprintln!("search more: {e}");
|
||||
current.loading_more = false;
|
||||
}
|
||||
(Err(e), _) => {
|
||||
eprintln!("search: {e}");
|
||||
self.results = Loadable::Failed(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Msg::More => {
|
||||
if let Loadable::Loaded(current) = &mut self.results
|
||||
&& !current.loading_more
|
||||
{
|
||||
current.loading_more = true;
|
||||
let next = current.page + 1;
|
||||
return (self.fetch(client, next), After::Nothing);
|
||||
}
|
||||
}
|
||||
}
|
||||
(Task::none(), After::Nothing)
|
||||
}
|
||||
|
||||
fn fetch(&mut self, client: Option<&YmClient>, page: u32) -> Task<Message> {
|
||||
let Some(client) = client.cloned() else { return Task::none() };
|
||||
if page == 0 {
|
||||
self.results = Loadable::Loading;
|
||||
}
|
||||
let (query, kind) = (self.query.clone(), self.kind);
|
||||
Task::future(async move {
|
||||
let result = client.search(&query, kind, page).await;
|
||||
Msg::Loaded { query, kind, page, result: Box::new(result) }
|
||||
})
|
||||
.map(Message::Search)
|
||||
}
|
||||
|
||||
fn has_more(&self, r: &Results) -> bool {
|
||||
let Some(total) = r.data.totals.get(self.kind) else { return false };
|
||||
let shown = match self.kind {
|
||||
SearchKind::All => return false,
|
||||
SearchKind::Tracks => r.data.tracks.len(),
|
||||
SearchKind::Albums => r.data.albums.len(),
|
||||
SearchKind::Artists => r.data.artists.len(),
|
||||
SearchKind::Playlists => r.data.playlists.len(),
|
||||
SearchKind::Podcasts => r.data.podcasts.len(),
|
||||
};
|
||||
(shown as u32) < total
|
||||
}
|
||||
}
|
||||
|
||||
pub fn view<'a>(env: Env<'a>, search: &'a Search, browse: Element<'a, Message>) -> Element<'a, Message> {
|
||||
let t = env.t;
|
||||
if search.query.is_empty() {
|
||||
return column![line(tr("Browse"), theme::DISPLAY, size::DISPLAY_S, t.fg), browse].spacing(24).into();
|
||||
}
|
||||
|
||||
let tabs = row(SearchKind::ALL.map(|kind| {
|
||||
let on = kind == search.kind;
|
||||
let total = search.results.get().and_then(|r| r.data.totals.get(kind)).filter(|n| *n > 0);
|
||||
let mut label = row![line(kind.label(), theme::MEDIUM, size::BODY, if on { t.fg } else { t.muted })]
|
||||
.spacing(6)
|
||||
.align_y(Alignment::Center);
|
||||
if let Some(n) = total {
|
||||
label = label.push(line(compact(i64::from(n)), theme::BODY, size::SMALL, t.muted));
|
||||
}
|
||||
button(
|
||||
column![
|
||||
label,
|
||||
container(iced::widget::space()).width(Fill).height(2).style(theme::tab_underline(on)),
|
||||
]
|
||||
.spacing(7)
|
||||
.width(iced::Shrink),
|
||||
)
|
||||
.padding([6, 10])
|
||||
.style(theme::tab(on))
|
||||
.on_press(Message::Search(Msg::Tab(kind)))
|
||||
.into()
|
||||
}))
|
||||
.spacing(4);
|
||||
|
||||
let title = line(trf("Results for “{}”", &[&search.query]), theme::DISPLAY, size::DISPLAY_S, t.fg);
|
||||
let body: Element<'a, Message> = match &search.results {
|
||||
Loadable::Loaded(r) if r.data.is_empty() => para(
|
||||
trf("Nothing found for “{}”. Check the spelling or try fewer words.", &[&search.query]),
|
||||
size::BODY,
|
||||
t.muted,
|
||||
)
|
||||
.into(),
|
||||
Loadable::Loaded(r) => results(env, search, r),
|
||||
Loadable::Failed(e) => status(t, LoadState::Failed(e), tr("the results"), Message::Search(Msg::Submit)),
|
||||
_ => para(tr("Searching…"), size::BODY, t.muted).into(),
|
||||
};
|
||||
|
||||
let mut page = column![title].spacing(24);
|
||||
if let Some(corrected) = search.results.get().and_then(|r| r.data.corrected.as_ref()) {
|
||||
page = page.push(line(trf("Showing results for “{}”", &[corrected]), theme::BODY, size::META, t.muted));
|
||||
}
|
||||
page.push(tabs).push(body).into()
|
||||
}
|
||||
|
||||
fn results<'a>(env: Env<'a>, search: &'a Search, r: &'a Results) -> Element<'a, Message> {
|
||||
let t = env.t;
|
||||
let covers = env.covers;
|
||||
let d = &r.data;
|
||||
let more = search.has_more(r).then(|| {
|
||||
button(line(if r.loading_more { tr("Loading…") } else { tr("Show more") }, theme::MEDIUM, size::BODY, t.fg))
|
||||
.padding([10, 18])
|
||||
.style(theme::ghost)
|
||||
.on_press_maybe((!r.loading_more).then_some(Message::Search(Msg::More)))
|
||||
});
|
||||
|
||||
let body: Element<'a, Message> = match search.kind {
|
||||
SearchKind::All => {
|
||||
let mut all = column![].spacing(34);
|
||||
if let Some(best) = &d.best {
|
||||
all = all.push(best_card(env, best));
|
||||
}
|
||||
if !r.tracks.is_empty() {
|
||||
all = all.push(
|
||||
column![
|
||||
row![
|
||||
line(tr("Tracks"), theme::SEMIBOLD, size::SECTION, t.fg).width(Fill),
|
||||
button(line(tr("Show all"), theme::MEDIUM, size::META, t.muted))
|
||||
.padding(0)
|
||||
.style(theme::tab(false))
|
||||
.on_press(Message::Search(Msg::Tab(SearchKind::Tracks))),
|
||||
],
|
||||
track_list::view(env, &r.top, Columns::FULL),
|
||||
]
|
||||
.spacing(14),
|
||||
);
|
||||
}
|
||||
if !d.artists.is_empty() {
|
||||
all = all.push(section(t, tr("Artists"), d.artists.iter().take(6).map(|a| artist_card(t, covers, a))));
|
||||
}
|
||||
if !d.albums.is_empty() {
|
||||
all = all.push(section(t, tr("Albums"), d.albums.iter().take(6).map(|a| album_card(t, covers, a))));
|
||||
}
|
||||
if !d.playlists.is_empty() {
|
||||
all = all.push(section(t, tr("Playlists"), d.playlists.iter().take(6).map(|p| playlist_card(t, covers, p))));
|
||||
}
|
||||
if !d.podcasts.is_empty() {
|
||||
all = all.push(section(t, tr("Podcasts"), d.podcasts.iter().take(6).map(|a| album_card(t, covers, a))));
|
||||
}
|
||||
all.into()
|
||||
}
|
||||
SearchKind::Tracks => column![
|
||||
play_bar(t, String::new(), &r.tracks),
|
||||
track_list::view(env, &r.tracks, Columns::FULL),
|
||||
]
|
||||
.spacing(18)
|
||||
.into(),
|
||||
SearchKind::Albums => card::grid(d.albums.iter().map(|a| album_card(t, covers, a))),
|
||||
SearchKind::Artists => card::grid(d.artists.iter().map(|a| artist_card(t, covers, a))),
|
||||
SearchKind::Playlists => card::grid(d.playlists.iter().map(|p| playlist_card(t, covers, p))),
|
||||
SearchKind::Podcasts => card::grid(d.podcasts.iter().map(|a| album_card(t, covers, a))),
|
||||
};
|
||||
column![body].push(more).spacing(22).into()
|
||||
}
|
||||
|
||||
/// The top result as a wide card: cover, name, kind, and the action it implies.
|
||||
fn best_card<'a>(env: Env<'a>, best: &'a BestMatch) -> Element<'a, Message> {
|
||||
let t = env.t;
|
||||
let (cover, hues, round, title, kind, action) = match best {
|
||||
BestMatch::Artist(a) => (
|
||||
a.cover_url(covers::LARGE), a.hues(), true, a.name.clone(), tr("Artist").to_owned(),
|
||||
Message::Navigate(Route::Artist(a.id)),
|
||||
),
|
||||
BestMatch::Album(a) => (
|
||||
a.cover_url(covers::LARGE), a.hues(), false, a.full_title(), format!("{} · {}", a.kind.label(), a.artist_line()),
|
||||
Message::Navigate(Route::Album(a.id)),
|
||||
),
|
||||
BestMatch::Playlist(p) => (
|
||||
p.cover_url(covers::LARGE), p.hues(), false, p.title.clone(), trf("Playlist · {}", &[&p.owner_name]),
|
||||
Message::Navigate(Route::Playlist(p.id)),
|
||||
),
|
||||
BestMatch::Track(tr) => (
|
||||
tr.cover_url(covers::LARGE), tr.hues(), false, tr.full_title(), trf("Track · {}", &[&tr.artist_line()]),
|
||||
Message::PlayTracks { tracks: Arc::from(vec![tr.clone()]), start: 0, shuffle: false },
|
||||
),
|
||||
};
|
||||
let size_px = 108.0;
|
||||
let corner = if round { size_px / 2.0 } else { radius::COVER };
|
||||
let glyph = if matches!(best, BestMatch::Track(_)) { Icon::Play } else { Icon::Forward };
|
||||
button(
|
||||
row![
|
||||
covers::view(env.covers, cover, hues, size_px, corner),
|
||||
column![
|
||||
line(tr("Top result"), theme::MEDIUM, size::SMALL, t.muted),
|
||||
line(title, theme::DISPLAY, 24.0, t.fg),
|
||||
line(kind, theme::BODY, size::META, t.muted),
|
||||
]
|
||||
.spacing(6)
|
||||
.width(Fill),
|
||||
container(icon(glyph, t.accent_ink))
|
||||
.center(44)
|
||||
.style(move |_| container::Style {
|
||||
background: Some(t.accent.into()),
|
||||
border: iced::Border { radius: radius::PILL.into(), ..Default::default() },
|
||||
..Default::default()
|
||||
})
|
||||
.padding(0),
|
||||
]
|
||||
.spacing(20)
|
||||
.align_y(Alignment::Center),
|
||||
)
|
||||
.padding(18)
|
||||
.width(Fill)
|
||||
.style(move |th, status| {
|
||||
let mut s = theme::nav_item(false)(th, status);
|
||||
if s.background.is_none() {
|
||||
s.background = Some(t.panel.into());
|
||||
}
|
||||
s.border = iced::Border { color: t.line, width: 1.0, radius: radius::CARD.into() };
|
||||
s
|
||||
})
|
||||
.on_press(action)
|
||||
.into()
|
||||
}
|
||||
|
||||
fn top_of(tracks: &[Track]) -> Arc<[Track]> {
|
||||
tracks.iter().take(ALL_TAB_TRACKS).cloned().collect()
|
||||
}
|
||||
|
||||
/// The suggestion list floating under the search field.
|
||||
pub fn suggestions<'a>(t: &'static theme::Tokens, list: &'a [String]) -> Element<'a, Message> {
|
||||
let items = list.iter().take(8).map(|s| {
|
||||
button(
|
||||
row![icon(Icon::Search, t.muted), line(s.clone(), theme::BODY, size::BODY, t.fg)]
|
||||
.spacing(10)
|
||||
.align_y(Alignment::Center),
|
||||
)
|
||||
.width(Fill)
|
||||
.padding([8, 12])
|
||||
.style(theme::nav_item(false))
|
||||
.on_press(Message::Search(Msg::Pick(s.clone())))
|
||||
.into()
|
||||
});
|
||||
container(column(items).spacing(2))
|
||||
.padding(6)
|
||||
.width(420)
|
||||
.style(move |_| container::Style {
|
||||
background: Some(t.panel.into()),
|
||||
border: iced::Border { color: t.line, width: 1.0, radius: 12.0.into() },
|
||||
shadow: iced::Shadow {
|
||||
color: iced::Color::BLACK.scale_alpha(0.3),
|
||||
offset: iced::Vector::new(0.0, 12.0),
|
||||
blur_radius: 30.0,
|
||||
},
|
||||
..Default::default()
|
||||
})
|
||||
.into()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn loaded(page: u32, titles: &[&str], total: u32) -> Msg {
|
||||
let tracks = titles
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, t)| Track::from_json(&format!(r#"{{"id":"{}{i}","title":"{t}"}}"#, page)).unwrap())
|
||||
.collect();
|
||||
let mut data = SearchResults { tracks, ..Default::default() };
|
||||
data.totals.tracks = total;
|
||||
Msg::Loaded { query: "q".into(), kind: SearchKind::Tracks, page, result: Box::new(Ok(data)) }
|
||||
}
|
||||
|
||||
fn searched() -> Search {
|
||||
let mut s = Search::default();
|
||||
let _ = s.update(Msg::Changed("q".into()), None);
|
||||
let _ = s.update(Msg::Submit, None);
|
||||
let _ = s.update(Msg::Tab(SearchKind::Tracks), None);
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_suggestions_and_results_are_dropped() {
|
||||
let mut s = Search::default();
|
||||
let _ = s.update(Msg::Changed("зем".into()), None);
|
||||
let _ = s.update(Msg::Changed("земф".into()), None);
|
||||
let _ = s.update(Msg::Suggestions("зем".into(), Ok(vec!["old".into()])), None);
|
||||
assert!(s.suggestions().is_none());
|
||||
let _ = s.update(Msg::Suggestions("земф".into(), Ok(vec!["земфира".into()])), None);
|
||||
assert_eq!(s.suggestions().unwrap(), ["земфира".to_owned()]);
|
||||
let _ = s.update(Msg::Submit, None);
|
||||
assert!(s.suggestions().is_none(), "submitting hides suggestions");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn more_pages_append() {
|
||||
let mut s = searched();
|
||||
let _ = s.update(loaded(0, &["a", "b"], 4), None);
|
||||
let Loadable::Loaded(r) = &s.results else { panic!() };
|
||||
assert!(s.has_more(r));
|
||||
let _ = s.update(Msg::More, None);
|
||||
let _ = s.update(loaded(1, &["c", "d"], 4), None);
|
||||
let Loadable::Loaded(r) = &s.results else { panic!() };
|
||||
assert_eq!(r.tracks.len(), 4);
|
||||
assert!(!s.has_more(r));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn results_for_another_tab_are_ignored() {
|
||||
let mut s = searched();
|
||||
let mut msg = loaded(0, &["a"], 1);
|
||||
if let Msg::Loaded { kind, .. } = &mut msg {
|
||||
*kind = SearchKind::Albums;
|
||||
}
|
||||
let _ = s.update(msg, None);
|
||||
assert!(s.results.get().is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
//! Settings: account, streaming quality, appearance, storage.
|
||||
|
||||
use iced::widget::{Row, button, column, container, row};
|
||||
use iced::{Alignment, Element, Fill};
|
||||
use crate::app::Message;
|
||||
use crate::store::{Appearance, Locale, Quality, Settings};
|
||||
use crate::ui::icons::{Icon, icon};
|
||||
use crate::ui::theme::{self, Tokens, size};
|
||||
use crate::ui::{line, para};
|
||||
use crate::i18n::{tr, trf};
|
||||
|
||||
pub fn view<'a>(t: &'static Tokens, settings: &Settings, account: Element<'a, Message>) -> Element<'a, Message> {
|
||||
let quality = Row::with_children(Quality::ALL.map(|q| chip(t, q.label(), q == settings.quality, Message::SetQuality(q))))
|
||||
.spacing(6);
|
||||
let appearance =
|
||||
Row::with_children(Appearance::ALL.map(|a| chip(t, a.label(), a == settings.appearance, Message::SetAppearance(a))))
|
||||
.spacing(6);
|
||||
let language =
|
||||
Row::with_children(Locale::ALL.map(|l| chip(t, l.label(), l == settings.language, Message::SetLanguage(l))))
|
||||
.spacing(6);
|
||||
|
||||
column![
|
||||
line(tr("Settings"), theme::DISPLAY, size::DISPLAY_S, t.fg),
|
||||
account,
|
||||
section(t, tr("Streaming quality"), column![quality, para(settings.quality.detail(), size::META, t.muted)].spacing(10).into()),
|
||||
section(t, tr("Appearance"), appearance.into()),
|
||||
section(t, tr("Language"), language.into()),
|
||||
section(
|
||||
t,
|
||||
tr("Storage"),
|
||||
column![
|
||||
para(
|
||||
tr("Covers are kept on disk so pages open instantly next time. Clearing them frees the space; they download again as you browse."),
|
||||
size::META,
|
||||
t.muted,
|
||||
),
|
||||
button(row![icon(Icon::Trash, t.fg), line(tr("Clear cover cache"), theme::MEDIUM, size::BODY, t.fg)].spacing(8).align_y(Alignment::Center))
|
||||
.padding([9, 16])
|
||||
.style(theme::ghost)
|
||||
.on_press(Message::ClearCoverCache),
|
||||
]
|
||||
.spacing(12)
|
||||
.into(),
|
||||
),
|
||||
line(trf("Musyx {} · unofficial Yandex Music client", &[&env!("CARGO_PKG_VERSION")]), theme::BODY, size::SMALL, t.muted),
|
||||
]
|
||||
.spacing(28)
|
||||
.width(Fill)
|
||||
.into()
|
||||
}
|
||||
|
||||
fn section<'a>(t: &'static Tokens, title: &'a str, body: Element<'a, Message>) -> Element<'a, Message> {
|
||||
container(column![line(title, theme::SEMIBOLD, size::SECTION, t.fg), body].spacing(14))
|
||||
.padding(24)
|
||||
.width(Fill)
|
||||
.style(theme::card)
|
||||
.into()
|
||||
}
|
||||
|
||||
fn chip<'a>(t: &'static Tokens, label: &'static str, on: bool, msg: Message) -> Element<'a, Message> {
|
||||
button(line(label, theme::MEDIUM, 13.5, if on { t.accent_ink } else { t.fg }))
|
||||
.padding([7, 13])
|
||||
.style(theme::chip(on))
|
||||
.on_press_maybe((!on).then_some(msg))
|
||||
.into()
|
||||
}
|
||||
@@ -0,0 +1,496 @@
|
||||
//! Device-code sign-in: get a code, the user confirms it on Yandex's page
|
||||
//! (or scans the QR), we poll until a token arrives. A pasted token is the
|
||||
//! fallback for people who already have one.
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use iced::widget::{button, column, container, qr_code, row, space, text_input};
|
||||
use iced::{Alignment, Element, Fill, Length, Padding, Subscription, Task};
|
||||
use ym_api::Error;
|
||||
use ym_api::auth::{Auth, Credentials, DeviceCode, Poll};
|
||||
|
||||
use crate::ui::icons::{Icon, icon};
|
||||
use crate::ui::theme::{self, Tokens, radius, size};
|
||||
use crate::ui::{line, para};
|
||||
use crate::widgets::sidebar;
|
||||
use crate::i18n::{tr, trf};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Msg {
|
||||
GetCode,
|
||||
CodeReady(Result<DeviceCode, Error>),
|
||||
Tick(Instant),
|
||||
Polled(Result<Poll, Error>),
|
||||
CopyCode,
|
||||
OpenPage,
|
||||
ToggleToken,
|
||||
TokenChanged(String),
|
||||
UseToken,
|
||||
Cancel,
|
||||
}
|
||||
|
||||
enum Stage {
|
||||
Idle,
|
||||
Requesting,
|
||||
Waiting(Box<Waiting>),
|
||||
}
|
||||
|
||||
struct Waiting {
|
||||
code: DeviceCode,
|
||||
qr: Option<qr_code::Data>,
|
||||
started: Instant,
|
||||
now: Instant,
|
||||
next_poll: Instant,
|
||||
polling: bool,
|
||||
copied_at: Option<Instant>,
|
||||
}
|
||||
|
||||
impl Waiting {
|
||||
fn remaining(&self) -> Duration {
|
||||
self.code.expires_in.saturating_sub(self.now.duration_since(self.started))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SignIn {
|
||||
stage: Stage,
|
||||
error: Option<String>,
|
||||
token_open: bool,
|
||||
token: String,
|
||||
}
|
||||
|
||||
impl Default for SignIn {
|
||||
fn default() -> Self {
|
||||
Self { stage: Stage::Idle, error: None, token_open: false, token: String::new() }
|
||||
}
|
||||
}
|
||||
|
||||
/// What the app should do after a sign-in message.
|
||||
pub enum Outcome {
|
||||
Continue(Task<Msg>),
|
||||
/// Credentials from Yandex (or pasted); the app saves them and connects.
|
||||
Granted(Credentials),
|
||||
}
|
||||
|
||||
impl SignIn {
|
||||
/// Shown after a pasted token turned out to be invalid.
|
||||
pub fn rejected_token() -> Self {
|
||||
Self {
|
||||
error: Some(tr("Yandex didn't accept that token. Check it and paste it again.").into()),
|
||||
token_open: true,
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Shown when connecting with fresh credentials failed.
|
||||
pub fn with_error(error: &Error) -> Self {
|
||||
Self { error: Some(describe(error).into()), ..Self::default() }
|
||||
}
|
||||
|
||||
pub fn update(&mut self, msg: Msg) -> Outcome {
|
||||
match msg {
|
||||
Msg::GetCode => {
|
||||
self.error = None;
|
||||
self.stage = Stage::Requesting;
|
||||
return Outcome::Continue(Task::future(async {
|
||||
match Auth::new() {
|
||||
Ok(auth) => auth.request_code().await,
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}).map(Msg::CodeReady));
|
||||
}
|
||||
Msg::CodeReady(Ok(code)) => {
|
||||
let now = Instant::now();
|
||||
let qr = qr_code::Data::new(code.verification_url.as_bytes()).ok();
|
||||
self.stage = Stage::Waiting(Box::new(Waiting {
|
||||
next_poll: now + code.interval,
|
||||
code,
|
||||
qr,
|
||||
started: now,
|
||||
now,
|
||||
polling: false,
|
||||
copied_at: None,
|
||||
}));
|
||||
}
|
||||
Msg::CodeReady(Err(e)) => self.fail(&e),
|
||||
Msg::Tick(now) => {
|
||||
let Stage::Waiting(w) = &mut self.stage else {
|
||||
return Outcome::Continue(Task::none());
|
||||
};
|
||||
w.now = now;
|
||||
if w.remaining().is_zero() {
|
||||
self.fail(&Error::CodeExpired);
|
||||
} else if !w.polling && now >= w.next_poll {
|
||||
w.polling = true;
|
||||
let code = w.code.clone();
|
||||
return Outcome::Continue(
|
||||
Task::future(async move {
|
||||
match Auth::new() {
|
||||
Ok(auth) => auth.poll(&code).await,
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
})
|
||||
.map(Msg::Polled),
|
||||
);
|
||||
}
|
||||
}
|
||||
Msg::Polled(result) => {
|
||||
let Stage::Waiting(w) = &mut self.stage else {
|
||||
return Outcome::Continue(Task::none());
|
||||
};
|
||||
w.polling = false;
|
||||
match result {
|
||||
Ok(Poll::Pending) => w.next_poll = Instant::now() + w.code.interval,
|
||||
// A dropped poll isn't fatal: try again next interval.
|
||||
Err(e) if e.is_retryable() => w.next_poll = Instant::now() + w.code.interval,
|
||||
Ok(Poll::Granted(credentials)) => {
|
||||
self.stage = Stage::Idle;
|
||||
return Outcome::Granted(credentials);
|
||||
}
|
||||
Err(e) => self.fail(&e),
|
||||
}
|
||||
}
|
||||
Msg::CopyCode => {
|
||||
if let Stage::Waiting(w) = &mut self.stage {
|
||||
w.copied_at = Some(w.now);
|
||||
return Outcome::Continue(iced::clipboard::write(w.code.user_code.clone()));
|
||||
}
|
||||
}
|
||||
Msg::OpenPage => {
|
||||
if let Stage::Waiting(w) = &self.stage
|
||||
&& open::that_detached(&w.code.verification_url).is_err()
|
||||
{
|
||||
self.error = Some(trf("Couldn't open your browser. Go to {} yourself.", &[&w.code.verification_url]));
|
||||
}
|
||||
}
|
||||
Msg::ToggleToken => self.token_open = !self.token_open,
|
||||
Msg::TokenChanged(token) => self.token = token,
|
||||
Msg::UseToken => {
|
||||
let credentials = Credentials::from_token(&self.token);
|
||||
if !credentials.access_token.is_empty() {
|
||||
self.token.clear();
|
||||
self.stage = Stage::Idle;
|
||||
return Outcome::Granted(credentials);
|
||||
}
|
||||
}
|
||||
Msg::Cancel => {
|
||||
self.stage = Stage::Idle;
|
||||
self.error = None;
|
||||
}
|
||||
}
|
||||
Outcome::Continue(Task::none())
|
||||
}
|
||||
|
||||
fn fail(&mut self, error: &Error) {
|
||||
self.stage = Stage::Idle;
|
||||
self.error = Some(describe(error).into());
|
||||
}
|
||||
|
||||
/// Ticks once a second while a code is on screen: drives the countdown and polling.
|
||||
pub fn subscription(&self) -> Subscription<Msg> {
|
||||
match self.stage {
|
||||
Stage::Waiting(_) => iced::time::every(Duration::from_secs(1)).map(Msg::Tick),
|
||||
_ => Subscription::none(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn view<'a>(&'a self, t: &'static Tokens) -> Element<'a, Msg> {
|
||||
let left = column![
|
||||
sidebar::wordmark(t),
|
||||
container(
|
||||
iced::widget::text(tr("Sign in with your Yandex account"))
|
||||
.font(theme::DISPLAY)
|
||||
.size(size::DISPLAY_M)
|
||||
.line_height(1.12)
|
||||
.color(t.fg),
|
||||
)
|
||||
.max_width(520),
|
||||
container(para(
|
||||
tr("Musyx plays your Yandex Music library, My Wave and playlists. You confirm sign-in on Yandex's own page, so your password never passes through this app."),
|
||||
15.0,
|
||||
t.muted,
|
||||
))
|
||||
.max_width(500),
|
||||
self.body(t),
|
||||
self.token_fallback(t),
|
||||
space().height(Fill),
|
||||
container(para(
|
||||
tr("Musyx is an unofficial client and isn't affiliated with Yandex. Your sign-in token is kept in the system keychain."),
|
||||
size::SMALL,
|
||||
t.muted,
|
||||
))
|
||||
.max_width(520),
|
||||
]
|
||||
.spacing(26)
|
||||
.padding(Padding::from([44, 56]))
|
||||
.width(Length::FillPortion(21))
|
||||
.clip(true)
|
||||
.height(Fill);
|
||||
|
||||
let right = container(self.qr_card(t))
|
||||
.center(Fill)
|
||||
.width(Length::FillPortion(20))
|
||||
.style(move |th| {
|
||||
let mut s = theme::panel(th);
|
||||
s.background = Some(iced::Background::Gradient(
|
||||
iced::gradient::Linear::new(0.4)
|
||||
.add_stop(0.0, t.panel)
|
||||
.add_stop(1.0, theme::mix(t.panel, t.accent, 0.14))
|
||||
.into(),
|
||||
));
|
||||
s
|
||||
});
|
||||
|
||||
row![left, container(space()).width(1).height(Fill).style(theme::divider), right]
|
||||
.height(Fill)
|
||||
.into()
|
||||
}
|
||||
|
||||
fn body<'a>(&'a self, t: &'static Tokens) -> Element<'a, Msg> {
|
||||
let error = self.error.as_deref().map(|e| {
|
||||
container(para(e, size::BODY, t.like)).max_width(500)
|
||||
});
|
||||
|
||||
let content: Element<'a, Msg> = match &self.stage {
|
||||
Stage::Idle => column![
|
||||
primary(t, tr("Get sign-in code"), Some(Msg::GetCode)),
|
||||
]
|
||||
.into(),
|
||||
Stage::Requesting => column![primary(t, tr("Getting a code…"), None)].into(),
|
||||
Stage::Waiting(w) => self.steps(t, w),
|
||||
};
|
||||
|
||||
column![content].push(error).spacing(16).into()
|
||||
}
|
||||
|
||||
fn steps<'a>(&'a self, t: &'static Tokens, w: &'a Waiting) -> Element<'a, Msg> {
|
||||
let host = w
|
||||
.code
|
||||
.verification_url
|
||||
.trim_start_matches("https://")
|
||||
.trim_start_matches("http://")
|
||||
.trim_end_matches('/')
|
||||
.to_owned();
|
||||
|
||||
let copied = w.copied_at.is_some_and(|at| w.now.duration_since(at) < Duration::from_secs(2));
|
||||
let code_box = row![
|
||||
container(line(spaced(&w.code.user_code), theme::DISPLAY, 30.0, t.fg))
|
||||
.padding([14, 18])
|
||||
.style(theme::card),
|
||||
ghost(t, Icon::Copy, if copied { tr("Copied") } else { tr("Copy code") }, Msg::CopyCode),
|
||||
]
|
||||
.spacing(14)
|
||||
.align_y(Alignment::Center);
|
||||
|
||||
let remaining = w.remaining().as_secs();
|
||||
let status = row![
|
||||
container(space()).width(9).height(9).style(theme::accent_dot),
|
||||
line(
|
||||
trf("Waiting for confirmation · code expires in {}", &[&format!("{}:{:02}", remaining / 60, remaining % 60)]),
|
||||
theme::BODY,
|
||||
13.5,
|
||||
t.muted,
|
||||
),
|
||||
space().width(12),
|
||||
button(line(tr("Cancel"), theme::MEDIUM, 13.5, t.muted))
|
||||
.padding(0)
|
||||
.style(theme::tab(false))
|
||||
.on_press(Msg::Cancel),
|
||||
]
|
||||
.spacing(10)
|
||||
.align_y(Alignment::Center);
|
||||
|
||||
column![
|
||||
step(t, 1, column![
|
||||
line(trf("Open {}", &[&host]), theme::MEDIUM, size::BODY, t.fg),
|
||||
para(tr("On this computer or your phone. You can also scan the QR code."), 13.5, t.muted),
|
||||
ghost(t, Icon::Globe, tr("Open in browser"), Msg::OpenPage),
|
||||
].spacing(6)),
|
||||
step(t, 2, column![
|
||||
line(tr("Enter this code"), theme::MEDIUM, size::BODY, t.fg),
|
||||
code_box,
|
||||
].spacing(10)),
|
||||
step(t, 3, column![
|
||||
line(tr("Come back here"), theme::MEDIUM, size::BODY, t.fg),
|
||||
para(tr("Musyx signs you in as soon as you allow access."), 13.5, t.muted),
|
||||
].spacing(4)),
|
||||
status,
|
||||
]
|
||||
.spacing(20)
|
||||
.into()
|
||||
}
|
||||
|
||||
fn token_fallback<'a>(&'a self, t: &'static Tokens) -> Element<'a, Msg> {
|
||||
let toggle = button(line(
|
||||
if self.token_open { tr("Hide token sign-in") } else { tr("Sign in with an existing token instead") },
|
||||
theme::BODY,
|
||||
13.5,
|
||||
t.muted,
|
||||
))
|
||||
.padding(0)
|
||||
.style(theme::tab(false))
|
||||
.on_press(Msg::ToggleToken);
|
||||
|
||||
if !self.token_open {
|
||||
return toggle.into();
|
||||
}
|
||||
|
||||
let can_submit = !self.token.trim().is_empty();
|
||||
column![
|
||||
toggle,
|
||||
row![
|
||||
text_input(tr("Paste OAuth token"), &self.token)
|
||||
.id("token")
|
||||
.secure(true)
|
||||
.on_input(Msg::TokenChanged)
|
||||
.on_submit_maybe(can_submit.then_some(Msg::UseToken))
|
||||
.padding([10, 14])
|
||||
.width(320)
|
||||
.style(theme::search_field),
|
||||
button(line(tr("Sign in"), theme::MEDIUM, size::BODY, t.fg))
|
||||
.padding([10, 18])
|
||||
.style(theme::ghost)
|
||||
.on_press_maybe(can_submit.then_some(Msg::UseToken)),
|
||||
]
|
||||
.spacing(8)
|
||||
.align_y(Alignment::Center),
|
||||
]
|
||||
.spacing(10)
|
||||
.into()
|
||||
}
|
||||
|
||||
fn qr_card<'a>(&'a self, t: &'static Tokens) -> Element<'a, Msg> {
|
||||
let qr = match &self.stage {
|
||||
Stage::Waiting(w) => w.qr.as_ref(),
|
||||
_ => None,
|
||||
};
|
||||
let (code, caption): (Element<'a, Msg>, &str) = match qr {
|
||||
Some(data) => (
|
||||
qr_code(data)
|
||||
.total_size(200)
|
||||
.style(|_| qr_code::Style {
|
||||
cell: iced::Color::from_rgb8(0x1C, 0x1A, 0x22),
|
||||
background: iced::Color::WHITE,
|
||||
})
|
||||
.into(),
|
||||
tr("Scan to open the sign-in page"),
|
||||
),
|
||||
None => (
|
||||
container(icon(Icon::Lock, iced::Color::from_rgb8(0x68, 0x61, 0x78)))
|
||||
.center(200)
|
||||
.into(),
|
||||
tr("A QR code appears with your sign-in code"),
|
||||
),
|
||||
};
|
||||
container(
|
||||
column![
|
||||
code,
|
||||
line(caption, theme::BODY, size::SMALL, iced::Color::from_rgb8(0x4A, 0x44, 0x58)),
|
||||
]
|
||||
.spacing(10)
|
||||
.align_x(Alignment::Center),
|
||||
)
|
||||
.padding(18)
|
||||
.style(move |_| iced::widget::container::Style {
|
||||
background: Some(iced::Color::WHITE.into()),
|
||||
border: iced::Border { radius: radius::HERO.into(), ..Default::default() },
|
||||
shadow: iced::Shadow {
|
||||
color: iced::Color::BLACK.scale_alpha(if t == &theme::DARK { 0.45 } else { 0.14 }),
|
||||
offset: iced::Vector::new(0.0, 18.0),
|
||||
blur_radius: 50.0,
|
||||
},
|
||||
..Default::default()
|
||||
})
|
||||
.into()
|
||||
}
|
||||
}
|
||||
|
||||
/// The user's next step for each failure. Never shows the raw error.
|
||||
fn describe(error: &Error) -> &'static str {
|
||||
match error {
|
||||
Error::CodeExpired => tr("The code expired before it was confirmed. Get a new code to try again."),
|
||||
Error::Denied => tr("Access was declined on Yandex's page. Get a new code if that was a mistake."),
|
||||
Error::Network(_) => tr("Can't reach Yandex. Check your connection and try again."),
|
||||
Error::Unauthorized(_) => tr("Yandex didn't accept the sign-in. Get a new code to try again."),
|
||||
Error::Api(_) => tr("Yandex sent an unexpected answer. Try again in a moment."),
|
||||
}
|
||||
}
|
||||
|
||||
/// `ABCD1234` → `ABCD 1234` for easier reading; codes that already have separators stay as they are.
|
||||
fn spaced(code: &str) -> String {
|
||||
if code.len() == 8 && code.chars().all(|c| c.is_ascii_alphanumeric()) {
|
||||
format!("{} {}", &code[..4], &code[4..])
|
||||
} else {
|
||||
code.to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
fn step<'a>(t: &'static Tokens, n: u8, content: impl Into<Element<'a, Msg>>) -> Element<'a, Msg> {
|
||||
let badge = container(line(n.to_string(), theme::SEMIBOLD, size::BODY, t.muted))
|
||||
.center(30)
|
||||
.style(move |_| iced::widget::container::Style {
|
||||
border: iced::Border { color: t.line, width: 1.0, radius: radius::PILL.into() },
|
||||
..Default::default()
|
||||
});
|
||||
row![badge, container(content).padding(Padding::default().top(4))]
|
||||
.spacing(14)
|
||||
.into()
|
||||
}
|
||||
|
||||
fn primary<'a>(t: &'static Tokens, label: &'a str, msg: Option<Msg>) -> Element<'a, Msg> {
|
||||
let ink = if msg.is_some() { t.accent_ink } else { t.muted };
|
||||
button(line(label, theme::SEMIBOLD, size::BODY, ink))
|
||||
.padding([11, 18])
|
||||
.style(theme::primary)
|
||||
.on_press_maybe(msg)
|
||||
.into()
|
||||
}
|
||||
|
||||
fn ghost<'a>(t: &'static Tokens, glyph: Icon, label: &'a str, msg: Msg) -> Element<'a, Msg> {
|
||||
button(
|
||||
row![icon(glyph, t.fg), line(label, theme::MEDIUM, size::BODY, t.fg)]
|
||||
.spacing(8)
|
||||
.align_y(Alignment::Center),
|
||||
)
|
||||
.padding([9, 16])
|
||||
.style(theme::ghost)
|
||||
.on_press(msg)
|
||||
.into()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn codes_are_split_for_reading() {
|
||||
assert_eq!(spaced("QX7K29PM"), "QX7K 29PM");
|
||||
assert_eq!(spaced("QX7-K29"), "QX7-K29");
|
||||
assert_eq!(spaced("1234567"), "1234567");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pasted_token_is_trimmed_and_granted() {
|
||||
let mut s = SignIn::default();
|
||||
let _ = s.update(Msg::TokenChanged(" y0_token \n".into()));
|
||||
match s.update(Msg::UseToken) {
|
||||
Outcome::Granted(c) => assert_eq!(c.access_token, "y0_token"),
|
||||
Outcome::Continue(_) => panic!("expected credentials"),
|
||||
}
|
||||
assert!(s.token.is_empty(), "token must not linger in UI state");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blank_token_is_ignored() {
|
||||
let mut s = SignIn::default();
|
||||
let _ = s.update(Msg::TokenChanged(" ".into()));
|
||||
assert!(matches!(s.update(Msg::UseToken), Outcome::Continue(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failures_leave_an_actionable_message() {
|
||||
let mut s = SignIn::default();
|
||||
let _ = s.update(Msg::CodeReady(Err(Error::Network("dns".into()))));
|
||||
assert!(matches!(s.stage, Stage::Idle));
|
||||
assert!(s.error.as_deref().unwrap().contains("connection"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
//! My Wave: the animated hero, station settings and other stations.
|
||||
|
||||
use iced::widget::canvas::{self, Frame, Geometry, Path, Stroke};
|
||||
use iced::widget::{Row, button, canvas as canvas_widget, column, container, row, stack};
|
||||
use iced::{Alignment, Color, Element, Fill, Length, Padding, Point, Rectangle, Renderer, Theme, mouse};
|
||||
use ym_api::{Character, Language, MY_WAVE, Mood, Station, WaveSettings};
|
||||
|
||||
use super::Loadable;
|
||||
use super::collection::{LoadState, status};
|
||||
use crate::app::Message;
|
||||
use crate::covers::{self, Covers};
|
||||
use crate::player::{self, Player, Status};
|
||||
use crate::ui::icons::{Icon, icon};
|
||||
use crate::ui::theme::{self, Tokens, radius, size};
|
||||
use crate::ui::{line, para};
|
||||
use crate::widgets::card;
|
||||
use crate::i18n::{tr, trf};
|
||||
|
||||
/// Everything the My Wave screen shows.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct WaveScreen {
|
||||
pub settings: Loadable<WaveSettings>,
|
||||
pub stations: Loadable<Vec<Station>>,
|
||||
/// Settings picked but not yet confirmed by Yandex.
|
||||
pub saving: Option<WaveSettings>,
|
||||
}
|
||||
|
||||
impl WaveScreen {
|
||||
/// The settings to show: the pending choice while saving.
|
||||
pub fn shown(&self) -> Option<WaveSettings> {
|
||||
self.saving.or_else(|| self.settings.get().copied())
|
||||
}
|
||||
}
|
||||
|
||||
/// Lines drifting across the hero. Moves only while a station plays.
|
||||
struct WaveArt {
|
||||
phase: f32,
|
||||
energy: f32,
|
||||
color: Color,
|
||||
}
|
||||
|
||||
impl canvas::Program<Message> for WaveArt {
|
||||
type State = ();
|
||||
|
||||
fn draw(&self, _: &(), renderer: &Renderer, _: &Theme, bounds: Rectangle, _: mouse::Cursor) -> Vec<Geometry> {
|
||||
let mut frame = Frame::new(renderer, bounds.size());
|
||||
let (w, h) = (bounds.width, bounds.height);
|
||||
const LINES: usize = 14;
|
||||
for k in 0..LINES {
|
||||
let kf = k as f32;
|
||||
let base = h * (0.22 + kf * 0.028);
|
||||
let amp = h * (0.05 + kf * 0.006) * self.energy;
|
||||
let freq = 1.6 + kf * 0.09;
|
||||
let ph = self.phase * (0.35 + kf * 0.02) + kf * 0.5;
|
||||
let path = Path::new(|b| {
|
||||
let steps = (w / 6.0).ceil() as usize;
|
||||
for i in 0..=steps {
|
||||
let x = i as f32 * 6.0;
|
||||
let u = x / w;
|
||||
let y = base
|
||||
+ (u * std::f32::consts::PI * freq + ph).sin() * amp
|
||||
+ (u * std::f32::consts::PI * 4.2 - ph * 0.7).sin() * amp * 0.35;
|
||||
if i == 0 { b.move_to(Point::new(x, y)) } else { b.line_to(Point::new(x, y)) }
|
||||
}
|
||||
});
|
||||
let alpha = 0.08 + (kf / LINES as f32) * 0.55;
|
||||
frame.stroke(&path, Stroke::default().with_color(self.color.scale_alpha(alpha)).with_width(1.0 + kf * 0.08));
|
||||
}
|
||||
vec![frame.into_geometry()]
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether My Wave itself is what's playing.
|
||||
fn my_wave_state(p: &Player) -> Option<Status> {
|
||||
(p.wave_station() == Some(MY_WAVE)).then(|| p.status())
|
||||
}
|
||||
|
||||
/// The My Wave hero, on Home (`big = false`) and the My Wave screen.
|
||||
pub fn hero<'a>(
|
||||
t: &'static Tokens,
|
||||
player: &Player,
|
||||
phase: f32,
|
||||
settings: Option<WaveSettings>,
|
||||
big: bool,
|
||||
) -> Element<'a, Message> {
|
||||
let state = my_wave_state(player);
|
||||
let playing = state == Some(Status::Playing);
|
||||
let art = canvas_widget(WaveArt { phase, energy: if playing { 1.0 } else { 0.45 }, color: t.accent })
|
||||
.width(Fill)
|
||||
.height(Fill);
|
||||
|
||||
let blurb = match settings {
|
||||
Some(s) if s != WaveSettings::default() => trf(
|
||||
"Tuned to: {} mood, {} tracks, {} language.",
|
||||
&[
|
||||
&tr(s.mood.label()).to_lowercase(),
|
||||
&tr(s.character.label()).to_lowercase(),
|
||||
&tr(s.language.label()).to_lowercase(),
|
||||
],
|
||||
),
|
||||
_ => tr("An endless stream picked from what you play, like and skip.").to_owned(),
|
||||
};
|
||||
|
||||
let (label, glyph, msg) = match state {
|
||||
Some(Status::Playing | Status::Loading) => (tr("Pause"), Icon::Pause, Message::Player(player::Msg::Toggle)),
|
||||
Some(_) => (tr("Resume"), Icon::Play, Message::Player(player::Msg::Toggle)),
|
||||
None => (tr("Play My Wave"), Icon::Play, Message::PlayWave(MY_WAVE.to_owned())),
|
||||
};
|
||||
|
||||
let content = row![
|
||||
column![
|
||||
line(tr("My Wave"), theme::DISPLAY, if big { size::DISPLAY_XL } else { size::DISPLAY_M }, t.fg),
|
||||
container(para(blurb, size::BODY, t.muted)).max_width(420),
|
||||
]
|
||||
.spacing(6)
|
||||
.width(Fill),
|
||||
button(row![icon(glyph, t.accent_ink), line(label, theme::SEMIBOLD, size::BODY, t.accent_ink)].spacing(8).align_y(Alignment::Center))
|
||||
.padding([11, 18])
|
||||
.style(theme::primary)
|
||||
.on_press(msg),
|
||||
]
|
||||
.spacing(28)
|
||||
.align_y(Alignment::End);
|
||||
|
||||
let height = if big { 340.0 } else { 260.0 };
|
||||
container(stack![
|
||||
art,
|
||||
container(content).padding(Padding::from([26, 28])).height(Fill).align_y(iced::alignment::Vertical::Bottom),
|
||||
])
|
||||
.height(height)
|
||||
.width(Fill)
|
||||
.clip(true)
|
||||
.style(move |th| {
|
||||
let mut s = theme::card(th);
|
||||
s.border.radius = radius::HERO.into();
|
||||
s.background = Some(iced::Background::Gradient(
|
||||
iced::gradient::Linear::new(0.0)
|
||||
.add_stop(0.0, t.panel)
|
||||
.add_stop(1.0, theme::mix(t.panel, t.accent, 0.10))
|
||||
.into(),
|
||||
));
|
||||
s
|
||||
})
|
||||
.into()
|
||||
}
|
||||
|
||||
pub fn view<'a>(
|
||||
t: &'static Tokens,
|
||||
covers: &Covers,
|
||||
screen: &'a WaveScreen,
|
||||
hero: Element<'a, Message>,
|
||||
) -> Element<'a, Message> {
|
||||
let settings: Element<'a, Message> = match (&screen.settings, screen.shown()) {
|
||||
(_, Some(s)) => {
|
||||
let saving = screen.saving.is_some();
|
||||
row![
|
||||
setting(t, tr("Mood"), Mood::ALL.map(|m| (tr(m.label()), m == s.mood, WaveSettings { mood: m, ..s })), saving),
|
||||
setting(t, tr("Character"), Character::ALL.map(|c| (tr(c.label()), c == s.character, WaveSettings { character: c, ..s })), saving),
|
||||
setting(t, tr("Language"), Language::ALL.map(|l| (tr(l.label()), l == s.language, WaveSettings { language: l, ..s })), saving),
|
||||
]
|
||||
.spacing(28)
|
||||
.wrap()
|
||||
.vertical_spacing(18)
|
||||
.into()
|
||||
}
|
||||
(Loadable::Failed(e), None) => status(t, LoadState::Failed(e), tr("your station settings"), Message::LoadWave),
|
||||
_ => para(tr("Loading your settings…"), size::BODY, t.muted).into(),
|
||||
};
|
||||
|
||||
let stations: Element<'a, Message> = match &screen.stations {
|
||||
Loadable::Loaded(list) => {
|
||||
let others: Vec<&Station> = list.iter().filter(|s| s.id != MY_WAVE).collect();
|
||||
if others.is_empty() {
|
||||
para(tr("No other stations suggested right now."), size::BODY, t.muted).into()
|
||||
} else {
|
||||
Row::with_children(others.into_iter().map(|s| station_tile(t, covers, s)))
|
||||
.spacing(12)
|
||||
.wrap()
|
||||
.vertical_spacing(14)
|
||||
.into()
|
||||
}
|
||||
}
|
||||
Loadable::Failed(e) => status(t, LoadState::Failed(e), tr("stations"), Message::LoadWave),
|
||||
_ => para(tr("Loading stations…"), size::BODY, t.muted).into(),
|
||||
};
|
||||
|
||||
column![
|
||||
hero,
|
||||
settings,
|
||||
column![line(tr("Stations"), theme::SEMIBOLD, size::SECTION, t.fg), stations].spacing(14),
|
||||
]
|
||||
.spacing(34)
|
||||
.into()
|
||||
}
|
||||
|
||||
fn setting<'a, const N: usize>(
|
||||
t: &'static Tokens,
|
||||
title: &'a str,
|
||||
options: [(&'static str, bool, WaveSettings); N],
|
||||
saving: bool,
|
||||
) -> Element<'a, Message> {
|
||||
let chips = options.map(|(label, on, next)| {
|
||||
button(line(label, theme::MEDIUM, 13.5, if on { t.accent_ink } else { t.fg }))
|
||||
.padding([7, 13])
|
||||
.style(theme::chip(on))
|
||||
.on_press_maybe((!on && !saving).then_some(Message::SetWaveSettings(next)))
|
||||
.into()
|
||||
});
|
||||
column![line(title, theme::MEDIUM, size::BODY, t.muted), Row::with_children(chips).spacing(6)]
|
||||
.spacing(10)
|
||||
.into()
|
||||
}
|
||||
|
||||
fn station_tile<'a>(t: &'static Tokens, covers: &Covers, s: &Station) -> Element<'a, Message> {
|
||||
let tint = s.color.as_deref().and_then(super::browse::parse_hex).unwrap_or(t.raised);
|
||||
let art = container(covers::view(covers, s.icon_url(200), (0.0, 0.0), 96.0, 0.0))
|
||||
.center(card::WIDTH)
|
||||
.style(move |_| container::Style {
|
||||
background: Some(tint.into()),
|
||||
border: iced::Border { radius: radius::COVER.into(), ..Default::default() },
|
||||
..Default::default()
|
||||
});
|
||||
button(column![art, line(s.name.clone(), theme::MEDIUM, size::BODY, t.fg)].spacing(9).width(Length::Fixed(card::WIDTH)))
|
||||
.padding(6)
|
||||
.style(theme::nav_item(false))
|
||||
.on_press(Message::PlayWave(s.id.clone()))
|
||||
.into()
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
//! Keeping the user signed in: credentials live in the system keychain, and
|
||||
//! startup turns them back into a connected client.
|
||||
|
||||
use std::time::SystemTime;
|
||||
|
||||
use ym_api::auth::{Auth, Credentials};
|
||||
use ym_api::{Account, Error, YmClient};
|
||||
|
||||
const SERVICE: &str = "musyx";
|
||||
const ACCOUNT: &str = "yandex-music";
|
||||
|
||||
/// What startup found.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Restored {
|
||||
SignedIn(YmClient, Account),
|
||||
/// Nothing stored, or the stored token was rejected (and has been removed).
|
||||
SignedOut,
|
||||
/// Credentials are stored but Yandex couldn't be reached; they're kept for a retry.
|
||||
Unreachable,
|
||||
}
|
||||
|
||||
/// Keychain access is blocking (and may show a system prompt), so it runs off the UI thread.
|
||||
async fn blocking<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> T {
|
||||
tokio::task::spawn_blocking(f).await.expect("keychain task panicked")
|
||||
}
|
||||
|
||||
fn entry() -> Result<keyring::Entry, String> {
|
||||
keyring::Entry::new(SERVICE, ACCOUNT).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub async fn load() -> Result<Option<Credentials>, String> {
|
||||
blocking(|| {
|
||||
let raw = match entry()?.get_password() {
|
||||
Ok(raw) => raw,
|
||||
Err(keyring::Error::NoEntry) => return Ok(None),
|
||||
Err(e) => return Err(e.to_string()),
|
||||
};
|
||||
// An unreadable entry is treated as absent; the next sign-in overwrites it.
|
||||
Ok(serde_json::from_str(&raw).ok())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn save(credentials: Credentials) -> Result<(), String> {
|
||||
blocking(move || {
|
||||
let json = serde_json::to_string(&credentials).map_err(|e| e.to_string())?;
|
||||
entry()?.set_password(&json).map_err(|e| e.to_string())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn clear() -> Result<(), String> {
|
||||
blocking(|| match entry()?.delete_credential() {
|
||||
Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
|
||||
Err(e) => Err(e.to_string()),
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Load stored credentials, refresh them if they're close to expiring, connect.
|
||||
pub async fn restore() -> Restored {
|
||||
let credentials = match load().await {
|
||||
Ok(Some(c)) => c,
|
||||
Ok(None) => return Restored::SignedOut,
|
||||
Err(e) => {
|
||||
eprintln!("keychain: {e}");
|
||||
return Restored::SignedOut;
|
||||
}
|
||||
};
|
||||
|
||||
let credentials = if credentials.needs_refresh(SystemTime::now()) {
|
||||
match refresh(&credentials).await {
|
||||
Some(fresh) => fresh,
|
||||
None => credentials,
|
||||
}
|
||||
} else {
|
||||
credentials
|
||||
};
|
||||
|
||||
let language = crate::i18n::lang().content();
|
||||
match YmClient::connect(&credentials, language).await {
|
||||
Ok((client, account)) => Restored::SignedIn(client, account),
|
||||
Err(Error::Unauthorized(_)) => match refresh(&credentials).await {
|
||||
Some(fresh) => match YmClient::connect(&fresh, language).await {
|
||||
Ok((client, account)) => Restored::SignedIn(client, account),
|
||||
Err(e) => forget(e).await,
|
||||
},
|
||||
None => forget(Error::Unauthorized("refresh failed".into())).await,
|
||||
},
|
||||
Err(e) if e.is_retryable() => Restored::Unreachable,
|
||||
Err(e) => forget(e).await,
|
||||
}
|
||||
}
|
||||
|
||||
/// Refresh and persist; `None` when there is nothing to refresh with or Yandex said no.
|
||||
async fn refresh(credentials: &Credentials) -> Option<Credentials> {
|
||||
credentials.refresh_token.as_ref()?;
|
||||
let fresh = Auth::new().ok()?.refresh(credentials).await.ok()?;
|
||||
if let Err(e) = save(fresh.clone()).await {
|
||||
eprintln!("keychain: {e}");
|
||||
}
|
||||
Some(fresh)
|
||||
}
|
||||
|
||||
async fn forget(reason: Error) -> Restored {
|
||||
eprintln!("stored sign-in rejected: {reason}");
|
||||
if let Err(e) = clear().await {
|
||||
eprintln!("keychain: {e}");
|
||||
}
|
||||
Restored::SignedOut
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
//! Headless-ish visual check: render one screen, save it as a PNG, quit.
|
||||
//!
|
||||
//! ```sh
|
||||
//! MUSYX_SNAPSHOT=home.png MUSYX_SNAPSHOT_ROUTE=wave MUSYX_SNAPSHOT_DRAWER=queue \
|
||||
//! MUSYX_SNAPSHOT_THEME=light MUSYX_SNAPSHOT_LANG=ru cargo run -p musyx --features snapshot
|
||||
//! ```
|
||||
//! iced's own `window::screenshot` is used, so it needs no screen-recording permission.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
use iced::Task;
|
||||
use iced::theme::Mode;
|
||||
use iced::window;
|
||||
|
||||
use ym_api::{Account, YmClient};
|
||||
|
||||
use crate::app::Session;
|
||||
use crate::i18n::Lang;
|
||||
use crate::route::Route;
|
||||
use crate::widgets::drawer::Panel;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Config {
|
||||
pub out: PathBuf,
|
||||
/// `MUSYX_SNAPSHOT_ROUTE=signin` shows the sign-in page instead of a signed-in shell.
|
||||
pub signed_out: bool,
|
||||
pub route: Option<Route>,
|
||||
pub drawer: Option<Panel>,
|
||||
pub mode: Option<Mode>,
|
||||
/// `MUSYX_SNAPSHOT_LIVE=1`: sign in with the stored account instead of sample data.
|
||||
pub live: bool,
|
||||
/// `MUSYX_SNAPSHOT_LANG=ru` or `en` overrides the language setting.
|
||||
pub lang: Option<Lang>,
|
||||
/// `MUSYX_SNAPSHOT_DELAY` in ms before capturing (default 1500; live runs need longer).
|
||||
pub delay: Duration,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn from_env() -> Option<Self> {
|
||||
let out = PathBuf::from(std::env::var_os("MUSYX_SNAPSHOT")?);
|
||||
let var = |k: &str| std::env::var(k).ok().map(|v| v.to_ascii_lowercase());
|
||||
let signed_out = var("MUSYX_SNAPSHOT_ROUTE").as_deref() == Some("signin");
|
||||
let route = var("MUSYX_SNAPSHOT_ROUTE").and_then(|r| {
|
||||
Some(match r.as_str() {
|
||||
"home" => Route::Home,
|
||||
"wave" => Route::Wave,
|
||||
"search" => Route::Search,
|
||||
"collection" => Route::Collection,
|
||||
"podcasts" => Route::Podcasts,
|
||||
"settings" => Route::Settings,
|
||||
"album" => Route::Album(1),
|
||||
"chart" => Route::Chart,
|
||||
// `artist:41075`, for live runs.
|
||||
other => Route::Artist(other.strip_prefix("artist:")?.parse().ok()?),
|
||||
})
|
||||
});
|
||||
let drawer = var("MUSYX_SNAPSHOT_DRAWER").and_then(|d| match d.as_str() {
|
||||
"queue" => Some(Panel::Queue),
|
||||
"lyrics" => Some(Panel::Lyrics),
|
||||
_ => None,
|
||||
});
|
||||
let mode = var("MUSYX_SNAPSHOT_THEME").and_then(|m| match m.as_str() {
|
||||
"light" => Some(Mode::Light),
|
||||
"dark" => Some(Mode::Dark),
|
||||
_ => None,
|
||||
});
|
||||
let lang = var("MUSYX_SNAPSHOT_LANG").map(|l| Lang::from_tag(&l));
|
||||
let live = var("MUSYX_SNAPSHOT_LIVE").is_some_and(|v| v == "1");
|
||||
let delay = var("MUSYX_SNAPSHOT_DELAY")
|
||||
.and_then(|d| d.parse().ok())
|
||||
.map_or(Duration::from_millis(if live { 8000 } else { 1500 }), Duration::from_millis);
|
||||
Some(Self { out, signed_out, route, drawer, mode, lang, live, delay })
|
||||
}
|
||||
|
||||
/// A made-up account so the shell renders without a network or keychain.
|
||||
pub fn session(&self) -> Session {
|
||||
if self.signed_out {
|
||||
return Session::SignedOut(Box::default());
|
||||
}
|
||||
Session::SignedIn {
|
||||
client: YmClient::unauthenticated().expect("client"),
|
||||
account: Account {
|
||||
uid: 1,
|
||||
login: "sample.listener".into(),
|
||||
name: "Sample Listener".into(),
|
||||
has_plus: true,
|
||||
subscription_end: Some("2027-01-05T00:00:00+03:00".into()),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Sample liked tracks so the Collection list has rows.
|
||||
pub fn sample_liked(&self) -> Vec<ym_api::Track> {
|
||||
[
|
||||
("1", "Звезда по имени Солнце", "Кино", 7, "Звезда по имени Солнце", 225),
|
||||
("2", "Хочешь?", "Земфира", 3, "Прости меня моя любовь", 225),
|
||||
("3", "Выхода нет", "Сплин", 25, "Гранатовый альбом", 230),
|
||||
("4", "Полковнику никто не пишет", "Би-2", 280, "Би-2", 285),
|
||||
("5", "Владивосток 2000", "Мумий Тролль", 185, "Морская", 165),
|
||||
("6", "Город золотой", "Аквариум", 48, "Десять стрел", 205),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(id, title, artist, album, album_title, secs)| {
|
||||
ym_api::Track::from_json(&format!(
|
||||
r#"{{"id":"{id}","title":"{title}","durationMs":{ms},"artists":[{{"name":"{artist}"}}],
|
||||
"albums":[{{"id":{album},"title":"{album_title}"}}]}}"#,
|
||||
ms = secs * 1000
|
||||
))
|
||||
.expect("sample track")
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A sample album page for `MUSYX_SNAPSHOT_ROUTE=album`.
|
||||
pub fn sample_album(&self) -> crate::screens::detail::Page {
|
||||
let tracks: Vec<String> = [
|
||||
("Группа крови", 286), ("Закрой за мной дверь, я ухожу", 256), ("Война", 274),
|
||||
("Попробуй спеть вместе со мной", 283), ("Звезда по имени Солнце", 225), ("Спокойная ночь", 366),
|
||||
]
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, (title, secs))| {
|
||||
format!(r#"{{"id":{},"title":"{title}","durationMs":{},"artists":[{{"id":1,"name":"Кино"}}]}}"#, i + 1, secs * 1000)
|
||||
})
|
||||
.collect();
|
||||
let json = format!(
|
||||
r#"{{"id":1,"title":"Группа крови","year":1988,"artists":[{{"id":1,"name":"Кино"}}],
|
||||
"labels":["Мелодия"],"volumes":[[{}]]}}"#,
|
||||
tracks.join(",")
|
||||
);
|
||||
let mut info = ym_api::AlbumPage::from_json(&json).expect("sample album");
|
||||
let tracks = std::mem::take(&mut info.tracks).into();
|
||||
crate::screens::detail::Page::Album { info, tracks }
|
||||
}
|
||||
|
||||
/// Waits for fonts and the first frames, captures the window, writes the PNG, exits.
|
||||
pub fn capture<M: Send + 'static>(self) -> Task<M> {
|
||||
Task::future(tokio::time::sleep(self.delay))
|
||||
.then(|()| window::latest())
|
||||
.then(|id| match id {
|
||||
Some(id) => window::screenshot(id),
|
||||
None => Task::none(),
|
||||
})
|
||||
.then(move |shot| {
|
||||
if let Err(e) = write_png(&self.out, &shot) {
|
||||
eprintln!("snapshot: {e}");
|
||||
} else {
|
||||
eprintln!("snapshot: wrote {}", self.out.display());
|
||||
}
|
||||
iced::exit()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn write_png(path: &std::path::Path, shot: &window::Screenshot) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let file = std::io::BufWriter::new(std::fs::File::create(path)?);
|
||||
let mut encoder = png::Encoder::new(file, shot.size.width, shot.size.height);
|
||||
encoder.set_color(png::ColorType::Rgba);
|
||||
encoder.set_depth(png::BitDepth::Eight);
|
||||
encoder.write_header()?.write_image_data(&shot.rgba)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
//! Preferences kept between launches, as JSON in the platform config folder
|
||||
//! (`~/Library/Application Support/Musyx/settings.json` on macOS).
|
||||
|
||||
use crate::i18n::{Lang, tr};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Streaming quality, as a cap on the bitrate Musyx asks for.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum Quality {
|
||||
/// FLAC where Yandex grants it, else the best lossy file it allows.
|
||||
Lossless,
|
||||
/// The best MP3 Yandex offers.
|
||||
#[default]
|
||||
Best,
|
||||
/// Up to 192 kbps.
|
||||
Balanced,
|
||||
/// Up to 128 kbps, for slow or metered connections.
|
||||
DataSaver,
|
||||
}
|
||||
|
||||
impl Quality {
|
||||
pub const ALL: [Quality; 4] = [Quality::Lossless, Quality::Best, Quality::Balanced, Quality::DataSaver];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Quality::Lossless => tr("Lossless"),
|
||||
Quality::Best => tr("Best"),
|
||||
Quality::Balanced => tr("Balanced"),
|
||||
Quality::DataSaver => tr("Data saver"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn detail(self) -> &'static str {
|
||||
match self {
|
||||
Quality::Lossless => {
|
||||
tr("FLAC when Yandex offers it for your subscription and region, otherwise the best it allows. About 3–5 times the data of MP3, and tracks take longer to start.")
|
||||
}
|
||||
Quality::Best => tr("Highest MP3 bitrate Yandex offers, up to 320 kbps."),
|
||||
Quality::Balanced => tr("Up to 192 kbps. About 40% less data."),
|
||||
Quality::DataSaver => tr("Up to 128 kbps, for slow or metered connections."),
|
||||
}
|
||||
}
|
||||
|
||||
/// The bitrate cap passed to the API; `None` means no cap.
|
||||
pub fn max_kbps(self) -> Option<u32> {
|
||||
match self {
|
||||
Quality::Lossless | Quality::Best => None,
|
||||
Quality::Balanced => Some(192),
|
||||
Quality::DataSaver => Some(128),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum Appearance {
|
||||
/// Follow the system's light or dark setting.
|
||||
#[default]
|
||||
System,
|
||||
Light,
|
||||
Dark,
|
||||
}
|
||||
|
||||
impl Appearance {
|
||||
pub const ALL: [Appearance; 3] = [Appearance::System, Appearance::Light, Appearance::Dark];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Appearance::System => tr("Match system"),
|
||||
Appearance::Light => tr("Light"),
|
||||
Appearance::Dark => tr("Dark"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The interface language.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum Locale {
|
||||
/// The system's first preferred language, when Musyx has it; else English.
|
||||
#[default]
|
||||
System,
|
||||
English,
|
||||
Russian,
|
||||
}
|
||||
|
||||
impl Locale {
|
||||
pub const ALL: [Locale; 3] = [Locale::System, Locale::English, Locale::Russian];
|
||||
|
||||
/// Language names stay in their own language so they can be found in either.
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Locale::System => tr("Match system"),
|
||||
Locale::English => "English",
|
||||
Locale::Russian => "Русский",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn resolve(self) -> Lang {
|
||||
match self {
|
||||
Locale::System => Lang::system(),
|
||||
Locale::English => Lang::En,
|
||||
Locale::Russian => Lang::Ru,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Settings {
|
||||
pub quality: Quality,
|
||||
pub appearance: Appearance,
|
||||
pub language: Locale,
|
||||
pub volume: f32,
|
||||
}
|
||||
|
||||
impl Default for Settings {
|
||||
fn default() -> Self {
|
||||
Self { quality: Quality::Best, appearance: Appearance::System, language: Locale::System, volume: 0.7 }
|
||||
}
|
||||
}
|
||||
|
||||
fn path() -> Option<PathBuf> {
|
||||
directories::ProjectDirs::from("", "", "Musyx").map(|d| d.config_dir().join("settings.json"))
|
||||
}
|
||||
|
||||
/// Saved settings, or defaults when there are none or the file is unreadable.
|
||||
/// Read once at startup, on the main thread; the file is tiny.
|
||||
pub fn load() -> Settings {
|
||||
path()
|
||||
.and_then(|p| std::fs::read_to_string(p).ok())
|
||||
.and_then(|s| serde_json::from_str(&s).ok())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Writes atomically (temp file, then rename) so a crash can't leave half a file.
|
||||
pub async fn save(settings: Settings) -> Result<(), String> {
|
||||
let path = path().ok_or("no config folder on this system")?;
|
||||
let json = serde_json::to_vec_pretty(&settings).map_err(|e| e.to_string())?;
|
||||
if let Some(dir) = path.parent() {
|
||||
tokio::fs::create_dir_all(dir).await.map_err(|e| e.to_string())?;
|
||||
}
|
||||
let tmp = path.with_extension("json.tmp");
|
||||
tokio::fs::write(&tmp, json).await.map_err(|e| e.to_string())?;
|
||||
tokio::fs::rename(&tmp, &path).await.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn settings_round_trip_and_tolerate_missing_fields() {
|
||||
let s = Settings { quality: Quality::DataSaver, appearance: Appearance::Dark, language: Locale::Russian, volume: 0.25 };
|
||||
let json = serde_json::to_string(&s).unwrap();
|
||||
assert!(json.contains("\"data-saver\""), "{json}");
|
||||
assert_eq!(serde_json::to_string(&Quality::Lossless).unwrap(), "\"lossless\"");
|
||||
assert_eq!(serde_json::from_str::<Settings>(&json).unwrap(), s);
|
||||
let partial: Settings = serde_json::from_str(r#"{"appearance":"light"}"#).unwrap();
|
||||
assert_eq!(partial, Settings { appearance: Appearance::Light, ..Settings::default() });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quality_caps() {
|
||||
assert_eq!(Quality::Best.max_kbps(), None);
|
||||
assert_eq!(Quality::Balanced.max_kbps(), Some(192));
|
||||
assert_eq!(Quality::DataSaver.max_kbps(), Some(128));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
//! Bundled Lucide 0.460 icons (ISC, see `assets/icons/LICENSE.txt`).
|
||||
//!
|
||||
//! The SVGs stroke with `currentColor`; iced ignores that, so every icon is tinted
|
||||
//! through `svg::Style::color` instead — pass the colour the surrounding text uses.
|
||||
|
||||
// Bundled ahead of the screens that use them.
|
||||
#![allow(dead_code)]
|
||||
|
||||
use iced::widget::{Svg, svg};
|
||||
use iced::{Color, Length, Theme};
|
||||
|
||||
use super::theme::shell;
|
||||
|
||||
macro_rules! icons {
|
||||
($($variant:ident => $file:literal),+ $(,)?) => {
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum Icon { $($variant),+ }
|
||||
|
||||
impl Icon {
|
||||
pub const ALL: &[Icon] = &[$(Icon::$variant),+];
|
||||
|
||||
fn bytes(self) -> &'static [u8] {
|
||||
match self {
|
||||
$(Icon::$variant => include_bytes!(concat!("../../assets/icons/", $file, ".svg"))),+
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
icons! {
|
||||
Home => "house",
|
||||
Wave => "audio-lines",
|
||||
Search => "search",
|
||||
Library => "library",
|
||||
Podcast => "podcast",
|
||||
Plus => "plus",
|
||||
LogOut => "log-out",
|
||||
Back => "chevron-left",
|
||||
Forward => "chevron-right",
|
||||
Chart => "trending-up",
|
||||
Play => "play-fill",
|
||||
Pause => "pause-fill",
|
||||
Previous => "skip-back",
|
||||
Next => "skip-forward",
|
||||
Shuffle => "shuffle",
|
||||
Repeat => "repeat",
|
||||
RepeatOne => "repeat-1",
|
||||
Heart => "heart",
|
||||
HeartFilled => "heart-fill",
|
||||
Dislike => "ban",
|
||||
Lyrics => "mic-vocal",
|
||||
Queue => "list-music",
|
||||
Volume => "volume-2",
|
||||
Muted => "volume-x",
|
||||
More => "ellipsis",
|
||||
Disc => "disc-3",
|
||||
Lock => "lock",
|
||||
Globe => "globe",
|
||||
Pencil => "pencil",
|
||||
Trash => "trash-2",
|
||||
Grip => "grip-vertical",
|
||||
Close => "x",
|
||||
Copy => "copy",
|
||||
Clock => "clock-3",
|
||||
Tune => "sliders-horizontal",
|
||||
Settings => "settings",
|
||||
}
|
||||
|
||||
impl Icon {
|
||||
pub fn handle(self) -> svg::Handle {
|
||||
svg::Handle::from_memory(self.bytes())
|
||||
}
|
||||
}
|
||||
|
||||
/// An icon at the standard 18px size, tinted `color`.
|
||||
pub fn icon<'a>(icon: Icon, color: Color) -> Svg<'a, Theme> {
|
||||
sized(icon, shell::ICON, color)
|
||||
}
|
||||
|
||||
pub fn sized<'a>(icon: Icon, size: f32, color: Color) -> Svg<'a, Theme> {
|
||||
svg(icon.handle())
|
||||
.width(Length::Fixed(size))
|
||||
.height(Length::Fixed(size))
|
||||
.style(move |_, _| svg::Style { color: Some(color) })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_icon_is_an_svg() {
|
||||
for icon in Icon::ALL {
|
||||
let text = std::str::from_utf8(icon.bytes()).expect("utf-8");
|
||||
assert!(text.contains("<svg"), "{icon:?} is not an SVG");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
pub mod icons;
|
||||
pub mod theme;
|
||||
|
||||
use iced::widget::{Text, text};
|
||||
use iced::widget::text::Wrapping;
|
||||
use iced::{Color, Font};
|
||||
|
||||
use crate::i18n::{self, Lang, trf};
|
||||
|
||||
/// Single-line text in the given face; long values are clipped by their container.
|
||||
pub fn line<'a>(content: impl text::IntoFragment<'a>, font: Font, size: f32, color: Color) -> Text<'a> {
|
||||
text(content).font(font).size(size).color(color).wrapping(Wrapping::None)
|
||||
}
|
||||
|
||||
/// Running text that wraps.
|
||||
pub fn para<'a>(content: impl text::IntoFragment<'a>, size: f32, color: Color) -> Text<'a> {
|
||||
text(content).font(theme::BODY).size(size).color(color).line_height(1.45)
|
||||
}
|
||||
|
||||
/// "47 min" or "1 h 12 min".
|
||||
pub fn duration_words(d: std::time::Duration) -> String {
|
||||
let mins = d.as_secs() / 60;
|
||||
if mins >= 60 {
|
||||
trf("{} h {} min", &[&(mins / 60), &(mins % 60)])
|
||||
} else {
|
||||
trf("{} min", &[&mins])
|
||||
}
|
||||
}
|
||||
|
||||
/// "1 track", "12 tracks".
|
||||
pub fn tracks_word(n: usize) -> String {
|
||||
i18n::count(n as u64, ["track", "tracks"], ["трек", "трека", "треков"])
|
||||
}
|
||||
|
||||
/// "4.1M", "830K", "912"; in Russian "4,1 млн", "830 тыс.", "912".
|
||||
pub fn compact(n: i64) -> String {
|
||||
let (value, en, ru) = match n {
|
||||
n if n >= 1_000_000 => (format!("{:.1}", n as f64 / 1e6), "M", " млн"),
|
||||
n if n >= 10_000 => ((n / 1000).to_string(), "K", " тыс."),
|
||||
n if n >= 1_000 => (format!("{:.1}", n as f64 / 1e3), "K", " тыс."),
|
||||
n => return n.to_string(),
|
||||
};
|
||||
let value = value.trim_end_matches(".0");
|
||||
match i18n::lang() {
|
||||
Lang::En => format!("{value}{en}"),
|
||||
Lang::Ru => format!("{}{ru}", value.replace('.', ",")),
|
||||
}
|
||||
}
|
||||
|
||||
/// A compact count and its noun: "4.1M listeners", "830 тыс. слушателей", "3 лайка".
|
||||
pub fn counted(n: i64, en: [&str; 2], ru: [&str; 3]) -> String {
|
||||
// An abbreviated number ("4,1 млн") reads as many.
|
||||
let form = if n >= 1_000 { 5 } else { n.max(0) as u64 };
|
||||
format!("{} {}", compact(n), i18n::plural(form, en, ru))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::time::Duration;
|
||||
|
||||
#[test]
|
||||
fn words() {
|
||||
assert_eq!(duration_words(Duration::from_secs(47 * 60 + 5)), "47 min");
|
||||
assert_eq!(duration_words(Duration::from_secs(72 * 60)), "1 h 12 min");
|
||||
assert_eq!(tracks_word(1), "1 track");
|
||||
assert_eq!(tracks_word(12), "12 tracks");
|
||||
assert_eq!(compact(4_100_000), "4.1M");
|
||||
assert_eq!(compact(2_000_000), "2M");
|
||||
assert_eq!(compact(830_412), "830K");
|
||||
assert_eq!(compact(1_250), "1.2K");
|
||||
assert_eq!(compact(912), "912");
|
||||
assert_eq!(counted(1, ["like", "likes"], ["лайк", "лайка", "лайков"]), "1 like");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn russian_words() {
|
||||
i18n::set(Lang::Ru);
|
||||
assert_eq!(duration_words(Duration::from_secs(72 * 60)), "1 ч 12 мин");
|
||||
assert_eq!(tracks_word(3), "3 трека");
|
||||
assert_eq!(compact(4_100_000), "4,1 млн");
|
||||
assert_eq!(compact(830_412), "830 тыс.");
|
||||
assert_eq!(compact(1_250), "1,2 тыс.");
|
||||
let listeners = ["listener", "listeners"];
|
||||
let ru = ["слушатель", "слушателя", "слушателей"];
|
||||
assert_eq!(counted(4_100_000, listeners, ru), "4,1 млн слушателей");
|
||||
assert_eq!(counted(21, listeners, ru), "21 слушатель");
|
||||
i18n::set(Lang::En);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,468 @@
|
||||
//! Design tokens and widget styles. Mirrors `DESIGN.md`; change both together.
|
||||
|
||||
// The token set is the whole design system; screens adopt pieces milestone by milestone.
|
||||
#![allow(dead_code)]
|
||||
|
||||
use iced::border::Radius;
|
||||
use iced::font::{Family, Weight};
|
||||
use iced::theme::{Mode, Palette};
|
||||
use iced::widget::{button, container, scrollable, slider, text_input};
|
||||
use iced::{Background, Border, Color, Font, Shadow, Theme, Vector};
|
||||
|
||||
/// Colour tokens for one theme mode.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Tokens {
|
||||
pub bg: Color,
|
||||
pub panel: Color,
|
||||
pub raised: Color,
|
||||
pub line: Color,
|
||||
pub fg: Color,
|
||||
pub muted: Color,
|
||||
pub accent: Color,
|
||||
pub accent_ink: Color,
|
||||
pub like: Color,
|
||||
pub ok: Color,
|
||||
}
|
||||
|
||||
const fn hex(h: u32) -> Color {
|
||||
Color::from_rgb8((h >> 16) as u8, (h >> 8) as u8, h as u8)
|
||||
}
|
||||
|
||||
pub const DARK: Tokens = Tokens {
|
||||
bg: hex(0x1C1A22),
|
||||
panel: hex(0x23202B),
|
||||
raised: hex(0x2D2937),
|
||||
line: hex(0x3A3546),
|
||||
fg: hex(0xEEEAF3),
|
||||
muted: hex(0xA39CB0),
|
||||
accent: hex(0xF0B23E),
|
||||
accent_ink: hex(0x2A1D04),
|
||||
like: hex(0xF27286),
|
||||
ok: hex(0x7FCB9B),
|
||||
};
|
||||
|
||||
pub const LIGHT: Tokens = Tokens {
|
||||
bg: hex(0xF3F1F6),
|
||||
panel: hex(0xFFFFFF),
|
||||
raised: hex(0xEAE6F0),
|
||||
line: hex(0xDCD6E4),
|
||||
fg: hex(0x1F1B27),
|
||||
muted: hex(0x686178),
|
||||
accent: hex(0xA86C05),
|
||||
accent_ink: hex(0xFFF7E6),
|
||||
like: hex(0xD2405A),
|
||||
ok: hex(0x2E8A55),
|
||||
};
|
||||
|
||||
/// Tokens for whichever theme is active. Style closures only receive `&Theme`,
|
||||
/// so the tokens are recovered from the palette's darkness.
|
||||
pub fn tokens(theme: &Theme) -> &'static Tokens {
|
||||
if theme.extended_palette().is_dark { &DARK } else { &LIGHT }
|
||||
}
|
||||
|
||||
/// The iced theme for a system appearance. Musyx is dark-first, so "no preference" is dark.
|
||||
pub fn for_mode(mode: Mode) -> Theme {
|
||||
let (name, t) = match mode {
|
||||
Mode::Light => ("Musyx Light", &LIGHT),
|
||||
Mode::Dark | Mode::None => ("Musyx Dark", &DARK),
|
||||
};
|
||||
Theme::custom(
|
||||
name,
|
||||
Palette {
|
||||
background: t.bg,
|
||||
text: t.fg,
|
||||
primary: t.accent,
|
||||
success: t.ok,
|
||||
warning: t.accent,
|
||||
danger: t.like,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// ---- Type ----
|
||||
|
||||
pub const BODY: Font = Font::with_name("Onest");
|
||||
pub const MEDIUM: Font = Font { weight: Weight::Medium, ..BODY };
|
||||
pub const SEMIBOLD: Font = Font { weight: Weight::Semibold, ..BODY };
|
||||
pub const DISPLAY: Font = Font {
|
||||
family: Family::Name("Unbounded"),
|
||||
weight: Weight::Semibold,
|
||||
..Font::DEFAULT
|
||||
};
|
||||
|
||||
pub const FONTS: [&[u8]; 4] = [
|
||||
include_bytes!("../../assets/fonts/Onest-Regular.ttf"),
|
||||
include_bytes!("../../assets/fonts/Onest-Medium.ttf"),
|
||||
include_bytes!("../../assets/fonts/Onest-SemiBold.ttf"),
|
||||
include_bytes!("../../assets/fonts/Unbounded-SemiBold.ttf"),
|
||||
];
|
||||
|
||||
pub mod size {
|
||||
pub const DISPLAY_XL: f32 = 46.0;
|
||||
pub const DISPLAY_L: f32 = 40.0;
|
||||
pub const DISPLAY_M: f32 = 34.0;
|
||||
pub const DISPLAY_S: f32 = 30.0;
|
||||
pub const WORDMARK: f32 = 20.0;
|
||||
pub const SECTION: f32 = 19.0;
|
||||
pub const BODY: f32 = 14.0;
|
||||
pub const META: f32 = 13.0;
|
||||
pub const SMALL: f32 = 12.5;
|
||||
}
|
||||
|
||||
// ---- Space and shape ----
|
||||
|
||||
pub mod space {
|
||||
pub const XS: f32 = 4.0;
|
||||
pub const S: f32 = 8.0;
|
||||
pub const M: f32 = 12.0;
|
||||
pub const L: f32 = 18.0;
|
||||
pub const XL: f32 = 22.0;
|
||||
pub const GUTTER: f32 = 28.0;
|
||||
pub const SECTION: f32 = 34.0;
|
||||
}
|
||||
|
||||
pub mod radius {
|
||||
pub const COVER: f32 = 10.0;
|
||||
pub const CONTROL: f32 = 8.0;
|
||||
pub const SMALL_COVER: f32 = 6.0;
|
||||
pub const PILL: f32 = 999.0;
|
||||
pub const HERO: f32 = 16.0;
|
||||
pub const CARD: f32 = 14.0;
|
||||
}
|
||||
|
||||
pub mod shell {
|
||||
pub const SIDEBAR: f32 = 232.0;
|
||||
pub const PLAYER: f32 = 80.0;
|
||||
pub const DRAWER: f32 = 320.0;
|
||||
pub const ICON: f32 = 18.0;
|
||||
}
|
||||
|
||||
// ---- Containers ----
|
||||
|
||||
fn hairline(color: Color) -> Border {
|
||||
Border { color, width: 1.0, radius: Radius::from(0.0) }
|
||||
}
|
||||
|
||||
pub fn app(theme: &Theme) -> container::Style {
|
||||
let t = tokens(theme);
|
||||
container::Style {
|
||||
background: Some(t.bg.into()),
|
||||
text_color: Some(t.fg),
|
||||
..container::Style::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Sidebar, player bar and drawer share the panel fill; the divider is drawn separately.
|
||||
pub fn panel(theme: &Theme) -> container::Style {
|
||||
let t = tokens(theme);
|
||||
container::Style {
|
||||
background: Some(t.panel.into()),
|
||||
text_color: Some(t.fg),
|
||||
..container::Style::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn divider(theme: &Theme) -> container::Style {
|
||||
container::Style {
|
||||
background: Some(tokens(theme).line.into()),
|
||||
..container::Style::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A bordered surface such as the empty-state card or the device-code box.
|
||||
pub fn card(theme: &Theme) -> container::Style {
|
||||
let t = tokens(theme);
|
||||
container::Style {
|
||||
background: Some(t.panel.into()),
|
||||
border: Border { radius: radius::CARD.into(), ..hairline(t.line) },
|
||||
..container::Style::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn badge(theme: &Theme) -> container::Style {
|
||||
let t = tokens(theme);
|
||||
container::Style {
|
||||
text_color: Some(t.muted),
|
||||
border: Border { radius: 5.0.into(), ..hairline(t.line) },
|
||||
..container::Style::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn accent_dot(theme: &Theme) -> container::Style {
|
||||
container::Style {
|
||||
background: Some(tokens(theme).accent.into()),
|
||||
border: Border { radius: radius::PILL.into(), ..Border::default() },
|
||||
..container::Style::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn avatar(theme: &Theme) -> container::Style {
|
||||
let t = tokens(theme);
|
||||
container::Style {
|
||||
background: Some(Background::Gradient(
|
||||
iced::gradient::Linear::new(std::f32::consts::FRAC_PI_4 * 3.0)
|
||||
.add_stop(0.0, hex(0x8E7AB5))
|
||||
.add_stop(1.0, hex(0xE0A84B))
|
||||
.into(),
|
||||
)),
|
||||
text_color: Some(hex(0x1C1A22)),
|
||||
border: Border { radius: radius::PILL.into(), ..hairline(t.line) },
|
||||
..container::Style::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Placeholder art for an item without a cover yet: two hues on a diagonal.
|
||||
pub fn cover(h1: f32, h2: f32, corner: f32) -> impl Fn(&Theme) -> container::Style {
|
||||
move |_| container::Style {
|
||||
background: Some(Background::Gradient(
|
||||
iced::gradient::Linear::new(std::f32::consts::FRAC_PI_4 * 3.0)
|
||||
.add_stop(0.0, hsl(h1, 0.70, 0.60))
|
||||
.add_stop(0.55, hsl((h1 + h2) / 2.0, 0.45, 0.30))
|
||||
.add_stop(1.0, hsl(h2, 0.40, 0.16))
|
||||
.into(),
|
||||
)),
|
||||
border: Border { radius: corner.into(), ..Border::default() },
|
||||
..container::Style::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn hsl(h: f32, s: f32, l: f32) -> Color {
|
||||
let c = (1.0 - (2.0 * l - 1.0).abs()) * s;
|
||||
let hp = (h.rem_euclid(360.0)) / 60.0;
|
||||
let x = c * (1.0 - (hp % 2.0 - 1.0).abs());
|
||||
let (r, g, b) = match hp as u32 {
|
||||
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 = l - c / 2.0;
|
||||
Color::from_rgb(r + m, g + m, b + m)
|
||||
}
|
||||
|
||||
// ---- Buttons ----
|
||||
|
||||
/// Sidebar navigation item; `active` is the current page.
|
||||
pub fn nav_item(active: bool) -> impl Fn(&Theme, button::Status) -> button::Style {
|
||||
move |theme, status| {
|
||||
let t = tokens(theme);
|
||||
let lit = active || matches!(status, button::Status::Hovered | button::Status::Pressed);
|
||||
button::Style {
|
||||
background: lit.then(|| t.raised.into()),
|
||||
text_color: if lit { t.fg } else { t.muted },
|
||||
border: Border { radius: radius::CONTROL.into(), ..Border::default() },
|
||||
shadow: Shadow::default(),
|
||||
snap: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Square icon button. `on` tints it (accent for toggles, `like` for hearts).
|
||||
pub fn icon_button(on: Option<Color>) -> impl Fn(&Theme, button::Status) -> button::Style {
|
||||
move |theme, status| {
|
||||
let t = tokens(theme);
|
||||
let hovered = matches!(status, button::Status::Hovered | button::Status::Pressed);
|
||||
let disabled = matches!(status, button::Status::Disabled);
|
||||
button::Style {
|
||||
background: (hovered && !disabled).then(|| t.raised.into()),
|
||||
text_color: match (on, disabled, hovered) {
|
||||
(_, true, _) => t.muted.scale_alpha(0.45),
|
||||
(Some(c), _, _) => c,
|
||||
(None, _, true) => t.fg,
|
||||
(None, _, false) => t.muted,
|
||||
},
|
||||
border: Border { radius: radius::CONTROL.into(), ..Border::default() },
|
||||
shadow: Shadow::default(),
|
||||
snap: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The round play/pause disc in the player bar.
|
||||
pub fn play_disc(theme: &Theme, status: button::Status) -> button::Style {
|
||||
let t = tokens(theme);
|
||||
let disabled = matches!(status, button::Status::Disabled);
|
||||
button::Style {
|
||||
background: Some(if disabled { t.raised } else { t.fg }.into()),
|
||||
text_color: if disabled { t.muted } else { t.bg },
|
||||
border: Border { radius: radius::PILL.into(), ..Border::default() },
|
||||
shadow: Shadow::default(),
|
||||
snap: true,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn primary(theme: &Theme, status: button::Status) -> button::Style {
|
||||
let t = tokens(theme);
|
||||
let bg = match status {
|
||||
button::Status::Hovered => mix(t.accent, t.fg, 0.12),
|
||||
button::Status::Pressed => mix(t.accent, t.bg, 0.12),
|
||||
button::Status::Disabled => t.raised,
|
||||
button::Status::Active => t.accent,
|
||||
};
|
||||
button::Style {
|
||||
background: Some(bg.into()),
|
||||
text_color: if matches!(status, button::Status::Disabled) { t.muted } else { t.accent_ink },
|
||||
border: Border { radius: radius::PILL.into(), ..Border::default() },
|
||||
shadow: Shadow {
|
||||
color: Color::BLACK.scale_alpha(0.18),
|
||||
offset: Vector::new(0.0, 4.0),
|
||||
blur_radius: 12.0,
|
||||
},
|
||||
snap: true,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ghost(theme: &Theme, status: button::Status) -> button::Style {
|
||||
let t = tokens(theme);
|
||||
button::Style {
|
||||
background: matches!(status, button::Status::Hovered | button::Status::Pressed)
|
||||
.then(|| t.raised.into()),
|
||||
text_color: t.fg,
|
||||
border: Border { radius: radius::PILL.into(), ..hairline(t.line) },
|
||||
shadow: Shadow::default(),
|
||||
snap: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// A pill in a segmented choice (My Wave settings). The selected one is filled.
|
||||
pub fn chip(selected: bool) -> impl Fn(&Theme, button::Status) -> button::Style {
|
||||
move |theme, status| {
|
||||
let t = tokens(theme);
|
||||
let hovered = matches!(status, button::Status::Hovered | button::Status::Pressed);
|
||||
button::Style {
|
||||
background: if selected {
|
||||
Some(t.accent.into())
|
||||
} else {
|
||||
hovered.then(|| t.raised.into())
|
||||
},
|
||||
text_color: if selected { t.accent_ink } else { t.fg },
|
||||
border: Border {
|
||||
radius: radius::PILL.into(),
|
||||
..hairline(if selected { t.accent } else { t.line })
|
||||
},
|
||||
shadow: Shadow::default(),
|
||||
snap: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Tab in a tab strip (drawer Queue | Lyrics, collection tabs).
|
||||
pub fn tab(selected: bool) -> impl Fn(&Theme, button::Status) -> button::Style {
|
||||
move |theme, status| {
|
||||
let t = tokens(theme);
|
||||
let hovered = matches!(status, button::Status::Hovered);
|
||||
button::Style {
|
||||
background: None,
|
||||
text_color: if selected || hovered { t.fg } else { t.muted },
|
||||
border: Border::default(),
|
||||
shadow: Shadow::default(),
|
||||
snap: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn tab_underline(selected: bool) -> impl Fn(&Theme) -> container::Style {
|
||||
move |theme| container::Style {
|
||||
background: selected.then(|| tokens(theme).accent.into()),
|
||||
..container::Style::default()
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Inputs ----
|
||||
|
||||
pub fn search_field(theme: &Theme, status: text_input::Status) -> text_input::Style {
|
||||
let t = tokens(theme);
|
||||
let focused = matches!(status, text_input::Status::Focused { .. });
|
||||
text_input::Style {
|
||||
background: t.panel.into(),
|
||||
border: Border {
|
||||
color: if focused { t.accent } else { t.line },
|
||||
width: 1.0,
|
||||
radius: radius::PILL.into(),
|
||||
},
|
||||
icon: t.muted,
|
||||
placeholder: t.muted,
|
||||
value: t.fg,
|
||||
selection: t.accent.scale_alpha(0.35),
|
||||
}
|
||||
}
|
||||
|
||||
/// Thin seek bar: amber fill, knob only while hovered or dragged.
|
||||
pub fn seek_bar(theme: &Theme, status: slider::Status) -> slider::Style {
|
||||
thin_slider(theme, status, tokens(theme).accent)
|
||||
}
|
||||
|
||||
pub fn volume_bar(theme: &Theme, status: slider::Status) -> slider::Style {
|
||||
thin_slider(theme, status, tokens(theme).fg)
|
||||
}
|
||||
|
||||
fn thin_slider(theme: &Theme, status: slider::Status, fill: Color) -> slider::Style {
|
||||
let t = tokens(theme);
|
||||
let engaged = matches!(status, slider::Status::Hovered | slider::Status::Dragged);
|
||||
slider::Style {
|
||||
rail: slider::Rail {
|
||||
backgrounds: (fill.into(), t.raised.into()),
|
||||
width: 4.0,
|
||||
border: Border { radius: 2.0.into(), ..Border::default() },
|
||||
},
|
||||
handle: slider::Handle {
|
||||
shape: slider::HandleShape::Circle { radius: if engaged { 6.0 } else { 0.0 } },
|
||||
background: t.fg.into(),
|
||||
border_width: 0.0,
|
||||
border_color: Color::TRANSPARENT,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn scroll(theme: &Theme, status: scrollable::Status) -> scrollable::Style {
|
||||
let t = tokens(theme);
|
||||
let mut style = scrollable::default(theme, status);
|
||||
let rail = scrollable::Rail {
|
||||
background: None,
|
||||
border: Border::default(),
|
||||
scroller: scrollable::Scroller {
|
||||
background: t.line.into(),
|
||||
border: Border { radius: radius::PILL.into(), ..Border::default() },
|
||||
},
|
||||
};
|
||||
style.vertical_rail = rail;
|
||||
style.horizontal_rail = rail;
|
||||
style
|
||||
}
|
||||
|
||||
/// Linear blend of two colours; `amount` is the share of `b`.
|
||||
pub fn mix(a: Color, b: Color, amount: f32) -> Color {
|
||||
Color {
|
||||
r: a.r + (b.r - a.r) * amount,
|
||||
g: a.g + (b.g - a.g) * amount,
|
||||
b: a.b + (b.b - a.b) * amount,
|
||||
a: a.a + (b.a - a.a) * amount,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn tokens_follow_theme_mode() {
|
||||
assert_eq!(tokens(&for_mode(Mode::Dark)), &DARK);
|
||||
assert_eq!(tokens(&for_mode(Mode::None)), &DARK);
|
||||
assert_eq!(tokens(&for_mode(Mode::Light)), &LIGHT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_unpacks_channels() {
|
||||
assert_eq!(hex(0xF0B23E), Color::from_rgb8(0xF0, 0xB2, 0x3E));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hsl_primaries() {
|
||||
let red = hsl(0.0, 1.0, 0.5);
|
||||
assert!((red.r - 1.0).abs() < 1e-5 && red.g.abs() < 1e-5 && red.b.abs() < 1e-5);
|
||||
let blue = hsl(240.0, 1.0, 0.5);
|
||||
assert!((blue.b - 1.0).abs() < 1e-5 && blue.r.abs() < 1e-5);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
//! Cover cards for albums, artists and playlists, laid out in wrapping rows.
|
||||
|
||||
use iced::widget::{Row, button, column, container, row};
|
||||
use iced::{Alignment, Element, Fill, Padding};
|
||||
|
||||
use crate::app::Message;
|
||||
use crate::covers::{self, Covers};
|
||||
use crate::ui::icons::{Icon, icon};
|
||||
use crate::ui::line;
|
||||
use crate::ui::theme::{self, Tokens, radius, size};
|
||||
|
||||
/// Card width; covers are square at this size.
|
||||
pub const WIDTH: f32 = 168.0;
|
||||
|
||||
pub struct Card {
|
||||
pub title: String,
|
||||
pub subtitle: String,
|
||||
pub cover: Option<String>,
|
||||
pub hues: (f32, f32),
|
||||
/// Artists get a round cover.
|
||||
pub round: bool,
|
||||
pub on_press: Message,
|
||||
}
|
||||
|
||||
pub fn view<'a>(t: &'static Tokens, covers: &Covers, card: Card) -> Element<'a, Message> {
|
||||
build(t, covers, card, None)
|
||||
}
|
||||
|
||||
/// A card with a heart beside its title.
|
||||
pub fn with_like<'a>(t: &'static Tokens, covers: &Covers, card: Card, liked: bool, on_like: Message) -> Element<'a, Message> {
|
||||
let heart = button(icon(
|
||||
if liked { Icon::HeartFilled } else { Icon::Heart },
|
||||
if liked { t.like } else { t.muted },
|
||||
))
|
||||
.padding(4)
|
||||
.style(theme::icon_button(None))
|
||||
.on_press(on_like);
|
||||
build(t, covers, card, Some(heart.into()))
|
||||
}
|
||||
|
||||
fn build<'a>(t: &'static Tokens, covers: &Covers, card: Card, action: Option<Element<'a, Message>>) -> Element<'a, Message> {
|
||||
let corner = if card.round { WIDTH / 2.0 } else { radius::COVER };
|
||||
let text = column![
|
||||
line(card.title, theme::MEDIUM, size::BODY, t.fg),
|
||||
line(card.subtitle, theme::BODY, size::META, t.muted),
|
||||
]
|
||||
.spacing(2)
|
||||
.width(Fill)
|
||||
.clip(true);
|
||||
button(
|
||||
column![
|
||||
covers::view(covers, card.cover, card.hues, WIDTH, corner),
|
||||
row![text].push(action).spacing(4).align_y(Alignment::Center).width(WIDTH),
|
||||
]
|
||||
.spacing(9),
|
||||
)
|
||||
.padding(Padding::from(6))
|
||||
.style(theme::nav_item(false))
|
||||
.on_press(card.on_press)
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Cards in rows that wrap to the available width.
|
||||
pub fn grid<'a>(cards: impl IntoIterator<Item = Element<'a, Message>>) -> Element<'a, Message> {
|
||||
container(Row::with_children(cards).spacing(12).wrap().vertical_spacing(14)).into()
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
//! Right-hand panel with the play queue and lyrics.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use iced::widget::{Column, button, column, container, row, scrollable, space};
|
||||
use ym_api::{Lyrics, Track};
|
||||
use iced::{Alignment, Element, Fill, Padding};
|
||||
|
||||
use crate::app::Message;
|
||||
use crate::covers::{self, Covers};
|
||||
use crate::player::{Msg, Player, Queue};
|
||||
use crate::screens::Loadable;
|
||||
use crate::ui::icons::{Icon, icon};
|
||||
use crate::ui::theme::{self, Tokens, radius, shell, size};
|
||||
use crate::widgets::player_bar::clock;
|
||||
use crate::ui::{line, para};
|
||||
use crate::i18n::{tr, trf};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Panel {
|
||||
Queue,
|
||||
Lyrics,
|
||||
}
|
||||
|
||||
impl Panel {
|
||||
fn label(self) -> &'static str {
|
||||
match self {
|
||||
Panel::Queue => tr("Queue"),
|
||||
Panel::Lyrics => tr("Lyrics"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The lyrics scrollable, so playback can keep the current line in view.
|
||||
pub const LYRICS_ID: &str = "lyrics";
|
||||
|
||||
pub fn view<'a>(
|
||||
t: &'static Tokens,
|
||||
panel: Panel,
|
||||
player: &'a Player,
|
||||
covers: &Covers,
|
||||
lyrics: Option<&'a Loadable<Option<Arc<Lyrics>>>>,
|
||||
) -> Element<'a, Message> {
|
||||
let tabs = row![tab(t, Panel::Queue, panel), tab(t, Panel::Lyrics, panel)].spacing(4);
|
||||
|
||||
let head = row![
|
||||
tabs,
|
||||
space().width(Fill),
|
||||
button(icon(Icon::Close, t.muted))
|
||||
.padding(8)
|
||||
.style(theme::icon_button(None))
|
||||
.on_press(Message::CloseDrawer),
|
||||
]
|
||||
.align_y(Alignment::Center)
|
||||
.padding(Padding::default().top(14).bottom(8).left(18).right(14));
|
||||
|
||||
let body: Element<'a, Message> = match (panel, player.queue()) {
|
||||
(Panel::Queue, Some(queue)) => queue_list(t, queue, covers),
|
||||
(Panel::Queue, None) => container(para(
|
||||
tr("Nothing queued yet. Tracks you play, and the ones lined up after them, show up here."),
|
||||
size::META,
|
||||
t.muted,
|
||||
))
|
||||
.padding([4, 20])
|
||||
.into(),
|
||||
(Panel::Lyrics, None) => note(t, tr("Play a track to see its lyrics.")),
|
||||
(Panel::Lyrics, Some(_)) => match lyrics {
|
||||
Some(Loadable::Loaded(Some(l))) => lyrics_view(t, l, player.position()),
|
||||
Some(Loadable::Loaded(None)) => note(t, tr("Yandex Music has no lyrics for this track.")),
|
||||
Some(Loadable::Failed(_)) => column![
|
||||
note(t, tr("Couldn't load the lyrics. Check your connection and try again.")),
|
||||
container(
|
||||
button(line(tr("Try again"), theme::SEMIBOLD, size::BODY, t.accent_ink))
|
||||
.padding([9, 16])
|
||||
.style(theme::primary)
|
||||
.on_press(Message::RetryLyrics),
|
||||
)
|
||||
.padding([0, 20]),
|
||||
]
|
||||
.spacing(12)
|
||||
.into(),
|
||||
_ => note(t, tr("Loading lyrics…")),
|
||||
},
|
||||
};
|
||||
|
||||
container(column![head, body])
|
||||
.width(shell::DRAWER)
|
||||
.height(Fill)
|
||||
.style(theme::panel)
|
||||
.into()
|
||||
}
|
||||
|
||||
fn note<'a>(t: &'static Tokens, text: &'a str) -> Element<'a, Message> {
|
||||
container(para(text, size::META, t.muted)).padding([4, 20]).into()
|
||||
}
|
||||
|
||||
/// Synced lyrics highlight the line being sung and seek on click; plain lyrics just scroll.
|
||||
fn lyrics_view<'a>(t: &'static Tokens, l: &'a Lyrics, position: Duration) -> Element<'a, Message> {
|
||||
let current = l.current(position);
|
||||
let lines = l.lines.iter().enumerate().map(|(i, lyric)| -> Element<'a, Message> {
|
||||
let (colour, font, sz) = match current {
|
||||
Some(c) if c == i => (t.fg, theme::SEMIBOLD, 17.0),
|
||||
Some(c) if i < c => (t.muted.scale_alpha(0.6), theme::MEDIUM, 15.0),
|
||||
_ if l.synced => (t.muted, theme::MEDIUM, 15.0),
|
||||
_ => (t.fg, theme::BODY, 14.0),
|
||||
};
|
||||
let text = iced::widget::text(if lyric.text.is_empty() { "♪".to_owned() } else { lyric.text.clone() })
|
||||
.font(font)
|
||||
.size(sz)
|
||||
.color(colour)
|
||||
.line_height(1.35);
|
||||
match lyric.at {
|
||||
Some(at) => button(text)
|
||||
.width(Fill)
|
||||
.padding([5, 8])
|
||||
.style(theme::nav_item(false))
|
||||
.on_press(Message::Player(Msg::Seek(at)))
|
||||
.into(),
|
||||
None => container(text).padding([2, 8]).into(),
|
||||
}
|
||||
});
|
||||
let mut list = Column::with_children(lines).spacing(2);
|
||||
if !l.writers.is_empty() {
|
||||
list = list.push(
|
||||
container(para(trf("Written by {}", &[&l.writers.join(", ")]), size::SMALL, t.muted))
|
||||
.padding(iced::Padding::default().top(18).left(8).right(8)),
|
||||
);
|
||||
}
|
||||
scrollable(list.padding(Padding::default().left(10).right(10).bottom(18)))
|
||||
.id(LYRICS_ID)
|
||||
.height(Fill)
|
||||
.style(theme::scroll)
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Upcoming items shown at once; a long liked list would otherwise build thousands of rows.
|
||||
const SHOWN: usize = 100;
|
||||
|
||||
fn queue_list<'a>(t: &'static Tokens, queue: &'a Queue<Track>, covers: &Covers) -> Element<'a, Message> {
|
||||
let heading = |s: String| {
|
||||
container(line(s, theme::MEDIUM, size::SMALL, t.muted)).padding(Padding::default().top(14).bottom(8).left(8))
|
||||
};
|
||||
let item = |track: &Track, now: bool, msg: Option<Message>| {
|
||||
button(
|
||||
row![
|
||||
covers::view(covers, track.cover_url(covers::SMALL), track.hues(), 40.0, radius::SMALL_COVER),
|
||||
column![
|
||||
line(track.full_title(), theme::MEDIUM, size::BODY, if now { t.accent } else { t.fg }),
|
||||
line(track.artist_line(), theme::BODY, size::SMALL, t.muted),
|
||||
]
|
||||
.spacing(1)
|
||||
.width(Fill)
|
||||
.clip(true),
|
||||
line(clock(track.duration.as_secs_f32()), theme::BODY, size::SMALL, t.muted),
|
||||
]
|
||||
.spacing(10)
|
||||
.align_y(Alignment::Center),
|
||||
)
|
||||
.width(Fill)
|
||||
.padding([6, 8])
|
||||
.style(theme::nav_item(false))
|
||||
.on_press_maybe(msg)
|
||||
};
|
||||
|
||||
let remaining = queue.upcoming().count();
|
||||
let mut list = column![heading(tr("Now playing").into()), item(queue.current(), true, None)];
|
||||
list = list.push(heading(if remaining == 0 {
|
||||
tr("Nothing after this").into()
|
||||
} else {
|
||||
trf("Next up · {}", &[&remaining])
|
||||
}));
|
||||
for (pos, track) in queue.upcoming().take(SHOWN) {
|
||||
list = list.push(item(track, false, Some(Message::Player(Msg::JumpTo(pos)))));
|
||||
}
|
||||
if remaining > SHOWN {
|
||||
list = list.push(
|
||||
container(line(trf("and {} more", &[&(remaining - SHOWN)]), theme::BODY, size::SMALL, t.muted))
|
||||
.padding([10, 8]),
|
||||
);
|
||||
}
|
||||
|
||||
scrollable(list.padding(Padding::default().left(10).right(10).bottom(18)))
|
||||
.height(Fill)
|
||||
.style(theme::scroll)
|
||||
.into()
|
||||
}
|
||||
|
||||
fn tab<'a>(t: &'static Tokens, panel: Panel, selected: Panel) -> Element<'a, Message> {
|
||||
let on = panel == selected;
|
||||
button(
|
||||
column![
|
||||
line(panel.label(), theme::MEDIUM, size::BODY, if on { t.fg } else { t.muted }),
|
||||
container(space()).width(Fill).height(2).style(theme::tab_underline(on)),
|
||||
]
|
||||
.spacing(7)
|
||||
.width(iced::Shrink),
|
||||
)
|
||||
.padding(Padding::default().left(10).right(10).top(6))
|
||||
.style(theme::tab(on))
|
||||
.on_press(Message::ToggleDrawer(panel))
|
||||
.into()
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
pub mod card;
|
||||
pub mod drawer;
|
||||
pub mod player_bar;
|
||||
pub mod sheet;
|
||||
pub mod sidebar;
|
||||
pub mod topbar;
|
||||
pub mod track_list;
|
||||
pub mod track_row;
|
||||
@@ -0,0 +1,227 @@
|
||||
//! The persistent bar along the bottom: now playing, transport, extras.
|
||||
|
||||
use iced::widget::{button, column, container, row, slider, space};
|
||||
use iced::{Alignment, Element, Fill, Length};
|
||||
|
||||
use crate::app::Message;
|
||||
use crate::covers::{self, Covers};
|
||||
use crate::player::{Msg, Player, Repeat, Status};
|
||||
use crate::ui::icons::{Icon, icon, sized};
|
||||
use crate::ui::line;
|
||||
use crate::ui::theme::{self, Tokens, radius, size};
|
||||
use crate::widgets::drawer::Panel;
|
||||
use crate::i18n::tr;
|
||||
|
||||
fn send(msg: Msg) -> Message {
|
||||
Message::Player(msg)
|
||||
}
|
||||
|
||||
pub fn view<'a>(
|
||||
t: &'static Tokens,
|
||||
p: &'a Player,
|
||||
liked: bool,
|
||||
drawer: Option<Panel>,
|
||||
covers: &Covers,
|
||||
) -> Element<'a, Message> {
|
||||
row![
|
||||
container(now_playing(t, p, liked, covers)).width(Length::FillPortion(2)),
|
||||
container(transport(t, p)).width(Length::FillPortion(3)).center_x(Fill),
|
||||
container(extras(t, p, drawer)).width(Length::FillPortion(2)).align_right(Fill),
|
||||
]
|
||||
.spacing(18)
|
||||
.align_y(Alignment::Center)
|
||||
.padding([0, 18])
|
||||
.height(Fill)
|
||||
.into()
|
||||
}
|
||||
|
||||
fn now_playing<'a>(t: &'static Tokens, p: &'a Player, liked: bool, covers: &Covers) -> Element<'a, Message> {
|
||||
let Some(track) = p.track() else {
|
||||
let blank = container(space()).width(52).height(52).style(move |_| container::Style {
|
||||
background: Some(t.raised.into()),
|
||||
border: iced::Border { radius: radius::CONTROL.into(), ..Default::default() },
|
||||
..Default::default()
|
||||
});
|
||||
let (title, sub) = match &p.notice {
|
||||
Some(notice) => (tr("Can't play"), notice.as_str()),
|
||||
None => (tr("Nothing playing"), tr("Pick a track to start")),
|
||||
};
|
||||
return row![
|
||||
blank,
|
||||
column![
|
||||
line(title, theme::MEDIUM, size::BODY, t.fg),
|
||||
line(sub, theme::BODY, size::META, t.muted),
|
||||
]
|
||||
.spacing(2),
|
||||
]
|
||||
.spacing(12)
|
||||
.align_y(Alignment::Center)
|
||||
.clip(true)
|
||||
.into();
|
||||
};
|
||||
|
||||
let cover = covers::view(covers, track.cover_url(covers::SMALL), track.hues(), 52.0, radius::CONTROL);
|
||||
|
||||
// A problem with the previous track shows in place of the artist line until the next one loads.
|
||||
let (sub, sub_colour) = match (&p.notice, p.status()) {
|
||||
(Some(notice), Status::Loading | Status::Paused) => (notice.clone(), t.like),
|
||||
_ => (track.artist_line(), t.muted),
|
||||
};
|
||||
|
||||
row![
|
||||
cover,
|
||||
column![
|
||||
line(track.full_title(), theme::MEDIUM, size::BODY, t.fg),
|
||||
line(sub, theme::BODY, size::META, sub_colour),
|
||||
]
|
||||
.spacing(2)
|
||||
.width(Length::Shrink),
|
||||
button(icon(
|
||||
if liked { Icon::HeartFilled } else { Icon::Heart },
|
||||
if liked { t.like } else { t.muted },
|
||||
))
|
||||
.padding(8)
|
||||
.style(theme::icon_button(None))
|
||||
.on_press(Message::LikeTrack(track.clone(), !liked)),
|
||||
button(icon(Icon::Dislike, t.muted))
|
||||
.padding(8)
|
||||
.style(theme::icon_button(None))
|
||||
.on_press(Message::DislikeTrack(track.clone(), true)),
|
||||
]
|
||||
.spacing(12)
|
||||
.align_y(Alignment::Center)
|
||||
.clip(true)
|
||||
.into()
|
||||
}
|
||||
|
||||
fn transport<'a>(t: &'static Tokens, p: &'a Player) -> Element<'a, Message> {
|
||||
let has_track = p.track().is_some();
|
||||
|
||||
let toggle = |glyph: Icon, on: bool, msg: Msg| {
|
||||
button(icon(glyph, if on { t.accent } else { t.muted }))
|
||||
.padding(8)
|
||||
.style(theme::icon_button(on.then_some(t.accent)))
|
||||
.on_press(send(msg))
|
||||
};
|
||||
let skip = |glyph: Icon, msg: Msg| {
|
||||
button(icon(glyph, if has_track { t.fg } else { t.muted.scale_alpha(0.45) }))
|
||||
.padding(8)
|
||||
.style(theme::icon_button(None))
|
||||
.on_press_maybe(has_track.then_some(send(msg)))
|
||||
};
|
||||
|
||||
let (glyph, tint) = match p.status() {
|
||||
_ if !has_track => (Icon::Play, t.muted),
|
||||
Status::Playing => (Icon::Pause, t.bg),
|
||||
Status::Loading => (Icon::Pause, t.bg.scale_alpha(0.5)),
|
||||
Status::Paused | Status::Ended => (Icon::Play, t.bg),
|
||||
};
|
||||
let disc = button(container(sized(glyph, 18.0, tint)).center(40))
|
||||
.width(40)
|
||||
.height(40)
|
||||
.padding(0)
|
||||
.style(theme::play_disc)
|
||||
.on_press_maybe(has_track.then_some(send(Msg::Toggle)));
|
||||
|
||||
let ctrls = row![
|
||||
toggle(Icon::Shuffle, p.shuffle(), Msg::ToggleShuffle),
|
||||
skip(Icon::Previous, Msg::Previous),
|
||||
disc,
|
||||
skip(Icon::Next, Msg::Next),
|
||||
toggle(
|
||||
if p.repeat == Repeat::One { Icon::RepeatOne } else { Icon::Repeat },
|
||||
p.repeat != Repeat::Off,
|
||||
Msg::CycleRepeat,
|
||||
),
|
||||
]
|
||||
.spacing(8)
|
||||
.align_y(Alignment::Center);
|
||||
|
||||
let duration = p.duration().as_secs_f32();
|
||||
let position = p.position().as_secs_f32().min(duration);
|
||||
let bar: Element<'a, Message> = if has_track && duration > 0.0 {
|
||||
slider(0.0..=duration, position, |v| send(Msg::SeekPreview(v)))
|
||||
.on_release(send(Msg::SeekCommit))
|
||||
.step(0.5_f32)
|
||||
.width(Fill)
|
||||
.style(theme::seek_bar)
|
||||
.into()
|
||||
} else {
|
||||
container(space())
|
||||
.width(Fill)
|
||||
.height(4)
|
||||
.style(move |_| container::Style {
|
||||
background: Some(t.raised.into()),
|
||||
border: iced::Border { radius: 2.0.into(), ..Default::default() },
|
||||
..Default::default()
|
||||
})
|
||||
.into()
|
||||
};
|
||||
|
||||
let seek = row![
|
||||
container(line(clock(position), theme::BODY, 12.0, t.muted)).width(42).align_right(42),
|
||||
bar,
|
||||
container(line(clock(duration), theme::BODY, 12.0, t.muted)).width(42),
|
||||
]
|
||||
.spacing(10)
|
||||
.align_y(Alignment::Center)
|
||||
.width(Fill);
|
||||
|
||||
column![ctrls, seek].spacing(4).align_x(Alignment::Center).max_width(560).into()
|
||||
}
|
||||
|
||||
fn extras<'a>(t: &'static Tokens, p: &'a Player, drawer: Option<Panel>) -> Element<'a, Message> {
|
||||
let panel_button = |glyph: Icon, panel: Panel| {
|
||||
let on = drawer == Some(panel);
|
||||
button(icon(glyph, if on { t.accent } else { t.muted }))
|
||||
.padding(8)
|
||||
.style(theme::icon_button(on.then_some(t.accent)))
|
||||
.on_press(Message::ToggleDrawer(panel))
|
||||
};
|
||||
|
||||
let mut items = row![].spacing(4).align_y(Alignment::Center);
|
||||
if let Some(stream) = p.stream() {
|
||||
let label = if stream.preview { tr("Preview").to_owned() } else { stream.label() };
|
||||
let ink = if stream.lossless() { t.accent } else { t.muted };
|
||||
items = items.push(container(line(label, theme::MEDIUM, 11.5, ink)).padding([2, 6]).style(theme::badge));
|
||||
}
|
||||
|
||||
let volume = if p.muted { 0.0 } else { p.volume };
|
||||
items
|
||||
.push(panel_button(Icon::Lyrics, Panel::Lyrics))
|
||||
.push(panel_button(Icon::Queue, Panel::Queue))
|
||||
.push(
|
||||
button(icon(if p.muted { Icon::Muted } else { Icon::Volume }, t.muted))
|
||||
.padding(8)
|
||||
.style(theme::icon_button(None))
|
||||
.on_press(send(Msg::ToggleMute)),
|
||||
)
|
||||
.push(
|
||||
slider(0.0..=1.0, volume, |v| send(Msg::SetVolume(v)))
|
||||
.step(0.01_f32)
|
||||
.width(96)
|
||||
.style(theme::volume_bar),
|
||||
)
|
||||
.into()
|
||||
}
|
||||
|
||||
/// `m:ss`, or `h:mm:ss` for podcast-length items.
|
||||
pub fn clock(seconds: f32) -> String {
|
||||
let s = seconds.max(0.0) as u64;
|
||||
let (h, m, s) = (s / 3600, (s / 60) % 60, s % 60);
|
||||
if h > 0 { format!("{h}:{m:02}:{s:02}") } else { format!("{m}:{s:02}") }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::clock;
|
||||
|
||||
#[test]
|
||||
fn clock_formats() {
|
||||
assert_eq!(clock(0.0), "0:00");
|
||||
assert_eq!(clock(225.4), "3:45");
|
||||
assert_eq!(clock(3132.0), "52:12");
|
||||
assert_eq!(clock(3725.0), "1:02:05");
|
||||
assert_eq!(clock(-3.0), "0:00");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
//! Small dialogs over the window: track actions, new/rename playlist, delete confirmation.
|
||||
|
||||
use iced::widget::{Column, button, column, container, mouse_area, opaque, row, space, text_input};
|
||||
use iced::{Alignment, Element, Fill, Length};
|
||||
use ym_api::{PlaylistId, PlaylistSummary, Track};
|
||||
|
||||
use crate::app::Message;
|
||||
use crate::route::Route;
|
||||
use crate::ui::icons::{Icon, icon};
|
||||
use crate::ui::theme::{self, Tokens, radius, size};
|
||||
use crate::ui::{line, para};
|
||||
use crate::i18n::{tr, trf};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Sheet {
|
||||
Track {
|
||||
track: Track,
|
||||
/// Set when opened from one of the user's own playlists: its id, the row, its length.
|
||||
playlist: Option<(PlaylistId, usize, usize)>,
|
||||
/// Showing the "Add to playlist" list instead of the actions.
|
||||
choosing: bool,
|
||||
},
|
||||
NewPlaylist { name: String, add: Option<Track> },
|
||||
Rename { id: PlaylistId, name: String },
|
||||
ConfirmDelete { id: PlaylistId, title: String },
|
||||
}
|
||||
|
||||
pub const INPUT_ID: &str = "sheet-input";
|
||||
|
||||
/// What the sheet needs to know about the library.
|
||||
pub struct Ctx<'a> {
|
||||
/// The menu is for the track playing now: "next" means skipping ahead.
|
||||
pub playing: bool,
|
||||
pub liked: bool,
|
||||
pub disliked: bool,
|
||||
pub own_playlists: &'a [PlaylistSummary],
|
||||
}
|
||||
|
||||
/// The dimmed backdrop plus the dialog; clicking the backdrop closes it.
|
||||
pub fn overlay<'a>(t: &'static Tokens, sheet: &'a Sheet, ctx: Ctx<'a>) -> Element<'a, Message> {
|
||||
let backdrop = mouse_area(
|
||||
container(space()).width(Fill).height(Fill).style(|_| container::Style {
|
||||
background: Some(iced::Color::BLACK.scale_alpha(0.45).into()),
|
||||
..Default::default()
|
||||
}),
|
||||
)
|
||||
.on_press(Message::CloseSheet);
|
||||
|
||||
let card = container(body(t, sheet, ctx))
|
||||
.width(380)
|
||||
.padding(18)
|
||||
.style(move |_| container::Style {
|
||||
background: Some(t.panel.into()),
|
||||
border: iced::Border { color: t.line, width: 1.0, radius: radius::CARD.into() },
|
||||
shadow: iced::Shadow {
|
||||
color: iced::Color::BLACK.scale_alpha(0.35),
|
||||
offset: iced::Vector::new(0.0, 18.0),
|
||||
blur_radius: 50.0,
|
||||
},
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
iced::widget::stack![backdrop, container(opaque(card)).center(Fill)].into()
|
||||
}
|
||||
|
||||
fn body<'a>(t: &'static Tokens, sheet: &'a Sheet, ctx: Ctx<'a>) -> Element<'a, Message> {
|
||||
match sheet {
|
||||
Sheet::Track { track, playlist, choosing: false } => {
|
||||
let mut items: Vec<Element<'a, Message>> = vec![
|
||||
if ctx.playing {
|
||||
item(t, Icon::Next, tr("Next track"), Some(Message::SkipFromMenu))
|
||||
} else {
|
||||
item(t, Icon::Next, tr("Play next"), Some(Message::PlayNext(track.clone())))
|
||||
},
|
||||
item(t, Icon::Queue, tr("Add to queue"), Some(Message::AddToQueue(track.clone()))),
|
||||
item(
|
||||
t,
|
||||
if ctx.liked { Icon::HeartFilled } else { Icon::Heart },
|
||||
if ctx.liked { tr("Remove from Liked tracks") } else { tr("Add to Liked tracks") },
|
||||
Some(Message::LikeTrack(track.clone(), !ctx.liked)),
|
||||
),
|
||||
item(
|
||||
t,
|
||||
Icon::Plus,
|
||||
tr("Add to playlist…"),
|
||||
Some(Message::OpenSheet(Sheet::Track { track: track.clone(), playlist: *playlist, choosing: true })),
|
||||
),
|
||||
item(t, Icon::Wave, tr("Play similar tracks"), Some(Message::PlaySimilar(track.clone()))),
|
||||
];
|
||||
if let Some(album) = &track.album {
|
||||
items.push(item(t, Icon::Disc, tr("Go to album"), Some(Message::Navigate(Route::Album(album.id)))));
|
||||
}
|
||||
for artist in track.artists.iter().filter(|a| a.id.is_some()).take(3) {
|
||||
items.push(item(
|
||||
t,
|
||||
Icon::Forward,
|
||||
tr("Go to artist"),
|
||||
artist.id.map(|id| Message::Navigate(Route::Artist(id))),
|
||||
));
|
||||
}
|
||||
items.push(item(
|
||||
t,
|
||||
Icon::Dislike,
|
||||
if ctx.disliked { tr("Recommend this track again") } else { tr("Don't recommend this track") },
|
||||
Some(Message::DislikeTrack(track.clone(), !ctx.disliked)),
|
||||
));
|
||||
if let Some((id, index, len)) = *playlist {
|
||||
items.push(divider());
|
||||
if index > 0 {
|
||||
items.push(item(t, Icon::Back, tr("Move up"), Some(Message::MovePlaylistTrack {
|
||||
id, track: track.clone(), from: index, to: index - 1,
|
||||
})));
|
||||
}
|
||||
if index + 1 < len {
|
||||
items.push(item(t, Icon::Forward, tr("Move down"), Some(Message::MovePlaylistTrack {
|
||||
id, track: track.clone(), from: index, to: index + 1,
|
||||
})));
|
||||
}
|
||||
items.push(item(t, Icon::Trash, tr("Remove from this playlist"), Some(Message::RemoveFromPlaylist(id, index))));
|
||||
}
|
||||
frame(t, track.full_title(), Some(track.artist_line()), Column::with_children(items).spacing(2).into())
|
||||
}
|
||||
Sheet::Track { track, choosing: true, .. } => {
|
||||
let mut items: Vec<Element<'a, Message>> = vec![item(
|
||||
t,
|
||||
Icon::Plus,
|
||||
tr("New playlist…"),
|
||||
Some(Message::OpenSheet(Sheet::NewPlaylist { name: String::new(), add: Some(track.clone()) })),
|
||||
)];
|
||||
items.extend(ctx.own_playlists.iter().map(|p| {
|
||||
item(t, Icon::Queue, &p.title, Some(Message::AddToPlaylist(p.id, track.clone())))
|
||||
}));
|
||||
frame(
|
||||
t,
|
||||
tr("Add to playlist").into(),
|
||||
Some(track.full_title()),
|
||||
iced::widget::scrollable(Column::with_children(items).spacing(2)).height(Length::Shrink).into(),
|
||||
)
|
||||
}
|
||||
Sheet::NewPlaylist { name, add } => {
|
||||
let can = !name.trim().is_empty();
|
||||
let hint = if add.is_some() { tr("The track goes in once it's created.") } else { tr("Only you can see it until you make it public.") };
|
||||
frame(
|
||||
t,
|
||||
tr("New playlist").into(),
|
||||
None,
|
||||
column![
|
||||
input(tr("Playlist name"), name, can.then_some(Message::CreatePlaylist)),
|
||||
para(hint, size::META, t.muted),
|
||||
actions(t, tr("Create"), can.then_some(Message::CreatePlaylist), false),
|
||||
]
|
||||
.spacing(14)
|
||||
.into(),
|
||||
)
|
||||
}
|
||||
Sheet::Rename { name, .. } => {
|
||||
let can = !name.trim().is_empty();
|
||||
frame(
|
||||
t,
|
||||
tr("Rename playlist").into(),
|
||||
None,
|
||||
column![
|
||||
input(tr("Playlist name"), name, can.then_some(Message::RenamePlaylist)),
|
||||
actions(t, tr("Rename"), can.then_some(Message::RenamePlaylist), false),
|
||||
]
|
||||
.spacing(14)
|
||||
.into(),
|
||||
)
|
||||
}
|
||||
Sheet::ConfirmDelete { id, title } => frame(
|
||||
t,
|
||||
trf("Delete “{}”?", &[title]),
|
||||
None,
|
||||
column![
|
||||
para(tr("The playlist and its track order go away for good. The tracks stay in Yandex Music."), size::BODY, t.muted),
|
||||
actions(t, tr("Delete"), Some(Message::DeletePlaylist(*id)), true),
|
||||
]
|
||||
.spacing(16)
|
||||
.into(),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn frame<'a>(t: &'static Tokens, title: String, subtitle: Option<String>, content: Element<'a, Message>) -> Element<'a, Message> {
|
||||
let mut head = column![line(title, theme::SEMIBOLD, size::SECTION, t.fg)].spacing(2);
|
||||
if let Some(sub) = subtitle {
|
||||
head = head.push(line(sub, theme::BODY, size::META, t.muted));
|
||||
}
|
||||
column![
|
||||
row![
|
||||
head.width(Fill).clip(true),
|
||||
button(icon(Icon::Close, t.muted)).padding(6).style(theme::icon_button(None)).on_press(Message::CloseSheet),
|
||||
]
|
||||
.align_y(Alignment::Start),
|
||||
content,
|
||||
]
|
||||
.spacing(14)
|
||||
.into()
|
||||
}
|
||||
|
||||
fn item<'a>(t: &'static Tokens, glyph: Icon, label: &str, msg: Option<Message>) -> Element<'a, Message> {
|
||||
button(row![icon(glyph, t.muted), line(label.to_owned(), theme::MEDIUM, size::BODY, t.fg)].spacing(12).align_y(Alignment::Center))
|
||||
.width(Fill)
|
||||
.padding([9, 10])
|
||||
.style(theme::nav_item(false))
|
||||
.on_press_maybe(msg)
|
||||
.into()
|
||||
}
|
||||
|
||||
fn divider<'a>() -> Element<'a, Message> {
|
||||
container(space()).width(Fill).height(1).style(theme::divider).into()
|
||||
}
|
||||
|
||||
fn input<'a>(placeholder: &'a str, value: &'a str, submit: Option<Message>) -> Element<'a, Message> {
|
||||
text_input(placeholder, value)
|
||||
.id(INPUT_ID)
|
||||
.on_input(Message::SheetText)
|
||||
.on_submit_maybe(submit)
|
||||
.padding([10, 14])
|
||||
.style(theme::search_field)
|
||||
.into()
|
||||
}
|
||||
|
||||
fn actions<'a>(t: &'static Tokens, confirm: &'a str, msg: Option<Message>, danger: bool) -> Element<'a, Message> {
|
||||
let ink = if danger { iced::Color::WHITE } else { t.accent_ink };
|
||||
let confirm = button(line(confirm, theme::SEMIBOLD, size::BODY, if msg.is_some() { ink } else { t.muted }))
|
||||
.padding([10, 18])
|
||||
.on_press_maybe(msg);
|
||||
let confirm = if danger {
|
||||
confirm.style(move |_, status| button::Style {
|
||||
background: Some(match status {
|
||||
button::Status::Hovered => theme::mix(t.like, iced::Color::WHITE, 0.1),
|
||||
_ => t.like,
|
||||
}.into()),
|
||||
text_color: iced::Color::WHITE,
|
||||
border: iced::Border { radius: radius::PILL.into(), ..Default::default() },
|
||||
..Default::default()
|
||||
})
|
||||
} else {
|
||||
confirm.style(theme::primary)
|
||||
};
|
||||
row![
|
||||
space().width(Fill),
|
||||
button(line(tr("Cancel"), theme::MEDIUM, size::BODY, t.fg)).padding([10, 18]).style(theme::ghost).on_press(Message::CloseSheet),
|
||||
confirm,
|
||||
]
|
||||
.spacing(8)
|
||||
.into()
|
||||
}
|
||||
|
||||
/// The status line that floats above the player bar after an action.
|
||||
pub fn toast<'a>(t: &'static Tokens, text: &'a str) -> Element<'a, Message> {
|
||||
container(
|
||||
container(line(text, theme::MEDIUM, size::BODY, t.bg))
|
||||
.padding([10, 18])
|
||||
.style(move |_| container::Style {
|
||||
background: Some(t.fg.into()),
|
||||
border: iced::Border { radius: radius::PILL.into(), ..Default::default() },
|
||||
shadow: iced::Shadow {
|
||||
color: iced::Color::BLACK.scale_alpha(0.3),
|
||||
offset: iced::Vector::new(0.0, 6.0),
|
||||
blur_radius: 18.0,
|
||||
},
|
||||
..Default::default()
|
||||
}),
|
||||
)
|
||||
.width(Fill)
|
||||
.height(Fill)
|
||||
.align_x(Alignment::Center)
|
||||
.align_y(iced::alignment::Vertical::Bottom)
|
||||
.padding(iced::Padding::default().bottom(96))
|
||||
.into()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::ui::theme::DARK;
|
||||
|
||||
fn track_sheet() -> Sheet {
|
||||
let track = Track::from_json(r#"{"id":"7","title":"Хочешь?","artists":[{"id":3,"name":"Земфира"}],"albums":[{"id":5,"title":"A"}]}"#).unwrap();
|
||||
Sheet::Track { track, playlist: None, choosing: false }
|
||||
}
|
||||
|
||||
fn click(label: &str) -> Vec<String> {
|
||||
let sheet = track_sheet();
|
||||
let mut ui = iced_test::simulator(overlay(&DARK, &sheet, Ctx { playing: false, liked: false, disliked: false, own_playlists: &[] }));
|
||||
ui.click(label).unwrap_or_else(|e| panic!("can't click {label}: {e:?}"));
|
||||
ui.into_messages().map(|m| format!("{m:?}").chars().take(40).collect()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn menu_for_the_playing_track_offers_next_track() {
|
||||
let sheet = track_sheet();
|
||||
let mut ui = iced_test::simulator(overlay(&DARK, &sheet, Ctx { playing: true, liked: false, disliked: false, own_playlists: &[] }));
|
||||
assert!(ui.find("Play next").is_err());
|
||||
ui.click("Next track").expect("next track item");
|
||||
let messages: Vec<String> = ui.into_messages().map(|m| format!("{m:?}")).collect();
|
||||
assert_eq!(messages, ["SkipFromMenu"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn menu_items_send_their_action_and_not_close() {
|
||||
for (label, expected) in [("Play next", "PlayNext("), ("Add to queue", "AddToQueue("), ("Go to album", "Navigate(Album(5))"), ("Play similar tracks", "PlaySimilar(")] {
|
||||
let messages = click(label);
|
||||
assert!(messages.first().is_some_and(|m| m.starts_with(expected)), "{label}: {messages:?}");
|
||||
assert!(!messages.iter().any(|m| m.starts_with("CloseSheet")), "{label} also closed the sheet: {messages:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
//! Left column: wordmark, main navigation, playlists and the account chip.
|
||||
|
||||
use iced::widget::{Column, button, column, container, row, scrollable, space};
|
||||
use iced::{Alignment, Element, Fill, Padding};
|
||||
|
||||
use ym_api::{Account, LibraryPlaylists};
|
||||
|
||||
use crate::app::Message;
|
||||
use crate::covers::{self, Covers};
|
||||
use crate::route::Route;
|
||||
use crate::ui::icons::{Icon, icon};
|
||||
use crate::ui::theme::{self, Tokens, radius, shell, size};
|
||||
use crate::ui::{line, para};
|
||||
use crate::i18n::tr;
|
||||
|
||||
pub fn view<'a>(
|
||||
t: &'static Tokens,
|
||||
current: Route,
|
||||
me: &'a Account,
|
||||
playlists: Option<&'a LibraryPlaylists>,
|
||||
covers: &Covers,
|
||||
) -> Element<'a, Message> {
|
||||
let nav = Column::with_children(Route::NAV.map(|route| nav_item(t, route, route == current)))
|
||||
.spacing(2);
|
||||
|
||||
let playlists_head = row![
|
||||
line(tr("Playlists"), theme::MEDIUM, size::SMALL, t.muted),
|
||||
space().width(Fill),
|
||||
button(icon(Icon::Plus, t.muted))
|
||||
.padding(4)
|
||||
.style(theme::icon_button(None))
|
||||
.on_press(Message::OpenSheet(crate::widgets::sheet::Sheet::NewPlaylist { name: String::new(), add: None })),
|
||||
]
|
||||
.align_y(Alignment::Center)
|
||||
.padding(Padding::default().left(10).right(2));
|
||||
|
||||
let list: Element<'a, Message> = match playlists {
|
||||
Some(p) if !p.own.is_empty() || !p.liked.is_empty() => {
|
||||
let items = p.own.iter().chain(&p.liked).map(|pl| {
|
||||
let route = Route::Playlist(pl.id);
|
||||
let active = route == current;
|
||||
button(
|
||||
row![
|
||||
covers::view(covers, pl.cover_url(covers::SMALL), pl.hues(), 30.0, radius::SMALL_COVER),
|
||||
line(pl.title.clone(), theme::BODY, size::BODY, if active { t.fg } else { t.muted }),
|
||||
]
|
||||
.spacing(10)
|
||||
.align_y(Alignment::Center),
|
||||
)
|
||||
.width(Fill)
|
||||
.padding([5, 10])
|
||||
.style(theme::nav_item(active))
|
||||
.on_press(Message::Navigate(route))
|
||||
.into()
|
||||
});
|
||||
scrollable(Column::with_children(items).spacing(1))
|
||||
.height(Fill)
|
||||
.style(theme::scroll)
|
||||
.into()
|
||||
}
|
||||
Some(_) => container(para(tr("Playlists you make or like show up here."), size::META, t.muted))
|
||||
.padding(Padding::default().left(10).right(10))
|
||||
.into(),
|
||||
None => container(para(tr("Loading playlists…"), size::META, t.muted))
|
||||
.padding(Padding::default().left(10).right(10))
|
||||
.into(),
|
||||
};
|
||||
|
||||
column![
|
||||
wordmark(t),
|
||||
nav,
|
||||
column![playlists_head, list].spacing(6).height(Fill),
|
||||
account(t, current, me),
|
||||
]
|
||||
.spacing(22)
|
||||
.padding(Padding::default().top(18).bottom(12).left(12).right(12))
|
||||
.width(shell::SIDEBAR)
|
||||
.height(Fill)
|
||||
.into()
|
||||
}
|
||||
|
||||
pub fn wordmark<'a, M: 'a>(t: &'static Tokens) -> Element<'a, M> {
|
||||
row![
|
||||
line("musyx", theme::DISPLAY, size::WORDMARK, t.fg),
|
||||
container(space()).width(7).height(7).style(theme::accent_dot),
|
||||
]
|
||||
.spacing(3)
|
||||
.align_y(Alignment::End)
|
||||
.padding(Padding::default().left(10).top(4).bottom(4))
|
||||
.into()
|
||||
}
|
||||
|
||||
fn nav_item<'a>(t: &'static Tokens, route: Route, active: bool) -> Element<'a, Message> {
|
||||
let tint = if active { t.accent } else { t.muted };
|
||||
button(
|
||||
row![
|
||||
icon(route.icon(), tint),
|
||||
line(route.label(), theme::MEDIUM, size::BODY, if active { t.fg } else { t.muted }),
|
||||
]
|
||||
.spacing(12)
|
||||
.align_y(Alignment::Center),
|
||||
)
|
||||
.width(Fill)
|
||||
.padding([9, 10])
|
||||
.style(theme::nav_item(active))
|
||||
.on_press(Message::Navigate(route))
|
||||
.into()
|
||||
}
|
||||
|
||||
fn account<'a>(t: &'static Tokens, current: Route, account: &'a Account) -> Element<'a, Message> {
|
||||
let avatar = container(line(account.initial().to_string(), theme::SEMIBOLD, size::BODY, iced::Color::from_rgb8(0x1C, 0x1A, 0x22)))
|
||||
.center(32)
|
||||
.style(theme::avatar);
|
||||
|
||||
let (plan, plan_colour) = if account.has_plus {
|
||||
(tr("Plus subscription"), t.ok)
|
||||
} else {
|
||||
(tr("No Plus: 30-second previews"), t.muted)
|
||||
};
|
||||
|
||||
let settings_active = current == Route::Settings;
|
||||
column![
|
||||
container(space()).width(Fill).height(1).style(theme::divider),
|
||||
row![
|
||||
avatar,
|
||||
column![
|
||||
line(&account.name, theme::MEDIUM, 13.5, t.fg),
|
||||
line(plan, theme::BODY, 12.0, plan_colour),
|
||||
]
|
||||
.spacing(1)
|
||||
.width(Fill)
|
||||
.clip(true),
|
||||
button(icon(Icon::Settings, if settings_active { t.accent } else { t.muted }))
|
||||
.padding(8)
|
||||
.style(theme::icon_button(None))
|
||||
.on_press(Message::Navigate(Route::Settings)),
|
||||
]
|
||||
.spacing(10)
|
||||
.align_y(Alignment::Center)
|
||||
.padding(Padding::default().left(10).right(2)),
|
||||
]
|
||||
.spacing(14)
|
||||
.into()
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
//! Back button and search field above the content.
|
||||
|
||||
use iced::widget::{button, row, text_input};
|
||||
use iced::{Alignment, Element};
|
||||
|
||||
use crate::app::Message;
|
||||
use crate::screens::search::Msg;
|
||||
use crate::ui::icons::{Icon, icon};
|
||||
use crate::ui::theme::{self, Tokens, size, space};
|
||||
use crate::i18n::tr;
|
||||
|
||||
pub const SEARCH_ID: &str = "search";
|
||||
|
||||
pub fn view<'a>(t: &'static Tokens, can_go_back: bool, query: &str) -> Element<'a, Message> {
|
||||
let back = button(icon(Icon::Back, if can_go_back { t.fg } else { t.muted }))
|
||||
.padding(8)
|
||||
.style(theme::icon_button(None))
|
||||
.on_press_maybe(can_go_back.then_some(Message::Back));
|
||||
|
||||
let search = text_input(tr("Search artists, tracks, podcasts"), query)
|
||||
.id(SEARCH_ID)
|
||||
.on_input(|text| Message::Search(Msg::Changed(text)))
|
||||
.on_submit(Message::Search(Msg::Submit))
|
||||
.font(theme::BODY)
|
||||
.size(size::BODY)
|
||||
.padding([10, 16])
|
||||
.width(420)
|
||||
.style(theme::search_field);
|
||||
|
||||
row![back, search]
|
||||
.spacing(10)
|
||||
.align_y(Alignment::Center)
|
||||
.padding([14.0, space::GUTTER])
|
||||
.into()
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
//! A whole track list, built once and reused (`lazy`) until something it
|
||||
//! shows changes. Position ticks four times a second must not rebuild 1000 rows.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use iced::widget::{Column, lazy};
|
||||
use iced::Element;
|
||||
use ym_api::{LikedIds, PlaylistId, Track};
|
||||
|
||||
use crate::app::Message;
|
||||
use crate::covers::{self, Covers};
|
||||
use crate::screens::collection::Liked;
|
||||
use crate::widgets::sheet::Sheet;
|
||||
use crate::ui::theme::{self, Tokens, radius};
|
||||
use crate::widgets::track_row::{self, Columns};
|
||||
|
||||
/// What every list needs from app state.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct Env<'a> {
|
||||
pub t: &'static Tokens,
|
||||
pub covers: &'a Covers,
|
||||
pub liked: &'a Liked,
|
||||
pub likes: &'a LikedIds,
|
||||
pub playing: Option<&'a str>,
|
||||
/// The signed-in user's uid, to tell their own playlists apart.
|
||||
pub me: i64,
|
||||
}
|
||||
|
||||
#[derive(Hash)]
|
||||
struct Key {
|
||||
/// Identity of the list contents: the slice address and length.
|
||||
list: (usize, usize),
|
||||
columns: Columns,
|
||||
playing: Option<String>,
|
||||
covers: u64,
|
||||
liked: u64,
|
||||
dark: bool,
|
||||
playlist: Option<PlaylistId>,
|
||||
lang: crate::i18n::Lang,
|
||||
}
|
||||
|
||||
pub fn view<'a>(env: Env<'a>, tracks: &Arc<[Track]>, columns: Columns) -> Element<'a, Message> {
|
||||
build(env, tracks, columns, None, None)
|
||||
}
|
||||
|
||||
/// [`view`] with chart movements, one per track.
|
||||
pub fn view_with<'a>(
|
||||
env: Env<'a>,
|
||||
tracks: &Arc<[Track]>,
|
||||
columns: Columns,
|
||||
shifts: Option<Arc<[i32]>>,
|
||||
) -> Element<'a, Message> {
|
||||
build(env, tracks, columns, shifts, None)
|
||||
}
|
||||
|
||||
/// One of the user's own playlists: rows get move and remove actions.
|
||||
pub fn view_own_playlist<'a>(env: Env<'a>, tracks: &Arc<[Track]>, id: PlaylistId) -> Element<'a, Message> {
|
||||
build(env, tracks, Columns::FULL, None, Some(id))
|
||||
}
|
||||
|
||||
fn build<'a>(
|
||||
env: Env<'a>,
|
||||
tracks: &Arc<[Track]>,
|
||||
columns: Columns,
|
||||
shifts: Option<Arc<[i32]>>,
|
||||
playlist: Option<PlaylistId>,
|
||||
) -> Element<'a, Message> {
|
||||
let Env { t, covers, liked, playing, .. } = env;
|
||||
let key = Key {
|
||||
list: (tracks.as_ptr() as usize, tracks.len()),
|
||||
columns,
|
||||
// Only matters when the playing track is in this list.
|
||||
playing: playing.filter(|id| tracks.iter().any(|tr| tr.id == *id)).map(str::to_owned),
|
||||
covers: if columns.cover { covers.version() } else { 0 },
|
||||
liked: liked.version(),
|
||||
dark: t == &theme::DARK,
|
||||
playlist,
|
||||
lang: crate::i18n::lang(),
|
||||
};
|
||||
let tracks = tracks.clone();
|
||||
|
||||
lazy(key, move |key: &Key| {
|
||||
let rows = tracks.iter().enumerate().map(|(index, track)| {
|
||||
let cover = columns.cover.then(|| {
|
||||
covers::view(covers, track.cover_url(covers::SMALL), track.hues(), 40.0, radius::SMALL_COVER)
|
||||
});
|
||||
track_row::view(
|
||||
t,
|
||||
track_row::Row {
|
||||
index,
|
||||
track,
|
||||
playing: key.playing.as_deref() == Some(track.id.as_str()),
|
||||
liked: liked.contains(&track.id),
|
||||
on_like: Message::LikeTrack(track.clone(), !liked.contains(&track.id)),
|
||||
on_more: Message::OpenSheet(Sheet::Track {
|
||||
track: track.clone(),
|
||||
playlist: key.playlist.map(|id| (id, index, tracks.len())),
|
||||
choosing: false,
|
||||
}),
|
||||
cover,
|
||||
columns,
|
||||
shift: shifts.as_ref().and_then(|s| s.get(index).copied()).unwrap_or(0),
|
||||
on_press: Message::PlayTracks { tracks: tracks.clone(), start: index, shuffle: false },
|
||||
},
|
||||
)
|
||||
});
|
||||
Column::with_children(std::iter::once(track_row::header(t, columns)).chain(rows)).spacing(2)
|
||||
})
|
||||
.into()
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
//! One row in a track list: number (or a playing marker), cover, title and
|
||||
//! artists, album, like state, duration. Clicking anywhere plays it.
|
||||
|
||||
use iced::widget::{button, column, container, row, space};
|
||||
use iced::{Alignment, Element, Fill, Length};
|
||||
use ym_api::Track;
|
||||
|
||||
use crate::app::Message;
|
||||
use crate::ui::icons::{Icon, icon, sized};
|
||||
use crate::ui::line;
|
||||
use crate::ui::theme::{self, Tokens, size};
|
||||
use crate::widgets::player_bar::clock;
|
||||
use crate::i18n::tr;
|
||||
|
||||
pub const HEIGHT: f32 = 52.0;
|
||||
|
||||
/// Which columns a list shows. Album pages drop the cover and album.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct Columns {
|
||||
pub cover: bool,
|
||||
pub album: bool,
|
||||
/// Chart lists show how far each track moved.
|
||||
pub shift: bool,
|
||||
}
|
||||
|
||||
impl Columns {
|
||||
pub const FULL: Columns = Columns { cover: true, album: true, shift: false };
|
||||
pub const ALBUM_PAGE: Columns = Columns { cover: false, album: false, shift: false };
|
||||
pub const CHART: Columns = Columns { cover: true, album: true, shift: true };
|
||||
}
|
||||
|
||||
pub struct Row<'a> {
|
||||
pub index: usize,
|
||||
pub track: &'a Track,
|
||||
pub playing: bool,
|
||||
pub liked: bool,
|
||||
pub cover: Option<Element<'static, Message>>,
|
||||
pub columns: Columns,
|
||||
/// Places moved in the chart; shown when `columns.shift`.
|
||||
pub shift: i32,
|
||||
pub on_press: Message,
|
||||
pub on_like: Message,
|
||||
pub on_more: Message,
|
||||
}
|
||||
|
||||
/// Builds an owned (`'static`) row so lists can sit inside `lazy`.
|
||||
pub fn view(t: &'static Tokens, r: Row<'_>) -> Element<'static, Message> {
|
||||
let track = r.track;
|
||||
let number: Element<'static, Message> = if r.playing {
|
||||
sized(Icon::Wave, 16.0, t.accent).into()
|
||||
} else {
|
||||
line((r.index + 1).to_string(), theme::BODY, size::META, t.muted).into()
|
||||
};
|
||||
|
||||
let unavailable = !track.available;
|
||||
let title_colour = match (unavailable, r.playing) {
|
||||
(true, _) => t.muted,
|
||||
(false, true) => t.accent,
|
||||
(false, false) => t.fg,
|
||||
};
|
||||
|
||||
let mut content = row![container(number).width(36).center_x(36)]
|
||||
.spacing(12)
|
||||
.align_y(Alignment::Center)
|
||||
.height(HEIGHT);
|
||||
if r.columns.shift {
|
||||
content = content.push(crate::screens::browse::shift_marker(t, r.shift));
|
||||
}
|
||||
if r.columns.cover {
|
||||
content = content.push(r.cover.unwrap_or_else(|| space().width(40).into()));
|
||||
}
|
||||
content = content.push(
|
||||
column![
|
||||
line(track.full_title(), theme::MEDIUM, size::BODY, title_colour),
|
||||
line(track.artist_line(), theme::BODY, size::META, t.muted),
|
||||
]
|
||||
.spacing(1)
|
||||
.width(Length::FillPortion(22))
|
||||
.clip(true),
|
||||
);
|
||||
if r.columns.album {
|
||||
content = content.push(
|
||||
container(line(
|
||||
track.album.as_ref().map(|a| a.title.clone()).unwrap_or_default(),
|
||||
theme::BODY,
|
||||
size::META,
|
||||
t.muted,
|
||||
))
|
||||
.width(Length::FillPortion(14))
|
||||
.clip(true),
|
||||
);
|
||||
}
|
||||
content = content
|
||||
.push(
|
||||
button(icon(
|
||||
if r.liked { Icon::HeartFilled } else { Icon::Heart },
|
||||
if r.liked { t.like } else { t.muted.scale_alpha(0.35) },
|
||||
))
|
||||
.padding(8)
|
||||
.style(theme::icon_button(None))
|
||||
.on_press(r.on_like),
|
||||
)
|
||||
.push(
|
||||
container(line(clock(track.duration.as_secs_f32()), theme::BODY, size::META, t.muted))
|
||||
.width(52)
|
||||
.align_right(52),
|
||||
)
|
||||
.push(
|
||||
button(icon(Icon::More, t.muted))
|
||||
.padding(8)
|
||||
.style(theme::icon_button(None))
|
||||
.on_press(r.on_more),
|
||||
);
|
||||
|
||||
button(content)
|
||||
.width(Fill)
|
||||
.padding([0, 10])
|
||||
.style(theme::nav_item(false))
|
||||
.on_press_maybe((!unavailable).then_some(r.on_press))
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Column headings above a track list, aligned with [`view`].
|
||||
pub fn header(t: &'static Tokens, columns: Columns) -> Element<'static, Message> {
|
||||
let label = |s: &'static str| line(s, theme::BODY, size::SMALL, t.muted);
|
||||
let mut heads = row![container(label("#")).width(36).center_x(36)]
|
||||
.spacing(12)
|
||||
.align_y(Alignment::Center)
|
||||
.padding([0, 10]);
|
||||
if columns.shift {
|
||||
heads = heads.push(space().width(14));
|
||||
}
|
||||
if columns.cover {
|
||||
heads = heads.push(space().width(40));
|
||||
}
|
||||
heads = heads.push(container(label(tr("Title"))).width(Length::FillPortion(22)));
|
||||
if columns.album {
|
||||
heads = heads.push(container(label(tr("Album"))).width(Length::FillPortion(14)));
|
||||
}
|
||||
heads = heads
|
||||
.push(space().width(34))
|
||||
.push(container(icon(Icon::Clock, t.muted)).width(52).align_right(52))
|
||||
.push(space().width(34));
|
||||
|
||||
column![heads, container(space()).width(Fill).height(1).style(theme::divider)]
|
||||
.spacing(8)
|
||||
.into()
|
||||
}
|
||||
Reference in new issue
Block a user