diff --git a/Cargo.lock b/Cargo.lock index 6a6c61a..e481a38 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3005,6 +3005,7 @@ dependencies = [ "serde", "serde_json", "souvlaki", + "sys-locale", "tokio", "ym-api", ] diff --git a/README.md b/README.md index a8b8f3e..3f13b72 100644 --- a/README.md +++ b/README.md @@ -44,7 +44,7 @@ This builds a release `Musyx.app` into `target/release/bundle/`, signed with the ## Settings -Settings (streaming quality, appearance, volume) are kept in +Settings (streaming quality, appearance, language, volume) are kept in `~/Library/Application Support/Musyx/settings.json`. Covers are cached under `~/Library/Caches/Musyx/covers` and can be cleared from Settings. @@ -54,6 +54,13 @@ subscription, region and track. When there's no FLAC, it answers with the best l it allows, and Musyx plays that. The badge in the player bar shows what was actually served, and turns accent-coloured for FLAC. +The interface is in English and Russian. **Language** in Settings follows the system's first +preferred language by default, and can be set to either. Yandex's own titles (genres, Home +blocks, station names) switch with it. Strings are written in English in the code as +`tr("…")` or `trf("… {} …", &[…])`. The Russian text lives in +`crates/musyx/src/i18n/ru.rs`, and `cargo test` fails for any string that has no entry +there. `MUSYX_SNAPSHOT_LANG=ru` renders a snapshot in Russian. + ## Check ```sh diff --git a/crates/musyx/Cargo.toml b/crates/musyx/Cargo.toml index 323524d..5fefbbb 100644 --- a/crates/musyx/Cargo.toml +++ b/crates/musyx/Cargo.toml @@ -18,6 +18,7 @@ serde = { version = "1", features = ["derive"] } souvlaki = "0.8.3" tokio = { version = "1", features = ["time", "rt", "fs", "sync"] } directories = "6.0.0" +sys-locale = "0.3.2" png = { version = "0.18.1", optional = true } [dev-dependencies] diff --git a/crates/musyx/examples/api_probe.rs b/crates/musyx/examples/api_probe.rs index 16c7db5..6833caa 100644 --- a/crates/musyx/examples/api_probe.rs +++ b/crates/musyx/examples/api_probe.rs @@ -9,7 +9,7 @@ async fn main() { .and_then(|e| e.get_password()) .expect("sign in with Musyx first"); let credentials: Credentials = serde_json::from_str(&raw).expect("stored credentials"); - let (client, account) = YmClient::connect(&credentials).await.expect("connect"); + let (client, account) = YmClient::connect(&credentials, ym_api::ContentLanguage::English).await.expect("connect"); println!("account: {} (plus: {})", account.login, account.has_plus); match client.home().await { diff --git a/crates/musyx/examples/stream_probe.rs b/crates/musyx/examples/stream_probe.rs index 9e00e88..4d6e850 100644 --- a/crates/musyx/examples/stream_probe.rs +++ b/crates/musyx/examples/stream_probe.rs @@ -14,7 +14,7 @@ async fn main() { .and_then(|e| e.get_password()) .expect("sign in with Musyx first"); let credentials: Credentials = serde_json::from_str(&raw).expect("stored credentials"); - let (client, account) = YmClient::connect(&credentials).await.expect("connect"); + let (client, account) = YmClient::connect(&credentials, ym_api::ContentLanguage::English).await.expect("connect"); println!("account: {} (plus: {})", account.login, account.has_plus); let query = std::env::args().nth(1).unwrap_or_else(|| "земфира хочешь".into()); diff --git a/crates/musyx/src/app.rs b/crates/musyx/src/app.rs index d600055..6d5248e 100644 --- a/crates/musyx/src/app.rs +++ b/crates/musyx/src/app.rs @@ -2,6 +2,7 @@ mod edit; +use crate::i18n::{tr, trf}; use std::collections::HashMap; use std::sync::Arc; @@ -24,7 +25,7 @@ use crate::screens::wave::WaveScreen; use crate::screens::detail::{self, Page}; use crate::screens::{self, Loadable, sign_in}; use crate::session::{self, Restored}; -use crate::store::{self, Appearance, Quality, Settings}; +use crate::store::{self, Appearance, Locale, Quality, Settings}; use crate::ui::theme::{self, shell}; use crate::widgets::drawer::{self, Panel}; use crate::widgets::player_bar; @@ -128,6 +129,8 @@ pub enum Message { WaveTick, SetQuality(Quality), SetAppearance(Appearance), + SetLanguage(Locale), + LanguageSwitched(Result), SaveSettings, SettingsSaved(Result<(), String>), ClearCoverCache, @@ -197,6 +200,7 @@ impl App { }; let mut app = app; app.settings = store::load(); + crate::i18n::set(app.settings.language.resolve()); app.player.volume = app.settings.volume; app.apply_theme(); let app = app; @@ -207,6 +211,9 @@ impl App { let mut app = app; app.drawer = config.drawer; app.forced_mode = config.mode; + if let Some(lang) = config.lang { + crate::i18n::set(lang); + } if let Some(mode) = config.mode { app.theme = theme::for_mode(mode); } @@ -332,9 +339,40 @@ impl App { } Message::SetQuality(quality) => { self.settings.quality = quality; - self.toast(format!("Streaming quality: {}. Applies from the next track.", quality.label())); + self.toast(trf("Streaming quality: {}. Applies from the next track.", &[&quality.label()])); return self.update(Message::SaveSettings); } + Message::SetLanguage(locale) => { + self.settings.language = locale; + let lang = locale.resolve(); + let changed = lang != crate::i18n::lang(); + crate::i18n::set(lang); + let save = self.update(Message::SaveSettings); + if !changed { + return save; + } + // Yandex's own titles (genres, Home blocks, stations) follow too. + let Some(client) = self.client().cloned() else { return save }; + let switch = Task::future(async move { client.in_language(lang.content()).await }) + .map(Message::LanguageSwitched); + return Task::batch([save, switch]); + } + Message::LanguageSwitched(Ok(client)) => { + if let Session::SignedIn { client: current, .. } = &mut self.session { + *current = client; + } + // Load Yandex's titles again in the new language. + self.discover = Discover::default(); + self.genre_playlists.clear(); + self.wave = WaveScreen::default(); + return self.on_enter(self.nav.current()); + } + Message::LanguageSwitched(Err(e)) => { + // The interface has switched; Yandex's titles stay as they were until restart. + if let Some(task) = self.failed("switch content language", &e) { + return task; + } + } Message::SetAppearance(appearance) => { self.settings.appearance = appearance; self.apply_theme(); @@ -351,16 +389,16 @@ impl App { Message::SettingsSaved(result) => { if let Err(e) = result { eprintln!("settings: {e}"); - self.toast("Couldn't save your settings. They'll apply until Musyx quits."); + self.toast(tr("Couldn't save your settings. They'll apply until Musyx quits.")); } } Message::ClearCoverCache => { return self.covers.clear_disk().map(Message::CoverCacheCleared); } - Message::CoverCacheCleared(Ok(())) => self.toast("Cover cache cleared"), + Message::CoverCacheCleared(Ok(())) => self.toast(tr("Cover cache cleared")), Message::CoverCacheCleared(Err(e)) => { eprintln!("clear covers: {e}"); - self.toast("Couldn't clear the cover cache."); + self.toast(tr("Couldn't clear the cover cache.")); } Message::Restore => { self.session = Session::Restoring; @@ -472,10 +510,10 @@ impl App { Message::PlayNext(track) => { self.sheet = None; if self.player.track().is_some_and(|t| t.id == track.id) { - self.toast(format!("“{}” is already playing", track.full_title())); + self.toast(trf("“{}” is already playing", &[&track.full_title()])); return Task::none(); } - self.toast(format!("“{}” plays next", track.full_title())); + self.toast(trf("“{}” plays next", &[&track.full_title()])); return self.update(Message::Player(player::Msg::PlayNext(track))); } Message::Media(command) => { @@ -502,13 +540,13 @@ impl App { } Message::AddToQueue(track) => { self.sheet = None; - self.toast(format!("Added “{}” to the queue", track.full_title())); + self.toast(trf("Added “{}” to the queue", &[&track.full_title()])); return self.update(Message::Player(player::Msg::Append(track))); } Message::PlaySimilar(track) => { self.sheet = None; let Some(client) = self.client().cloned() else { return Task::none() }; - self.toast(format!("Finding tracks like “{}”…", track.full_title())); + self.toast(trf("Finding tracks like “{}”…", &[&track.full_title()])); return Task::future(async move { let result = client.similar_tracks(&track.id).await; Message::SimilarLoaded(track, result) @@ -516,17 +554,17 @@ impl App { } Message::SimilarLoaded(track, result) => match result { Ok(tracks) if tracks.is_empty() => { - self.toast(format!("Yandex has no similar tracks for “{}”", track.full_title())); + self.toast(trf("Yandex has no similar tracks for “{}”", &[&track.full_title()])); } Ok(tracks) => { - self.toast(format!("Playing {} like “{}”", crate::ui::tracks_word(tracks.len()), track.full_title())); + self.toast(trf("Playing {} like “{}”", &[&crate::ui::tracks_word(tracks.len()), &track.full_title()])); return self.update(Message::PlayTracks { tracks: tracks.into(), start: 0, shuffle: false }); } Err(e) => { if let Some(task) = self.failed("similar tracks", &e) { return task; } - self.toast("Couldn't find similar tracks. Try again."); + self.toast(tr("Couldn't find similar tracks. Try again.")); } }, Message::OpenSheet(sheet) => { @@ -652,10 +690,10 @@ impl App { self.library.clips = Loadable::from_result(result); } Message::OpenClip(clip) => match open::that_detached(clip.url()) { - Ok(()) => self.toast(format!("Opening “{}” in your browser", clip.title)), + Ok(()) => self.toast(trf("Opening “{}” in your browser", &[&clip.title])), Err(e) => { eprintln!("open clip: {e}"); - self.toast("Couldn't open your browser."); + self.toast(tr("Couldn't open your browser.")); } }, Message::PageLoaded(route, result) => { @@ -927,8 +965,8 @@ impl App { pub fn view(&self) -> Element<'_, Message> { let t = theme::tokens(&self.theme); let page = match &self.session { - Session::Restoring => screens::connecting(t, "Checking your sign-in…"), - Session::Connecting { .. } => screens::connecting(t, "Signing in…"), + Session::Restoring => screens::connecting(t, tr("Checking your sign-in…")), + Session::Connecting { .. } => screens::connecting(t, tr("Signing in…")), Session::Unreachable => screens::unreachable(t), Session::SignedOut(sign_in) => sign_in.view(t).map(Message::SignIn), Session::SignedIn { account, .. } => return self.shell(t, account), @@ -1132,7 +1170,7 @@ fn connect(credentials: Credentials) -> Task { if let Err(e) = session::save(credentials.clone()).await { eprintln!("keychain: {e}"); } - YmClient::connect(&credentials).await + YmClient::connect(&credentials, crate::i18n::lang().content()).await }) .map(Message::Connected) } @@ -1152,6 +1190,8 @@ mod tests { /// A signed-in app with no network behind it; tasks returned by `update` are dropped. fn signed_in() -> App { let (mut app, _) = App::new(); + // The saved setting and the machine's language mustn't change what tests read. + crate::i18n::set(crate::i18n::Lang::En); app.session = Session::SignedIn { client: YmClient::unauthenticated().unwrap(), account: Account { uid: 1, login: "t".into(), name: "T".into(), has_plus: true, subscription_end: None }, diff --git a/crates/musyx/src/app/edit.rs b/crates/musyx/src/app/edit.rs index 5929b17..75f8e40 100644 --- a/crates/musyx/src/app/edit.rs +++ b/crates/musyx/src/app/edit.rs @@ -1,6 +1,7 @@ //! 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}; @@ -64,8 +65,8 @@ impl App { let c = client.clone(); self.send_edit( async move { c.set_track_liked(&id, on).await }, - if on { "Added to Liked tracks" } else { "Removed from Liked tracks" }.into(), - "Couldn't change the like. Try again.".into(), + if on { tr("Added to Liked tracks") } else { tr("Removed from Liked tracks") }.into(), + tr("Couldn't change the like. Try again.").into(), vec![], ) } @@ -88,8 +89,8 @@ impl App { skip, self.send_edit( async move { c.set_track_disliked(&id, on).await }, - if on { "You won't be recommended this track" } else { "Recommendations for this track restored" }.into(), - "Couldn't change that. Try again.".into(), + 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![], ), ]) @@ -99,8 +100,8 @@ impl App { self.library.albums = Loadable::NotLoaded; self.send_edit( async move { client.set_album_liked(id, on).await }, - if on { "Album added to your collection" } else { "Album removed from your collection" }.into(), - "Couldn't change the like. Try again.".into(), + 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], ) } @@ -109,8 +110,8 @@ impl App { self.library.artists = Loadable::NotLoaded; self.send_edit( async move { client.set_artist_liked(id, on).await }, - if on { "Artist added to your collection" } else { "Artist removed from your collection" }.into(), - "Couldn't change the like. Try again.".into(), + 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], ) } @@ -118,8 +119,8 @@ impl App { toggle(&mut self.likes.playlists, id, on); self.send_edit( async move { client.set_playlist_liked(id, on).await }, - if on { "Playlist added to your collection" } else { "Playlist removed from your collection" }.into(), - "Couldn't change the like. Try again.".into(), + 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], ) } @@ -133,8 +134,8 @@ impl App { } self.send_edit( async move { client.set_clip_liked(clip.id, on).await }, - if on { "Clip added to your collection" } else { "Clip removed from your collection" }.into(), - "Couldn't change the like. Try again.".into(), + 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![], ) } @@ -143,8 +144,8 @@ impl App { let title = self.playlist_title(id); self.send_edit( async move { client.add_to_playlist(id, &track).await }, - format!("Added to “{title}”"), - format!("Couldn't add to “{title}”. Try again."), + trf("Added to “{}”", &[&title]), + trf("Couldn't add to “{}”. Try again.", &[&title]), vec![Refresh::Playlist(id), Refresh::Playlists], ) } @@ -155,8 +156,8 @@ impl App { return Task::none(); } let done = match &add { - Some(_) => format!("Created “{name}” with the track"), - None => format!("Created “{name}”"), + Some(_) => trf("Created “{}” with the track", &[&name]), + None => trf("Created “{}”", &[&name]), }; self.send_edit( async move { @@ -167,7 +168,7 @@ impl App { Ok(()) }, done, - "Couldn't create the playlist. Try again.".into(), + tr("Couldn't create the playlist. Try again.").into(), vec![Refresh::Playlists], ) } @@ -177,18 +178,18 @@ impl App { if name.is_empty() { return Task::none(); } - let done = format!("Renamed to “{name}”"); + let done = trf("Renamed to “{}”", &[&name]); self.send_edit( async move { client.rename_playlist(id, &name).await }, done, - "Couldn't rename the playlist. Try again.".into(), + 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 { "Anyone with the link can now see this playlist" } else { "Only you can see this playlist now" }.into(), - "Couldn't change who can see it. Try again.".into(), + 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) => { @@ -200,8 +201,8 @@ impl App { self.pages.remove(&Route::Playlist(id)); self.send_edit( async move { client.delete_playlist(id).await }, - format!("Deleted “{title}”"), - format!("Couldn't delete “{title}”. Try again."), + trf("Deleted “{}”", &[&title]), + trf("Couldn't delete “{}”. Try again.", &[&title]), vec![Refresh::Playlists], ) } @@ -209,8 +210,8 @@ impl App { self.sheet = None; self.send_edit( async move { client.remove_from_playlist(id, index).await }, - "Removed from the playlist".into(), - "Couldn't remove the track. Try again.".into(), + tr("Removed from the playlist").into(), + tr("Couldn't remove the track. Try again.").into(), vec![Refresh::Playlist(id), Refresh::Playlists], ) } @@ -218,8 +219,8 @@ impl App { self.sheet = None; self.send_edit( async move { client.move_in_playlist(id, &track, from, to).await }, - "Moved".into(), - "Couldn't move the track. Try again.".into(), + tr("Moved").into(), + tr("Couldn't move the track. Try again.").into(), vec![Refresh::Playlist(id)], ) } @@ -249,7 +250,7 @@ impl App { .playlists .get() .and_then(|p| p.own.iter().chain(&p.liked).find(|pl| pl.id == id)) - .map_or_else(|| "the playlist".to_owned(), |p| p.title.clone()) + .map_or_else(|| tr("the playlist").to_owned(), |p| p.title.clone()) } pub(super) fn refresh(&mut self, what: Refresh) -> Task { diff --git a/crates/musyx/src/i18n.rs b/crates/musyx/src/i18n.rs new file mode 100644 index 0000000..245981e --- /dev/null +++ b/crates/musyx/src/i18n.rs @@ -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 = 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 = [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) { + 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")); + } +} diff --git a/crates/musyx/src/i18n/ru.rs b/crates/musyx/src/i18n/ru.rs new file mode 100644 index 0000000..19a6f04 --- /dev/null +++ b/crates/musyx/src/i18n/ru.rs @@ -0,0 +1,360 @@ +//! 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" => "Следующий трек", + "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, + }) +} diff --git a/crates/musyx/src/main.rs b/crates/musyx/src/main.rs index c50e5cc..8185db8 100644 --- a/crates/musyx/src/main.rs +++ b/crates/musyx/src/main.rs @@ -1,5 +1,6 @@ mod app; mod covers; +mod i18n; mod media; mod player; mod route; diff --git a/crates/musyx/src/player/mod.rs b/crates/musyx/src/player/mod.rs index c3c32e0..7653938 100644 --- a/crates/musyx/src/player/mod.rs +++ b/crates/musyx/src/player/mod.rs @@ -5,6 +5,7 @@ pub mod engine; pub mod queue; +use crate::i18n::{tr, trf}; use std::sync::Arc; use std::time::Duration; @@ -358,7 +359,7 @@ impl Player { Event::NoOutput(reason) => { eprintln!("audio output: {reason}"); self.notice = Some( - "No sound output found. Connect speakers or headphones and playback picks up.".into(), + tr("No sound output found. Connect speakers or headphones and playback picks up.").into(), ); } Event::OutputReady => self.notice = None, @@ -495,7 +496,7 @@ impl Player { if wave.waiting { wave.waiting = false; self.status = if self.queue.is_some() { Status::Ended } else { Status::Paused }; - self.notice = Some("Couldn't load more of this station. Check your connection and try again.".into()); + self.notice = Some(tr("Couldn't load more of this station. Check your connection and try again.").into()); } return vec![]; } @@ -607,10 +608,10 @@ impl Player { self.current = None; if self.skips >= MAX_SKIPS { self.status = Status::Paused; - self.notice = Some("Several tracks in a row couldn't be played. Check your connection and try again.".into()); + 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(format!("Couldn't play “{title}”, so it was skipped.")); + self.notice = Some(trf("Couldn't play “{}”, so it was skipped.", &[&title])); self.step(true, false) } } diff --git a/crates/musyx/src/route.rs b/crates/musyx/src/route.rs index 629185b..ee56f7a 100644 --- a/crates/musyx/src/route.rs +++ b/crates/musyx/src/route.rs @@ -1,6 +1,7 @@ //! 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; @@ -28,17 +29,17 @@ impl Route { pub fn label(self) -> &'static str { match self { - Route::Home => "Home", - Route::Wave => "My Wave", - Route::Search => "Search", - Route::Collection => "Collection", - Route::Podcasts => "Podcasts", - Route::Settings => "Settings", - Route::Album(_) => "Album", - Route::Artist(_) => "Artist", - Route::Playlist(_) => "Playlist", - Route::Chart => "Chart", - Route::Genre(_) => "Genre", + 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"), } } diff --git a/crates/musyx/src/screens/browse.rs b/crates/musyx/src/screens/browse.rs index 83fb649..a509391 100644 --- a/crates/musyx/src/screens/browse.rs +++ b/crates/musyx/src/screens/browse.rs @@ -16,6 +16,7 @@ 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; @@ -81,7 +82,7 @@ pub fn home<'a>(env: Env<'a>, discover: &'a Discover, hero: Element<'a, Message> { page = page.push( column![ - line("Recently played", theme::SEMIBOLD, size::SECTION, t.fg), + line(tr("Recently played"), theme::SEMIBOLD, size::SECTION, t.fg), track_list::view(env, recent, Columns::FULL), ] .spacing(14) @@ -95,7 +96,7 @@ pub fn home<'a>(env: Env<'a>, discover: &'a Discover, hero: Element<'a, Message> if !h.personal.is_empty() { page = page.push(section( t, - "Made for you", + tr("Made for you"), h.personal.iter().map(|p| { card::view(t, covers, Card { title: p.playlist.title.clone(), @@ -112,8 +113,8 @@ pub fn home<'a>(env: Env<'a>, discover: &'a Discover, hero: Element<'a, Message> page = page.push( column![ row![ - line("Chart", theme::SEMIBOLD, size::SECTION, t.fg).width(Fill), - button(line(format!("Show all {}", data.chart.len()), theme::MEDIUM, size::META, t.muted)) + 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)), @@ -127,20 +128,20 @@ pub fn home<'a>(env: Env<'a>, discover: &'a Discover, hero: Element<'a, Message> if !h.new_releases.is_empty() { page = page.push(section( t, - "New releases", + 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, - "New playlists", + 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), "home page", Message::LoadHome)), - _ => page = page.push(para("Loading your picks…", size::BODY, t.muted)), + 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() @@ -150,16 +151,16 @@ 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, "The most played tracks on Yandex Music today".into(), &data.chart), + 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("The chart is empty right now.", size::BODY, t.muted).into(), - Loadable::Failed(e) => status(t, LoadState::Failed(e), "chart", Message::LoadHome), - _ => para("Loading the chart…", size::BODY, t.muted).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("Chart", theme::DISPLAY, size::DISPLAY_S, t.fg), body].spacing(24).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>) -> Element<'a, Message> { @@ -170,10 +171,10 @@ pub fn genres_section<'a>(env: Env<'a>, genres: &'a Loadable>) -> Ele 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), "genres", Message::LoadGenres), - _ => para("Loading genres…", size::BODY, t.muted).into(), + Loadable::Failed(e) => status(t, LoadState::Failed(e), tr("genres"), Message::LoadGenres), + _ => para(tr("Loading genres…"), size::BODY, t.muted).into(), }; - column![line("Genres", theme::SEMIBOLD, size::SECTION, t.fg), body].spacing(14).into() + column![line(tr("Genres"), theme::SEMIBOLD, size::SECTION, t.fg), body].spacing(14).into() } fn is_sub_genre(all: &[Genre], g: &Genre) -> bool { @@ -183,11 +184,19 @@ fn is_sub_genre(all: &[Genre], g: &Genre) -> bool { 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( - container(line(g.title.clone(), theme::SEMIBOLD, size::BODY, Color::WHITE)) - .padding([0, 16]) - .align_y(iced::alignment::Vertical::Center) - .height(72) - .width(card::WIDTH), + // 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| { @@ -226,12 +235,12 @@ pub fn genre<'a>( ) -> Element<'a, Message> { let t = env.t; let Some(g) = genres.get(index) else { - return para("This genre isn't available any more.", size::BODY, t.muted).into(); + 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("Play radio", theme::SEMIBOLD, size::BODY, t.accent_ink), + line(tr("Play radio"), theme::SEMIBOLD, size::BODY, t.accent_ink), ] .spacing(8) .align_y(Alignment::Center), @@ -263,11 +272,11 @@ pub fn genre<'a>( let body: Element<'a, Message> = match playlists { Loadable::Loaded(list) if list.is_empty() => { - para("No playlists in this genre yet.", size::BODY, t.muted).into() + para(tr("No playlists in this genre yet."), size::BODY, t.muted).into() } - Loadable::Loaded(list) => section(t, "Playlists", list.iter().map(|p| playlist_card(t, env.covers, p))), - Loadable::Failed(e) => status(t, LoadState::Failed(e), "playlists", Message::Navigate(Route::Genre(index))), - _ => para("Loading playlists…", 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() } @@ -279,20 +288,20 @@ pub fn podcasts<'a>( ) -> Element<'a, Message> { let t = env.t; let covers = env.covers; - let mut page = column![line("Podcasts and books", theme::DISPLAY, size::DISPLAY_S, t.fg)].spacing(34); + 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, "Yours", mine.into_iter().map(|a| album_card(t, covers, a)))); + 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, "Featured", list.iter().map(|a| album_card(t, covers, a))), - Loadable::Failed(e) => status(t, LoadState::Failed(e), "podcasts", Message::LoadPodcasts), - _ => para("Loading podcasts…", size::BODY, t.muted).into(), + 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() } diff --git a/crates/musyx/src/screens/collection.rs b/crates/musyx/src/screens/collection.rs index a4281d3..cab04e7 100644 --- a/crates/musyx/src/screens/collection.rs +++ b/crates/musyx/src/screens/collection.rs @@ -17,6 +17,7 @@ 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)] @@ -96,11 +97,11 @@ impl Tab { fn label(self) -> &'static str { match self { - Tab::Tracks => "Liked tracks", - Tab::Albums => "Albums", - Tab::Artists => "Artists", - Tab::Playlists => "Playlists", - Tab::Clips => "Clips", + Tab::Tracks => tr("Liked tracks"), + Tab::Albums => tr("Albums"), + Tab::Artists => tr("Artists"), + Tab::Playlists => tr("Playlists"), + Tab::Clips => tr("Clips"), } } } @@ -136,52 +137,52 @@ pub fn view<'a>(env: Env<'a>, library: &'a Library) -> Element<'a, Message> { Tab::Tracks => liked_tracks(env, &library.liked), Tab::Albums => match &library.albums { Loadable::Loaded(albums) if albums.is_empty() => { - empty(t, "No liked albums yet. Like an album and it lands here.") + 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(), "albums", Message::LoadLibrary(Tab::Albums)), + 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, "No liked artists yet. Like an artist and they land here.") + 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(), "artists", Message::LoadLibrary(Tab::Artists)), + 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, "No playlists yet. Playlists you make or like show up here.") + 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, - "Your playlists", + tr("Your playlists"), p.own.iter().map(|pl| playlist_card(t, env.covers, pl)), )); } if !p.liked.is_empty() { sections = sections.push(section( t, - "Liked playlists", + tr("Liked playlists"), p.liked.iter().map(|pl| playlist_card(t, env.covers, pl)), )); } sections.into() } - other => status(t, other.state(), "playlists", Message::LoadLibrary(Tab::Playlists)), + 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, "No liked clips yet. Like a clip on an artist's page and it lands here.") + 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(), "clips", Message::LoadLibrary(Tab::Clips)), + other => status(t, other.state(), tr("your clips"), Message::LoadLibrary(Tab::Clips)), }, }; - column![line("Collection", theme::DISPLAY, size::DISPLAY_S, t.fg), tabs, body] + column![line(tr("Collection"), theme::DISPLAY, size::DISPLAY_S, t.fg), tabs, body] .spacing(24) .width(Fill) .into() @@ -209,10 +210,10 @@ fn tab_button<'a>(t: &'static Tokens, tab: Tab, library: &Library) -> Element<'a fn liked_tracks<'a>(env: Env<'a>, liked: &'a Liked) -> Element<'a, Message> { let t = env.t; match liked { - Liked::NotLoaded | Liked::Loading => para("Loading your liked tracks…", size::BODY, t.muted).into(), - Liked::Failed(e) => status(t, LoadState::Failed(e), "liked tracks", Message::LoadLiked), + 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, "No liked tracks yet. Tap the heart on any track and it lands here.") + 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(); @@ -247,14 +248,14 @@ pub fn play_bar<'a>(t: &'static Tokens, summary: String, tracks: &Arc<[Track]>) container(line(summary, theme::BODY, size::META, t.muted)).width(Fill), pill( Icon::Play, - "Play", + tr("Play"), t.accent_ink, theme::primary, Message::PlayTracks { tracks: tracks.clone(), start: 0, shuffle: false }, ), pill( Icon::Shuffle, - "Shuffle", + tr("Shuffle"), t.fg, theme::ghost, Message::PlayTracks { tracks: tracks.clone(), start: 0, shuffle: true }, @@ -286,7 +287,7 @@ pub fn artist_card<'a>(t: &'static Tokens, covers: &Covers, a: &ArtistSummary) - covers, Card { title: a.name.clone(), - subtitle: a.genres.first().cloned().unwrap_or_else(|| "Artist".into()), + subtitle: a.genres.first().cloned().unwrap_or_else(|| tr("Artist").into()), cover: a.cover_url(covers::LARGE), hues: a.hues(), round: true, @@ -345,22 +346,23 @@ pub enum LoadState<'a> { Failed(&'a Error), } -/// Loading text, or a failure with a retry button. +/// 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(format!("Loading your {what}…"), size::BODY, t.muted).into(), + LoadState::Loading => para(trf("Loading {}…", &[&what]), size::BODY, t.muted).into(), LoadState::Failed(e) => column![ para( match e { Error::Network(_) => { - format!("Couldn't load your {what}. Check your connection and try again.") + trf("Couldn't load {}. Check your connection and try again.", &[&what]) } - _ => format!("Couldn't load your {what}. Try again in a moment."), + _ => trf("Couldn't load {}. Try again in a moment.", &[&what]), }, size::BODY, t.muted, ), - button(line("Try again", theme::SEMIBOLD, size::BODY, t.accent_ink)) + button(line(tr("Try again"), theme::SEMIBOLD, size::BODY, t.accent_ink)) .padding([11, 18]) .style(theme::primary) .on_press(retry), diff --git a/crates/musyx/src/screens/detail.rs b/crates/musyx/src/screens/detail.rs index 056776c..a2504d0 100644 --- a/crates/musyx/src/screens/detail.rs +++ b/crates/musyx/src/screens/detail.rs @@ -12,11 +12,12 @@ use crate::app::Message; use crate::covers; use crate::route::Route; use crate::ui::theme::{self, size}; -use crate::ui::{compact, duration_words, line, para, tracks_word}; +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)] @@ -56,9 +57,9 @@ pub fn load(client: &YmClient, route: Route) -> Option> { pub fn view<'a>(env: Env<'a>, route: Route, page: &'a Loadable) -> Element<'a, Message> { let t = env.t; let what = match route { - Route::Album(_) => "album", - Route::Artist(_) => "artist", - _ => "playlist", + 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), @@ -66,19 +67,25 @@ pub fn view<'a>(env: Env<'a>, route: Route, page: &'a Loadable) -> Element 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(format!("Loading the {what}…"), size::BODY, t.muted).into() + para(what.loading, size::BODY, t.muted).into() } } } -fn not_found_or_retry<'a>(env: Env<'a>, e: &'a Error, what: &str, route: Route) -> Element<'a, Message> { +/// 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(format!("This {what} isn't available on Yandex Music any more."), size::BODY, env.t.muted) - .into(); + return para(what.gone, size::BODY, env.t.muted).into(); } - status(env.t, LoadState::Failed(e), what, Message::Navigate(route)) + status(env.t, LoadState::Failed(e), what.retry, Message::Navigate(route)) } struct Head<'a> { @@ -151,8 +158,8 @@ fn artist_links<'a>(env: Env<'a>, artists: &[ArtistRef]) -> Element<'a, Message> 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}", a.kind.label()), - None => a.kind.label().to_owned(), + 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())); @@ -181,11 +188,11 @@ fn album<'a>(env: Env<'a>, info: &'a AlbumPage, tracks: &'a Arc<[Track]>) -> Ele 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() { "Artist".to_owned() } else { format!("Artist · {}", a.genres.join(", ")) }; + let kind = if a.genres.is_empty() { tr("Artist").to_owned() } else { trf("Artist · {}", &[&a.genres.join(", ")]) }; let meta = info .monthly_listeners - .map(|n| format!("{} listeners a month", compact(n))) - .or_else(|| a.likes.map(|n| format!("{} likes", compact(n)))) + .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![ @@ -205,7 +212,7 @@ fn artist<'a>(env: Env<'a>, info: &'a ArtistPage, popular: &'a Arc<[Track]>) -> if !popular.is_empty() { page = page.push( column![ - line("Popular tracks", theme::SEMIBOLD, size::SECTION, t.fg), + line(tr("Popular tracks"), theme::SEMIBOLD, size::SECTION, t.fg), play_bar(t, String::new(), popular), track_list::view(env, popular, Columns::FULL), ] @@ -213,16 +220,16 @@ fn artist<'a>(env: Env<'a>, info: &'a ArtistPage, popular: &'a Arc<[Track]>) -> ); } if !info.albums.is_empty() { - page = page.push(section(t, "Albums", info.albums.iter().map(|al| album_card(t, env.covers, al)))); + 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, "Appears on", info.also_albums.iter().map(|al| album_card(t, env.covers, al)))); + 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, "Clips", info.clips.iter().map(|c| clip_card(env, c)))); + 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, "Similar artists", info.similar.iter().map(|ar| artist_card(t, env.covers, ar)))); + page = page.push(section(t, tr("Similar artists"), info.similar.iter().map(|ar| artist_card(t, env.covers, ar)))); } page.into() } @@ -237,20 +244,20 @@ fn playlist<'a>(env: Env<'a>, info: &'a PlaylistPage, tracks: &'a Arc<[Track]>) cover: p.cover_url(covers::LARGE), hues: p.hues(), round: false, - kind: format!("Playlist · {}", if p.public { "Public" } else { "Private" }), + 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, "Rename", Message::OpenSheet(Sheet::Rename { id: p.id, name: p.title.clone() })), + 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 { "Make private" } else { "Make public" }, + if p.public { tr("Make private") } else { tr("Make public") }, Message::SetPlaylistPublic(p.id, !p.public), ), - pill(t, Icon::Trash, "Delete", Message::OpenSheet(Sheet::ConfirmDelete { id: p.id, title: p.title.clone() })), + 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)))] @@ -262,7 +269,7 @@ fn playlist<'a>(env: Env<'a>, info: &'a PlaylistPage, tracks: &'a Arc<[Track]>) page = page.push(container(para(description.clone(), size::BODY, t.muted)).max_width(640)); } if tracks.is_empty() { - return page.push(para("This playlist is empty.", size::BODY, t.muted)).into(); + 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) diff --git a/crates/musyx/src/screens/mod.rs b/crates/musyx/src/screens/mod.rs index dfd6cba..de134ad 100644 --- a/crates/musyx/src/screens/mod.rs +++ b/crates/musyx/src/screens/mod.rs @@ -21,6 +21,7 @@ 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)] @@ -118,9 +119,9 @@ fn account_card<'a>(t: &'static Tokens, me: &'a Account) -> Element<'a, Message> .style(theme::avatar); let plan = match (me.has_plus, me.subscription_end.as_deref().and_then(human_date)) { - (true, Some(end)) => format!("Yandex Plus until {end}"), - (true, None) => "Yandex Plus".to_owned(), - (false, _) => "No Plus subscription. Tracks play as 30-second previews.".to_owned(), + (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( @@ -134,7 +135,7 @@ fn account_card<'a>(t: &'static Tokens, me: &'a Account) -> Element<'a, Message> .spacing(4) .width(Fill), button( - row![icon(Icon::LogOut, t.fg), line("Sign out", theme::MEDIUM, size::BODY, t.fg)] + row![icon(Icon::LogOut, t.fg), line(tr("Sign out"), theme::MEDIUM, size::BODY, t.fg)] .spacing(8) .align_y(Alignment::Center), ) @@ -151,16 +152,25 @@ fn account_card<'a>(t: &'static Tokens, me: &'a Account) -> Element<'a, Message> .into() } -/// `2027-01-05T00:00:00+03:00` → `5 January 2027`. +/// `2027-01-05T00:00:00+03:00` → `5 January 2027` (`5 января 2027`). pub fn human_date(iso: &str) -> Option { 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::().ok()?.checked_sub(1)?)?; + let month = months.get(m.parse::().ok()?.checked_sub(1)?)?; let day: u32 = d.parse().ok()?; y.parse::().ok()?; Some(format!("{day} {month} {y}")) @@ -185,19 +195,19 @@ pub fn unreachable<'a>(t: &'static Tokens) -> Element<'a, Message> { container( column![ sidebar::wordmark(t), - line("Can't reach Yandex Music", theme::DISPLAY, size::DISPLAY_S, t.fg), + line(tr("Can't reach Yandex Music"), theme::DISPLAY, size::DISPLAY_S, t.fg), container(para( - "You're still signed in. Check your internet connection, then try again.", + tr("You're still signed in. Check your internet connection, then try again."), 15.0, t.muted, )) .max_width(440), row![ - button(line("Try again", theme::SEMIBOLD, size::BODY, t.accent_ink)) + button(line(tr("Try again"), theme::SEMIBOLD, size::BODY, t.accent_ink)) .padding([11, 18]) .style(theme::primary) .on_press(Message::Restore), - button(line("Sign out", theme::MEDIUM, size::BODY, t.fg)) + button(line(tr("Sign out"), theme::MEDIUM, size::BODY, t.fg)) .padding([11, 18]) .style(theme::ghost) .on_press(Message::SignOut), @@ -221,6 +231,9 @@ mod tests { 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); } } diff --git a/crates/musyx/src/screens/search.rs b/crates/musyx/src/screens/search.rs index 7d2f6d0..a2eba60 100644 --- a/crates/musyx/src/screens/search.rs +++ b/crates/musyx/src/screens/search.rs @@ -21,6 +21,7 @@ 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); @@ -203,7 +204,7 @@ impl Search { 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("Browse", theme::DISPLAY, size::DISPLAY_S, t.fg), browse].spacing(24).into(); + return column![line(tr("Browse"), theme::DISPLAY, size::DISPLAY_S, t.fg), browse].spacing(24).into(); } let tabs = row(SearchKind::ALL.map(|kind| { @@ -230,22 +231,22 @@ pub fn view<'a>(env: Env<'a>, search: &'a Search, browse: Element<'a, Message>) })) .spacing(4); - let title = line(format!("Results for “{}”", search.query), theme::DISPLAY, size::DISPLAY_S, t.fg); + 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( - format!("Nothing found for “{}”. Check the spelling or try fewer words.", search.query), + 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), "results", Message::Search(Msg::Submit)), - _ => para("Searching…", size::BODY, t.muted).into(), + 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(format!("Showing results for “{corrected}”"), theme::BODY, size::META, t.muted)); + page = page.push(line(trf("Showing results for “{}”", &[corrected]), theme::BODY, size::META, t.muted)); } page.push(tabs).push(body).into() } @@ -255,7 +256,7 @@ fn results<'a>(env: Env<'a>, search: &'a Search, r: &'a Results) -> Element<'a, let covers = env.covers; let d = &r.data; let more = search.has_more(r).then(|| { - button(line(if r.loading_more { "Loading…" } else { "Show more" }, theme::MEDIUM, size::BODY, t.fg)) + 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))) @@ -271,8 +272,8 @@ fn results<'a>(env: Env<'a>, search: &'a Search, r: &'a Results) -> Element<'a, all = all.push( column![ row![ - line("Tracks", theme::SEMIBOLD, size::SECTION, t.fg).width(Fill), - button(line("Show all", theme::MEDIUM, size::META, t.muted)) + 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))), @@ -283,16 +284,16 @@ fn results<'a>(env: Env<'a>, search: &'a Search, r: &'a Results) -> Element<'a, ); } if !d.artists.is_empty() { - all = all.push(section(t, "Artists", d.artists.iter().take(6).map(|a| artist_card(t, covers, a)))); + 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, "Albums", d.albums.iter().take(6).map(|a| album_card(t, covers, a)))); + 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, "Playlists", d.playlists.iter().take(6).map(|p| playlist_card(t, covers, p)))); + 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, "Podcasts", d.podcasts.iter().take(6).map(|a| album_card(t, covers, a)))); + all = all.push(section(t, tr("Podcasts"), d.podcasts.iter().take(6).map(|a| album_card(t, covers, a)))); } all.into() } @@ -315,7 +316,7 @@ 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(), "Artist".to_owned(), + a.cover_url(covers::LARGE), a.hues(), true, a.name.clone(), tr("Artist").to_owned(), Message::Navigate(Route::Artist(a.id)), ), BestMatch::Album(a) => ( @@ -323,11 +324,11 @@ fn best_card<'a>(env: Env<'a>, best: &'a BestMatch) -> Element<'a, Message> { Message::Navigate(Route::Album(a.id)), ), BestMatch::Playlist(p) => ( - p.cover_url(covers::LARGE), p.hues(), false, p.title.clone(), format!("Playlist · {}", p.owner_name), + 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(), format!("Track · {}", tr.artist_line()), + 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 }, ), }; @@ -338,7 +339,7 @@ fn best_card<'a>(env: Env<'a>, best: &'a BestMatch) -> Element<'a, Message> { row![ covers::view(env.covers, cover, hues, size_px, corner), column![ - line("Top result", theme::MEDIUM, size::SMALL, t.muted), + 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), ] diff --git a/crates/musyx/src/screens/settings.rs b/crates/musyx/src/screens/settings.rs index c520f94..f85bf30 100644 --- a/crates/musyx/src/screens/settings.rs +++ b/crates/musyx/src/screens/settings.rs @@ -3,10 +3,11 @@ use iced::widget::{Row, button, column, container, row}; use iced::{Alignment, Element, Fill}; use crate::app::Message; -use crate::store::{Appearance, Quality, Settings}; +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)))) @@ -14,22 +15,26 @@ pub fn view<'a>(t: &'static Tokens, settings: &Settings, account: Element<'a, Me 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("Settings", theme::DISPLAY, size::DISPLAY_S, t.fg), + line(tr("Settings"), theme::DISPLAY, size::DISPLAY_S, t.fg), account, - section(t, "Streaming quality", column![quality, para(settings.quality.detail(), size::META, t.muted)].spacing(10).into()), - section(t, "Appearance", appearance.into()), + 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, - "Storage", + tr("Storage"), column![ para( - "Covers are kept on disk so pages open instantly next time. Clearing them frees the space; they download again as you browse.", + 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("Clear cover cache", theme::MEDIUM, size::BODY, t.fg)].spacing(8).align_y(Alignment::Center)) + 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), @@ -37,7 +42,7 @@ pub fn view<'a>(t: &'static Tokens, settings: &Settings, account: Element<'a, Me .spacing(12) .into(), ), - line(format!("Musyx {} · unofficial Yandex Music client", env!("CARGO_PKG_VERSION")), theme::BODY, size::SMALL, t.muted), + line(trf("Musyx {} · unofficial Yandex Music client", &[&env!("CARGO_PKG_VERSION")]), theme::BODY, size::SMALL, t.muted), ] .spacing(28) .width(Fill) diff --git a/crates/musyx/src/screens/sign_in.rs b/crates/musyx/src/screens/sign_in.rs index e46ca00..744e03d 100644 --- a/crates/musyx/src/screens/sign_in.rs +++ b/crates/musyx/src/screens/sign_in.rs @@ -13,6 +13,7 @@ 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 { @@ -74,7 +75,7 @@ impl SignIn { /// Shown after a pasted token turned out to be invalid. pub fn rejected_token() -> Self { Self { - error: Some("Yandex didn't accept that token. Check it and paste it again.".into()), + error: Some(tr("Yandex didn't accept that token. Check it and paste it again.").into()), token_open: true, ..Self::default() } @@ -158,10 +159,7 @@ impl SignIn { if let Stage::Waiting(w) = &self.stage && open::that_detached(&w.code.verification_url).is_err() { - self.error = Some(format!( - "Couldn't open your browser. Go to {} yourself.", - w.code.verification_url - )); + self.error = Some(trf("Couldn't open your browser. Go to {} yourself.", &[&w.code.verification_url])); } } Msg::ToggleToken => self.token_open = !self.token_open, @@ -199,7 +197,7 @@ impl SignIn { let left = column![ sidebar::wordmark(t), container( - iced::widget::text("Sign in with your Yandex account") + iced::widget::text(tr("Sign in with your Yandex account")) .font(theme::DISPLAY) .size(size::DISPLAY_M) .line_height(1.12) @@ -207,8 +205,7 @@ impl SignIn { ) .max_width(520), container(para( - "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.", + 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, )) @@ -217,8 +214,7 @@ impl SignIn { self.token_fallback(t), space().height(Fill), container(para( - "Musyx is an unofficial client and isn't affiliated with Yandex. Your sign-in \ - token is kept in the system keychain.", + 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, )) @@ -256,10 +252,10 @@ impl SignIn { let content: Element<'a, Msg> = match &self.stage { Stage::Idle => column![ - primary(t, "Get sign-in code", Some(Msg::GetCode)), + primary(t, tr("Get sign-in code"), Some(Msg::GetCode)), ] .into(), - Stage::Requesting => column![primary(t, "Getting a code…", None)].into(), + Stage::Requesting => column![primary(t, tr("Getting a code…"), None)].into(), Stage::Waiting(w) => self.steps(t, w), }; @@ -280,7 +276,7 @@ impl SignIn { 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 { "Copied" } else { "Copy code" }, Msg::CopyCode), + ghost(t, Icon::Copy, if copied { tr("Copied") } else { tr("Copy code") }, Msg::CopyCode), ] .spacing(14) .align_y(Alignment::Center); @@ -289,13 +285,13 @@ impl SignIn { let status = row![ container(space()).width(9).height(9).style(theme::accent_dot), line( - format!("Waiting for confirmation · code expires in {}:{:02}", remaining / 60, remaining % 60), + trf("Waiting for confirmation · code expires in {}", &[&format!("{}:{:02}", remaining / 60, remaining % 60)]), theme::BODY, 13.5, t.muted, ), space().width(12), - button(line("Cancel", theme::MEDIUM, 13.5, t.muted)) + button(line(tr("Cancel"), theme::MEDIUM, 13.5, t.muted)) .padding(0) .style(theme::tab(false)) .on_press(Msg::Cancel), @@ -305,17 +301,17 @@ impl SignIn { column![ step(t, 1, column![ - line(format!("Open {host}"), theme::MEDIUM, size::BODY, t.fg), - para("On this computer or your phone. You can also scan the QR code.", 13.5, t.muted), - ghost(t, Icon::Globe, "Open in browser", Msg::OpenPage), + 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("Enter this code", theme::MEDIUM, size::BODY, t.fg), + line(tr("Enter this code"), theme::MEDIUM, size::BODY, t.fg), code_box, ].spacing(10)), step(t, 3, column![ - line("Come back here", theme::MEDIUM, size::BODY, t.fg), - para("Musyx signs you in as soon as you allow access.", 13.5, t.muted), + 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, ] @@ -325,7 +321,7 @@ impl SignIn { fn token_fallback<'a>(&'a self, t: &'static Tokens) -> Element<'a, Msg> { let toggle = button(line( - if self.token_open { "Hide token sign-in" } else { "Sign in with an existing token instead" }, + if self.token_open { tr("Hide token sign-in") } else { tr("Sign in with an existing token instead") }, theme::BODY, 13.5, t.muted, @@ -342,7 +338,7 @@ impl SignIn { column![ toggle, row![ - text_input("Paste OAuth token", &self.token) + text_input(tr("Paste OAuth token"), &self.token) .id("token") .secure(true) .on_input(Msg::TokenChanged) @@ -350,7 +346,7 @@ impl SignIn { .padding([10, 14]) .width(320) .style(theme::search_field), - button(line("Sign in", theme::MEDIUM, size::BODY, t.fg)) + 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)), @@ -376,13 +372,13 @@ impl SignIn { background: iced::Color::WHITE, }) .into(), - "Scan to open the sign-in page", + tr("Scan to open the sign-in page"), ), None => ( container(icon(Icon::Lock, iced::Color::from_rgb8(0x68, 0x61, 0x78))) .center(200) .into(), - "A QR code appears with your sign-in code", + tr("A QR code appears with your sign-in code"), ), }; container( @@ -411,11 +407,11 @@ impl SignIn { /// The user's next step for each failure. Never shows the raw error. fn describe(error: &Error) -> &'static str { match error { - Error::CodeExpired => "The code expired before it was confirmed. Get a new code to try again.", - Error::Denied => "Access was declined on Yandex's page. Get a new code if that was a mistake.", - Error::Network(_) => "Can't reach Yandex. Check your connection and try again.", - Error::Unauthorized(_) => "Yandex didn't accept the sign-in. Get a new code to try again.", - Error::Api(_) => "Yandex sent an unexpected answer. Try again in a moment.", + 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."), } } diff --git a/crates/musyx/src/screens/wave.rs b/crates/musyx/src/screens/wave.rs index 921aee8..bc93ab2 100644 --- a/crates/musyx/src/screens/wave.rs +++ b/crates/musyx/src/screens/wave.rs @@ -14,6 +14,7 @@ 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)] @@ -89,24 +90,26 @@ pub fn hero<'a>( .height(Fill); let blurb = match settings { - Some(s) if s != WaveSettings::default() => format!( + Some(s) if s != WaveSettings::default() => trf( "Tuned to: {} mood, {} tracks, {} language.", - s.mood.label().to_lowercase(), - s.character.label().to_lowercase(), - s.language.label().to_lowercase() + &[ + &tr(s.mood.label()).to_lowercase(), + &tr(s.character.label()).to_lowercase(), + &tr(s.language.label()).to_lowercase(), + ], ), - _ => "An endless stream picked from what you play, like and skip.".to_owned(), + _ => 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) => ("Pause", Icon::Pause, Message::Player(player::Msg::Toggle)), - Some(_) => ("Resume", Icon::Play, Message::Player(player::Msg::Toggle)), - None => ("Play My Wave", Icon::Play, Message::PlayWave(MY_WAVE.to_owned())), + 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("My Wave", theme::DISPLAY, if big { size::DISPLAY_XL } else { size::DISPLAY_M }, t.fg), + 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) @@ -151,24 +154,24 @@ pub fn view<'a>( (_, Some(s)) => { let saving = screen.saving.is_some(); row![ - setting(t, "Mood", Mood::ALL.map(|m| (m.label(), m == s.mood, WaveSettings { mood: m, ..s })), saving), - setting(t, "Character", Character::ALL.map(|c| (c.label(), c == s.character, WaveSettings { character: c, ..s })), saving), - setting(t, "Language", Language::ALL.map(|l| (l.label(), l == s.language, WaveSettings { language: l, ..s })), saving), + 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), "station settings", Message::LoadWave), - _ => para("Loading your settings…", size::BODY, t.muted).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("No other stations suggested right now.", size::BODY, t.muted).into() + 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) @@ -177,14 +180,14 @@ pub fn view<'a>( .into() } } - Loadable::Failed(e) => status(t, LoadState::Failed(e), "stations", Message::LoadWave), - _ => para("Loading stations…", size::BODY, t.muted).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("Stations", theme::SEMIBOLD, size::SECTION, t.fg), stations].spacing(14), + column![line(tr("Stations"), theme::SEMIBOLD, size::SECTION, t.fg), stations].spacing(14), ] .spacing(34) .into() diff --git a/crates/musyx/src/session.rs b/crates/musyx/src/session.rs index 4341260..20a4bc1 100644 --- a/crates/musyx/src/session.rs +++ b/crates/musyx/src/session.rs @@ -77,10 +77,11 @@ pub async fn restore() -> Restored { credentials }; - match YmClient::connect(&credentials).await { + 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).await { + Some(fresh) => match YmClient::connect(&fresh, language).await { Ok((client, account)) => Restored::SignedIn(client, account), Err(e) => forget(e).await, }, diff --git a/crates/musyx/src/snapshot.rs b/crates/musyx/src/snapshot.rs index c192e27..86598e6 100644 --- a/crates/musyx/src/snapshot.rs +++ b/crates/musyx/src/snapshot.rs @@ -2,7 +2,7 @@ //! //! ```sh //! MUSYX_SNAPSHOT=home.png MUSYX_SNAPSHOT_ROUTE=wave MUSYX_SNAPSHOT_DRAWER=queue \ -//! MUSYX_SNAPSHOT_THEME=light cargo run -p musyx --features snapshot +//! 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. @@ -16,6 +16,7 @@ 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; @@ -29,6 +30,8 @@ pub struct Config { pub mode: Option, /// `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, /// `MUSYX_SNAPSHOT_DELAY` in ms before capturing (default 1500; live runs need longer). pub delay: Duration, } @@ -62,11 +65,12 @@ impl Config { "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, live, delay }) + Some(Self { out, signed_out, route, drawer, mode, lang, live, delay }) } /// A made-up account so the shell renders without a network or keychain. diff --git a/crates/musyx/src/store.rs b/crates/musyx/src/store.rs index 602874d..871f3db 100644 --- a/crates/musyx/src/store.rs +++ b/crates/musyx/src/store.rs @@ -1,6 +1,7 @@ //! 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}; @@ -25,22 +26,21 @@ impl Quality { pub fn label(self) -> &'static str { match self { - Quality::Lossless => "Lossless", - Quality::Best => "Best", - Quality::Balanced => "Balanced", - Quality::DataSaver => "Data saver", + 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 => { - "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." + 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 => "Highest MP3 bitrate Yandex offers, up to 320 kbps.", - Quality::Balanced => "Up to 192 kbps. About 40% less data.", - Quality::DataSaver => "Up to 128 kbps, for slow or metered connections.", + 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."), } } @@ -69,9 +69,41 @@ impl Appearance { pub fn label(self) -> &'static str { match self { - Appearance::System => "Match system", - Appearance::Light => "Light", - Appearance::Dark => "Dark", + 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, } } } @@ -81,12 +113,13 @@ impl Appearance { 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, volume: 0.7 } + Self { quality: Quality::Best, appearance: Appearance::System, language: Locale::System, volume: 0.7 } } } @@ -121,7 +154,7 @@ mod tests { #[test] fn settings_round_trip_and_tolerate_missing_fields() { - let s = Settings { quality: Quality::DataSaver, appearance: Appearance::Dark, volume: 0.25 }; + 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\""); diff --git a/crates/musyx/src/ui/mod.rs b/crates/musyx/src/ui/mod.rs index beba3eb..333594f 100644 --- a/crates/musyx/src/ui/mod.rs +++ b/crates/musyx/src/ui/mod.rs @@ -5,6 +5,8 @@ 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) @@ -18,24 +20,40 @@ pub fn para<'a>(content: impl text::IntoFragment<'a>, size: f32, color: Color) - /// "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 { format!("{} h {} min", mins / 60, mins % 60) } else { format!("{mins} min") } + 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 { - if n == 1 { "1 track".into() } else { format!("{n} tracks") } + i18n::count(n as u64, ["track", "tracks"], ["трек", "трека", "треков"]) } -/// "4.1M", "830K", "912". +/// "4.1M", "830K", "912"; in Russian "4,1 млн", "830 тыс.", "912". pub fn compact(n: i64) -> String { - match n { - n if n >= 1_000_000 => format!("{:.1}M", n as f64 / 1e6).replace(".0M", "M"), - n if n >= 10_000 => format!("{}K", n / 1000), - n if n >= 1_000 => format!("{:.1}K", n as f64 / 1e3).replace(".0K", "K"), - n => n.to_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::*; @@ -52,5 +70,21 @@ mod tests { 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); } } diff --git a/crates/musyx/src/widgets/drawer.rs b/crates/musyx/src/widgets/drawer.rs index eff49e3..9086568 100644 --- a/crates/musyx/src/widgets/drawer.rs +++ b/crates/musyx/src/widgets/drawer.rs @@ -15,6 +15,7 @@ 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 { @@ -25,8 +26,8 @@ pub enum Panel { impl Panel { fn label(self) -> &'static str { match self { - Panel::Queue => "Queue", - Panel::Lyrics => "Lyrics", + Panel::Queue => tr("Queue"), + Panel::Lyrics => tr("Lyrics"), } } } @@ -57,20 +58,20 @@ pub fn view<'a>( let body: Element<'a, Message> = match (panel, player.queue()) { (Panel::Queue, Some(queue)) => queue_list(t, queue, covers), (Panel::Queue, None) => container(para( - "Nothing queued yet. Tracks you play, and the ones lined up after them, show up here.", + 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, "Play a track to see its lyrics."), + (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, "Yandex Music has no lyrics for this track."), + Some(Loadable::Loaded(None)) => note(t, tr("Yandex Music has no lyrics for this track.")), Some(Loadable::Failed(_)) => column![ - note(t, "Couldn't load the lyrics. Check your connection and try again."), + note(t, tr("Couldn't load the lyrics. Check your connection and try again.")), container( - button(line("Try again", theme::SEMIBOLD, size::BODY, t.accent_ink)) + button(line(tr("Try again"), theme::SEMIBOLD, size::BODY, t.accent_ink)) .padding([9, 16]) .style(theme::primary) .on_press(Message::RetryLyrics), @@ -79,7 +80,7 @@ pub fn view<'a>( ] .spacing(12) .into(), - _ => note(t, "Loading lyrics…"), + _ => note(t, tr("Loading lyrics…")), }, }; @@ -122,7 +123,7 @@ fn lyrics_view<'a>(t: &'static Tokens, l: &'a Lyrics, position: Duration) -> Ele let mut list = Column::with_children(lines).spacing(2); if !l.writers.is_empty() { list = list.push( - container(para(format!("Written by {}", l.writers.join(", ")), size::SMALL, t.muted)) + container(para(trf("Written by {}", &[&l.writers.join(", ")]), size::SMALL, t.muted)) .padding(iced::Padding::default().top(18).left(8).right(8)), ); } @@ -163,18 +164,18 @@ fn queue_list<'a>(t: &'static Tokens, queue: &'a Queue, covers: &Covers) }; let remaining = queue.upcoming().count(); - let mut list = column![heading("Now playing".into()), item(queue.current(), true, None)]; + let mut list = column![heading(tr("Now playing").into()), item(queue.current(), true, None)]; list = list.push(heading(if remaining == 0 { - "Nothing after this".into() + tr("Nothing after this").into() } else { - format!("Next up · {remaining}") + 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(format!("and {} more", remaining - SHOWN), theme::BODY, size::SMALL, t.muted)) + container(line(trf("and {} more", &[&(remaining - SHOWN)]), theme::BODY, size::SMALL, t.muted)) .padding([10, 8]), ); } diff --git a/crates/musyx/src/widgets/player_bar.rs b/crates/musyx/src/widgets/player_bar.rs index 97231cd..d126be6 100644 --- a/crates/musyx/src/widgets/player_bar.rs +++ b/crates/musyx/src/widgets/player_bar.rs @@ -10,6 +10,7 @@ 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) @@ -42,8 +43,8 @@ fn now_playing<'a>(t: &'static Tokens, p: &'a Player, liked: bool, covers: &Cove ..Default::default() }); let (title, sub) = match &p.notice { - Some(notice) => ("Can't play", notice.as_str()), - None => ("Nothing playing", "Pick a track to start"), + Some(notice) => (tr("Can't play"), notice.as_str()), + None => (tr("Nothing playing"), tr("Pick a track to start")), }; return row![ blank, @@ -180,7 +181,7 @@ fn extras<'a>(t: &'static Tokens, p: &'a Player, drawer: Option) -> Eleme let mut items = row![].spacing(4).align_y(Alignment::Center); if let Some(stream) = p.stream() { - let label = if stream.preview { "Preview".to_owned() } else { stream.label() }; + 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)); } diff --git a/crates/musyx/src/widgets/sheet.rs b/crates/musyx/src/widgets/sheet.rs index dacb71f..b075b98 100644 --- a/crates/musyx/src/widgets/sheet.rs +++ b/crates/musyx/src/widgets/sheet.rs @@ -9,6 +9,7 @@ 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 { @@ -67,55 +68,55 @@ fn body<'a>(t: &'static Tokens, sheet: &'a Sheet, ctx: Ctx<'a>) -> Element<'a, M Sheet::Track { track, playlist, choosing: false } => { let mut items: Vec> = vec![ if ctx.playing { - item(t, Icon::Next, "Next track", Some(Message::SkipFromMenu)) + item(t, Icon::Next, tr("Next track"), Some(Message::SkipFromMenu)) } else { - item(t, Icon::Next, "Play next", Some(Message::PlayNext(track.clone()))) + item(t, Icon::Next, tr("Play next"), Some(Message::PlayNext(track.clone()))) }, - item(t, Icon::Queue, "Add to queue", Some(Message::AddToQueue(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 { "Remove from Liked tracks" } else { "Add to Liked tracks" }, + 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, - "Add to playlist…", + tr("Add to playlist…"), Some(Message::OpenSheet(Sheet::Track { track: track.clone(), playlist: *playlist, choosing: true })), ), - item(t, Icon::Wave, "Play similar tracks", Some(Message::PlaySimilar(track.clone()))), + 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, "Go to album", Some(Message::Navigate(Route::Album(album.id))))); + 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, - "Go to artist", + tr("Go to artist"), artist.id.map(|id| Message::Navigate(Route::Artist(id))), )); } items.push(item( t, Icon::Dislike, - if ctx.disliked { "Recommend this track again" } else { "Don't recommend this track" }, + 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, "Move up", Some(Message::MovePlaylistTrack { + 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, "Move down", Some(Message::MovePlaylistTrack { + 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, "Remove from this playlist", Some(Message::RemoveFromPlaylist(id, index)))); + 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()) } @@ -123,7 +124,7 @@ fn body<'a>(t: &'static Tokens, sheet: &'a Sheet, ctx: Ctx<'a>) -> Element<'a, M let mut items: Vec> = vec![item( t, Icon::Plus, - "New playlist…", + tr("New playlist…"), Some(Message::OpenSheet(Sheet::NewPlaylist { name: String::new(), add: Some(track.clone()) })), )]; items.extend(ctx.own_playlists.iter().map(|p| { @@ -131,22 +132,22 @@ fn body<'a>(t: &'static Tokens, sheet: &'a Sheet, ctx: Ctx<'a>) -> Element<'a, M })); frame( t, - "Add to playlist".into(), + 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() { "The track goes in once it's created." } else { "Only you can see it until you make it public." }; + 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, - "New playlist".into(), + tr("New playlist").into(), None, column![ - input("Playlist name", name, can.then_some(Message::CreatePlaylist)), + input(tr("Playlist name"), name, can.then_some(Message::CreatePlaylist)), para(hint, size::META, t.muted), - actions(t, "Create", can.then_some(Message::CreatePlaylist), false), + actions(t, tr("Create"), can.then_some(Message::CreatePlaylist), false), ] .spacing(14) .into(), @@ -156,11 +157,11 @@ fn body<'a>(t: &'static Tokens, sheet: &'a Sheet, ctx: Ctx<'a>) -> Element<'a, M let can = !name.trim().is_empty(); frame( t, - "Rename playlist".into(), + tr("Rename playlist").into(), None, column![ - input("Playlist name", name, can.then_some(Message::RenamePlaylist)), - actions(t, "Rename", can.then_some(Message::RenamePlaylist), false), + input(tr("Playlist name"), name, can.then_some(Message::RenamePlaylist)), + actions(t, tr("Rename"), can.then_some(Message::RenamePlaylist), false), ] .spacing(14) .into(), @@ -168,11 +169,11 @@ fn body<'a>(t: &'static Tokens, sheet: &'a Sheet, ctx: Ctx<'a>) -> Element<'a, M } Sheet::ConfirmDelete { id, title } => frame( t, - format!("Delete “{title}”?"), + trf("Delete “{}”?", &[title]), None, column![ - para("The playlist and its track order go away for good. The tracks stay in Yandex Music.", size::BODY, t.muted), - actions(t, "Delete", Some(Message::DeletePlaylist(*id)), true), + 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(), @@ -240,7 +241,7 @@ fn actions<'a>(t: &'static Tokens, confirm: &'a str, msg: Option, dange }; row![ space().width(Fill), - button(line("Cancel", theme::MEDIUM, size::BODY, t.fg)).padding([10, 18]).style(theme::ghost).on_press(Message::CloseSheet), + button(line(tr("Cancel"), theme::MEDIUM, size::BODY, t.fg)).padding([10, 18]).style(theme::ghost).on_press(Message::CloseSheet), confirm, ] .spacing(8) diff --git a/crates/musyx/src/widgets/sidebar.rs b/crates/musyx/src/widgets/sidebar.rs index 86971d1..2d2276a 100644 --- a/crates/musyx/src/widgets/sidebar.rs +++ b/crates/musyx/src/widgets/sidebar.rs @@ -11,6 +11,7 @@ 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, @@ -23,7 +24,7 @@ pub fn view<'a>( .spacing(2); let playlists_head = row![ - line("Playlists", theme::MEDIUM, size::SMALL, t.muted), + line(tr("Playlists"), theme::MEDIUM, size::SMALL, t.muted), space().width(Fill), button(icon(Icon::Plus, t.muted)) .padding(4) @@ -57,10 +58,10 @@ pub fn view<'a>( .style(theme::scroll) .into() } - Some(_) => container(para("Playlists you make or like show up here.", size::META, t.muted)) + 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("Loading playlists…", size::META, t.muted)) + None => container(para(tr("Loading playlists…"), size::META, t.muted)) .padding(Padding::default().left(10).right(10)) .into(), }; @@ -112,9 +113,9 @@ fn account<'a>(t: &'static Tokens, current: Route, account: &'a Account) -> Elem .style(theme::avatar); let (plan, plan_colour) = if account.has_plus { - ("Plus subscription", t.ok) + (tr("Plus subscription"), t.ok) } else { - ("No Plus: 30-second previews", t.muted) + (tr("No Plus: 30-second previews"), t.muted) }; let settings_active = current == Route::Settings; diff --git a/crates/musyx/src/widgets/topbar.rs b/crates/musyx/src/widgets/topbar.rs index 095cfd3..cda6e8b 100644 --- a/crates/musyx/src/widgets/topbar.rs +++ b/crates/musyx/src/widgets/topbar.rs @@ -7,6 +7,7 @@ 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"; @@ -16,7 +17,7 @@ pub fn view<'a>(t: &'static Tokens, can_go_back: bool, query: &str) -> Element<' .style(theme::icon_button(None)) .on_press_maybe(can_go_back.then_some(Message::Back)); - let search = text_input("Search artists, tracks, podcasts", query) + 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)) diff --git a/crates/musyx/src/widgets/track_list.rs b/crates/musyx/src/widgets/track_list.rs index 36da617..74b2225 100644 --- a/crates/musyx/src/widgets/track_list.rs +++ b/crates/musyx/src/widgets/track_list.rs @@ -36,6 +36,7 @@ struct Key { liked: u64, dark: bool, playlist: Option, + lang: crate::i18n::Lang, } pub fn view<'a>(env: Env<'a>, tracks: &Arc<[Track]>, columns: Columns) -> Element<'a, Message> { @@ -74,6 +75,7 @@ fn build<'a>( liked: liked.version(), dark: t == &theme::DARK, playlist, + lang: crate::i18n::lang(), }; let tracks = tracks.clone(); diff --git a/crates/musyx/src/widgets/track_row.rs b/crates/musyx/src/widgets/track_row.rs index a2f494f..543bba4 100644 --- a/crates/musyx/src/widgets/track_row.rs +++ b/crates/musyx/src/widgets/track_row.rs @@ -10,6 +10,7 @@ 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; @@ -132,9 +133,9 @@ pub fn header(t: &'static Tokens, columns: Columns) -> Element<'static, Message> if columns.cover { heads = heads.push(space().width(40)); } - heads = heads.push(container(label("Title")).width(Length::FillPortion(22))); + heads = heads.push(container(label(tr("Title"))).width(Length::FillPortion(22))); if columns.album { - heads = heads.push(container(label("Album")).width(Length::FillPortion(14))); + heads = heads.push(container(label(tr("Album"))).width(Length::FillPortion(14))); } heads = heads .push(space().width(34)) diff --git a/crates/ym-api/src/client.rs b/crates/ym-api/src/client.rs index 1e431c6..ae1e771 100644 --- a/crates/ym-api/src/client.rs +++ b/crates/ym-api/src/client.rs @@ -116,17 +116,50 @@ impl std::fmt::Debug for YmClient { } } +/// The language Yandex writes its own titles in: genres, Home blocks, stations. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ContentLanguage { + Russian, + English, +} + +impl ContentLanguage { + fn yamuse(self) -> yamuse::Language { + match self { + ContentLanguage::Russian => yamuse::Language::Ru, + ContentLanguage::English => yamuse::Language::En, + } + } +} + impl YmClient { /// Builds a client for `credentials` and loads the account. Fails with /// [`crate::Error::Unauthorized`] when the token is no longer valid. - pub async fn connect(credentials: &Credentials) -> Result<(Self, Account)> { - let inner = yamuse::Client::builder().token(&credentials.access_token).build()?; + pub async fn connect(credentials: &Credentials, language: ContentLanguage) -> Result<(Self, Account)> { + let inner = yamuse::Client::builder() + .token(&credentials.access_token) + .language(language.yamuse()) + .build()?; let status = inner.refresh_account().await?; let account = Account::from_status(status) .ok_or_else(|| Error::Unauthorized("account status has no user".into()))?; Ok((Self { inner, token: Some(credentials.access_token.as_str().into()) }, account)) } + /// The same account, with Yandex answering in `language`. Loads the account + /// again, since that's how the client learns whose library it reads. + pub async fn in_language(&self, language: ContentLanguage) -> Result { + let mut builder = yamuse::Client::builder().language(language.yamuse()); + if let Some(token) = &self.token { + builder = builder.token(token.as_ref()); + } + let inner = builder.build()?; + if self.token.is_some() { + inner.init().await?; + } + Ok(Self { inner, token: self.token.clone() }) + } + /// A client with no token, for previews and tests. Every account call fails. pub fn unauthenticated() -> Result { Ok(Self { inner: yamuse::Client::anonymous()?, token: None }) diff --git a/crates/ym-api/src/lib.rs b/crates/ym-api/src/lib.rs index 4800852..5edcac2 100644 --- a/crates/ym-api/src/lib.rs +++ b/crates/ym-api/src/lib.rs @@ -13,7 +13,7 @@ mod library; mod models; mod wave; -pub use client::{Account, YmClient}; +pub use client::{Account, ContentLanguage, YmClient}; pub use clips::Clip; pub use library::{ AlbumKind, AlbumPage, AlbumSummary, ArtistPage, ArtistSummary, LibraryPlaylists, PlaylistId, diff --git a/crates/ym-api/src/library.rs b/crates/ym-api/src/library.rs index 82b7054..6c8a051 100644 --- a/crates/ym-api/src/library.rs +++ b/crates/ym-api/src/library.rs @@ -16,6 +16,9 @@ pub enum AlbumKind { } impl AlbumKind { + pub const ALL: [AlbumKind; 5] = + [AlbumKind::Album, AlbumKind::Single, AlbumKind::Compilation, AlbumKind::Podcast, AlbumKind::Audiobook]; + fn from_api(meta_type: Option<&str>, kind: Option<&str>) -> Self { match (meta_type, kind) { (Some("podcast"), _) | (_, Some("podcast")) => AlbumKind::Podcast, diff --git a/tool/bundle-macos.sh b/tool/bundle-macos.sh index 9df7df8..839a1f1 100755 --- a/tool/bundle-macos.sh +++ b/tool/bundle-macos.sh @@ -37,6 +37,8 @@ cat > "$bundle/Contents/Info.plist" <CFBundleNameMusyx CFBundleDisplayNameMusyx CFBundleIdentifierdev.musyx.desktop + CFBundleDevelopmentRegionen + CFBundleLocalizationsenru CFBundleExecutableMusyx CFBundleIconFileMusyx CFBundlePackageTypeAPPL