Merge branch 'russian-locale'

This commit is contained in:
Yuriy Panov committed 2026-10-15 21:57:12 +06:00
commit 33c48de638
35 files changed
+1070 -305

No files matched your search

Generated
+1
View File
@@ -3005,6 +3005,7 @@ dependencies = [
"serde", "serde",
"serde_json", "serde_json",
"souvlaki", "souvlaki",
"sys-locale",
"tokio", "tokio",
"ym-api", "ym-api",
] ]
+8 -1
View File
@@ -44,7 +44,7 @@ This builds a release `Musyx.app` into `target/release/bundle/`, signed with the
## Settings ## 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/Application Support/Musyx/settings.json`. Covers are cached under
`~/Library/Caches/Musyx/covers` and can be cleared from Settings. `~/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, it allows, and Musyx plays that. The badge in the player bar shows what was actually served,
and turns accent-coloured for FLAC. 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 ## Check
```sh ```sh
+1
View File
@@ -18,6 +18,7 @@ serde = { version = "1", features = ["derive"] }
souvlaki = "0.8.3" souvlaki = "0.8.3"
tokio = { version = "1", features = ["time", "rt", "fs", "sync"] } tokio = { version = "1", features = ["time", "rt", "fs", "sync"] }
directories = "6.0.0" directories = "6.0.0"
sys-locale = "0.3.2"
png = { version = "0.18.1", optional = true } png = { version = "0.18.1", optional = true }
[dev-dependencies] [dev-dependencies]
+1 -1
View File
@@ -9,7 +9,7 @@ async fn main() {
.and_then(|e| e.get_password()) .and_then(|e| e.get_password())
.expect("sign in with Musyx first"); .expect("sign in with Musyx first");
let credentials: Credentials = serde_json::from_str(&raw).expect("stored credentials"); 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); println!("account: {} (plus: {})", account.login, account.has_plus);
match client.home().await { match client.home().await {
+1 -1
View File
@@ -14,7 +14,7 @@ async fn main() {
.and_then(|e| e.get_password()) .and_then(|e| e.get_password())
.expect("sign in with Musyx first"); .expect("sign in with Musyx first");
let credentials: Credentials = serde_json::from_str(&raw).expect("stored credentials"); 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); println!("account: {} (plus: {})", account.login, account.has_plus);
let query = std::env::args().nth(1).unwrap_or_else(|| "земфира хочешь".into()); let query = std::env::args().nth(1).unwrap_or_else(|| "земфира хочешь".into());
+57 -17
View File
@@ -2,6 +2,7 @@
mod edit; mod edit;
use crate::i18n::{tr, trf};
use std::collections::HashMap; use std::collections::HashMap;
use std::sync::Arc; use std::sync::Arc;
@@ -24,7 +25,7 @@ use crate::screens::wave::WaveScreen;
use crate::screens::detail::{self, Page}; use crate::screens::detail::{self, Page};
use crate::screens::{self, Loadable, sign_in}; use crate::screens::{self, Loadable, sign_in};
use crate::session::{self, Restored}; 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::ui::theme::{self, shell};
use crate::widgets::drawer::{self, Panel}; use crate::widgets::drawer::{self, Panel};
use crate::widgets::player_bar; use crate::widgets::player_bar;
@@ -128,6 +129,8 @@ pub enum Message {
WaveTick, WaveTick,
SetQuality(Quality), SetQuality(Quality),
SetAppearance(Appearance), SetAppearance(Appearance),
SetLanguage(Locale),
LanguageSwitched(Result<YmClient, Error>),
SaveSettings, SaveSettings,
SettingsSaved(Result<(), String>), SettingsSaved(Result<(), String>),
ClearCoverCache, ClearCoverCache,
@@ -197,6 +200,7 @@ impl App {
}; };
let mut app = app; let mut app = app;
app.settings = store::load(); app.settings = store::load();
crate::i18n::set(app.settings.language.resolve());
app.player.volume = app.settings.volume; app.player.volume = app.settings.volume;
app.apply_theme(); app.apply_theme();
let app = app; let app = app;
@@ -207,6 +211,9 @@ impl App {
let mut app = app; let mut app = app;
app.drawer = config.drawer; app.drawer = config.drawer;
app.forced_mode = config.mode; app.forced_mode = config.mode;
if let Some(lang) = config.lang {
crate::i18n::set(lang);
}
if let Some(mode) = config.mode { if let Some(mode) = config.mode {
app.theme = theme::for_mode(mode); app.theme = theme::for_mode(mode);
} }
@@ -332,9 +339,40 @@ impl App {
} }
Message::SetQuality(quality) => { Message::SetQuality(quality) => {
self.settings.quality = 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); 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) => { Message::SetAppearance(appearance) => {
self.settings.appearance = appearance; self.settings.appearance = appearance;
self.apply_theme(); self.apply_theme();
@@ -351,16 +389,16 @@ impl App {
Message::SettingsSaved(result) => { Message::SettingsSaved(result) => {
if let Err(e) = result { if let Err(e) = result {
eprintln!("settings: {e}"); 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 => { Message::ClearCoverCache => {
return self.covers.clear_disk().map(Message::CoverCacheCleared); 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)) => { Message::CoverCacheCleared(Err(e)) => {
eprintln!("clear covers: {e}"); eprintln!("clear covers: {e}");
self.toast("Couldn't clear the cover cache."); self.toast(tr("Couldn't clear the cover cache."));
} }
Message::Restore => { Message::Restore => {
self.session = Session::Restoring; self.session = Session::Restoring;
@@ -472,10 +510,10 @@ impl App {
Message::PlayNext(track) => { Message::PlayNext(track) => {
self.sheet = None; self.sheet = None;
if self.player.track().is_some_and(|t| t.id == track.id) { 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(); 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))); return self.update(Message::Player(player::Msg::PlayNext(track)));
} }
Message::Media(command) => { Message::Media(command) => {
@@ -502,13 +540,13 @@ impl App {
} }
Message::AddToQueue(track) => { Message::AddToQueue(track) => {
self.sheet = None; 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))); return self.update(Message::Player(player::Msg::Append(track)));
} }
Message::PlaySimilar(track) => { Message::PlaySimilar(track) => {
self.sheet = None; self.sheet = None;
let Some(client) = self.client().cloned() else { return Task::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 { return Task::future(async move {
let result = client.similar_tracks(&track.id).await; let result = client.similar_tracks(&track.id).await;
Message::SimilarLoaded(track, result) Message::SimilarLoaded(track, result)
@@ -516,17 +554,17 @@ impl App {
} }
Message::SimilarLoaded(track, result) => match result { Message::SimilarLoaded(track, result) => match result {
Ok(tracks) if tracks.is_empty() => { 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) => { 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 }); return self.update(Message::PlayTracks { tracks: tracks.into(), start: 0, shuffle: false });
} }
Err(e) => { Err(e) => {
if let Some(task) = self.failed("similar tracks", &e) { if let Some(task) = self.failed("similar tracks", &e) {
return task; return task;
} }
self.toast("Couldn't find similar tracks. Try again."); self.toast(tr("Couldn't find similar tracks. Try again."));
} }
}, },
Message::OpenSheet(sheet) => { Message::OpenSheet(sheet) => {
@@ -652,10 +690,10 @@ impl App {
self.library.clips = Loadable::from_result(result); self.library.clips = Loadable::from_result(result);
} }
Message::OpenClip(clip) => match open::that_detached(clip.url()) { 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) => { Err(e) => {
eprintln!("open clip: {e}"); eprintln!("open clip: {e}");
self.toast("Couldn't open your browser."); self.toast(tr("Couldn't open your browser."));
} }
}, },
Message::PageLoaded(route, result) => { Message::PageLoaded(route, result) => {
@@ -927,8 +965,8 @@ impl App {
pub fn view(&self) -> Element<'_, Message> { pub fn view(&self) -> Element<'_, Message> {
let t = theme::tokens(&self.theme); let t = theme::tokens(&self.theme);
let page = match &self.session { let page = match &self.session {
Session::Restoring => screens::connecting(t, "Checking your sign-in…"), Session::Restoring => screens::connecting(t, tr("Checking your sign-in…")),
Session::Connecting { .. } => screens::connecting(t, "Signing in…"), Session::Connecting { .. } => screens::connecting(t, tr("Signing in…")),
Session::Unreachable => screens::unreachable(t), Session::Unreachable => screens::unreachable(t),
Session::SignedOut(sign_in) => sign_in.view(t).map(Message::SignIn), Session::SignedOut(sign_in) => sign_in.view(t).map(Message::SignIn),
Session::SignedIn { account, .. } => return self.shell(t, account), Session::SignedIn { account, .. } => return self.shell(t, account),
@@ -1132,7 +1170,7 @@ fn connect(credentials: Credentials) -> Task<Message> {
if let Err(e) = session::save(credentials.clone()).await { if let Err(e) = session::save(credentials.clone()).await {
eprintln!("keychain: {e}"); eprintln!("keychain: {e}");
} }
YmClient::connect(&credentials).await YmClient::connect(&credentials, crate::i18n::lang().content()).await
}) })
.map(Message::Connected) .map(Message::Connected)
} }
@@ -1152,6 +1190,8 @@ mod tests {
/// A signed-in app with no network behind it; tasks returned by `update` are dropped. /// A signed-in app with no network behind it; tasks returned by `update` are dropped.
fn signed_in() -> App { fn signed_in() -> App {
let (mut app, _) = App::new(); 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 { app.session = Session::SignedIn {
client: YmClient::unauthenticated().unwrap(), client: YmClient::unauthenticated().unwrap(),
account: Account { uid: 1, login: "t".into(), name: "T".into(), has_plus: true, subscription_end: None }, account: Account { uid: 1, login: "t".into(), name: "T".into(), has_plus: true, subscription_end: None },
+29 -28
View File
@@ -1,6 +1,7 @@
//! Changing things: likes, dislikes, playlist edits, plus lyrics and the //! Changing things: likes, dislikes, playlist edits, plus lyrics and the
//! server-side queue. Every change is shown at once and undone if Yandex refuses. //! 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::sync::Arc;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
@@ -64,8 +65,8 @@ impl App {
let c = client.clone(); let c = client.clone();
self.send_edit( self.send_edit(
async move { c.set_track_liked(&id, on).await }, async move { c.set_track_liked(&id, on).await },
if on { "Added to Liked tracks" } else { "Removed from Liked tracks" }.into(), if on { tr("Added to Liked tracks") } else { tr("Removed from Liked tracks") }.into(),
"Couldn't change the like. Try again.".into(), tr("Couldn't change the like. Try again.").into(),
vec![], vec![],
) )
} }
@@ -88,8 +89,8 @@ impl App {
skip, skip,
self.send_edit( self.send_edit(
async move { c.set_track_disliked(&id, on).await }, 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(), if on { tr("You won't be recommended this track") } else { tr("Recommendations for this track restored") }.into(),
"Couldn't change that. Try again.".into(), tr("Couldn't change that. Try again.").into(),
vec![], vec![],
), ),
]) ])
@@ -99,8 +100,8 @@ impl App {
self.library.albums = Loadable::NotLoaded; self.library.albums = Loadable::NotLoaded;
self.send_edit( self.send_edit(
async move { client.set_album_liked(id, on).await }, async move { client.set_album_liked(id, on).await },
if on { "Album added to your collection" } else { "Album removed from your collection" }.into(), if on { tr("Album added to your collection") } else { tr("Album removed from your collection") }.into(),
"Couldn't change the like. Try again.".into(), tr("Couldn't change the like. Try again.").into(),
vec![Refresh::LikedIds], vec![Refresh::LikedIds],
) )
} }
@@ -109,8 +110,8 @@ impl App {
self.library.artists = Loadable::NotLoaded; self.library.artists = Loadable::NotLoaded;
self.send_edit( self.send_edit(
async move { client.set_artist_liked(id, on).await }, async move { client.set_artist_liked(id, on).await },
if on { "Artist added to your collection" } else { "Artist removed from your collection" }.into(), if on { tr("Artist added to your collection") } else { tr("Artist removed from your collection") }.into(),
"Couldn't change the like. Try again.".into(), tr("Couldn't change the like. Try again.").into(),
vec![Refresh::LikedIds], vec![Refresh::LikedIds],
) )
} }
@@ -118,8 +119,8 @@ impl App {
toggle(&mut self.likes.playlists, id, on); toggle(&mut self.likes.playlists, id, on);
self.send_edit( self.send_edit(
async move { client.set_playlist_liked(id, on).await }, async move { client.set_playlist_liked(id, on).await },
if on { "Playlist added to your collection" } else { "Playlist removed from your collection" }.into(), if on { tr("Playlist added to your collection") } else { tr("Playlist removed from your collection") }.into(),
"Couldn't change the like. Try again.".into(), tr("Couldn't change the like. Try again.").into(),
vec![Refresh::Playlists, Refresh::LikedIds], vec![Refresh::Playlists, Refresh::LikedIds],
) )
} }
@@ -133,8 +134,8 @@ impl App {
} }
self.send_edit( self.send_edit(
async move { client.set_clip_liked(clip.id, on).await }, async move { client.set_clip_liked(clip.id, on).await },
if on { "Clip added to your collection" } else { "Clip removed from your collection" }.into(), if on { tr("Clip added to your collection") } else { tr("Clip removed from your collection") }.into(),
"Couldn't change the like. Try again.".into(), tr("Couldn't change the like. Try again.").into(),
vec![], vec![],
) )
} }
@@ -143,8 +144,8 @@ impl App {
let title = self.playlist_title(id); let title = self.playlist_title(id);
self.send_edit( self.send_edit(
async move { client.add_to_playlist(id, &track).await }, async move { client.add_to_playlist(id, &track).await },
format!("Added to “{title}”"), trf("Added to “{}”", &[&title]),
format!("Couldn't add to “{title}”. Try again."), trf("Couldn't add to “{}”. Try again.", &[&title]),
vec![Refresh::Playlist(id), Refresh::Playlists], vec![Refresh::Playlist(id), Refresh::Playlists],
) )
} }
@@ -155,8 +156,8 @@ impl App {
return Task::none(); return Task::none();
} }
let done = match &add { let done = match &add {
Some(_) => format!("Created “{name}” with the track"), Some(_) => trf("Created “{}” with the track", &[&name]),
None => format!("Created “{name}”"), None => trf("Created “{}”", &[&name]),
}; };
self.send_edit( self.send_edit(
async move { async move {
@@ -167,7 +168,7 @@ impl App {
Ok(()) Ok(())
}, },
done, done,
"Couldn't create the playlist. Try again.".into(), tr("Couldn't create the playlist. Try again.").into(),
vec![Refresh::Playlists], vec![Refresh::Playlists],
) )
} }
@@ -177,18 +178,18 @@ impl App {
if name.is_empty() { if name.is_empty() {
return Task::none(); return Task::none();
} }
let done = format!("Renamed to “{name}”"); let done = trf("Renamed to “{}”", &[&name]);
self.send_edit( self.send_edit(
async move { client.rename_playlist(id, &name).await }, async move { client.rename_playlist(id, &name).await },
done, done,
"Couldn't rename the playlist. Try again.".into(), tr("Couldn't rename the playlist. Try again.").into(),
vec![Refresh::Playlist(id), Refresh::Playlists], vec![Refresh::Playlist(id), Refresh::Playlists],
) )
} }
Message::SetPlaylistPublic(id, public) => self.send_edit( Message::SetPlaylistPublic(id, public) => self.send_edit(
async move { client.set_playlist_public(id, public).await }, 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(), if public { tr("Anyone with the link can now see this playlist") } else { tr("Only you can see this playlist now") }.into(),
"Couldn't change who can see it. Try again.".into(), tr("Couldn't change who can see it. Try again.").into(),
vec![Refresh::Playlist(id), Refresh::Playlists], vec![Refresh::Playlist(id), Refresh::Playlists],
), ),
Message::DeletePlaylist(id) => { Message::DeletePlaylist(id) => {
@@ -200,8 +201,8 @@ impl App {
self.pages.remove(&Route::Playlist(id)); self.pages.remove(&Route::Playlist(id));
self.send_edit( self.send_edit(
async move { client.delete_playlist(id).await }, async move { client.delete_playlist(id).await },
format!("Deleted “{title}”"), trf("Deleted “{}”", &[&title]),
format!("Couldn't delete “{title}”. Try again."), trf("Couldn't delete “{}”. Try again.", &[&title]),
vec![Refresh::Playlists], vec![Refresh::Playlists],
) )
} }
@@ -209,8 +210,8 @@ impl App {
self.sheet = None; self.sheet = None;
self.send_edit( self.send_edit(
async move { client.remove_from_playlist(id, index).await }, async move { client.remove_from_playlist(id, index).await },
"Removed from the playlist".into(), tr("Removed from the playlist").into(),
"Couldn't remove the track. Try again.".into(), tr("Couldn't remove the track. Try again.").into(),
vec![Refresh::Playlist(id), Refresh::Playlists], vec![Refresh::Playlist(id), Refresh::Playlists],
) )
} }
@@ -218,8 +219,8 @@ impl App {
self.sheet = None; self.sheet = None;
self.send_edit( self.send_edit(
async move { client.move_in_playlist(id, &track, from, to).await }, async move { client.move_in_playlist(id, &track, from, to).await },
"Moved".into(), tr("Moved").into(),
"Couldn't move the track. Try again.".into(), tr("Couldn't move the track. Try again.").into(),
vec![Refresh::Playlist(id)], vec![Refresh::Playlist(id)],
) )
} }
@@ -249,7 +250,7 @@ impl App {
.playlists .playlists
.get() .get()
.and_then(|p| p.own.iter().chain(&p.liked).find(|pl| pl.id == id)) .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<Message> { pub(super) fn refresh(&mut self, what: Refresh) -> Task<Message> {
+198
View File
@@ -0,0 +1,198 @@
//! Interface language. Strings are written in English where they're used and
//! looked up here; Russian falls back to English for anything missing (a test
//! scans the sources so nothing is).
use std::fmt::Display;
mod ru;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Lang {
#[default]
En,
Ru,
}
impl Lang {
/// From a BCP 47 tag such as `ru-RU` or `en-US`.
pub fn from_tag(tag: &str) -> Lang {
let primary = tag.split(['-', '_']).next().unwrap_or_default();
if primary.eq_ignore_ascii_case("ru") { Lang::Ru } else { Lang::En }
}
/// The first language the system prefers.
pub fn system() -> Lang {
sys_locale::get_locale().map_or(Lang::En, |tag| Lang::from_tag(&tag))
}
/// What Yandex should write its own titles in (genres, Home blocks, station names).
pub fn content(self) -> ym_api::ContentLanguage {
match self {
Lang::En => ym_api::ContentLanguage::English,
Lang::Ru => ym_api::ContentLanguage::Russian,
}
}
}
// The app's state lives on the main thread, but tests run in parallel threads,
// so there each thread keeps its own language.
#[cfg(not(test))]
static RUSSIAN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
#[cfg(test)]
thread_local! {
static RUSSIAN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
pub fn set(lang: Lang) {
#[cfg(not(test))]
RUSSIAN.store(lang == Lang::Ru, std::sync::atomic::Ordering::Relaxed);
#[cfg(test)]
RUSSIAN.set(lang == Lang::Ru);
}
pub fn lang() -> Lang {
#[cfg(not(test))]
let russian = RUSSIAN.load(std::sync::atomic::Ordering::Relaxed);
#[cfg(test)]
let russian = RUSSIAN.get();
if russian { Lang::Ru } else { Lang::En }
}
/// `english` in the interface language.
pub fn tr(english: &str) -> &str {
match lang() {
Lang::En => english,
Lang::Ru => ru::get(english).unwrap_or(english),
}
}
/// [`tr`] with each `{}` in the template filled from `args`, in order.
pub fn trf(template: &str, args: &[&dyn Display]) -> String {
let mut out = String::with_capacity(template.len() + 16);
let mut args = args.iter();
let mut pieces = tr(template).split("{}");
out.push_str(pieces.next().unwrap_or_default());
for piece in pieces {
if let Some(arg) = args.next() {
out.push_str(&arg.to_string());
}
out.push_str(piece);
}
out
}
/// The word that goes with `n`: `en` is [one, other], `ru` is [one, few, many].
pub fn plural<'a>(n: u64, en: [&'a str; 2], ru: [&'a str; 3]) -> &'a str {
match lang() {
Lang::En => en[usize::from(n != 1)],
Lang::Ru => ru[ru_form(n)],
}
}
/// "1 track" / "5 tracks", "1 трек" / "3 трека" / "5 треков".
pub fn count(n: u64, en: [&str; 2], ru: [&str; 3]) -> String {
format!("{n} {}", plural(n, en, ru))
}
/// Russian plural form: 0 for 1, 21, 101…; 1 for 2–4, 22–24…; 2 for the rest.
fn ru_form(n: u64) -> usize {
match (n % 10, n % 100) {
(1, r) if r != 11 => 0,
(2..=4, r) if !(12..=14).contains(&r) => 1,
_ => 2,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn russian_lookups_fall_back_to_english() {
set(Lang::Ru);
assert_eq!(tr("Settings"), "Настройки");
assert_eq!(tr("not a key"), "not a key");
assert_eq!(trf("Added “{}” to the queue", &[&"Хочешь?"]), "«Хочешь?» добавлен в очередь");
set(Lang::En);
assert_eq!(tr("Settings"), "Settings");
assert_eq!(trf("Added “{}” to the queue", &[&"Hm"]), "Added “Hm” to the queue");
}
#[test]
fn plural_forms() {
let forms = ([("track"), "tracks"], ["трек", "трека", "треков"]);
set(Lang::Ru);
let ru: Vec<String> = [1, 2, 5, 11, 12, 21, 22, 25, 101, 111].map(|n| count(n, forms.0, forms.1)).into();
assert_eq!(ru, ["1 трек", "2 трека", "5 треков", "11 треков", "12 треков", "21 трек", "22 трека", "25 треков", "101 трек", "111 треков"]);
set(Lang::En);
assert_eq!(count(1, forms.0, forms.1), "1 track");
assert_eq!(count(0, forms.0, forms.1), "0 tracks");
}
#[test]
fn system_tags() {
assert_eq!(Lang::from_tag("ru-RU"), Lang::Ru);
assert_eq!(Lang::from_tag("ru"), Lang::Ru);
assert_eq!(Lang::from_tag("en-US"), Lang::En);
assert_eq!(Lang::from_tag("kk_KZ"), Lang::En);
}
/// Every `tr("…")` and `trf("…"` literal in the sources has a Russian entry,
/// and so does every label that reaches `tr` from ym-api.
#[test]
fn every_string_has_a_russian_translation() {
fn walk(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
for entry in std::fs::read_dir(dir).unwrap().flatten() {
let path = entry.path();
if path.is_dir() {
walk(&path, out);
} else if path.extension().is_some_and(|e| e == "rs") {
out.push(path);
}
}
}
let mut files = Vec::new();
walk(&std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"), &mut files);
let mut missing = Vec::new();
let mut seen = 0;
// This file's own examples aren't interface strings.
for file in files.into_iter().filter(|f| !f.ends_with("i18n.rs")) {
let source = std::fs::read_to_string(&file).unwrap();
// The scan reads a literal up to its closing quote, so it can't follow a
// string continued with a backslash; keep interface strings on one line.
let name = file.file_name().unwrap().to_string_lossy().into_owned();
let code = source.split("#[cfg(test)]").next().unwrap_or_default();
for (n, line) in code.lines().enumerate() {
if line.trim_end().ends_with('\\') && line.contains('"') {
missing.push(format!("{name}:{}: string continues on the next line", n + 1));
}
}
for call in ["tr(\"", "trf(\""] {
for (at, _) in source.match_indices(call) {
// Skip `ustr(`, `attr(` and the like.
if source[..at].ends_with(|c: char| c.is_alphanumeric() || c == '_') {
continue;
}
let rest = &source[at + call.len()..];
let end = rest.find('"').unwrap();
let key = rest[..end].replace("\\n", "\n");
seen += 1;
if ru::get(&key).is_none() {
missing.push(format!("{}: {key}", file.file_name().unwrap().to_string_lossy()));
}
}
}
}
use ym_api::{AlbumKind, Character, Language, Mood, SearchKind};
let labels = Mood::ALL.iter().map(|m| m.label())
.chain(Character::ALL.iter().map(|c| c.label()))
.chain(Language::ALL.iter().map(|l| l.label()))
.chain(SearchKind::ALL.iter().map(|k| k.label()))
.chain(AlbumKind::ALL.iter().map(|k| k.label()));
missing.extend(labels.filter(|l| ru::get(l).is_none()).map(|l| format!("ym-api label: {l}")));
missing.sort();
missing.dedup();
assert!(seen > 200, "found only {seen} strings; is the scan broken?");
assert!(missing.is_empty(), "{} strings have no Russian:\n{}", missing.len(), missing.join("\n"));
}
}
+360
View File
@@ -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,
})
}
+1
View File
@@ -1,5 +1,6 @@
mod app; mod app;
mod covers; mod covers;
mod i18n;
mod media; mod media;
mod player; mod player;
mod route; mod route;
+5 -4
View File
@@ -5,6 +5,7 @@
pub mod engine; pub mod engine;
pub mod queue; pub mod queue;
use crate::i18n::{tr, trf};
use std::sync::Arc; use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
@@ -358,7 +359,7 @@ impl Player {
Event::NoOutput(reason) => { Event::NoOutput(reason) => {
eprintln!("audio output: {reason}"); eprintln!("audio output: {reason}");
self.notice = Some( 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, Event::OutputReady => self.notice = None,
@@ -495,7 +496,7 @@ impl Player {
if wave.waiting { if wave.waiting {
wave.waiting = false; wave.waiting = false;
self.status = if self.queue.is_some() { Status::Ended } else { Status::Paused }; 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![]; return vec![];
} }
@@ -607,10 +608,10 @@ impl Player {
self.current = None; self.current = None;
if self.skips >= MAX_SKIPS { if self.skips >= MAX_SKIPS {
self.status = Status::Paused; 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![]; 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) self.step(true, false)
} }
} }
+12 -11
View File
@@ -1,6 +1,7 @@
//! Every place the content area can show. Detail pages (album, artist, playlist) //! Every place the content area can show. Detail pages (album, artist, playlist)
//! join this enum once they carry ids from the API. //! join this enum once they carry ids from the API.
use crate::i18n::tr;
use ym_api::PlaylistId; use ym_api::PlaylistId;
use crate::ui::icons::Icon; use crate::ui::icons::Icon;
@@ -28,17 +29,17 @@ impl Route {
pub fn label(self) -> &'static str { pub fn label(self) -> &'static str {
match self { match self {
Route::Home => "Home", Route::Home => tr("Home"),
Route::Wave => "My Wave", Route::Wave => tr("My Wave"),
Route::Search => "Search", Route::Search => tr("Search"),
Route::Collection => "Collection", Route::Collection => tr("Collection"),
Route::Podcasts => "Podcasts", Route::Podcasts => tr("Podcasts"),
Route::Settings => "Settings", Route::Settings => tr("Settings"),
Route::Album(_) => "Album", Route::Album(_) => tr("Album"),
Route::Artist(_) => "Artist", Route::Artist(_) => tr("Artist"),
Route::Playlist(_) => "Playlist", Route::Playlist(_) => tr("Playlist"),
Route::Chart => "Chart", Route::Chart => tr("Chart"),
Route::Genre(_) => "Genre", Route::Genre(_) => tr("Genre"),
} }
} }
+38 -29
View File
@@ -16,6 +16,7 @@ use crate::ui::{line, para};
use crate::widgets::card::{self, Card}; use crate::widgets::card::{self, Card};
use crate::widgets::track_list::{self, Env}; use crate::widgets::track_list::{self, Env};
use crate::widgets::track_row::Columns; use crate::widgets::track_row::Columns;
use crate::i18n::{tr, trf};
/// Chart rows shown on Home before "Show all". /// Chart rows shown on Home before "Show all".
const HOME_CHART: usize = 10; 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( page = page.push(
column![ 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), track_list::view(env, recent, Columns::FULL),
] ]
.spacing(14) .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() { if !h.personal.is_empty() {
page = page.push(section( page = page.push(section(
t, t,
"Made for you", tr("Made for you"),
h.personal.iter().map(|p| { h.personal.iter().map(|p| {
card::view(t, covers, Card { card::view(t, covers, Card {
title: p.playlist.title.clone(), 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( page = page.push(
column![ column![
row![ row![
line("Chart", theme::SEMIBOLD, size::SECTION, t.fg).width(Fill), line(tr("Chart"), theme::SEMIBOLD, size::SECTION, t.fg).width(Fill),
button(line(format!("Show all {}", data.chart.len()), theme::MEDIUM, size::META, t.muted)) button(line(trf("Show all {}", &[&data.chart.len()]), theme::MEDIUM, size::META, t.muted))
.padding(0) .padding(0)
.style(theme::tab(false)) .style(theme::tab(false))
.on_press(Message::Navigate(Route::Chart)), .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() { if !h.new_releases.is_empty() {
page = page.push(section( page = page.push(section(
t, t,
"New releases", tr("New releases"),
h.new_releases.iter().take(HOME_CARDS).map(|a| album_card(t, covers, a)), h.new_releases.iter().take(HOME_CARDS).map(|a| album_card(t, covers, a)),
)); ));
} }
if !h.new_playlists.is_empty() { if !h.new_playlists.is_empty() {
page = page.push(section( page = page.push(section(
t, t,
"New playlists", tr("New playlists"),
h.new_playlists.iter().take(HOME_CARDS).map(|p| playlist_card(t, covers, p)), 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)), Loadable::Failed(e) => page = page.push(status(t, LoadState::Failed(e), tr("your home page"), Message::LoadHome)),
_ => page = page.push(para("Loading your picks…", size::BODY, t.muted)), _ => page = page.push(para(tr("Loading your picks…"), size::BODY, t.muted)),
} }
page.push(genres_section(env, &discover.genres)).into() 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 t = env.t;
let body: Element<'a, Message> = match &discover.home { let body: Element<'a, Message> = match &discover.home {
Loadable::Loaded(data) if !data.chart.is_empty() => column![ 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())), track_list::view_with(env, &data.chart, Columns::CHART, Some(data.shifts.clone())),
] ]
.spacing(22) .spacing(22)
.into(), .into(),
Loadable::Loaded(_) => para("The chart is empty right now.", 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), "chart", Message::LoadHome), Loadable::Failed(e) => status(t, LoadState::Failed(e), tr("the chart"), Message::LoadHome),
_ => para("Loading the chart…", size::BODY, t.muted).into(), _ => 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<Vec<Genre>>) -> Element<'a, Message> { pub fn genres_section<'a>(env: Env<'a>, genres: &'a Loadable<Vec<Genre>>) -> Element<'a, Message> {
@@ -170,10 +171,10 @@ pub fn genres_section<'a>(env: Env<'a>, genres: &'a Loadable<Vec<Genre>>) -> Ele
let top = list.iter().enumerate().filter(|(_, g)| !is_sub_genre(list, g)); 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() 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), Loadable::Failed(e) => status(t, LoadState::Failed(e), tr("genres"), Message::LoadGenres),
_ => para("Loading genres…", size::BODY, t.muted).into(), _ => 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 { 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> { 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); let tint = g.color.as_deref().and_then(parse_hex).unwrap_or(t.raised);
button( button(
container(line(g.title.clone(), theme::SEMIBOLD, size::BODY, Color::WHITE)) // 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]) .padding([0, 16])
.align_y(iced::alignment::Vertical::Center) .align_y(iced::alignment::Vertical::Center)
.height(72) .height(72)
.width(card::WIDTH), .width(card::WIDTH)
.clip(true),
) )
.padding(0) .padding(0)
.style(move |_, status| { .style(move |_, status| {
@@ -226,12 +235,12 @@ pub fn genre<'a>(
) -> Element<'a, Message> { ) -> Element<'a, Message> {
let t = env.t; let t = env.t;
let Some(g) = genres.get(index) else { 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( let radio = button(
row![ row![
crate::ui::icons::icon(crate::ui::icons::Icon::Wave, t.accent_ink), 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) .spacing(8)
.align_y(Alignment::Center), .align_y(Alignment::Center),
@@ -263,11 +272,11 @@ pub fn genre<'a>(
let body: Element<'a, Message> = match playlists { let body: Element<'a, Message> = match playlists {
Loadable::Loaded(list) if list.is_empty() => { 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::Loaded(list) => section(t, tr("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))), Loadable::Failed(e) => status(t, LoadState::Failed(e), tr("the playlists"), Message::Navigate(Route::Genre(index))),
_ => para("Loading playlists…", size::BODY, t.muted).into(), _ => para(tr("Loading playlists…"), size::BODY, t.muted).into(),
}; };
page.push(body).into() page.push(body).into()
} }
@@ -279,20 +288,20 @@ pub fn podcasts<'a>(
) -> Element<'a, Message> { ) -> Element<'a, Message> {
let t = env.t; let t = env.t;
let covers = env.covers; 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 { if let Loadable::Loaded(albums) = liked {
let mine: Vec<&AlbumSummary> = let mine: Vec<&AlbumSummary> =
albums.iter().filter(|a| matches!(a.kind, AlbumKind::Podcast | AlbumKind::Audiobook)).collect(); albums.iter().filter(|a| matches!(a.kind, AlbumKind::Podcast | AlbumKind::Audiobook)).collect();
if !mine.is_empty() { 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 { page.push(match &discover.podcasts {
Loadable::Loaded(list) => section(t, "Featured", list.iter().map(|a| album_card(t, covers, a))), Loadable::Loaded(list) => section(t, tr("Featured"), list.iter().map(|a| album_card(t, covers, a))),
Loadable::Failed(e) => status(t, LoadState::Failed(e), "podcasts", Message::LoadPodcasts), Loadable::Failed(e) => status(t, LoadState::Failed(e), tr("podcasts"), Message::LoadPodcasts),
_ => para("Loading podcasts…", size::BODY, t.muted).into(), _ => para(tr("Loading podcasts…"), size::BODY, t.muted).into(),
}) })
.into() .into()
} }
+29 -27
View File
@@ -17,6 +17,7 @@ use crate::ui::{duration_words, line, para, tracks_word};
use crate::widgets::card::{self, Card}; use crate::widgets::card::{self, Card};
use crate::widgets::track_list::{self, Env}; use crate::widgets::track_list::{self, Env};
use crate::widgets::track_row::Columns; 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?". /// The liked-tracks list as the app holds it. Also answers "is this track liked?".
#[derive(Debug, Default)] #[derive(Debug, Default)]
@@ -96,11 +97,11 @@ impl Tab {
fn label(self) -> &'static str { fn label(self) -> &'static str {
match self { match self {
Tab::Tracks => "Liked tracks", Tab::Tracks => tr("Liked tracks"),
Tab::Albums => "Albums", Tab::Albums => tr("Albums"),
Tab::Artists => "Artists", Tab::Artists => tr("Artists"),
Tab::Playlists => "Playlists", Tab::Playlists => tr("Playlists"),
Tab::Clips => "Clips", 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::Tracks => liked_tracks(env, &library.liked),
Tab::Albums => match &library.albums { Tab::Albums => match &library.albums {
Loadable::Loaded(albums) if albums.is_empty() => { 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))), 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 { Tab::Artists => match &library.artists {
Loadable::Loaded(artists) if artists.is_empty() => { 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))), 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 { Tab::Playlists => match &library.playlists {
Loadable::Loaded(p) if p.own.is_empty() && p.liked.is_empty() => { 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) => { Loadable::Loaded(p) => {
let mut sections = column![].spacing(28); let mut sections = column![].spacing(28);
if !p.own.is_empty() { if !p.own.is_empty() {
sections = sections.push(section( sections = sections.push(section(
t, t,
"Your playlists", tr("Your playlists"),
p.own.iter().map(|pl| playlist_card(t, env.covers, pl)), p.own.iter().map(|pl| playlist_card(t, env.covers, pl)),
)); ));
} }
if !p.liked.is_empty() { if !p.liked.is_empty() {
sections = sections.push(section( sections = sections.push(section(
t, t,
"Liked playlists", tr("Liked playlists"),
p.liked.iter().map(|pl| playlist_card(t, env.covers, pl)), p.liked.iter().map(|pl| playlist_card(t, env.covers, pl)),
)); ));
} }
sections.into() 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 { Tab::Clips => match &library.clips {
Loadable::Loaded(clips) if clips.is_empty() => { 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))), 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) .spacing(24)
.width(Fill) .width(Fill)
.into() .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> { fn liked_tracks<'a>(env: Env<'a>, liked: &'a Liked) -> Element<'a, Message> {
let t = env.t; let t = env.t;
match liked { match liked {
Liked::NotLoaded | Liked::Loading => para("Loading your liked tracks…", size::BODY, t.muted).into(), Liked::NotLoaded | Liked::Loading => para(tr("Loading your liked tracks…"), size::BODY, t.muted).into(),
Liked::Failed(e) => status(t, LoadState::Failed(e), "liked tracks", Message::LoadLiked), Liked::Failed(e) => status(t, LoadState::Failed(e), tr("your liked tracks"), Message::LoadLiked),
Liked::Loaded { tracks, .. } if tracks.is_empty() => { 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, .. } => { Liked::Loaded { tracks, .. } => {
let total = tracks.iter().map(|t| t.duration).sum(); 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), container(line(summary, theme::BODY, size::META, t.muted)).width(Fill),
pill( pill(
Icon::Play, Icon::Play,
"Play", tr("Play"),
t.accent_ink, t.accent_ink,
theme::primary, theme::primary,
Message::PlayTracks { tracks: tracks.clone(), start: 0, shuffle: false }, Message::PlayTracks { tracks: tracks.clone(), start: 0, shuffle: false },
), ),
pill( pill(
Icon::Shuffle, Icon::Shuffle,
"Shuffle", tr("Shuffle"),
t.fg, t.fg,
theme::ghost, theme::ghost,
Message::PlayTracks { tracks: tracks.clone(), start: 0, shuffle: true }, 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, covers,
Card { Card {
title: a.name.clone(), 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), cover: a.cover_url(covers::LARGE),
hues: a.hues(), hues: a.hues(),
round: true, round: true,
@@ -345,22 +346,23 @@ pub enum LoadState<'a> {
Failed(&'a Error), 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> { pub fn status<'a>(t: &'static Tokens, state: LoadState<'_>, what: &str, retry: Message) -> Element<'a, Message> {
match state { 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![ LoadState::Failed(e) => column![
para( para(
match e { match e {
Error::Network(_) => { 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, size::BODY,
t.muted, 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]) .padding([11, 18])
.style(theme::primary) .style(theme::primary)
.on_press(retry), .on_press(retry),
+31 -24
View File
@@ -12,11 +12,12 @@ use crate::app::Message;
use crate::covers; use crate::covers;
use crate::route::Route; use crate::route::Route;
use crate::ui::theme::{self, size}; 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::track_list::{self, Env};
use crate::widgets::sheet::Sheet; use crate::widgets::sheet::Sheet;
use crate::widgets::track_row::Columns; use crate::widgets::track_row::Columns;
use crate::ui::icons::{Icon, icon}; 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. /// A loaded page. Tracks are split out as `Arc<[Track]>` so playing them shares the list.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
@@ -56,9 +57,9 @@ pub fn load(client: &YmClient, route: Route) -> Option<Task<Message>> {
pub fn view<'a>(env: Env<'a>, route: Route, page: &'a Loadable<Page>) -> Element<'a, Message> { pub fn view<'a>(env: Env<'a>, route: Route, page: &'a Loadable<Page>) -> Element<'a, Message> {
let t = env.t; let t = env.t;
let what = match route { let what = match route {
Route::Album(_) => "album", 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(_) => "artist", Route::Artist(_) => What { loading: tr("Loading the artist…"), gone: tr("This artist isn't available on Yandex Music any more."), retry: tr("the artist") },
_ => "playlist", _ => What { loading: tr("Loading the playlist…"), gone: tr("This playlist isn't available on Yandex Music any more."), retry: tr("the playlist") },
}; };
match page { match page {
Loadable::Loaded(Page::Album { info, tracks }) => album(env, info, tracks), 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<Page>) -> Element
Loadable::Loaded(Page::Playlist { info, tracks }) => playlist(env, info, tracks), Loadable::Loaded(Page::Playlist { info, tracks }) => playlist(env, info, tracks),
Loadable::Failed(e) => not_found_or_retry(env, e, what, route), Loadable::Failed(e) => not_found_or_retry(env, e, what, route),
Loadable::NotLoaded | Loadable::Loading => { 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 if let Error::Api(m) = e
&& m.contains("not found") && m.contains("not found")
{ {
return para(format!("This {what} isn't available on Yandex Music any more."), size::BODY, env.t.muted) return para(what.gone, size::BODY, env.t.muted).into();
.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> { 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> { fn album<'a>(env: Env<'a>, info: &'a AlbumPage, tracks: &'a Arc<[Track]>) -> Element<'a, Message> {
let a = &info.album; let a = &info.album;
let kind = match a.year { let kind = match a.year {
Some(year) => format!("{} · {year}", a.kind.label()), Some(year) => format!("{} · {year}", tr(a.kind.label())),
None => a.kind.label().to_owned(), None => tr(a.kind.label()).to_owned(),
}; };
// `info.tracks` was moved into `tracks`, so measure the list itself. // `info.tracks` was moved into `tracks`, so measure the list itself.
let length = format!("{} · {}", tracks_word(tracks.len()), duration_words(tracks.iter().map(|tr| tr.duration).sum())); let 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> { fn artist<'a>(env: Env<'a>, info: &'a ArtistPage, popular: &'a Arc<[Track]>) -> Element<'a, Message> {
let t = env.t; let t = env.t;
let a = &info.artist; 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 let meta = info
.monthly_listeners .monthly_listeners
.map(|n| format!("{} listeners a month", compact(n))) .map(|n| counted(n, ["listener a month", "listeners a month"], ["слушатель в месяц", "слушателя в месяц", "слушателей в месяц"]))
.or_else(|| a.likes.map(|n| format!("{} likes", compact(n)))) .or_else(|| a.likes.map(|n| counted(n, ["like", "likes"], ["лайк", "лайка", "лайков"])))
.unwrap_or_default(); .unwrap_or_default();
let mut page = column![ 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() { if !popular.is_empty() {
page = page.push( page = page.push(
column![ 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), play_bar(t, String::new(), popular),
track_list::view(env, popular, Columns::FULL), 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() { 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() { 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() { 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() { 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() 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), cover: p.cover_url(covers::LARGE),
hues: p.hues(), hues: p.hues(),
round: false, 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(), title: p.title.clone(),
by: Some(line(p.owner_name.clone(), theme::MEDIUM, size::BODY, t.fg).into()), by: Some(line(p.owner_name.clone(), theme::MEDIUM, size::BODY, t.fg).into()),
meta: format!("{} · {}", tracks_word(tracks.len()), duration_words(total)), meta: format!("{} · {}", tracks_word(tracks.len()), duration_words(total)),
actions: if own { actions: if own {
vec![ 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( pill(
t, t,
if p.public { Icon::Lock } else { Icon::Globe }, 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), 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 { } else {
vec![like_button(t, env.likes.playlists.contains(&p.id), Message::LikePlaylist(p.id, !env.likes.playlists.contains(&p.id)))] 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)); page = page.push(container(para(description.clone(), size::BODY, t.muted)).max_width(640));
} }
if tracks.is_empty() { 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 { let list = if own {
track_list::view_own_playlist(env, tracks, p.id) track_list::view_own_playlist(env, tracks, p.id)
+23 -10
View File
@@ -21,6 +21,7 @@ use crate::ui::theme::{self, Tokens, size, space as sp};
use crate::ui::{line, para}; use crate::ui::{line, para};
use crate::widgets::sidebar; use crate::widgets::sidebar;
use crate::widgets::track_list::Env; 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. /// Something fetched from the API: not asked for yet, on its way, here, or failed.
#[derive(Debug, Default)] #[derive(Debug, Default)]
@@ -118,9 +119,9 @@ fn account_card<'a>(t: &'static Tokens, me: &'a Account) -> Element<'a, Message>
.style(theme::avatar); .style(theme::avatar);
let plan = match (me.has_plus, me.subscription_end.as_deref().and_then(human_date)) { let plan = match (me.has_plus, me.subscription_end.as_deref().and_then(human_date)) {
(true, Some(end)) => format!("Yandex Plus until {end}"), (true, Some(end)) => trf("Yandex Plus until {}", &[&end]),
(true, None) => "Yandex Plus".to_owned(), (true, None) => tr("Yandex Plus").to_owned(),
(false, _) => "No Plus subscription. Tracks play as 30-second previews.".to_owned(), (false, _) => tr("No Plus subscription. Tracks play as 30-second previews.").to_owned(),
}; };
container( container(
@@ -134,7 +135,7 @@ fn account_card<'a>(t: &'static Tokens, me: &'a Account) -> Element<'a, Message>
.spacing(4) .spacing(4)
.width(Fill), .width(Fill),
button( 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) .spacing(8)
.align_y(Alignment::Center), .align_y(Alignment::Center),
) )
@@ -151,16 +152,25 @@ fn account_card<'a>(t: &'static Tokens, me: &'a Account) -> Element<'a, Message>
.into() .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<String> { pub fn human_date(iso: &str) -> Option<String> {
const MONTHS: [&str; 12] = [ const MONTHS: [&str; 12] = [
"January", "February", "March", "April", "May", "June", "July", "August", "September", "January", "February", "March", "April", "May", "June", "July", "August", "September",
"October", "November", "December", "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 date = iso.get(..10)?;
let mut parts = date.split('-'); let mut parts = date.split('-');
let (y, m, d) = (parts.next()?, parts.next()?, parts.next()?); let (y, m, d) = (parts.next()?, parts.next()?, parts.next()?);
let month = MONTHS.get(m.parse::<usize>().ok()?.checked_sub(1)?)?; let month = months.get(m.parse::<usize>().ok()?.checked_sub(1)?)?;
let day: u32 = d.parse().ok()?; let day: u32 = d.parse().ok()?;
y.parse::<u32>().ok()?; y.parse::<u32>().ok()?;
Some(format!("{day} {month} {y}")) Some(format!("{day} {month} {y}"))
@@ -185,19 +195,19 @@ pub fn unreachable<'a>(t: &'static Tokens) -> Element<'a, Message> {
container( container(
column![ column![
sidebar::wordmark(t), 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( 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, 15.0,
t.muted, t.muted,
)) ))
.max_width(440), .max_width(440),
row![ 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]) .padding([11, 18])
.style(theme::primary) .style(theme::primary)
.on_press(Message::Restore), .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]) .padding([11, 18])
.style(theme::ghost) .style(theme::ghost)
.on_press(Message::SignOut), .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("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-12-31").as_deref(), Some("31 December 2026"));
assert_eq!(human_date("2026-13-01"), None); 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); assert_eq!(human_date("soon"), None);
} }
} }
+18 -17
View File
@@ -21,6 +21,7 @@ use crate::ui::{compact, line, para};
use crate::widgets::card; use crate::widgets::card;
use crate::widgets::track_list::{self, Env}; use crate::widgets::track_list::{self, Env};
use crate::widgets::track_row::Columns; use crate::widgets::track_row::Columns;
use crate::i18n::{tr, trf};
/// Wait this long after the last keystroke before asking for suggestions. /// Wait this long after the last keystroke before asking for suggestions.
const DEBOUNCE: Duration = Duration::from_millis(250); 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> { pub fn view<'a>(env: Env<'a>, search: &'a Search, browse: Element<'a, Message>) -> Element<'a, Message> {
let t = env.t; let t = env.t;
if search.query.is_empty() { 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| { 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); .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 { let body: Element<'a, Message> = match &search.results {
Loadable::Loaded(r) if r.data.is_empty() => para( 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, size::BODY,
t.muted, t.muted,
) )
.into(), .into(),
Loadable::Loaded(r) => results(env, search, r), Loadable::Loaded(r) => results(env, search, r),
Loadable::Failed(e) => status(t, LoadState::Failed(e), "results", Message::Search(Msg::Submit)), Loadable::Failed(e) => status(t, LoadState::Failed(e), tr("the results"), Message::Search(Msg::Submit)),
_ => para("Searching…", size::BODY, t.muted).into(), _ => para(tr("Searching…"), size::BODY, t.muted).into(),
}; };
let mut page = column![title].spacing(24); let mut page = column![title].spacing(24);
if let Some(corrected) = search.results.get().and_then(|r| r.data.corrected.as_ref()) { 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() 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 covers = env.covers;
let d = &r.data; let d = &r.data;
let more = search.has_more(r).then(|| { 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]) .padding([10, 18])
.style(theme::ghost) .style(theme::ghost)
.on_press_maybe((!r.loading_more).then_some(Message::Search(Msg::More))) .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( all = all.push(
column![ column![
row![ row![
line("Tracks", theme::SEMIBOLD, size::SECTION, t.fg).width(Fill), line(tr("Tracks"), theme::SEMIBOLD, size::SECTION, t.fg).width(Fill),
button(line("Show all", theme::MEDIUM, size::META, t.muted)) button(line(tr("Show all"), theme::MEDIUM, size::META, t.muted))
.padding(0) .padding(0)
.style(theme::tab(false)) .style(theme::tab(false))
.on_press(Message::Search(Msg::Tab(SearchKind::Tracks))), .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() { 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() { 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() { 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() { 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() all.into()
} }
@@ -315,7 +316,7 @@ fn best_card<'a>(env: Env<'a>, best: &'a BestMatch) -> Element<'a, Message> {
let t = env.t; let t = env.t;
let (cover, hues, round, title, kind, action) = match best { let (cover, hues, round, title, kind, action) = match best {
BestMatch::Artist(a) => ( 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)), Message::Navigate(Route::Artist(a.id)),
), ),
BestMatch::Album(a) => ( 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)), Message::Navigate(Route::Album(a.id)),
), ),
BestMatch::Playlist(p) => ( 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)), Message::Navigate(Route::Playlist(p.id)),
), ),
BestMatch::Track(tr) => ( 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 }, 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![ row![
covers::view(env.covers, cover, hues, size_px, corner), covers::view(env.covers, cover, hues, size_px, corner),
column![ 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(title, theme::DISPLAY, 24.0, t.fg),
line(kind, theme::BODY, size::META, t.muted), line(kind, theme::BODY, size::META, t.muted),
] ]
+13 -8
View File
@@ -3,10 +3,11 @@
use iced::widget::{Row, button, column, container, row}; use iced::widget::{Row, button, column, container, row};
use iced::{Alignment, Element, Fill}; use iced::{Alignment, Element, Fill};
use crate::app::Message; 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::icons::{Icon, icon};
use crate::ui::theme::{self, Tokens, size}; use crate::ui::theme::{self, Tokens, size};
use crate::ui::{line, para}; 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> { 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)))) 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 = let appearance =
Row::with_children(Appearance::ALL.map(|a| chip(t, a.label(), a == settings.appearance, Message::SetAppearance(a)))) Row::with_children(Appearance::ALL.map(|a| chip(t, a.label(), a == settings.appearance, Message::SetAppearance(a))))
.spacing(6); .spacing(6);
let language =
Row::with_children(Locale::ALL.map(|l| chip(t, l.label(), l == settings.language, Message::SetLanguage(l))))
.spacing(6);
column![ column![
line("Settings", theme::DISPLAY, size::DISPLAY_S, t.fg), line(tr("Settings"), theme::DISPLAY, size::DISPLAY_S, t.fg),
account, account,
section(t, "Streaming quality", column![quality, para(settings.quality.detail(), size::META, t.muted)].spacing(10).into()), section(t, tr("Streaming quality"), column![quality, para(settings.quality.detail(), size::META, t.muted)].spacing(10).into()),
section(t, "Appearance", appearance.into()), section(t, tr("Appearance"), appearance.into()),
section(t, tr("Language"), language.into()),
section( section(
t, t,
"Storage", tr("Storage"),
column![ column![
para( 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, size::META,
t.muted, 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]) .padding([9, 16])
.style(theme::ghost) .style(theme::ghost)
.on_press(Message::ClearCoverCache), .on_press(Message::ClearCoverCache),
@@ -37,7 +42,7 @@ pub fn view<'a>(t: &'static Tokens, settings: &Settings, account: Element<'a, Me
.spacing(12) .spacing(12)
.into(), .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) .spacing(28)
.width(Fill) .width(Fill)
+27 -31
View File
@@ -13,6 +13,7 @@ use crate::ui::icons::{Icon, icon};
use crate::ui::theme::{self, Tokens, radius, size}; use crate::ui::theme::{self, Tokens, radius, size};
use crate::ui::{line, para}; use crate::ui::{line, para};
use crate::widgets::sidebar; use crate::widgets::sidebar;
use crate::i18n::{tr, trf};
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum Msg { pub enum Msg {
@@ -74,7 +75,7 @@ impl SignIn {
/// Shown after a pasted token turned out to be invalid. /// Shown after a pasted token turned out to be invalid.
pub fn rejected_token() -> Self { pub fn rejected_token() -> Self {
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, token_open: true,
..Self::default() ..Self::default()
} }
@@ -158,10 +159,7 @@ impl SignIn {
if let Stage::Waiting(w) = &self.stage if let Stage::Waiting(w) = &self.stage
&& open::that_detached(&w.code.verification_url).is_err() && open::that_detached(&w.code.verification_url).is_err()
{ {
self.error = Some(format!( self.error = Some(trf("Couldn't open your browser. Go to {} yourself.", &[&w.code.verification_url]));
"Couldn't open your browser. Go to {} yourself.",
w.code.verification_url
));
} }
} }
Msg::ToggleToken => self.token_open = !self.token_open, Msg::ToggleToken => self.token_open = !self.token_open,
@@ -199,7 +197,7 @@ impl SignIn {
let left = column![ let left = column![
sidebar::wordmark(t), sidebar::wordmark(t),
container( container(
iced::widget::text("Sign in with your Yandex account") iced::widget::text(tr("Sign in with your Yandex account"))
.font(theme::DISPLAY) .font(theme::DISPLAY)
.size(size::DISPLAY_M) .size(size::DISPLAY_M)
.line_height(1.12) .line_height(1.12)
@@ -207,8 +205,7 @@ impl SignIn {
) )
.max_width(520), .max_width(520),
container(para( container(para(
"Musyx plays your Yandex Music library, My Wave and playlists. You confirm sign-in \ 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."),
on Yandex's own page, so your password never passes through this app.",
15.0, 15.0,
t.muted, t.muted,
)) ))
@@ -217,8 +214,7 @@ impl SignIn {
self.token_fallback(t), self.token_fallback(t),
space().height(Fill), space().height(Fill),
container(para( container(para(
"Musyx is an unofficial client and isn't affiliated with Yandex. Your sign-in \ tr("Musyx is an unofficial client and isn't affiliated with Yandex. Your sign-in token is kept in the system keychain."),
token is kept in the system keychain.",
size::SMALL, size::SMALL,
t.muted, t.muted,
)) ))
@@ -256,10 +252,10 @@ impl SignIn {
let content: Element<'a, Msg> = match &self.stage { let content: Element<'a, Msg> = match &self.stage {
Stage::Idle => column![ Stage::Idle => column![
primary(t, "Get sign-in code", Some(Msg::GetCode)), primary(t, tr("Get sign-in code"), Some(Msg::GetCode)),
] ]
.into(), .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), 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)) container(line(spaced(&w.code.user_code), theme::DISPLAY, 30.0, t.fg))
.padding([14, 18]) .padding([14, 18])
.style(theme::card), .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) .spacing(14)
.align_y(Alignment::Center); .align_y(Alignment::Center);
@@ -289,13 +285,13 @@ impl SignIn {
let status = row![ let status = row![
container(space()).width(9).height(9).style(theme::accent_dot), container(space()).width(9).height(9).style(theme::accent_dot),
line( 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, theme::BODY,
13.5, 13.5,
t.muted, t.muted,
), ),
space().width(12), space().width(12),
button(line("Cancel", theme::MEDIUM, 13.5, t.muted)) button(line(tr("Cancel"), theme::MEDIUM, 13.5, t.muted))
.padding(0) .padding(0)
.style(theme::tab(false)) .style(theme::tab(false))
.on_press(Msg::Cancel), .on_press(Msg::Cancel),
@@ -305,17 +301,17 @@ impl SignIn {
column![ column![
step(t, 1, column![ step(t, 1, column![
line(format!("Open {host}"), theme::MEDIUM, size::BODY, t.fg), line(trf("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), para(tr("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), ghost(t, Icon::Globe, tr("Open in browser"), Msg::OpenPage),
].spacing(6)), ].spacing(6)),
step(t, 2, column![ 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, code_box,
].spacing(10)), ].spacing(10)),
step(t, 3, column![ step(t, 3, column![
line("Come back here", theme::MEDIUM, size::BODY, t.fg), line(tr("Come back here"), theme::MEDIUM, size::BODY, t.fg),
para("Musyx signs you in as soon as you allow access.", 13.5, t.muted), para(tr("Musyx signs you in as soon as you allow access."), 13.5, t.muted),
].spacing(4)), ].spacing(4)),
status, status,
] ]
@@ -325,7 +321,7 @@ impl SignIn {
fn token_fallback<'a>(&'a self, t: &'static Tokens) -> Element<'a, Msg> { fn token_fallback<'a>(&'a self, t: &'static Tokens) -> Element<'a, Msg> {
let toggle = button(line( 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, theme::BODY,
13.5, 13.5,
t.muted, t.muted,
@@ -342,7 +338,7 @@ impl SignIn {
column![ column![
toggle, toggle,
row![ row![
text_input("Paste OAuth token", &self.token) text_input(tr("Paste OAuth token"), &self.token)
.id("token") .id("token")
.secure(true) .secure(true)
.on_input(Msg::TokenChanged) .on_input(Msg::TokenChanged)
@@ -350,7 +346,7 @@ impl SignIn {
.padding([10, 14]) .padding([10, 14])
.width(320) .width(320)
.style(theme::search_field), .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]) .padding([10, 18])
.style(theme::ghost) .style(theme::ghost)
.on_press_maybe(can_submit.then_some(Msg::UseToken)), .on_press_maybe(can_submit.then_some(Msg::UseToken)),
@@ -376,13 +372,13 @@ impl SignIn {
background: iced::Color::WHITE, background: iced::Color::WHITE,
}) })
.into(), .into(),
"Scan to open the sign-in page", tr("Scan to open the sign-in page"),
), ),
None => ( None => (
container(icon(Icon::Lock, iced::Color::from_rgb8(0x68, 0x61, 0x78))) container(icon(Icon::Lock, iced::Color::from_rgb8(0x68, 0x61, 0x78)))
.center(200) .center(200)
.into(), .into(),
"A QR code appears with your sign-in code", tr("A QR code appears with your sign-in code"),
), ),
}; };
container( container(
@@ -411,11 +407,11 @@ impl SignIn {
/// The user's next step for each failure. Never shows the raw error. /// The user's next step for each failure. Never shows the raw error.
fn describe(error: &Error) -> &'static str { fn describe(error: &Error) -> &'static str {
match error { match error {
Error::CodeExpired => "The code expired before it was confirmed. Get a new code to try again.", Error::CodeExpired => tr("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::Denied => tr("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::Network(_) => tr("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::Unauthorized(_) => tr("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::Api(_) => tr("Yandex sent an unexpected answer. Try again in a moment."),
} }
} }
+21 -18
View File
@@ -14,6 +14,7 @@ use crate::ui::icons::{Icon, icon};
use crate::ui::theme::{self, Tokens, radius, size}; use crate::ui::theme::{self, Tokens, radius, size};
use crate::ui::{line, para}; use crate::ui::{line, para};
use crate::widgets::card; use crate::widgets::card;
use crate::i18n::{tr, trf};
/// Everything the My Wave screen shows. /// Everything the My Wave screen shows.
#[derive(Debug, Default)] #[derive(Debug, Default)]
@@ -89,24 +90,26 @@ pub fn hero<'a>(
.height(Fill); .height(Fill);
let blurb = match settings { let blurb = match settings {
Some(s) if s != WaveSettings::default() => format!( Some(s) if s != WaveSettings::default() => trf(
"Tuned to: {} mood, {} tracks, {} language.", "Tuned to: {} mood, {} tracks, {} language.",
s.mood.label().to_lowercase(), &[
s.character.label().to_lowercase(), &tr(s.mood.label()).to_lowercase(),
s.language.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 { let (label, glyph, msg) = match state {
Some(Status::Playing | Status::Loading) => ("Pause", Icon::Pause, Message::Player(player::Msg::Toggle)), Some(Status::Playing | Status::Loading) => (tr("Pause"), Icon::Pause, Message::Player(player::Msg::Toggle)),
Some(_) => ("Resume", Icon::Play, Message::Player(player::Msg::Toggle)), Some(_) => (tr("Resume"), Icon::Play, Message::Player(player::Msg::Toggle)),
None => ("Play My Wave", Icon::Play, Message::PlayWave(MY_WAVE.to_owned())), None => (tr("Play My Wave"), Icon::Play, Message::PlayWave(MY_WAVE.to_owned())),
}; };
let content = row![ let content = row![
column![ 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), container(para(blurb, size::BODY, t.muted)).max_width(420),
] ]
.spacing(6) .spacing(6)
@@ -151,24 +154,24 @@ pub fn view<'a>(
(_, Some(s)) => { (_, Some(s)) => {
let saving = screen.saving.is_some(); let saving = screen.saving.is_some();
row![ row![
setting(t, "Mood", Mood::ALL.map(|m| (m.label(), m == s.mood, WaveSettings { mood: m, ..s })), saving), setting(t, tr("Mood"), Mood::ALL.map(|m| (tr(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, tr("Character"), Character::ALL.map(|c| (tr(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("Language"), Language::ALL.map(|l| (tr(l.label()), l == s.language, WaveSettings { language: l, ..s })), saving),
] ]
.spacing(28) .spacing(28)
.wrap() .wrap()
.vertical_spacing(18) .vertical_spacing(18)
.into() .into()
} }
(Loadable::Failed(e), None) => status(t, LoadState::Failed(e), "station settings", Message::LoadWave), (Loadable::Failed(e), None) => status(t, LoadState::Failed(e), tr("your station settings"), Message::LoadWave),
_ => para("Loading your settings…", size::BODY, t.muted).into(), _ => para(tr("Loading your settings…"), size::BODY, t.muted).into(),
}; };
let stations: Element<'a, Message> = match &screen.stations { let stations: Element<'a, Message> = match &screen.stations {
Loadable::Loaded(list) => { Loadable::Loaded(list) => {
let others: Vec<&Station> = list.iter().filter(|s| s.id != MY_WAVE).collect(); let others: Vec<&Station> = list.iter().filter(|s| s.id != MY_WAVE).collect();
if others.is_empty() { 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 { } else {
Row::with_children(others.into_iter().map(|s| station_tile(t, covers, s))) Row::with_children(others.into_iter().map(|s| station_tile(t, covers, s)))
.spacing(12) .spacing(12)
@@ -177,14 +180,14 @@ pub fn view<'a>(
.into() .into()
} }
} }
Loadable::Failed(e) => status(t, LoadState::Failed(e), "stations", Message::LoadWave), Loadable::Failed(e) => status(t, LoadState::Failed(e), tr("stations"), Message::LoadWave),
_ => para("Loading stations…", size::BODY, t.muted).into(), _ => para(tr("Loading stations…"), size::BODY, t.muted).into(),
}; };
column![ column![
hero, hero,
settings, 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) .spacing(34)
.into() .into()
+3 -2
View File
@@ -77,10 +77,11 @@ pub async fn restore() -> Restored {
credentials 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), Ok((client, account)) => Restored::SignedIn(client, account),
Err(Error::Unauthorized(_)) => match refresh(&credentials).await { 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), Ok((client, account)) => Restored::SignedIn(client, account),
Err(e) => forget(e).await, Err(e) => forget(e).await,
}, },
+6 -2
View File
@@ -2,7 +2,7 @@
//! //!
//! ```sh //! ```sh
//! MUSYX_SNAPSHOT=home.png MUSYX_SNAPSHOT_ROUTE=wave MUSYX_SNAPSHOT_DRAWER=queue \ //! 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. //! 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 ym_api::{Account, YmClient};
use crate::app::Session; use crate::app::Session;
use crate::i18n::Lang;
use crate::route::Route; use crate::route::Route;
use crate::widgets::drawer::Panel; use crate::widgets::drawer::Panel;
@@ -29,6 +30,8 @@ pub struct Config {
pub mode: Option<Mode>, pub mode: Option<Mode>,
/// `MUSYX_SNAPSHOT_LIVE=1`: sign in with the stored account instead of sample data. /// `MUSYX_SNAPSHOT_LIVE=1`: sign in with the stored account instead of sample data.
pub live: bool, pub live: bool,
/// `MUSYX_SNAPSHOT_LANG=ru` or `en` overrides the language setting.
pub lang: Option<Lang>,
/// `MUSYX_SNAPSHOT_DELAY` in ms before capturing (default 1500; live runs need longer). /// `MUSYX_SNAPSHOT_DELAY` in ms before capturing (default 1500; live runs need longer).
pub delay: Duration, pub delay: Duration,
} }
@@ -62,11 +65,12 @@ impl Config {
"dark" => Some(Mode::Dark), "dark" => Some(Mode::Dark),
_ => None, _ => 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 live = var("MUSYX_SNAPSHOT_LIVE").is_some_and(|v| v == "1");
let delay = var("MUSYX_SNAPSHOT_DELAY") let delay = var("MUSYX_SNAPSHOT_DELAY")
.and_then(|d| d.parse().ok()) .and_then(|d| d.parse().ok())
.map_or(Duration::from_millis(if live { 8000 } else { 1500 }), Duration::from_millis); .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. /// A made-up account so the shell renders without a network or keychain.
+47 -14
View File
@@ -1,6 +1,7 @@
//! Preferences kept between launches, as JSON in the platform config folder //! Preferences kept between launches, as JSON in the platform config folder
//! (`~/Library/Application Support/Musyx/settings.json` on macOS). //! (`~/Library/Application Support/Musyx/settings.json` on macOS).
use crate::i18n::{Lang, tr};
use std::path::PathBuf; use std::path::PathBuf;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@@ -25,22 +26,21 @@ impl Quality {
pub fn label(self) -> &'static str { pub fn label(self) -> &'static str {
match self { match self {
Quality::Lossless => "Lossless", Quality::Lossless => tr("Lossless"),
Quality::Best => "Best", Quality::Best => tr("Best"),
Quality::Balanced => "Balanced", Quality::Balanced => tr("Balanced"),
Quality::DataSaver => "Data saver", Quality::DataSaver => tr("Data saver"),
} }
} }
pub fn detail(self) -> &'static str { pub fn detail(self) -> &'static str {
match self { match self {
Quality::Lossless => { Quality::Lossless => {
"FLAC when Yandex offers it for your subscription and region, otherwise the best it allows. \ 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.")
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::Best => tr("Highest MP3 bitrate Yandex offers, up to 320 kbps."),
Quality::Balanced => "Up to 192 kbps. About 40% less data.", Quality::Balanced => tr("Up to 192 kbps. About 40% less data."),
Quality::DataSaver => "Up to 128 kbps, for slow or metered connections.", Quality::DataSaver => tr("Up to 128 kbps, for slow or metered connections."),
} }
} }
@@ -69,9 +69,41 @@ impl Appearance {
pub fn label(self) -> &'static str { pub fn label(self) -> &'static str {
match self { match self {
Appearance::System => "Match system", Appearance::System => tr("Match system"),
Appearance::Light => "Light", Appearance::Light => tr("Light"),
Appearance::Dark => "Dark", 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 struct Settings {
pub quality: Quality, pub quality: Quality,
pub appearance: Appearance, pub appearance: Appearance,
pub language: Locale,
pub volume: f32, pub volume: f32,
} }
impl Default for Settings { impl Default for Settings {
fn default() -> Self { 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] #[test]
fn settings_round_trip_and_tolerate_missing_fields() { 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(); let json = serde_json::to_string(&s).unwrap();
assert!(json.contains("\"data-saver\""), "{json}"); assert!(json.contains("\"data-saver\""), "{json}");
assert_eq!(serde_json::to_string(&Quality::Lossless).unwrap(), "\"lossless\""); assert_eq!(serde_json::to_string(&Quality::Lossless).unwrap(), "\"lossless\"");
+42 -8
View File
@@ -5,6 +5,8 @@ use iced::widget::{Text, text};
use iced::widget::text::Wrapping; use iced::widget::text::Wrapping;
use iced::{Color, Font}; use iced::{Color, Font};
use crate::i18n::{self, Lang, trf};
/// Single-line text in the given face; long values are clipped by their container. /// 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> { 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) 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". /// "47 min" or "1 h 12 min".
pub fn duration_words(d: std::time::Duration) -> String { pub fn duration_words(d: std::time::Duration) -> String {
let mins = d.as_secs() / 60; 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". /// "1 track", "12 tracks".
pub fn tracks_word(n: usize) -> String { 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 { pub fn compact(n: i64) -> String {
match n { let (value, en, ru) = match n {
n if n >= 1_000_000 => format!("{:.1}M", n as f64 / 1e6).replace(".0M", "M"), n if n >= 1_000_000 => (format!("{:.1}", n as f64 / 1e6), "M", " млн"),
n if n >= 10_000 => format!("{}K", n / 1000), n if n >= 10_000 => ((n / 1000).to_string(), "K", " тыс."),
n if n >= 1_000 => format!("{:.1}K", n as f64 / 1e3).replace(".0K", "K"), n if n >= 1_000 => (format!("{:.1}", n as f64 / 1e3), "K", " тыс."),
n => n.to_string(), 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)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -52,5 +70,21 @@ mod tests {
assert_eq!(compact(830_412), "830K"); assert_eq!(compact(830_412), "830K");
assert_eq!(compact(1_250), "1.2K"); assert_eq!(compact(1_250), "1.2K");
assert_eq!(compact(912), "912"); 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);
} }
} }
+14 -13
View File
@@ -15,6 +15,7 @@ use crate::ui::icons::{Icon, icon};
use crate::ui::theme::{self, Tokens, radius, shell, size}; use crate::ui::theme::{self, Tokens, radius, shell, size};
use crate::widgets::player_bar::clock; use crate::widgets::player_bar::clock;
use crate::ui::{line, para}; use crate::ui::{line, para};
use crate::i18n::{tr, trf};
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Panel { pub enum Panel {
@@ -25,8 +26,8 @@ pub enum Panel {
impl Panel { impl Panel {
fn label(self) -> &'static str { fn label(self) -> &'static str {
match self { match self {
Panel::Queue => "Queue", Panel::Queue => tr("Queue"),
Panel::Lyrics => "Lyrics", Panel::Lyrics => tr("Lyrics"),
} }
} }
} }
@@ -57,20 +58,20 @@ pub fn view<'a>(
let body: Element<'a, Message> = match (panel, player.queue()) { let body: Element<'a, Message> = match (panel, player.queue()) {
(Panel::Queue, Some(queue)) => queue_list(t, queue, covers), (Panel::Queue, Some(queue)) => queue_list(t, queue, covers),
(Panel::Queue, None) => container(para( (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, size::META,
t.muted, t.muted,
)) ))
.padding([4, 20]) .padding([4, 20])
.into(), .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 { (Panel::Lyrics, Some(_)) => match lyrics {
Some(Loadable::Loaded(Some(l))) => lyrics_view(t, l, player.position()), 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![ 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( 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]) .padding([9, 16])
.style(theme::primary) .style(theme::primary)
.on_press(Message::RetryLyrics), .on_press(Message::RetryLyrics),
@@ -79,7 +80,7 @@ pub fn view<'a>(
] ]
.spacing(12) .spacing(12)
.into(), .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); let mut list = Column::with_children(lines).spacing(2);
if !l.writers.is_empty() { if !l.writers.is_empty() {
list = list.push( 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)), .padding(iced::Padding::default().top(18).left(8).right(8)),
); );
} }
@@ -163,18 +164,18 @@ fn queue_list<'a>(t: &'static Tokens, queue: &'a Queue<Track>, covers: &Covers)
}; };
let remaining = queue.upcoming().count(); 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 { list = list.push(heading(if remaining == 0 {
"Nothing after this".into() tr("Nothing after this").into()
} else { } else {
format!("Next up · {remaining}") trf("Next up · {}", &[&remaining])
})); }));
for (pos, track) in queue.upcoming().take(SHOWN) { for (pos, track) in queue.upcoming().take(SHOWN) {
list = list.push(item(track, false, Some(Message::Player(Msg::JumpTo(pos))))); list = list.push(item(track, false, Some(Message::Player(Msg::JumpTo(pos)))));
} }
if remaining > SHOWN { if remaining > SHOWN {
list = list.push( 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]), .padding([10, 8]),
); );
} }
+4 -3
View File
@@ -10,6 +10,7 @@ use crate::ui::icons::{Icon, icon, sized};
use crate::ui::line; use crate::ui::line;
use crate::ui::theme::{self, Tokens, radius, size}; use crate::ui::theme::{self, Tokens, radius, size};
use crate::widgets::drawer::Panel; use crate::widgets::drawer::Panel;
use crate::i18n::tr;
fn send(msg: Msg) -> Message { fn send(msg: Msg) -> Message {
Message::Player(msg) Message::Player(msg)
@@ -42,8 +43,8 @@ fn now_playing<'a>(t: &'static Tokens, p: &'a Player, liked: bool, covers: &Cove
..Default::default() ..Default::default()
}); });
let (title, sub) = match &p.notice { let (title, sub) = match &p.notice {
Some(notice) => ("Can't play", notice.as_str()), Some(notice) => (tr("Can't play"), notice.as_str()),
None => ("Nothing playing", "Pick a track to start"), None => (tr("Nothing playing"), tr("Pick a track to start")),
}; };
return row![ return row![
blank, blank,
@@ -180,7 +181,7 @@ fn extras<'a>(t: &'static Tokens, p: &'a Player, drawer: Option<Panel>) -> Eleme
let mut items = row![].spacing(4).align_y(Alignment::Center); let mut items = row![].spacing(4).align_y(Alignment::Center);
if let Some(stream) = p.stream() { 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 }; 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)); items = items.push(container(line(label, theme::MEDIUM, 11.5, ink)).padding([2, 6]).style(theme::badge));
} }
+26 -25
View File
@@ -9,6 +9,7 @@ use crate::route::Route;
use crate::ui::icons::{Icon, icon}; use crate::ui::icons::{Icon, icon};
use crate::ui::theme::{self, Tokens, radius, size}; use crate::ui::theme::{self, Tokens, radius, size};
use crate::ui::{line, para}; use crate::ui::{line, para};
use crate::i18n::{tr, trf};
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum Sheet { 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 } => { Sheet::Track { track, playlist, choosing: false } => {
let mut items: Vec<Element<'a, Message>> = vec![ let mut items: Vec<Element<'a, Message>> = vec![
if ctx.playing { if ctx.playing {
item(t, Icon::Next, "Next track", Some(Message::SkipFromMenu)) item(t, Icon::Next, tr("Next track"), Some(Message::SkipFromMenu))
} else { } 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( item(
t, t,
if ctx.liked { Icon::HeartFilled } else { Icon::Heart }, 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)), Some(Message::LikeTrack(track.clone(), !ctx.liked)),
), ),
item( item(
t, t,
Icon::Plus, Icon::Plus,
"Add to playlist…", tr("Add to playlist…"),
Some(Message::OpenSheet(Sheet::Track { track: track.clone(), playlist: *playlist, choosing: true })), 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 { 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) { for artist in track.artists.iter().filter(|a| a.id.is_some()).take(3) {
items.push(item( items.push(item(
t, t,
Icon::Forward, Icon::Forward,
"Go to artist", tr("Go to artist"),
artist.id.map(|id| Message::Navigate(Route::Artist(id))), artist.id.map(|id| Message::Navigate(Route::Artist(id))),
)); ));
} }
items.push(item( items.push(item(
t, t,
Icon::Dislike, 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)), Some(Message::DislikeTrack(track.clone(), !ctx.disliked)),
)); ));
if let Some((id, index, len)) = *playlist { if let Some((id, index, len)) = *playlist {
items.push(divider()); items.push(divider());
if index > 0 { 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, id, track: track.clone(), from: index, to: index - 1,
}))); })));
} }
if index + 1 < len { 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, 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()) 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<Element<'a, Message>> = vec![item( let mut items: Vec<Element<'a, Message>> = vec![item(
t, t,
Icon::Plus, Icon::Plus,
"New playlist…", tr("New playlist…"),
Some(Message::OpenSheet(Sheet::NewPlaylist { name: String::new(), add: Some(track.clone()) })), Some(Message::OpenSheet(Sheet::NewPlaylist { name: String::new(), add: Some(track.clone()) })),
)]; )];
items.extend(ctx.own_playlists.iter().map(|p| { 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( frame(
t, t,
"Add to playlist".into(), tr("Add to playlist").into(),
Some(track.full_title()), Some(track.full_title()),
iced::widget::scrollable(Column::with_children(items).spacing(2)).height(Length::Shrink).into(), iced::widget::scrollable(Column::with_children(items).spacing(2)).height(Length::Shrink).into(),
) )
} }
Sheet::NewPlaylist { name, add } => { Sheet::NewPlaylist { name, add } => {
let can = !name.trim().is_empty(); 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( frame(
t, t,
"New playlist".into(), tr("New playlist").into(),
None, None,
column![ 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), 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) .spacing(14)
.into(), .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(); let can = !name.trim().is_empty();
frame( frame(
t, t,
"Rename playlist".into(), tr("Rename playlist").into(),
None, None,
column![ column![
input("Playlist name", name, can.then_some(Message::RenamePlaylist)), input(tr("Playlist name"), name, can.then_some(Message::RenamePlaylist)),
actions(t, "Rename", can.then_some(Message::RenamePlaylist), false), actions(t, tr("Rename"), can.then_some(Message::RenamePlaylist), false),
] ]
.spacing(14) .spacing(14)
.into(), .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( Sheet::ConfirmDelete { id, title } => frame(
t, t,
format!("Delete “{title}”?"), trf("Delete “{}”?", &[title]),
None, None,
column![ column![
para("The playlist and its track order go away for good. The tracks stay in Yandex Music.", size::BODY, t.muted), para(tr("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), actions(t, tr("Delete"), Some(Message::DeletePlaylist(*id)), true),
] ]
.spacing(16) .spacing(16)
.into(), .into(),
@@ -240,7 +241,7 @@ fn actions<'a>(t: &'static Tokens, confirm: &'a str, msg: Option<Message>, dange
}; };
row![ row![
space().width(Fill), 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, confirm,
] ]
.spacing(8) .spacing(8)
+6 -5
View File
@@ -11,6 +11,7 @@ use crate::route::Route;
use crate::ui::icons::{Icon, icon}; use crate::ui::icons::{Icon, icon};
use crate::ui::theme::{self, Tokens, radius, shell, size}; use crate::ui::theme::{self, Tokens, radius, shell, size};
use crate::ui::{line, para}; use crate::ui::{line, para};
use crate::i18n::tr;
pub fn view<'a>( pub fn view<'a>(
t: &'static Tokens, t: &'static Tokens,
@@ -23,7 +24,7 @@ pub fn view<'a>(
.spacing(2); .spacing(2);
let playlists_head = row![ let playlists_head = row![
line("Playlists", theme::MEDIUM, size::SMALL, t.muted), line(tr("Playlists"), theme::MEDIUM, size::SMALL, t.muted),
space().width(Fill), space().width(Fill),
button(icon(Icon::Plus, t.muted)) button(icon(Icon::Plus, t.muted))
.padding(4) .padding(4)
@@ -57,10 +58,10 @@ pub fn view<'a>(
.style(theme::scroll) .style(theme::scroll)
.into() .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)) .padding(Padding::default().left(10).right(10))
.into(), .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)) .padding(Padding::default().left(10).right(10))
.into(), .into(),
}; };
@@ -112,9 +113,9 @@ fn account<'a>(t: &'static Tokens, current: Route, account: &'a Account) -> Elem
.style(theme::avatar); .style(theme::avatar);
let (plan, plan_colour) = if account.has_plus { let (plan, plan_colour) = if account.has_plus {
("Plus subscription", t.ok) (tr("Plus subscription"), t.ok)
} else { } else {
("No Plus: 30-second previews", t.muted) (tr("No Plus: 30-second previews"), t.muted)
}; };
let settings_active = current == Route::Settings; let settings_active = current == Route::Settings;
+2 -1
View File
@@ -7,6 +7,7 @@ use crate::app::Message;
use crate::screens::search::Msg; use crate::screens::search::Msg;
use crate::ui::icons::{Icon, icon}; use crate::ui::icons::{Icon, icon};
use crate::ui::theme::{self, Tokens, size, space}; use crate::ui::theme::{self, Tokens, size, space};
use crate::i18n::tr;
pub const SEARCH_ID: &str = "search"; 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)) .style(theme::icon_button(None))
.on_press_maybe(can_go_back.then_some(Message::Back)); .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) .id(SEARCH_ID)
.on_input(|text| Message::Search(Msg::Changed(text))) .on_input(|text| Message::Search(Msg::Changed(text)))
.on_submit(Message::Search(Msg::Submit)) .on_submit(Message::Search(Msg::Submit))
+2
View File
@@ -36,6 +36,7 @@ struct Key {
liked: u64, liked: u64,
dark: bool, dark: bool,
playlist: Option<PlaylistId>, playlist: Option<PlaylistId>,
lang: crate::i18n::Lang,
} }
pub fn view<'a>(env: Env<'a>, tracks: &Arc<[Track]>, columns: Columns) -> Element<'a, Message> { 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(), liked: liked.version(),
dark: t == &theme::DARK, dark: t == &theme::DARK,
playlist, playlist,
lang: crate::i18n::lang(),
}; };
let tracks = tracks.clone(); let tracks = tracks.clone();
+3 -2
View File
@@ -10,6 +10,7 @@ use crate::ui::icons::{Icon, icon, sized};
use crate::ui::line; use crate::ui::line;
use crate::ui::theme::{self, Tokens, size}; use crate::ui::theme::{self, Tokens, size};
use crate::widgets::player_bar::clock; use crate::widgets::player_bar::clock;
use crate::i18n::tr;
pub const HEIGHT: f32 = 52.0; pub const HEIGHT: f32 = 52.0;
@@ -132,9 +133,9 @@ pub fn header(t: &'static Tokens, columns: Columns) -> Element<'static, Message>
if columns.cover { if columns.cover {
heads = heads.push(space().width(40)); 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 { 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 heads = heads
.push(space().width(34)) .push(space().width(34))
+35 -2
View File
@@ -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 { impl YmClient {
/// Builds a client for `credentials` and loads the account. Fails with /// Builds a client for `credentials` and loads the account. Fails with
/// [`crate::Error::Unauthorized`] when the token is no longer valid. /// [`crate::Error::Unauthorized`] when the token is no longer valid.
pub async fn connect(credentials: &Credentials) -> Result<(Self, Account)> { pub async fn connect(credentials: &Credentials, language: ContentLanguage) -> Result<(Self, Account)> {
let inner = yamuse::Client::builder().token(&credentials.access_token).build()?; let inner = yamuse::Client::builder()
.token(&credentials.access_token)
.language(language.yamuse())
.build()?;
let status = inner.refresh_account().await?; let status = inner.refresh_account().await?;
let account = Account::from_status(status) let account = Account::from_status(status)
.ok_or_else(|| Error::Unauthorized("account status has no user".into()))?; .ok_or_else(|| Error::Unauthorized("account status has no user".into()))?;
Ok((Self { inner, token: Some(credentials.access_token.as_str().into()) }, account)) 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<Self> {
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. /// A client with no token, for previews and tests. Every account call fails.
pub fn unauthenticated() -> Result<Self> { pub fn unauthenticated() -> Result<Self> {
Ok(Self { inner: yamuse::Client::anonymous()?, token: None }) Ok(Self { inner: yamuse::Client::anonymous()?, token: None })
+1 -1
View File
@@ -13,7 +13,7 @@ mod library;
mod models; mod models;
mod wave; mod wave;
pub use client::{Account, YmClient}; pub use client::{Account, ContentLanguage, YmClient};
pub use clips::Clip; pub use clips::Clip;
pub use library::{ pub use library::{
AlbumKind, AlbumPage, AlbumSummary, ArtistPage, ArtistSummary, LibraryPlaylists, PlaylistId, AlbumKind, AlbumPage, AlbumSummary, ArtistPage, ArtistSummary, LibraryPlaylists, PlaylistId,
+3
View File
@@ -16,6 +16,9 @@ pub enum AlbumKind {
} }
impl 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 { fn from_api(meta_type: Option<&str>, kind: Option<&str>) -> Self {
match (meta_type, kind) { match (meta_type, kind) {
(Some("podcast"), _) | (_, Some("podcast")) => AlbumKind::Podcast, (Some("podcast"), _) | (_, Some("podcast")) => AlbumKind::Podcast,
+2
View File
@@ -37,6 +37,8 @@ cat > "$bundle/Contents/Info.plist" <<PLIST
<key>CFBundleName</key><string>Musyx</string> <key>CFBundleName</key><string>Musyx</string>
<key>CFBundleDisplayName</key><string>Musyx</string> <key>CFBundleDisplayName</key><string>Musyx</string>
<key>CFBundleIdentifier</key><string>dev.musyx.desktop</string> <key>CFBundleIdentifier</key><string>dev.musyx.desktop</string>
<key>CFBundleDevelopmentRegion</key><string>en</string>
<key>CFBundleLocalizations</key><array><string>en</string><string>ru</string></array>
<key>CFBundleExecutable</key><string>Musyx</string> <key>CFBundleExecutable</key><string>Musyx</string>
<key>CFBundleIconFile</key><string>Musyx</string> <key>CFBundleIconFile</key><string>Musyx</string>
<key>CFBundlePackageType</key><string>APPL</string> <key>CFBundlePackageType</key><string>APPL</string>