diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1b36f97..4dd839b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,6 +23,10 @@ jobs: steps: - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.x' + - name: System libraries (Linux) if: runner.os == 'Linux' run: | @@ -40,6 +44,10 @@ jobs: shell: bash run: cargo test --release --locked 2>&1 | tee test.log + - name: Test locale scaffolder + shell: bash + run: python scripts/test_new_locale.py + # downloads the pinned ffmpeg for this system, checks its checksum, unpacks it and runs # it: proves the build list and the binary work on a real Windows / macOS / Linux machine - name: Download and run the bundled ffmpeg diff --git a/.gitignore b/.gitignore index 6fd8364..de78b69 100644 --- a/.gitignore +++ b/.gitignore @@ -11,3 +11,7 @@ # local state (never commit personal data) *.log /tubeglass-backup*.json + +# Python locale tooling +__pycache__/ +*.pyc diff --git a/Cargo.toml b/Cargo.toml index a8458fe..e792f47 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,6 +24,9 @@ serde_json = "1.0.154" sha2 = "0.11.1" ureq = { version = "3.4.2", features = ["json"] } +[build-dependencies] +serde_json = "1.0.154" + # media keys and "now playing" over D-Bus exist on Linux only [target.'cfg(target_os = "linux")'.dependencies] zbus = "5.19.0" diff --git a/README.md b/README.md index b70e295..c579821 100644 --- a/README.md +++ b/README.md @@ -399,6 +399,21 @@ CI runs the same on Linux, Windows and macOS. Please keep commits focused with a *what* changed and *why*. If you find a video that will not play, include its link and the output of **Settings → Check YouTube access**. +### Translating the interface + +Choose a UI language in Settings. System follows the system locale and falls back to English. +The UI language is separate from YouTube content and captions. + +Run `python scripts/new-locale.py CODE "Language name"` to scaffold a catalog, or edit an +existing file in `locales/`. Keep the English keys and the names and counts of placeholders +such as `{count}`. Use `{{` and `}}` for literal braces. Blank or missing translations fall +back to English. When adding a UI string, add its key to `locales/en.json` and translate it +in `locales/id.json`. + +Run `python scripts/new-locale.py --coverage` to check coverage, +`python scripts/test_new_locale.py` to test the scaffolder, and +`cargo test --release --locked` to validate catalogs and placeholder rendering. + ## Releasing 1. Raise `version` in `Cargo.toml` and commit it. diff --git a/build.rs b/build.rs index f2568d3..1d40cf3 100644 --- a/build.rs +++ b/build.rs @@ -1,12 +1,337 @@ -//! Build script: gives the Windows executable its icon. Nothing happens on other systems. +//! Build script: validates UI catalogs, embeds them, and gives Windows its icon. + +#[path = "src/locale_format.rs"] +mod locale_format; fn main() { + println!("cargo:rerun-if-changed=locales"); + println!("cargo:rerun-if-changed=src/ui"); + println!("cargo:rerun-if-changed=src/app"); + println!("cargo:rerun-if-changed=src/util.rs"); + println!("cargo:rerun-if-changed=src/locale_format.rs"); + generate_locale_manifest(); println!("cargo:rerun-if-changed=packaging/windows/tubeglass.ico"); if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") { embed_windows_icon(); } } +/// Discover catalogs without requiring new languages to be registered in Rust code. +fn generate_locale_manifest() { + let dir = std::path::Path::new("locales"); + let out = std::path::PathBuf::from(std::env::var_os("OUT_DIR").unwrap()).join("locales.rs"); + let mut catalogs = std::fs::read_dir(dir) + .into_iter() + .flatten() + .flatten() + .map(|entry| entry.path()) + .filter(|path| path.extension().is_some_and(|ext| ext == "json")) + .collect::>(); + catalogs.sort(); + validate_catalogs(&catalogs); + let mut generated = String::from("pub static CATALOG_SOURCES: &[(&str, &str)] = &[\n"); + for path in catalogs { + println!("cargo:rerun-if-changed={}", path.display()); + let Some(code) = path.file_stem().and_then(|stem| stem.to_str()) else { + continue; + }; + generated.push_str(&format!( + " ({code:?}, include_str!({:?})),\n", + path.canonicalize() + .unwrap_or_else(|_| path.clone()) + .display() + .to_string() + )); + } + generated.push_str("];\n"); + std::fs::write(out, generated).expect("write locale manifest"); +} + +/// Catch untranslated literal `tr("...")` calls during every build. +fn validate_catalogs(catalogs: &[std::path::PathBuf]) { + let locale_sources = catalogs + .iter() + .map(|path| { + ( + path, + serde_json::from_str::>( + &std::fs::read_to_string(path).expect("read locale catalog"), + ).unwrap_or_else(|error| panic!("invalid catalog {}: {error}", path.display())), + ) + }) + .collect::>(); + let english = locale_sources + .iter() + .find(|(path, _)| path.file_stem().is_some_and(|stem| stem == "en")) + .map(|(_, source)| source) + .expect("locales/en.json is required"); + let english_keys = english.keys().cloned().collect::>(); + for (key, value) in english { + if key == "__language_name" { continue; } + assert!(!value.trim().is_empty(), "English source value is blank for {key:?}"); + let names = locale_format::placeholder_names(key) + .unwrap_or_else(|error| panic!("invalid English source key {key:?}: {error}")); + let translated = locale_format::placeholder_names(value) + .unwrap_or_else(|error| panic!("invalid English source value for {key:?}: {error}")); + assert_eq!(names, translated, "English placeholders differ for {key:?}"); + } + for (path, catalog) in &locale_sources { + for (key, value) in catalog { + if key == "__language_name" { continue; } + let source = english.get(key).unwrap_or_else(|| { + panic!("{} contains unknown translation key {key:?}", path.display()) + }); + if !value.trim().is_empty() { + let expected = locale_format::placeholder_names(source).unwrap(); + let actual = locale_format::placeholder_names(value).unwrap_or_else(|error| { + panic!("invalid placeholders in {} for {key:?}: {error}", path.display()) + }); + assert_eq!(expected, actual, "invalid placeholders in {} for {key:?}", path.display()); + } + } + } + + let mut source_files = ["src/ui", "src/app"] + .into_iter() + .flat_map(|directory| { + std::fs::read_dir(directory) + .expect("read UI source directory") + .flatten() + .map(|entry| entry.path()) + .filter(|path| path.extension().is_some_and(|ext| ext == "rs")) + .collect::>() + }) + .collect::>(); + source_files.push(std::path::PathBuf::from("src/util.rs")); + source_files.sort(); + for source_path in source_files { + let source = std::fs::read_to_string(&source_path).expect("read UI source file"); + let mut keys = Vec::new(); + for call in ["tr", "trf"] { + for args in call_arguments(&source, call) { + if let Some(key) = args.first().and_then(|arg| string_literal(arg)) { + keys.push(key); + } + } + } + // These helpers translate their label/hint arguments internally. Keep their + // literal call-site keys checked even though the call does not spell `tr(...)`. + for (call, indexes) in [("row", &[1usize, 2][..]), ("section", &[1][..]), ("ask", &[2, 3][..])] { + for args in call_arguments(&source, call) { + for index in indexes { + if let Some(key) = args.get(*index).and_then(|arg| string_literal(arg)) { + if !key.is_empty() { + keys.push(key); + } + } + } + } + } + keys.sort_unstable(); + keys.dedup(); + for key in keys { + if !english_keys.contains(&key) { + panic!( + "locales/en.json is missing source key {key:?} used in {}", + source_path.display() + ); + } + } + + // Static strings passed directly to egui text sinks are a common source of + // English-only UI regressions. Require those literals to go through tr/trf. + let sinks: &[(&str, &[usize])] = &[ + ("RichText::new", &[0]), + ("Button::new", &[0]), + ("ui.button", &[0]), + ("ui.small_button", &[0]), + ("ui.menu_button", &[0]), + ("ui.link", &[0]), + ("ui.label", &[0]), + ("ui.colored_label", &[1]), + ("ui.selectable_label", &[1]), + (".on_hover_text", &[0]), + ("Window::new", &[0]), + (".set_title", &[0]), + (".set_description", &[0]), + (".add_filter", &[0]), + ("toast", &[0]), + ("text_field", &[2, 6]), + ("icon_btn", &[2]), + ("icon_label", &[3]), + ("pill_button", &[1]), + (".text", &[2]), + ]; + for (call, indexes) in sinks { + for args in call_arguments(&source, call) { + for index in *indexes { + if let Some(value) = args.get(*index).and_then(|arg| string_literal(arg)) { + let neutral = value.is_empty() + || value == "TubeGlass" + || value == "◌" + || value == "●" + || value.starts_with("https://"); + if !neutral { + panic!( + "untranslated UI literal {value:?} in {}; use tr/trf", + source_path.display() + ); + } + } + } + } + } + + // A full-text source audit catches app-authored phrases stored in label tables or + // formatted branches before they reach a widget through a variable. Provider content, + // operating-system error fragments, and shortcut glyphs are intentionally excluded. + if source_path == std::path::Path::new("src/util.rs") + || (source_path.starts_with("src/ui") && source_path.file_name().is_some_and(|name| name == "i18n.rs")) { + continue; + } + for value in string_literals(&source) { + let human_text = value.chars().next().is_some_and(char::is_alphabetic) + && value.chars().any(char::is_whitespace); + if !human_text || is_non_ui_literal(&value) { + continue; + } + if !english_keys.contains(&value) { + panic!( + "locales/en.json is missing source string {value:?} from {}", + source_path.display() + ); + } + } + } +} + +fn string_literals(source: &str) -> Vec { + let mut values = Vec::new(); + for line in source.lines() { + let bytes = line.as_bytes(); + let mut i = 0; + let mut in_string = false; + let mut escaped = false; + let mut start = 0; + while i < bytes.len() { + let c = bytes[i] as char; + if in_string { + if escaped { + escaped = false; + } else if c == '\\' { + escaped = true; + } else if c == '"' { + values.push(line[start + 1..i].replace("\\\"", "\"").replace("\\n", "\n").replace("\\t", "\t")); + in_string = false; + } + } else if c == '/' && bytes.get(i + 1) == Some(&b'/') { + break; + } else if c == '"' { + start = i; + in_string = true; + } + i += 1; + } + } + values +} + +fn is_non_ui_literal(value: &str) -> bool { + matches!( + value, + "opening input" + | "Input/output error" + | "Server returned" + | "channel not found" + | "Space / K" + | "← →" + | "J / L" + | "↑ ↓" + | "[ / ]" + | "N / P" + ) || value.starts_with("[recover]") + || value.starts_with("[gapless]") +} + +/// Split a Rust call's top-level arguments without treating nested calls or strings as separators. +fn call_arguments<'a>(source: &'a str, name: &str) -> Vec> { + let token = format!("{name}("); + let mut result = Vec::new(); + let mut search = 0; + while let Some(relative) = source[search..].find(&token) { + let start = search + relative; + let body_start = start + token.len(); + let mut i = body_start; + let mut depth = 1usize; + let mut in_string = false; + let mut escaped = false; + while i < source.len() && depth > 0 { + let c = source.as_bytes()[i] as char; + if in_string { + if escaped { + escaped = false; + } else if c == '\\' { + escaped = true; + } else if c == '"' { + in_string = false; + } + } else if c == '"' { + in_string = true; + } else if c == '(' { + depth += 1; + } else if c == ')' { + depth -= 1; + } + i += 1; + } + if depth != 0 { + break; + } + let body_end = i - 1; + let body = &source[body_start..body_end]; + let mut args = Vec::new(); + let mut arg_start = 0; + let mut nested = 0usize; + let mut in_string = false; + let mut escaped = false; + for (offset, byte) in body.bytes().enumerate() { + let c = byte as char; + if in_string { + if escaped { + escaped = false; + } else if c == '\\' { + escaped = true; + } else if c == '"' { + in_string = false; + } + } else if c == '"' { + in_string = true; + } else if matches!(c, '(' | '[' | '{') { + nested += 1; + } else if matches!(c, ')' | ']' | '}') { + nested = nested.saturating_sub(1); + } else if c == ',' && nested == 0 { + args.push(body[arg_start..offset].trim()); + arg_start = offset + 1; + } + } + if !body[arg_start..].trim().is_empty() { + args.push(body[arg_start..].trim()); + } + result.push(args); + search = i; + } + result +} + +fn string_literal(expression: &str) -> Option { + let expression = expression.trim(); + if !expression.starts_with('"') || !expression.ends_with('"') || expression.len() < 2 { + return None; + } + Some(expression[1..expression.len() - 1].replace("\\\"", "\"").replace("\\n", "\n").replace("\\t", "\t")) +} + #[cfg(windows)] fn embed_windows_icon() { let mut res = winresource::WindowsResource::new(); diff --git a/locales/en.json b/locales/en.json new file mode 100644 index 0000000..68c5c5f --- /dev/null +++ b/locales/en.json @@ -0,0 +1,554 @@ +{ + "Settings": "Settings", + "PLAYBACK": "PLAYBACK", + "Default quality": "Default quality", + "Used whenever a video starts": "Used whenever a video starts", + "Resume where you left off": "Resume where you left off", + "Videos you have watched reopen at the same place": "Videos you have watched reopen at the same place", + "Ambient mode": "Ambient mode", + "A soft glow of the video's colours around the picture": "A soft glow of the video's colours around the picture", + "Gapless playback": "Gapless playback", + "Songs in a queue run into each other with no pause": "Songs in a queue run into each other with no pause", + "Crossfade": "Crossfade", + "Blend the end of a song into the next (needs gapless)": "Blend the end of a song into the next (needs gapless)", + "Autoplay next in queue": "Autoplay next in queue", + "Move on to the next item when one ends": "Move on to the next item when one ends", + "Skip sponsor segments": "Skip sponsor segments", + "Uses the community SponsorBlock database": "Uses the community SponsorBlock database", + "AUDIO": "AUDIO", + "Equalizer": "Equalizer", + "Presets or your own bass / mid / treble": "Presets or your own bass / mid / treble", + "Vocal": "Vocal", + "Treble": "Treble", + "Bass": "Bass", + "Flat": "Flat", + "Even out volume": "Even out volume", + "Quiet parts are lifted so songs and videos feel equally loud": "Quiet parts are lifted so songs and videos feel equally loud", + "Skip silence": "Skip silence", + "Cuts long pauses in spoken audio (not for music; the time shown runs a little ahead)": "Cuts long pauses in spoken audio (not for music; the time shown runs a little ahead)", + "STORAGE": "STORAGE", + "Downloads": "Downloads", + "Clips": "Clips", + "Thumbnails and avatars": "Thumbnails and avatars", + "Saved feeds": "Saved feeds", + "Free on this disk": "Free on this disk", + "Finished downloads": "Finished downloads", + "Videos and songs you have already watched or listened to all the way": "Videos and songs you have already watched or listened to all the way", + "Downloads older than 30 days": "Downloads older than 30 days", + "Frees the most space when you download a lot": "Frees the most space when you download a lot", + "Downloads older than 90 days": "Downloads older than 90 days", + "Confirm": "Confirm", + "Delete…": "Delete…", + "OFFLINE": "OFFLINE", + "Save captions and lyrics with downloads": "Save captions and lyrics with downloads", + "So subtitles and lyrics also work without a connection": "So subtitles and lyrics also work without a connection", + "CAPTIONS": "CAPTIONS", + "Show captions by default": "Show captions by default", + "When a video has them": "When a video has them", + "Preferred language": "Preferred language", + "Language code, for example en, es, fr": "Language code, for example en, es, fr", + "DOWNLOADS": "DOWNLOADS", + "Folder": "Folder", + "Choose…": "Choose…", + "Reset": "Reset", + "APPEARANCE": "APPEARANCE", + "Theme": "Theme", + "Dark, light, or follow the system (the video page stays dark)": "Dark, light, or follow the system (the video page stays dark)", + "System": "System", + "Light": "Light", + "Dark": "Dark", + "Text size": "Text size", + "Scales the whole interface": "Scales the whole interface", + "Density": "Density", + "How big and how far apart video cards are": "How big and how far apart video cards are", + "Spacious": "Spacious", + "Comfortable": "Comfortable", + "Compact": "Compact", + "Accent colour": "Accent colour", + "Pick a preset or mix your own": "Pick a preset or mix your own", + "custom": "custom", + "SUBSCRIPTIONS": "SUBSCRIPTIONS", + "Import": "Import", + "NewPipe export, YouTube Takeout CSV, OPML, or a list of links": "NewPipe export, YouTube Takeout CSV, OPML, or a list of links", + "Import…": "Import…", + "Export": "Export", + "Saves a NewPipe-compatible subscriptions file": "Saves a NewPipe-compatible subscriptions file", + "Export…": "Export…", + "NOTIFICATIONS": "NOTIFICATIONS", + "Notify me": "Notify me", + "Live streams by default. Right-click a channel to also get new uploads, or to mute it": "Live streams by default. Right-click a channel to also get new uploads, or to mute it", + "DATA": "DATA", + "Back up everything": "Back up everything", + "Channels, playlists, history, liked songs, groups and settings in one file": "Channels, playlists, history, liked songs, groups and settings in one file", + "Back up…": "Back up…", + "Restore a backup": "Restore a backup", + "Replaces what is here with the file's contents, then restarts": "Replaces what is here with the file's contents, then restarts", + "Restore…": "Restore…", + "Check for updates automatically": "Check for updates automatically", + "Looks at the project's GitHub releases now and then (nothing else is sent)": "Looks at the project's GitHub releases now and then (nothing else is sent)", + "Check for updates now": "Check for updates now", + "Check now": "Check now", + "ffmpeg": "ffmpeg", + "Everything plays through it. In use: {ffmpeg}": "Everything plays through it. In use: {ffmpeg}", + "Download a fresh copy": "Download a fresh copy", + "Check YouTube access": "Check YouTube access", + "Tests search, playback, comments and music, to see what broke if something stops working": "Tests search, playback, comments and music, to see what broke if something stops working", + "Run check": "Run check", + "Clear image cache": "Clear image cache", + "Thumbnails and avatars are downloaded again when needed": "Thumbnails and avatars are downloaded again when needed", + "Clear watch history": "Clear watch history", + "Also forgets where you left each video": "Also forgets where you left each video", + "Interface language": "Interface language", + "Choose the language used for TubeGlass controls": "Choose the language used for TubeGlass controls", + "Use system language": "Use system language", + "English": "English", + "Indonesian": "Indonesian", + "Home": "Home", + "Live now": "Live now", + "Music": "Music", + "Podcasts": "Podcasts", + "History": "History", + "Insights": "Insights", + "Open file…": "Open file…", + "LIBRARY": "LIBRARY", + "PLAYLISTS": "PLAYLISTS", + "New playlist": "New playlist", + "Import playlists from YouTube": "Import playlists from YouTube", + "Expand sidebar (Ctrl+B)": "Expand sidebar (Ctrl+B)", + "Collapse sidebar (Ctrl+B)": "Collapse sidebar (Ctrl+B)", + "Add": "Add", + "Clear": "Clear", + "@handle or link": "@handle or link", + "__language_name": "English", + "+ New group…": "+ New group…", + "+ New playlist…": "+ New playlist…", + "Add to queue": "Add to queue", + "Audio only (m4a)": "Audio only (m4a)", + "Cancel": "Cancel", + "Clip this moment…": "Clip this moment…", + "Delete clip": "Delete clip", + "Delete group": "Delete group", + "Delete playlist": "Delete playlist", + "Download": "Download", + "Download audio only": "Download audio only", + "End of this video": "End of this video", + "Keyboard shortcuts": "Keyboard shortcuts", + "Look up lyrics anyway": "Look up lyrics anyway", + "Mark as played": "Mark as played", + "Not interested": "Not interested", + "Open folder": "Open folder", + "Open the full transcript": "Open the full transcript", + "Open the source video": "Open the source video", + "Play": "Play", + "Play audio only": "Play audio only", + "Play next": "Play next", + "Preview": "Preview", + "Recommend less from this channel": "Recommend less from this channel", + "Remove channel": "Remove channel", + "Remove from history": "Remove from history", + "Remove from this playlist": "Remove from this playlist", + "Show folder": "Show folder", + "Turn off": "Turn off", + " • about {time} left": " • about {time} left", + " • {speed} MB/s": " • {speed} MB/s", + "(you have {version})": "(you have {version})", + "Add {time}": "Add {time}", + "Add a note at this moment": "Add a note at this moment", + "Add to group": "Add to group", + "Add to playlist": "Add to playlist", + "Added": "Added", + "Added to Watch later": "Added to Watch later", + "All files": "All files", + "Ambient mode (B)": "Ambient mode (B)", + "Ambient mode on": "Ambient mode on", + "Ambient mode off": "Ambient mode off", + "Any length": "Any length", + "Any time": "Any time", + "Audio": "Audio", + "Audio downloaded": "Audio downloaded", + "Audio only (A)": "Audio only (A)", + "Audio only (A)": "Audio only (A)", + "Back (Alt+←)": "Back (Alt+←)", + "Back online": "Back online", + "Back up TubeGlass": "Back up TubeGlass", + "Backup saved to {path}": "Backup saved to {path}", + "Because you like {title}": "Because you like {title}", + "Bookmark": "Bookmark", + "Buffering": "Buffering", + "CHANNELS": "CHANNELS", + "CLIPS OF THIS VIDEO": "CLIPS OF THIS VIDEO", + "Can't play this video": "Can't play this video", + "Captions unavailable: {error}": "Captions unavailable: {error}", + "Clip": "Clip", + "Clip cancelled": "Clip cancelled", + "Clip saved": "Clip saved", + "Clip {start}–{end}": "Clip {start}–{end}", + "Close": "Close", + "Comments": "Comments", + "Confirm clear": "Confirm clear", + "Confirm delete ({count})": "Confirm delete ({count})", + "Confirm unsubscribe": "Confirm unsubscribe", + "Could not download “{title}”": "Could not download “{title}”", + "Could not import {id}: {error}": "Could not import {id}: {error}", + "Could not load YouTube Music: {error}": "Could not load YouTube Music: {error}", + "Could not load live streams: {error}": "Could not load live streams: {error}", + "Could not load playlist: {error}": "Could not load playlist: {error}", + "Could not load the transcript: {error}": "Could not load the transcript: {error}", + "Could not load this tab: {error}": "Could not load this tab: {error}", + "Could not load: {error}": "Could not load: {error}", + "Could not open the channel: {error}": "Could not open the channel: {error}", + "Could not restore: {error}": "Could not restore: {error}", + "Could not save the backup: {error}": "Could not save the backup: {error}", + "Create": "Create", + "Cut a piece out of this video and save it as a file.": "Cut a piece out of this video and save it as a file.", + "Cutting… {percent}% • about {time} left": "Cutting… {percent}% • about {time} left", + "Delete ({count})": "Delete ({count})", + "Description": "Description", + "Dismiss": "Dismiss", + "Done": "Done", + "Download ({downloaded}/{total})": "Download ({downloaded}/{total})", + "Download all ({downloaded}/{total})": "Download all ({downloaded}/{total})", + "Download failed: {error}": "Download failed: {error}", + "Download folder": "Download folder", + "Download folder updated": "Download folder updated", + "Download video": "Download video", + "Downloaded": "Downloaded", + "Downloading TubeGlass {version}…": "Downloading TubeGlass {version}…", + "Downloading {count} item": "Downloading {count} item", + "Downloading {count} items": "Downloading {count} items", + "Everything is already downloaded": "Everything is already downloaded", + "Export subscriptions": "Export subscriptions", + "Exported {count} channels": "Exported {count} channels", + "Filter channels": "Filter channels", + "Following": "Following", + "Following {name}": "Following {name}", + "GIFs get big fast; 20 seconds or less works best.": "GIFs get big fast; 20 seconds or less works best.", + "GROUPS": "GROUPS", + "Get ffmpeg": "Get ffmpeg", + "Group channels, e.g. Music or News. Right-click a channel to add it.": "Group channels, e.g. Music or News. Right-click a channel to add it.", + "Group name, e.g. Music": "Group name, e.g. Music", + "Hidden from your recommendations": "Hidden from your recommendations", + "Hide": "Hide", + "Hide for now": "Hide for now", + "Image cache cleared (restart to refetch avatars)": "Image cache cleared (restart to refetch avatars)", + "Import subscriptions": "Import subscriptions", + "Imported {count} channel": "Imported {count} channel", + "Imported {count} channels": "Imported {count} channels", + "Imported “{name}” with {count} videos": "Imported “{name}” with {count} videos", + "Importing… {count} left": "Importing… {count} left", + "JSON": "JSON", + "Jump back in": "Jump back in", + "Keep every item of this playlist downloaded, including ones added later": "Keep every item of this playlist downloaded, including ones added later", + "Kept offline": "Kept offline", + "LATEST EPISODES": "LATEST EPISODES", + "LIVE": "LIVE", + "Latest from your channels": "Latest from your channels", + "Length {time}": "Length {time}", + "Like this song": "Like this song", + "Liked songs": "Liked songs", + "Links": "Links", + "Live streams can't be clipped.": "Live streams can't be clipped.", + "Load more comments": "Load more comments", + "Lyrics": "Lyrics", + "Lyrics are only looked up for YouTube songs.": "Lyrics are only looked up for YouTube songs.", + "Lyrics: {source}": "Lyrics: {source}", + "Mark all as played": "Mark all as played", + "Mark all as seen": "Mark all as seen", + "NEW": "NEW", + "New from artists you follow": "New from artists you follow", + "New group": "New group", + "No channels match.": "No channels match.", + "No clips yet.": "No clips yet.", + "No downloads match your search.": "No downloads match your search.", + "No playlist link found yet. Private playlists cannot be imported.": "No playlist link found yet. Private playlists cannot be imported.", + "No podcasts found.": "No podcasts found.", + "No podcasts yet.": "No podcasts yet.", + "Notes": "Notes", + "Notes ({count})": "Notes ({count})", + "Notes and bookmarks you add show up here and as dots on the seek bar.": "Notes and bookmarks you add show up here and as dots on the seek bar.", + "Nothing downloaded yet. Use the Download button in the player, or right-click any video.": "Nothing downloaded yet. Use the Download button in the player, or right-click any video.", + "Nothing found.": "Nothing found.", + "Nothing here yet. Add a channel above to get started.": "Nothing here yet. Add a channel above to get started.", + "Nothing in the queue can be saved as a playlist": "Nothing in the queue can be saved as a playlist", + "Notifications": "Notifications", + "Off": "Off", + "Open a video, choose the Clip tab (or “Clip this moment…” in the … menu) and save a section.": "Open a video, choose the Clip tab (or “Clip this moment…” in the … menu) and save a section.", + "Open downloads": "Open downloads", + "Open media file": "Open media file", + "Open the release page": "Open the release page", + "Opening the video…": "Opening the video…", + "Opening {name}…": "Opening {name}…", + "Ordered by what you watch and listen to": "Ordered by what you watch and listen to", + "Paste one or more playlist links (or ids). Each becomes a playlist you can edit, download and keep offline.": "Paste one or more playlist links (or ids). Each becomes a playlist you can edit, download and keep offline.", + "Paused": "Paused", + "Play all": "Play all", + "Play audio only (A)": "Play audio only (A)", + "Play latest": "Play latest", + "Play some songs and your own picks will appear here.": "Play some songs and your own picks will appear here.", + "Play this clip": "Play this clip", + "Playing next": "Playing next", + "Playlist": "Playlist", + "Playlist name": "Playlist name", + "Podcast": "Podcast", + "Queue": "Queue", + "Queue ({count})": "Queue ({count})", + "RECENT SEARCHES": "RECENT SEARCHES", + "REPEAT": "REPEAT", + "Refresh": "Refresh", + "Refreshing {done} / {total}": "Refreshing {done} / {total}", + "Related": "Related", + "Related videos are only available for YouTube videos.": "Related videos are only available for YouTube videos.", + "Remove from Watch later": "Remove from Watch later", + "Removed {count} download, freed {size}": "Removed {count} download, freed {size}", + "Removed {count} downloads, freed {size}": "Removed {count} downloads, freed {size}", + "Replay": "Replay", + "Replies": "Replies", + "Restart now": "Restart now", + "Restore backup": "Restore backup", + "Results for “{query}”": "Results for “{query}”", + "Results for “{query}” • {videos} videos, {playlists} playlists": "Results for “{query}” • {videos} videos, {playlists} playlists", + "Resume": "Resume", + "Retry": "Retry", + "SEGMENTS": "SEGMENTS", + "SLEEP TIMER": "SLEEP TIMER", + "Save as playlist": "Save as playlist", + "Save clip": "Save clip", + "Saved": "Saved", + "Saved queue ({count} item)": "Saved queue ({count} item)", + "Saved queue ({count} items)": "Saved queue ({count} items)", + "Saved to {path}": "Saved to {path}", + "Saved {name}": "Saved {name}", + "Saved “{name}” with {count} videos": "Saved “{name}” with {count} videos", + "Saved “{name}” — find it under Playlists": "Saved “{name}” — find it under Playlists", + "Search": "Search", + "Search YouTube — videos and channels": "Search YouTube — videos and channels", + "Search above, or paste a podcast's feed address (RSS) or its Apple Podcasts link.": "Search above, or paste a podcast's feed address (RSS) or its Apple Podcasts link.", + "Search downloads": "Search downloads", + "Search failed: {error}": "Search failed: {error}", + "Search in {channel}": "Search in {channel}", + "Search podcasts, or paste a feed or Apple Podcasts link": "Search podcasts, or paste a feed or Apple Podcasts link", + "Search songs, albums, artists": "Search songs, albums, artists", + "Search the transcript": "Search the transcript", + "Search this list": "Search this list", + "Searching “{query}”…": "Searching “{query}”…", + "Select": "Select", + "Select none": "Select none", + "Setting up ffmpeg (once, about 30 MB) so video and audio can play…": "Setting up ffmpeg (once, about 30 MB) so video and audio can play…", + "Showing {shown} of {total} episodes": "Showing {shown} of {total} episodes", + "Shuffle": "Shuffle", + "Shuffle the queue": "Shuffle the queue", + "Skip this version": "Skip this version", + "Skipped {category}": "Skipped {category}", + "Sleep timer set": "Sleep timer set", + "Sleep timer: playback paused": "Sleep timer: playback paused", + "Sleep timer: stopped after this video": "Sleep timer: stopped after this video", + "Something went wrong on this page (details are in crash.log)": "Something went wrong on this page (details are in crash.log)", + "Songs": "Songs", + "Sort: {value}": "Sort: {value}", + "Source video": "Source video", + "Speed {speed}×": "Speed {speed}×", + "Start": "Start", + "Stats": "Stats", + "Stops after this video": "Stops after this video", + "Stops in {time}": "Stops in {time}", + "Subscribed": "Subscribed", + "Subscriptions": "Subscriptions", + "That playlist has no videos (or it is private)": "That playlist has no videos (or it is private)", + "The queue is empty.": "The queue is empty.", + "This doesn't look like a song, so lyrics are not looked up automatically.": "This doesn't look like a song, so lyrics are not looked up automatically.", + "This replaces your current channels, playlists, history and settings with the backup, then restarts TubeGlass.": "This replaces your current channels, playlists, history and settings with the backup, then restarts TubeGlass.", + "This video has no captions, so there is no transcript.": "This video has no captions, so there is no transcript.", + "Transcript": "Transcript", + "Translate to…": "Translate to…", + "Translating captions to {name}": "Translating captions to {name}", + "Try again": "Try again", + "Trying another way to play this video…": "Trying another way to play this video…", + "TubeGlass {version} is available": "TubeGlass {version} is available", + "TubeGlass {version} is installed. Restart to use it.": "TubeGlass {version} is installed. Restart to use it.", + "Turn on notifications in Settings to receive them": "Turn on notifications in Settings to receive them", + "UPCOMING": "UPCOMING", + "Unfollowed {name}": "Unfollowed {name}", + "Unsubscribed from {channel}": "Unsubscribed from {channel}", + "Update": "Update", + "Updated {time}": "Updated {time}", + "Use {time}": "Use {time}", + "Use “Play all” on a playlist or channel, or right-click a video and choose “Add to queue”.": "Use “Play all” on a playlist or channel, or right-click a video and choose “Add to queue”.", + "VIDEO (mp4)": "VIDEO (mp4)", + "VIDEOS": "VIDEOS", + "Video downloaded": "Video downloaded", + "Watch history cleared": "Watch history cleared", + "Watch later (W)": "Watch later (W)", + "Watching for {time}": "Watching for {time}", + "What's new": "What's new", + "YOUR SHOWS": "YOUR SHOWS", + "You are not subscribed to this show.": "You are not subscribed to this show.", + "You have version {version}": "You have version {version}", + "You'll see less from {channel}": "You'll see less from {channel}", + "You're offline — downloads, history and saved playlists still work.": "You're offline — downloads, history and saved playlists still work.", + "YouTube Music": "YouTube Music", + "YouTube did not hand over this video ({detail}).": "YouTube did not hand over this video ({detail}).", + "YouTube did not hand over this video.": "YouTube did not hand over this video.", + "Your artists": "Your artists", + "applies to the videos loaded so far": "applies to the videos loaded so far", + "ffmpeg is not available, so nothing can play yet.": "ffmpeg is not available, so nothing can play yet.", + "ffmpeg is ready": "ffmpeg is ready", + "{author} • {count} episode": "{author} • {count} episode", + "{author} • {count} episodes": "{author} • {count} episodes", + "{channel} • Up next: {title}": "{channel} • Up next: {title}", + "{channel} • clip {start}–{end}": "{channel} • clip {start}–{end}", + "{count} download failed:": "{count} download failed:", + "{count} downloads failed:": "{count} downloads failed:", + "{count} item": "{count} item", + "{count} item • drag to reorder": "{count} item • drag to reorder", + "{count} items": "{count} items", + "{count} items • drag to reorder": "{count} items • drag to reorder", + "{count} items • {used} • {free} free": "{count} items • {used} • {free} free", + "{count} new": "{count} new", + "{count} playlist found": "{count} playlist found", + "{count} playlists found": "{count} playlists found", + "{count} replies": "{count} replies", + "{count} reply": "{count} reply", + "{name} — {note}": "{name} — {note}", + "{percent}% • {size} MB": "{percent}% • {size} MB", + "{start} – {end} {kind}": "{start} – {end} {kind}", + "“{title}” will be added to it.": "“{title}” will be added to it.", + "● LIVE": "● LIVE", + "About": "About", + "All": "All", + "Albums": "Albums", + "A–Z": "A–Z", + "Best available": "Best available", + "Default order": "Default order", + "For you": "For you", + "Grid": "Grid", + "Live": "Live", + "Live streams and new uploads": "Live streams and new uploads", + "Live streams only": "Live streams only", + "List": "List", + "Compact grid": "Compact grid", + "Longest": "Longest", + "Least viewed": "Least viewed", + "Most viewed": "Most viewed", + "New": "New", + "Newest": "Newest", + "Newest first": "Newest first", + "Oldest": "Oldest", + "Off for this channel": "Off for this channel", + "Playlists": "Playlists", + "Rating": "Rating", + "Relevance": "Relevance", + "Series": "Series", + "Shorts": "Shorts", + "Shortest": "Shortest", + "Title A–Z": "Title A–Z", + "Today": "Today", + "This month": "This month", + "This week": "This week", + "This year": "This year", + "Under 4 min": "Under 4 min", + "4–20 min": "4–20 min", + "Over 20 min": "Over 20 min", + "Upload date": "Upload date", + "View count": "View count", + "Videos": "Videos", + "Volume": "Volume", + "Mid": "Mid", + "Largest": "Largest", + "Unsubscribe": "Unsubscribe", + "Pause": "Pause", + "select none": "select none", + "Select all": "Select all", + "Repeat this video": "Repeat this video", + "Repeat the queue": "Repeat the queue", + "15 minutes": "15 minutes", + "30 minutes": "30 minutes", + "45 minutes": "45 minutes", + "1 hour": "1 hour", + "Audio saved": "Audio saved", + "Follow": "Follow", + "Open release page": "Open release page", + "Load more": "Load more", + "Keep offline": "Keep offline", + "Clear history": "Clear history", + "Sort": "Sort", + "Latest": "Latest", + "Normal": "Normal", + "Subscribe": "Subscribe", + "Video": "Video", + "GIF": "GIF", + "Video only": "Video only", + "Audio only": "Audio only", + "Watch later": "Watch later", + "Channel": "Channel", + "Subscribers": "Subscribers", + "Views": "Views", + "Joined": "Joined", + "Country": "Country", + "Updated": "Updated", + "Searching": "Searching", + "Results": "Results", + "Search failed": "Search failed", + "No videos to show.": "No videos to show.", + "Nothing watched yet. Videos you open will show up here, and pick up where you left off.": "Nothing watched yet. Videos you open will show up here, and pick up where you left off.", + "This playlist is empty. Right-click any video and choose “Add to playlist”.": "This playlist is empty. Right-click any video and choose “Add to playlist”.", + "Add your favourite channels to see their videos and live streams here.": "Add your favourite channels to see their videos and live streams here.", + "Nothing in this list matches your search.": "Nothing in this list matches your search.", + "Results for": "Results for", + "Episodes": "Episodes", + "Ambient mode on or off": "Ambient mode on or off", + "Audio only on or off": "Audio only on or off", + "Back (keeps playing in PiP)": "Back (keeps playing in PiP)", + "Collapse the sidebar": "Collapse the sidebar", + "Could not check for updates: {error}": "Could not check for updates: {error}", + "Could not open {path}: {error}": "Could not open {path}: {error}", + "Downloads ({active} • {percent}%)": "Downloads ({active} • {percent}%)", + "Fullscreen": "Fullscreen", + "Lyrics (music)": "Lyrics (music)", + "Media files": "Media files", + "Mini player on or off": "Mini player on or off", + "Mute": "Mute", + "New from {name}": "New from {name}", + "Next / previous in queue": "Next / previous in queue", + "Open a file": "Open a file", + "Play or pause": "Play or pause", + "Seek 10 seconds": "Seek 10 seconds", + "Seek 5 seconds": "Seek 5 seconds", + "Show more replies": "Show more replies", + "Slower / faster": "Slower / faster", + "This sheet": "This sheet", + "Version {version} is available": "Version {version} is available", + "Version {version} is available (you skipped it)": "Version {version} is available (you skipped it)", + "Watch later on or off": "Watch later on or off", + "What's new in {version}": "What's new in {version}", + "You have the latest version ({version})": "You have the latest version ({version})", + "3 s": "3 s", + "6 s": "6 s", + "Artists": "Artists", + "TubeGlass — Picture in Picture": "TubeGlass — Picture in Picture", + "Sleep timer off": "Sleep timer off", + "Removed from Watch later": "Removed from Watch later", + "Local file": "Local file", + "Orange": "Orange", + "Teal": "Teal", + "Violet": "Violet", + "Rose": "Rose", + "Lime": "Lime", + " • {status}": " • {status}", + "No ready-made ffmpeg exists for {platform}. {hint}": "No ready-made ffmpeg exists for {platform}. {hint}", + "Added to queue": "Added to queue", + "{channel} • {kind} • {size} MB": "{channel} • {kind} • {size} MB", + "{channel} • {kind} • {time} • {size} MB": "{channel} • {kind} • {time} • {size} MB", + "{channel} • {quality}p • {size} MB": "{channel} • {quality}p • {size} MB", + "{channel} • {quality}p • {time} • {size} MB": "{channel} • {quality}p • {time} • {size} MB", + "{count} item • {size} MB": "{count} item • {size} MB", + "{count} items • {size} MB": "{count} items • {size} MB", + "● {seconds}s behind": "● {seconds}s behind", + "● {minutes}m {seconds}s behind": "● {minutes}m {seconds}s behind", + "Jump to the live broadcast": "Jump to the live broadcast", + "Go live": "Go live", + "just now": "just now", + "{count} min ago": "{count} min ago", + "{count} h ago": "{count} h ago", + "{count} d ago": "{count} d ago", + "Favorites": "Favorites" +} diff --git a/locales/id.json b/locales/id.json new file mode 100644 index 0000000..bcc894c --- /dev/null +++ b/locales/id.json @@ -0,0 +1,554 @@ +{ + "Settings": "Pengaturan", + "PLAYBACK": "PEMUTARAN", + "Default quality": "Kualitas default", + "Used whenever a video starts": "Digunakan setiap kali video dimulai", + "Resume where you left off": "Lanjutkan dari posisi terakhir", + "Videos you have watched reopen at the same place": "Video dibuka kembali pada posisi terakhir", + "Ambient mode": "Mode ambien", + "A soft glow of the video's colours around the picture": "Pendar lembut warna video di sekitar gambar", + "Gapless playback": "Pemutaran tanpa jeda", + "Songs in a queue run into each other with no pause": "Lagu dalam antrean diputar tanpa jeda", + "Crossfade": "Pudar silang", + "Blend the end of a song into the next (needs gapless)": "Padukan akhir lagu dengan lagu berikutnya (perlu pemutaran tanpa jeda)", + "Autoplay next in queue": "Putar item antrean berikutnya", + "Move on to the next item when one ends": "Lanjut ke item berikutnya saat pemutaran selesai", + "Skip sponsor segments": "Lewati segmen sponsor", + "Uses the community SponsorBlock database": "Menggunakan basis data SponsorBlock komunitas", + "AUDIO": "AUDIO", + "Equalizer": "Equalizer", + "Presets or your own bass / mid / treble": "Prasetel atau atur bass / mid / treble", + "Vocal": "Vokal", + "Treble": "Treble", + "Bass": "Bass", + "Flat": "Rata", + "Even out volume": "Ratakan volume", + "Quiet parts are lifted so songs and videos feel equally loud": "Bagian pelan diperkeras agar volume lagu dan video terasa merata", + "Skip silence": "Lewati keheningan", + "Cuts long pauses in spoken audio (not for music; the time shown runs a little ahead)": "Memotong jeda panjang pada audio percakapan (bukan musik; waktu yang ditampilkan sedikit lebih cepat)", + "STORAGE": "PENYIMPANAN", + "Downloads": "Unduhan", + "Clips": "Klip", + "Thumbnails and avatars": "Gambar mini dan avatar", + "Saved feeds": "Feed tersimpan", + "Free on this disk": "Ruang kosong di disk ini", + "Finished downloads": "Unduhan selesai ditonton", + "Videos and songs you have already watched or listened to all the way": "Video dan lagu yang sudah ditonton atau didengarkan sampai selesai", + "Downloads older than 30 days": "Unduhan lebih lama dari 30 hari", + "Frees the most space when you download a lot": "Mengosongkan banyak ruang jika Anda sering mengunduh", + "Downloads older than 90 days": "Unduhan lebih lama dari 90 hari", + "Confirm": "Konfirmasi", + "Delete…": "Hapus…", + "OFFLINE": "OFFLINE", + "Save captions and lyrics with downloads": "Simpan teks dan lirik bersama unduhan", + "So subtitles and lyrics also work without a connection": "Agar subtitel dan lirik tetap tersedia tanpa koneksi", + "CAPTIONS": "TEKS", + "Show captions by default": "Tampilkan teks secara default", + "When a video has them": "Jika tersedia untuk video", + "Preferred language": "Bahasa pilihan", + "Language code, for example en, es, fr": "Kode bahasa, misalnya en, es, fr", + "DOWNLOADS": "UNDUHAN", + "Folder": "Folder", + "Choose…": "Pilih…", + "Reset": "Atur ulang", + "APPEARANCE": "TAMPILAN", + "Theme": "Tema", + "Dark, light, or follow the system (the video page stays dark)": "Gelap, terang, atau ikuti sistem (halaman video tetap gelap)", + "System": "Sistem", + "Light": "Terang", + "Dark": "Gelap", + "Text size": "Ukuran teks", + "Scales the whole interface": "Mengubah skala seluruh antarmuka", + "Density": "Kepadatan", + "How big and how far apart video cards are": "Ukuran dan jarak antarkartu video", + "Spacious": "Lapang", + "Comfortable": "Nyaman", + "Compact": "Ringkas", + "Accent colour": "Warna aksen", + "Pick a preset or mix your own": "Pilih prasetel atau buat warna sendiri", + "custom": "khusus", + "SUBSCRIPTIONS": "LANGGANAN", + "Import": "Impor", + "NewPipe export, YouTube Takeout CSV, OPML, or a list of links": "Ekspor NewPipe, CSV YouTube Takeout, OPML, atau daftar tautan", + "Import…": "Impor…", + "Export": "Ekspor", + "Saves a NewPipe-compatible subscriptions file": "Menyimpan file langganan yang kompatibel dengan NewPipe", + "Export…": "Ekspor…", + "NOTIFICATIONS": "NOTIFIKASI", + "Notify me": "Beri tahu saya", + "Live streams by default. Right-click a channel to also get new uploads, or to mute it": "Notifikasi live secara default. Klik kanan kanal untuk menerima unggahan baru atau membisukannya", + "DATA": "DATA", + "Back up everything": "Cadangkan semua", + "Channels, playlists, history, liked songs, groups and settings in one file": "Kanal, daftar putar, riwayat, lagu disukai, grup, dan pengaturan dalam satu file", + "Back up…": "Cadangkan…", + "Restore a backup": "Pulihkan cadangan", + "Replaces what is here with the file's contents, then restarts": "Mengganti data ini dengan isi file, lalu memulai ulang", + "Restore…": "Pulihkan…", + "Check for updates automatically": "Periksa pembaruan otomatis", + "Looks at the project's GitHub releases now and then (nothing else is sent)": "Memeriksa rilis GitHub proyek sesekali (tidak ada data lain yang dikirim)", + "Check for updates now": "Periksa pembaruan sekarang", + "Check now": "Periksa sekarang", + "ffmpeg": "ffmpeg", + "Everything plays through it. In use: {ffmpeg}": "Semua media diputar dengannya. Sedang digunakan: {ffmpeg}", + "Download a fresh copy": "Unduh salinan baru", + "Check YouTube access": "Periksa akses YouTube", + "Tests search, playback, comments and music, to see what broke if something stops working": "Menguji pencarian, pemutaran, komentar, dan musik untuk mencari penyebab jika ada masalah", + "Run check": "Jalankan pemeriksaan", + "Clear image cache": "Hapus cache gambar", + "Thumbnails and avatars are downloaded again when needed": "Gambar mini dan avatar akan diunduh lagi saat diperlukan", + "Clear watch history": "Hapus riwayat tontonan", + "Also forgets where you left each video": "Juga menghapus posisi terakhir setiap video", + "Interface language": "Bahasa antarmuka", + "Choose the language used for TubeGlass controls": "Pilih bahasa untuk antarmuka TubeGlass", + "Use system language": "Gunakan bahasa sistem", + "English": "Inggris", + "Indonesian": "Indonesia", + "Home": "Beranda", + "Live now": "Sedang tayang", + "Music": "Musik", + "Podcasts": "Podcast", + "History": "Riwayat", + "Insights": "Statistik", + "Open file…": "Buka file…", + "LIBRARY": "KOLEKSI", + "PLAYLISTS": "DAFTAR PUTAR", + "New playlist": "Daftar putar baru", + "Import playlists from YouTube": "Impor daftar putar dari YouTube", + "Expand sidebar (Ctrl+B)": "Perluas bilah sisi (Ctrl+B)", + "Collapse sidebar (Ctrl+B)": "Ciutkan bilah sisi (Ctrl+B)", + "Add": "Tambah", + "Clear": "Hapus", + "@handle or link": "@handle atau tautan", + "__language_name": "Bahasa Indonesia", + "+ New group…": "+ Grup baru…", + "+ New playlist…": "+ Daftar putar baru…", + "Add to queue": "Tambahkan ke antrean", + "Audio only (m4a)": "Audio saja (m4a)", + "Cancel": "Batal", + "Clip this moment…": "Klip bagian ini…", + "Delete clip": "Hapus klip", + "Delete group": "Hapus grup", + "Delete playlist": "Hapus daftar putar", + "Download": "Unduh", + "Download audio only": "Unduh audio saja", + "End of this video": "Akhir video ini", + "Keyboard shortcuts": "Pintasan keyboard", + "Look up lyrics anyway": "Cari lirik tetap", + "Mark as played": "Tandai sudah diputar", + "Not interested": "Tidak tertarik", + "Open folder": "Buka folder", + "Open the full transcript": "Buka transkrip lengkap", + "Open the source video": "Buka video sumber", + "Play": "Putar", + "Play audio only": "Putar audio saja", + "Play next": "Putar berikutnya", + "Preview": "Pratinjau", + "Recommend less from this channel": "Kurangi rekomendasi kanal ini", + "Remove channel": "Hapus kanal", + "Remove from history": "Hapus dari riwayat", + "Remove from this playlist": "Hapus dari daftar putar ini", + "Show folder": "Tampilkan folder", + "Turn off": "Matikan", + " • about {time} left": " • sekitar {time} lagi", + " • {speed} MB/s": " • {speed} MB/dtk", + "(you have {version})": "(versi Anda {version})", + "Add {time}": "Tambah {time}", + "Add a note at this moment": "Tambahkan catatan pada waktu ini", + "Add to group": "Tambahkan ke grup", + "Add to playlist": "Tambahkan ke daftar putar", + "Added": "Ditambahkan", + "Added to Watch later": "Ditambahkan ke Tonton nanti", + "All files": "Semua file", + "Ambient mode (B)": "Mode ambien (B)", + "Ambient mode on": "Mode ambien aktif", + "Ambient mode off": "Mode ambien nonaktif", + "Any length": "Durasi berapa pun", + "Any time": "Kapan saja", + "Audio": "Audio", + "Audio downloaded": "Audio telah diunduh", + "Audio only (A)": "Audio saja (A)", + "Audio only (A)": "Audio saja (A)", + "Back (Alt+←)": "Kembali (Alt+←)", + "Back online": "Kembali online", + "Back up TubeGlass": "Cadangkan TubeGlass", + "Backup saved to {path}": "Cadangan disimpan di {path}", + "Because you like {title}": "Karena Anda menyukai {title}", + "Bookmark": "Penanda", + "Buffering": "Memuat buffer", + "CHANNELS": "KANAL", + "CLIPS OF THIS VIDEO": "KLIP VIDEO INI", + "Can't play this video": "Video ini tidak dapat diputar", + "Captions unavailable: {error}": "Teks tidak tersedia: {error}", + "Clip": "Klip", + "Clip cancelled": "Klip dibatalkan", + "Clip saved": "Klip disimpan", + "Clip {start}–{end}": "Klip {start}–{end}", + "Close": "Tutup", + "Comments": "Komentar", + "Confirm clear": "Konfirmasi penghapusan", + "Confirm delete ({count})": "Konfirmasi hapus ({count})", + "Confirm unsubscribe": "Konfirmasi berhenti berlangganan", + "Could not download “{title}”": "Tidak dapat mengunduh “{title}”", + "Could not import {id}: {error}": "Tidak dapat mengimpor {id}: {error}", + "Could not load YouTube Music: {error}": "Tidak dapat memuat YouTube Music: {error}", + "Could not load live streams: {error}": "Tidak dapat memuat siaran langsung: {error}", + "Could not load playlist: {error}": "Tidak dapat memuat daftar putar: {error}", + "Could not load the transcript: {error}": "Tidak dapat memuat transkrip: {error}", + "Could not load this tab: {error}": "Tidak dapat memuat tab ini: {error}", + "Could not load: {error}": "Tidak dapat memuat: {error}", + "Could not open the channel: {error}": "Tidak dapat membuka kanal: {error}", + "Could not restore: {error}": "Tidak dapat memulihkan: {error}", + "Could not save the backup: {error}": "Tidak dapat menyimpan cadangan: {error}", + "Create": "Buat", + "Cut a piece out of this video and save it as a file.": "Potong bagian video ini dan simpan sebagai file.", + "Cutting… {percent}% • about {time} left": "Memotong… {percent}% • sekitar {time} lagi", + "Delete ({count})": "Hapus ({count})", + "Description": "Deskripsi", + "Dismiss": "Tutup", + "Done": "Selesai", + "Download ({downloaded}/{total})": "Unduh ({downloaded}/{total})", + "Download all ({downloaded}/{total})": "Unduh semua ({downloaded}/{total})", + "Download failed: {error}": "Unduhan gagal: {error}", + "Download folder": "Folder unduhan", + "Download folder updated": "Folder unduhan diperbarui", + "Download video": "Unduh video", + "Downloaded": "Diunduh", + "Downloading TubeGlass {version}…": "Mengunduh TubeGlass {version}…", + "Downloading {count} item": "Mengunduh {count} item", + "Downloading {count} items": "Mengunduh {count} item", + "Everything is already downloaded": "Semua sudah diunduh", + "Export subscriptions": "Ekspor langganan", + "Exported {count} channels": "Mengekspor {count} kanal", + "Filter channels": "Filter kanal", + "Following": "Mengikuti", + "Following {name}": "Mengikuti {name}", + "GIFs get big fast; 20 seconds or less works best.": "Ukuran GIF cepat membesar; durasi 20 detik atau kurang paling cocok.", + "GROUPS": "GRUP", + "Get ffmpeg": "Dapatkan ffmpeg", + "Group channels, e.g. Music or News. Right-click a channel to add it.": "Kelompokkan kanal, misalnya Musik atau Berita. Klik kanan kanal untuk menambahkannya.", + "Group name, e.g. Music": "Nama grup, misalnya Musik", + "Hidden from your recommendations": "Disembunyikan dari rekomendasi", + "Hide": "Sembunyikan", + "Hide for now": "Sembunyikan untuk saat ini", + "Image cache cleared (restart to refetch avatars)": "Cache gambar dihapus (mulai ulang untuk mengambil ulang avatar)", + "Import subscriptions": "Impor langganan", + "Imported {count} channel": "{count} kanal diimpor", + "Imported {count} channels": "{count} kanal diimpor", + "Imported “{name}” with {count} videos": "“{name}” diimpor dengan {count} video", + "Importing… {count} left": "Mengimpor… tersisa {count}", + "JSON": "JSON", + "Jump back in": "Lanjutkan lagi", + "Keep every item of this playlist downloaded, including ones added later": "Simpan semua item daftar putar ini untuk offline, termasuk yang ditambahkan nanti", + "Kept offline": "Tersimpan offline", + "LATEST EPISODES": "EPISODE TERBARU", + "LIVE": "LANGSUNG", + "Latest from your channels": "Terbaru dari kanal Anda", + "Length {time}": "Durasi {time}", + "Like this song": "Sukai lagu ini", + "Liked songs": "Lagu yang disukai", + "Links": "Tautan", + "Live streams can't be clipped.": "Siaran langsung tidak dapat dipotong.", + "Load more comments": "Muat komentar lainnya", + "Lyrics": "Lirik", + "Lyrics are only looked up for YouTube songs.": "Lirik hanya dicari untuk lagu YouTube.", + "Lyrics: {source}": "Lirik: {source}", + "Mark all as played": "Tandai semua telah diputar", + "Mark all as seen": "Tandai semua telah dilihat", + "NEW": "BARU", + "New from artists you follow": "Rilisan baru dari artis yang Anda ikuti", + "New group": "Grup baru", + "No channels match.": "Tidak ada kanal yang cocok.", + "No clips yet.": "Belum ada klip.", + "No downloads match your search.": "Tidak ada unduhan yang cocok dengan pencarian.", + "No playlist link found yet. Private playlists cannot be imported.": "Tautan daftar putar belum ditemukan. Daftar putar privat tidak dapat diimpor.", + "No podcasts found.": "Podcast tidak ditemukan.", + "No podcasts yet.": "Belum ada podcast.", + "Notes": "Catatan", + "Notes ({count})": "Catatan ({count})", + "Notes and bookmarks you add show up here and as dots on the seek bar.": "Catatan dan penanda yang Anda tambahkan muncul di sini dan sebagai titik di bilah pencarian waktu.", + "Nothing downloaded yet. Use the Download button in the player, or right-click any video.": "Belum ada unduhan. Gunakan tombol Unduh di pemutar atau klik kanan video.", + "Nothing found.": "Tidak ditemukan.", + "Nothing here yet. Add a channel above to get started.": "Belum ada apa pun. Tambahkan kanal di atas untuk memulai.", + "Nothing in the queue can be saved as a playlist": "Tidak ada item antrean yang dapat disimpan sebagai daftar putar", + "Notifications": "Notifikasi", + "Off": "Nonaktif", + "Open a video, choose the Clip tab (or “Clip this moment…” in the … menu) and save a section.": "Buka video, pilih tab Klip (atau “Klip bagian ini…” di menu …), lalu simpan bagian video.", + "Open downloads": "Buka unduhan", + "Open media file": "Buka file media", + "Open the release page": "Buka halaman rilis", + "Opening the video…": "Membuka video…", + "Opening {name}…": "Membuka {name}…", + "Ordered by what you watch and listen to": "Diurutkan berdasarkan tontonan dan lagu Anda", + "Paste one or more playlist links (or ids). Each becomes a playlist you can edit, download and keep offline.": "Tempel satu atau beberapa tautan daftar putar (atau ID). Masing-masing menjadi daftar putar yang dapat diedit dan diunduh untuk penggunaan offline.", + "Paused": "Dijeda", + "Play all": "Putar semua", + "Play audio only (A)": "Putar audio saja (A)", + "Play latest": "Putar terbaru", + "Play some songs and your own picks will appear here.": "Putar beberapa lagu agar pilihan Anda muncul di sini.", + "Play this clip": "Putar klip ini", + "Playing next": "Memutar berikutnya", + "Playlist": "Daftar putar", + "Playlist name": "Nama daftar putar", + "Podcast": "Podcast", + "Queue": "Antrean", + "Queue ({count})": "Antrean ({count})", + "RECENT SEARCHES": "PENCARIAN TERBARU", + "REPEAT": "ULANGI", + "Refresh": "Segarkan", + "Refreshing {done} / {total}": "Memperbarui {done} / {total}", + "Related": "Terkait", + "Related videos are only available for YouTube videos.": "Video terkait hanya tersedia untuk video YouTube.", + "Remove from Watch later": "Hapus dari Tonton nanti", + "Removed {count} download, freed {size}": "Menghapus {count} unduhan, membebaskan {size}", + "Removed {count} downloads, freed {size}": "Menghapus {count} unduhan, membebaskan {size}", + "Replay": "Putar ulang", + "Replies": "Balasan", + "Restart now": "Mulai ulang sekarang", + "Restore backup": "Pulihkan cadangan", + "Results for “{query}”": "Hasil untuk “{query}”", + "Results for “{query}” • {videos} videos, {playlists} playlists": "Hasil untuk “{query}” • {videos} video, {playlists} daftar putar", + "Resume": "Lanjutkan", + "Retry": "Coba lagi", + "SEGMENTS": "BAGIAN", + "SLEEP TIMER": "TIMER TIDUR", + "Save as playlist": "Simpan sebagai daftar putar", + "Save clip": "Simpan klip", + "Saved": "Tersimpan", + "Saved queue ({count} item)": "Antrean disimpan ({count} item)", + "Saved queue ({count} items)": "Antrean disimpan ({count} item)", + "Saved to {path}": "Disimpan ke {path}", + "Saved {name}": "Disimpan {name}", + "Saved “{name}” with {count} videos": "Menyimpan “{name}” dengan {count} video", + "Saved “{name}” — find it under Playlists": "“{name}” disimpan — cari di Daftar putar", + "Search": "Cari", + "Search YouTube — videos and channels": "Cari di YouTube — video dan kanal", + "Search above, or paste a podcast's feed address (RSS) or its Apple Podcasts link.": "Cari di atas, atau tempel alamat feed podcast (RSS) maupun tautan Apple Podcasts.", + "Search downloads": "Cari unduhan", + "Search failed: {error}": "Pencarian gagal: {error}", + "Search in {channel}": "Cari di {channel}", + "Search podcasts, or paste a feed or Apple Podcasts link": "Cari podcast atau tempel feed maupun tautan Apple Podcasts", + "Search songs, albums, artists": "Cari lagu, album, artis", + "Search the transcript": "Cari dalam transkrip", + "Search this list": "Cari dalam daftar ini", + "Searching “{query}”…": "Mencari “{query}”…", + "Select": "Pilih", + "Select none": "Batalkan pilihan", + "Setting up ffmpeg (once, about 30 MB) so video and audio can play…": "Menyiapkan ffmpeg (sekali, sekitar 30 MB) agar video dan audio dapat diputar…", + "Showing {shown} of {total} episodes": "Menampilkan {shown} dari {total} episode", + "Shuffle": "Acak", + "Shuffle the queue": "Acak antrean", + "Skip this version": "Lewati versi ini", + "Skipped {category}": "Melewati {category}", + "Sleep timer set": "Timer tidur diatur", + "Sleep timer: playback paused": "Timer tidur: pemutaran dijeda", + "Sleep timer: stopped after this video": "Timer tidur: berhenti setelah video ini", + "Something went wrong on this page (details are in crash.log)": "Terjadi kesalahan pada halaman ini (detail ada di crash.log)", + "Songs": "Lagu", + "Sort: {value}": "Urutkan: {value}", + "Source video": "Video sumber", + "Speed {speed}×": "Kecepatan {speed}×", + "Start": "Mulai", + "Stats": "Statistik", + "Stops after this video": "Berhenti setelah video ini", + "Stops in {time}": "Berhenti dalam {time}", + "Subscribed": "Berlangganan", + "Subscriptions": "Langganan", + "That playlist has no videos (or it is private)": "Daftar putar tersebut tidak memiliki video (atau bersifat privat)", + "The queue is empty.": "Antrean kosong.", + "This doesn't look like a song, so lyrics are not looked up automatically.": "Ini tampaknya bukan lagu, jadi lirik tidak dicari otomatis.", + "This replaces your current channels, playlists, history and settings with the backup, then restarts TubeGlass.": "Ini akan mengganti kanal, daftar putar, riwayat, dan pengaturan Anda dengan isi cadangan, lalu memulai ulang TubeGlass.", + "This video has no captions, so there is no transcript.": "Video ini tidak memiliki teks, jadi transkrip tidak tersedia.", + "Transcript": "Transkrip", + "Translate to…": "Terjemahkan ke…", + "Translating captions to {name}": "Menerjemahkan teks ke {name}", + "Try again": "Coba lagi", + "Trying another way to play this video…": "Mencoba cara lain untuk memutar video ini…", + "TubeGlass {version} is available": "TubeGlass {version} tersedia", + "TubeGlass {version} is installed. Restart to use it.": "TubeGlass {version} terpasang. Mulai ulang untuk menggunakannya.", + "Turn on notifications in Settings to receive them": "Aktifkan notifikasi di Pengaturan untuk menerimanya", + "UPCOMING": "AKAN TAYANG", + "Unfollowed {name}": "Berhenti mengikuti {name}", + "Unsubscribed from {channel}": "Berhenti berlangganan dari {channel}", + "Update": "Perbarui", + "Updated {time}": "Diperbarui {time}", + "Use {time}": "Gunakan {time}", + "Use “Play all” on a playlist or channel, or right-click a video and choose “Add to queue”.": "Gunakan “Putar semua” pada daftar putar atau kanal, atau klik kanan video lalu pilih “Tambahkan ke antrean”.", + "VIDEO (mp4)": "VIDEO (mp4)", + "VIDEOS": "VIDEO", + "Video downloaded": "Video telah diunduh", + "Watch history cleared": "Riwayat tontonan dihapus", + "Watch later (W)": "Tonton nanti (W)", + "Watching for {time}": "Menonton selama {time}", + "What's new": "Yang baru", + "YOUR SHOWS": "ACARA ANDA", + "You are not subscribed to this show.": "Anda belum berlangganan acara ini.", + "You have version {version}": "Versi Anda {version}", + "You'll see less from {channel}": "Anda akan lebih jarang melihat {channel}", + "You're offline — downloads, history and saved playlists still work.": "Anda sedang offline — unduhan, riwayat, dan daftar putar tersimpan tetap berfungsi.", + "YouTube Music": "YouTube Music", + "YouTube did not hand over this video ({detail}).": "YouTube tidak memberikan video ini ({detail}).", + "YouTube did not hand over this video.": "YouTube tidak memberikan video ini.", + "Your artists": "Artis Anda", + "applies to the videos loaded so far": "berlaku untuk video yang telah dimuat", + "ffmpeg is not available, so nothing can play yet.": "ffmpeg tidak tersedia, jadi belum ada yang dapat diputar.", + "ffmpeg is ready": "ffmpeg siap", + "{author} • {count} episode": "{author} • {count} episode", + "{author} • {count} episodes": "{author} • {count} episode", + "{channel} • Up next: {title}": "{channel} • Berikutnya: {title}", + "{channel} • clip {start}–{end}": "{channel} • klip {start}–{end}", + "{count} download failed:": "{count} unduhan gagal:", + "{count} downloads failed:": "{count} unduhan gagal:", + "{count} item": "{count} item", + "{count} item • drag to reorder": "{count} item • seret untuk mengurutkan", + "{count} items": "{count} item", + "{count} items • drag to reorder": "{count} item • seret untuk mengurutkan", + "{count} items • {used} • {free} free": "{count} item • terpakai {used} • kosong {free}", + "{count} new": "{count} baru", + "{count} playlist found": "{count} daftar putar ditemukan", + "{count} playlists found": "{count} daftar putar ditemukan", + "{count} replies": "{count} balasan", + "{count} reply": "{count} balasan", + "{name} — {note}": "{name} — {note}", + "{percent}% • {size} MB": "{percent}% • {size} MB", + "{start} – {end} {kind}": "{start} – {end} {kind}", + "“{title}” will be added to it.": "“{title}” akan ditambahkan ke dalamnya.", + "● LIVE": "● LANGSUNG", + "About": "Tentang", + "All": "Semua", + "Albums": "Album", + "A–Z": "A–Z", + "Best available": "Kualitas terbaik", + "Default order": "Urutan default", + "For you": "Untuk Anda", + "Grid": "Kisi", + "Live": "Langsung", + "Live streams and new uploads": "Siaran langsung dan unggahan baru", + "Live streams only": "Siaran langsung saja", + "List": "Daftar", + "Compact grid": "Kisi ringkas", + "Longest": "Terpanjang", + "Least viewed": "Paling sedikit dilihat", + "Most viewed": "Paling banyak dilihat", + "New": "Baru", + "Newest": "Terbaru", + "Newest first": "Terbaru lebih dulu", + "Oldest": "Terlama", + "Off for this channel": "Nonaktif untuk kanal ini", + "Playlists": "Daftar putar", + "Rating": "Rating", + "Relevance": "Relevansi", + "Series": "Seri", + "Shorts": "Shorts", + "Shortest": "Terpendek", + "Title A–Z": "Judul A–Z", + "Today": "Hari ini", + "This month": "Bulan ini", + "This week": "Minggu ini", + "This year": "Tahun ini", + "Under 4 min": "Di bawah 4 mnt", + "4–20 min": "4–20 mnt", + "Over 20 min": "Lebih dari 20 mnt", + "Upload date": "Tanggal unggah", + "View count": "Jumlah penayangan", + "Videos": "Video", + "Volume": "Volume", + "Mid": "Mid", + "Largest": "Terbesar", + "Unsubscribe": "Berhenti berlangganan", + "Pause": "Jeda", + "select none": "Batalkan pilihan", + "Select all": "Pilih semua", + "Repeat this video": "Ulangi video ini", + "Repeat the queue": "Ulangi antrean", + "15 minutes": "15 menit", + "30 minutes": "30 menit", + "45 minutes": "45 menit", + "1 hour": "1 jam", + "Audio saved": "Audio tersimpan", + "Follow": "Ikuti", + "Open release page": "Buka halaman rilis", + "Load more": "Muat lainnya", + "Keep offline": "Simpan untuk offline", + "Clear history": "Hapus riwayat", + "Sort": "Urutkan", + "Latest": "Terbaru", + "Normal": "Normal", + "Subscribe": "Berlangganan", + "Video": "Video", + "GIF": "GIF", + "Video only": "Video saja", + "Audio only": "Audio saja", + "Watch later": "Tonton nanti", + "Channel": "Kanal", + "Subscribers": "Pelanggan", + "Views": "Penayangan", + "Joined": "Bergabung", + "Country": "Negara", + "Updated": "Diperbarui", + "Searching": "Mencari", + "Results": "Hasil", + "Search failed": "Pencarian gagal", + "No videos to show.": "Tidak ada video untuk ditampilkan.", + "Nothing watched yet. Videos you open will show up here, and pick up where you left off.": "Belum ada tontonan. Video yang Anda buka akan muncul di sini dan dapat dilanjutkan dari posisi terakhir.", + "This playlist is empty. Right-click any video and choose “Add to playlist”.": "Daftar putar ini kosong. Klik kanan video dan pilih “Tambahkan ke daftar putar”.", + "Add your favourite channels to see their videos and live streams here.": "Tambahkan kanal favorit untuk melihat video dan siaran langsungnya di sini.", + "Nothing in this list matches your search.": "Tidak ada item dalam daftar ini yang cocok dengan pencarian.", + "Results for": "Hasil untuk", + "Episodes": "Episode", + "Ambient mode on or off": "Mode ambien aktif atau nonaktif", + "Audio only on or off": "Audio saja aktif atau nonaktif", + "Back (keeps playing in PiP)": "Kembali (pemutaran tetap berjalan di PiP)", + "Collapse the sidebar": "Ciutkan bilah sisi", + "Could not check for updates: {error}": "Tidak dapat memeriksa pembaruan: {error}", + "Could not open {path}: {error}": "Tidak dapat membuka {path}: {error}", + "Downloads ({active} • {percent}%)": "Unduhan ({active} • {percent}%)", + "Fullscreen": "Layar penuh", + "Lyrics (music)": "Lirik (musik)", + "Media files": "File media", + "Mini player on or off": "Pemutar mini aktif atau nonaktif", + "Mute": "Bisukan", + "New from {name}": "Baru dari {name}", + "Next / previous in queue": "Berikutnya / sebelumnya dalam antrean", + "Open a file": "Buka file", + "Play or pause": "Putar atau jeda", + "Seek 10 seconds": "Lompat 10 detik", + "Seek 5 seconds": "Lompat 5 detik", + "Show more replies": "Tampilkan balasan lainnya", + "Slower / faster": "Lebih lambat / lebih cepat", + "This sheet": "Lembar ini", + "Version {version} is available": "Versi {version} tersedia", + "Version {version} is available (you skipped it)": "Versi {version} tersedia (Anda melewatinya)", + "Watch later on or off": "Tonton nanti aktif atau nonaktif", + "What's new in {version}": "Yang baru di versi {version}", + "You have the latest version ({version})": "Anda menggunakan versi terbaru ({version})", + "3 s": "3 dtk", + "6 s": "6 dtk", + "Artists": "Artis", + "TubeGlass — Picture in Picture": "TubeGlass — Gambar dalam Gambar", + "Sleep timer off": "Timer tidur nonaktif", + "Removed from Watch later": "Dihapus dari Tonton nanti", + "Local file": "File lokal", + "Orange": "Jingga", + "Teal": "Teal", + "Violet": "Ungu", + "Rose": "Merah muda", + "Lime": "Lime", + " • {status}": " • {status}", + "No ready-made ffmpeg exists for {platform}. {hint}": "Tidak tersedia ffmpeg siap pakai untuk {platform}. {hint}", + "Added to queue": "Ditambahkan ke antrean", + "{channel} • {kind} • {size} MB": "{channel} • {kind} • {size} MB", + "{channel} • {kind} • {time} • {size} MB": "{channel} • {kind} • {time} • {size} MB", + "{channel} • {quality}p • {size} MB": "{channel} • {quality}p • {size} MB", + "{channel} • {quality}p • {time} • {size} MB": "{channel} • {quality}p • {time} • {size} MB", + "{count} item • {size} MB": "{count} item • {size} MB", + "{count} items • {size} MB": "{count} item • {size} MB", + "● {seconds}s behind": "● terlambat {seconds} dtk", + "● {minutes}m {seconds}s behind": "● terlambat {minutes}m {seconds} dtk", + "Jump to the live broadcast": "Lompat ke siaran langsung", + "Go live": "Ke siaran langsung", + "just now": "baru saja", + "{count} min ago": "{count} mnt lalu", + "{count} h ago": "{count} jam lalu", + "{count} d ago": "{count} hari lalu", + "Favorites": "Favorit" +} diff --git a/scripts/new-locale.py b/scripts/new-locale.py new file mode 100644 index 0000000..f9d2d18 --- /dev/null +++ b/scripts/new-locale.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python3 +"""Create a partial translation catalog or report locale coverage.""" + +from __future__ import annotations + +import argparse +import json +import re +import sys +from pathlib import Path + + +LANGUAGE_CODE = re.compile(r"[a-z]{2,3}\Z") +PLACEHOLDER_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*\Z") +ROOT = Path(__file__).resolve().parents[1] +DEFAULT_LOCALES = ROOT / "locales" + + +def load_catalog(path: Path) -> dict[str, str]: + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as error: + raise ValueError(f"could not read {path}: {error}") from error + if not isinstance(data, dict) or not all( + isinstance(key, str) and isinstance(value, str) for key, value in data.items() + ): + raise ValueError(f"{path} must be a JSON object of string values") + return data + + +def placeholder_names(text: str) -> list[str]: + names = [] + index = 0 + while index < len(text): + char = text[index] + if char == "{": + if index + 1 < len(text) and text[index + 1] == "{": + index += 2 + continue + + end = text.find("}", index + 1) + if end == -1: + raise ValueError("malformed placeholder braces") + name = text[index + 1 : end] + if "{" in name or not PLACEHOLDER_NAME.fullmatch(name): + raise ValueError("malformed placeholder braces") + names.append(name) + index = end + 1 + continue + + if char == "}": + if index + 1 < len(text) and text[index + 1] == "}": + index += 2 + continue + raise ValueError("malformed placeholder braces") + + index += 1 + + return sorted(names) + + +def create_locale(code: str, display_name: str, locales_dir: Path = DEFAULT_LOCALES) -> Path: + if not LANGUAGE_CODE.fullmatch(code): + raise ValueError("language code must be a lowercase two- or three-letter base code, such as 'fr'") + if code == "en": + raise ValueError("English is the source catalog and cannot be scaffolded") + if not display_name.strip(): + raise ValueError("display name cannot be empty") + + english = load_catalog(locales_dir / "en.json") + output = {"__language_name": display_name.strip()} + output.update({key: "" for key in english if key != "__language_name"}) + destination = locales_dir / f"{code}.json" + # Exclusive creation prevents accidentally replacing an existing translation. + with destination.open("x", encoding="utf-8", newline="\n") as file: + json.dump(output, file, ensure_ascii=False, indent=2) + file.write("\n") + return destination + + +def locale_coverage(locales_dir: Path = DEFAULT_LOCALES) -> list[tuple[str, str, int, int, float]]: + english = load_catalog(locales_dir / "en.json") + source_keys = {key for key in english if key != "__language_name"} + if not source_keys or any(not english[key].strip() for key in source_keys): + raise ValueError("locales/en.json must contain a nonempty value for every source key") + + source_placeholder_names = {} + for key in source_keys: + try: + key_names = placeholder_names(key) + value_names = placeholder_names(english[key]) + except ValueError as error: + raise ValueError(f"locales/en.json has invalid placeholders for {key!r}") from error + if key_names != value_names: + raise ValueError(f"locales/en.json has invalid placeholders for {key!r}") + source_placeholder_names[key] = key_names + + report = [] + for path in sorted(locales_dir.glob("*.json")): + if path.stem == "en": + continue + catalog = load_catalog(path) + unknown = set(catalog) - source_keys - {"__language_name"} + if unknown: + raise ValueError(f"{path.name} has unknown keys: {', '.join(sorted(unknown))}") + translated = 0 + for key, value in catalog.items(): + if key == "__language_name" or not value.strip(): + continue + try: + translation_names = placeholder_names(value) + except ValueError as error: + raise ValueError(f"{path.name} has invalid placeholders for {key!r}") from error + if source_placeholder_names[key] != translation_names: + raise ValueError(f"{path.name} has invalid placeholders for {key!r}") + translated += 1 + name = catalog.get("__language_name", "").strip() or path.stem + percentage = translated * 100.0 / len(source_keys) + report.append((path.stem, name, translated, len(source_keys), percentage)) + return report + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("code", nargs="?", help="lowercase base language code, such as fr") + parser.add_argument("display_name", nargs="?", help="language name shown in Settings") + parser.add_argument("--coverage", action="store_true", help="report translation coverage for all catalogs") + args = parser.parse_args() + + try: + if args.coverage: + for code, name, translated, total, percentage in locale_coverage(): + print(f"{code} ({name}): {translated}/{total} translated ({percentage:.1f}%)") + return 0 + if not args.code or not args.display_name: + parser.error("provide CODE and DISPLAY_NAME, or use --coverage") + destination = create_locale(args.code, args.display_name) + print(f"Created {destination.relative_to(ROOT)} with blank translations that fall back to English.") + return 0 + except (FileExistsError, ValueError) as error: + print(f"error: {error}", file=sys.stderr) + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/test_new_locale.py b/scripts/test_new_locale.py new file mode 100644 index 0000000..f7afc9a --- /dev/null +++ b/scripts/test_new_locale.py @@ -0,0 +1,107 @@ +import importlib.util +import json +import tempfile +import unittest +from pathlib import Path + + +SCRIPT = Path(__file__).with_name("new-locale.py") +PLACEHOLDER_FIXTURE = SCRIPT.parents[1] / "tests" / "fixtures" / "locale-placeholders.json" +SPEC = importlib.util.spec_from_file_location("new_locale", SCRIPT) +new_locale = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(new_locale) + + +class NewLocaleTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.locales = Path(self.temp.name) + (self.locales / "en.json").write_text( + json.dumps( + { + "__language_name": "English", + "Settings": "Settings", + "Download {count} items": "Download {count} items", + } + ), + encoding="utf-8", + ) + + def tearDown(self): + self.temp.cleanup() + + def test_creates_full_blank_template_with_display_name(self): + path = new_locale.create_locale("fr", "Français", self.locales) + catalog = json.loads(path.read_text(encoding="utf-8")) + self.assertEqual(catalog["__language_name"], "Français") + self.assertEqual(catalog["Settings"], "") + self.assertEqual(catalog["Download {count} items"], "") + self.assertEqual(set(catalog), {"__language_name", "Settings", "Download {count} items"}) + + def test_rejects_invalid_codes_and_english(self): + for code in ("FR", "fr-CA", "f", "four"): + with self.subTest(code=code), self.assertRaises(ValueError): + new_locale.create_locale(code, "Français", self.locales) + with self.assertRaises(ValueError): + new_locale.create_locale("en", "English", self.locales) + + def test_placeholder_names_match_shared_cases(self): + cases = json.loads(PLACEHOLDER_FIXTURE.read_text(encoding="utf-8")) + for case in cases: + with self.subTest(text=case["text"]): + if case["names"] is None: + with self.assertRaises(ValueError): + new_locale.placeholder_names(case["text"]) + else: + self.assertEqual(new_locale.placeholder_names(case["text"]), case["names"]) + + def test_refuses_to_overwrite_existing_locale(self): + target = self.locales / "fr.json" + target.write_text('{"keep":"this"}\n', encoding="utf-8") + with self.assertRaises(FileExistsError): + new_locale.create_locale("fr", "Français", self.locales) + self.assertEqual(target.read_text(encoding="utf-8"), '{"keep":"this"}\n') + + def test_coverage_counts_nonempty_valid_entries_only(self): + (self.locales / "fr.json").write_text( + json.dumps( + { + "__language_name": "Français", + "Settings": "Paramètres", + "Download {count} items": "", + } + ), + encoding="utf-8", + ) + self.assertEqual(new_locale.locale_coverage(self.locales), [("fr", "Français", 1, 2, 50.0)]) + + def test_coverage_rejects_bad_placeholders_and_unknown_keys(self): + path = self.locales / "fr.json" + path.write_text(json.dumps({"Settings": "Paramètres", "Download {count} items": "Télécharger"}), encoding="utf-8") + with self.assertRaisesRegex(ValueError, "invalid placeholders"): + new_locale.locale_coverage(self.locales) + path.write_text(json.dumps({"Settings": "Paramètres", "Not a source key": "Valeur"}), encoding="utf-8") + with self.assertRaisesRegex(ValueError, "unknown keys"): + new_locale.locale_coverage(self.locales) + + def test_coverage_rejects_malformed_nonblank_translation_without_source_placeholders(self): + path = self.locales / "fr.json" + path.write_text(json.dumps({"Settings": "Paramètres {bad-name}"}), encoding="utf-8") + with self.assertRaisesRegex(ValueError, "invalid placeholders"): + new_locale.locale_coverage(self.locales) + + def test_coverage_rejects_malformed_english_when_translations_are_blank(self): + source = json.loads((self.locales / "en.json").read_text(encoding="utf-8")) + source["Settings"] = "Settings {unclosed" + (self.locales / "en.json").write_text(json.dumps(source), encoding="utf-8") + (self.locales / "fr.json").write_text( + json.dumps({"Settings": "", "Download {count} items": ""}), + encoding="utf-8", + ) + + with self.assertRaisesRegex(ValueError, "locales/en.json has invalid placeholders"): + new_locale.locale_coverage(self.locales) + + +if __name__ == "__main__": + unittest.main() diff --git a/src/app/channels.rs b/src/app/channels.rs index 93e2740..3b8a589 100644 --- a/src/app/channels.rs +++ b/src/app/channels.rs @@ -306,7 +306,7 @@ impl App { return; } let (tx, ctx, name) = (self.tx.clone(), self.ctx.clone(), v.channel_name.clone()); - self.toast(format!("Opening {name}…")); + self.toast(trf("Opening {name}…", &[("name", &name)])); std::thread::spawn(move || { let r = yt::search_channels(&name).and_then(|hits| { hits.into_iter() diff --git a/src/app/downloads.rs b/src/app/downloads.rs index e09afd4..fa7e941 100644 --- a/src/app/downloads.rs +++ b/src/app/downloads.rs @@ -8,7 +8,7 @@ impl App { // a manual request tries everything again, including what gave up before self.dl_gaveup.clear(); let n = self.download_missing(vids, group); - self.toast(if n == 0 { "Everything is already downloaded".to_string() } else { format!("Downloading {n} item{}", if n == 1 { "" } else { "s" }) }); + self.toast(if n == 0 { tr("Everything is already downloaded") } else if n == 1 { trf("Downloading {count} item", &[("count", &n.to_string())]) } else { trf("Downloading {count} items", &[("count", &n.to_string())]) }); } /// Queue everything in `vids` that is not saved yet; returns how many were queued. diff --git a/src/app/ffmpeg.rs b/src/app/ffmpeg.rs index 84ec0c6..730bc88 100644 --- a/src/app/ffmpeg.rs +++ b/src/app/ffmpeg.rs @@ -35,7 +35,7 @@ impl App { crate::platform::reject_ffmpeg(); self.start_ffmpeg_setup(); } else { - self.ffmpeg = FfmpegState::Failed(format!("No ready-made ffmpeg exists for {}. {}", ffmpeg_setup::platform_key(), crate::platform::ffmpeg_hint())); + self.ffmpeg = FfmpegState::Failed(trf("No ready-made ffmpeg exists for {platform}. {hint}", &[("platform", &ffmpeg_setup::platform_key()), ("hint", &crate::platform::ffmpeg_hint())])); } } @@ -44,7 +44,7 @@ impl App { match r { Ok(_) => { self.ffmpeg = FfmpegState::Ready; - self.toast("ffmpeg is ready"); + self.toast(tr("ffmpeg is ready")); // a video that failed only because ffmpeg was missing can be played now if matches!(self.player.state(), State::Error(_)) { self.want_retry = true; diff --git a/src/app/frame.rs b/src/app/frame.rs index 213dae9..c688234 100644 --- a/src/app/frame.rs +++ b/src/app/frame.rs @@ -15,7 +15,7 @@ impl eframe::App for App { /// written to the crash log and the next frame simply tries again. fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.draw(ui))).is_err() { - self.toast("Something went wrong on this page (details are in crash.log)".to_string()); + self.toast(tr("Something went wrong on this page (details are in crash.log)")); // a page that panics every frame would spin: go back to a safe page after a repeat self.panics += 1; if self.panics >= 3 { @@ -79,7 +79,7 @@ impl App { if watching && !self.player.paused { self.player.toggle_pause(); } - self.toast("Sleep timer: playback paused"); + self.toast(tr("Sleep timer: playback paused")); } else { ctx.request_repaint_after(Duration::from_secs(1)); } @@ -170,8 +170,8 @@ impl App { .frame(egui::Frame::new().fill(Color32::from_rgb(70, 48, 18)).inner_margin(egui::Margin::symmetric(24, 6))) .show(ui, |ui| { ui.horizontal_centered(|ui| { - ui.label(egui::RichText::new("You're offline — downloads, history and saved playlists still work.").size(13.5).color(Color32::from_rgb(255, 214, 160))); - if self.sel != Sel::Downloads && ui.add(egui::Button::new("Open downloads").small()).clicked() { + ui.label(egui::RichText::new(tr("You're offline — downloads, history and saved playlists still work.")).size(13.5).color(Color32::from_rgb(255, 214, 160))); + if self.sel != Sel::Downloads && ui.add(egui::Button::new(tr("Open downloads")).small()).clicked() { self.sel = Sel::Downloads; } }); diff --git a/src/app/init.rs b/src/app/init.rs index 11c82fb..2b49965 100644 --- a/src/app/init.rs +++ b/src/app/init.rs @@ -114,7 +114,11 @@ impl App { amb_cur: vec![], amb_tex: None, nav_back: vec![], - nav_cur: NavEntry { sel: Sel::Home, tab: ChanTab::Videos, query: String::new() }, + nav_cur: NavEntry { + sel: Sel::Home, + tab: ChanTab::Videos, + query: String::new(), + }, nav_skip: false, settings: load_settings(), sleep: None, @@ -193,6 +197,7 @@ impl App { fullscreen: false, ctx: cc.egui_ctx.clone(), }; + i18n::set_language(&app.settings.language); // Show what was fetched last time right away; only channels we have never seen // are fetched. Everything else updates when the user presses Refresh. apply_settings(&app.settings); @@ -219,7 +224,9 @@ impl App { .to_socket_addrs() .ok() .and_then(|mut a| a.next()) - .is_some_and(|a| std::net::TcpStream::connect_timeout(&a, Duration::from_secs(4)).is_ok()); + .is_some_and(|a| { + std::net::TcpStream::connect_timeout(&a, Duration::from_secs(4)).is_ok() + }); let _ = tx.send(Msg::Online(up)); ctx.request_repaint(); std::thread::sleep(Duration::from_secs(if up { 30 } else { 8 })); @@ -229,7 +236,10 @@ impl App { app.player.quality = app.settings.default_quality; app.player.speed = app.settings.speed.clamp(0.5, 2.0); app.player.ambient_on = app.settings.ambient; - if let Some(arg) = std::env::args().skip(1).find(|a| !a.starts_with('-') && !a.trim().is_empty()) { + if let Some(arg) = std::env::args() + .skip(1) + .find(|a| !a.starts_with('-') && !a.trim().is_empty()) + { app.open_local(arg); } let fc = load_feed_cache(); diff --git a/src/app/library.rs b/src/app/library.rs index ea32239..614271a 100644 --- a/src/app/library.rs +++ b/src/app/library.rs @@ -30,12 +30,12 @@ impl App { CardAction::NotInterested => { self.settings.hidden.insert(v.id.clone()); self.save_settings(); - self.toast("Hidden from your recommendations"); + self.toast(tr("Hidden from your recommendations")); } CardAction::FewerFromChannel => { self.settings.chan_prefs.entry(v.channel_id.clone()).or_default().fewer = true; self.save_settings(); - self.toast(format!("You'll see less from {}", v.channel_name)); + self.toast(trf("You'll see less from {channel}", &[("channel", &v.channel_name)])); } CardAction::PlayNext => self.queue_add(QItem::Yt(v), true), CardAction::AddToQueue => self.queue_add(QItem::Yt(v), false), @@ -245,7 +245,7 @@ impl App { .collect(); self.lists.push(LocalList { id: id.clone(), name: name.clone(), videos, offline: false }); save_lists(&self.lists); - self.toast(format!("Saved “{name}” with {n} videos")); + self.toast(trf("Saved “{name}” with {count} videos", &[("name", &name), ("count", &n.to_string())])); self.sel = Sel::Local(id); } } diff --git a/src/app/messages.rs b/src/app/messages.rs index 8ecbe29..459af36 100644 --- a/src/app/messages.rs +++ b/src/app/messages.rs @@ -31,7 +31,7 @@ impl App { let name = self.channels.iter().find(|c| c.id == id).map(|c| c.name.clone()).unwrap_or_default(); for v in new.iter().filter(|v| v.kind == Kind::Video && !known.contains(&v.id)).take(3) { if self.notified.insert(v.id.clone()) { - mpris::notify(&format!("New from {name}"), &v.title); + mpris::notify(&trf("New from {name}", &[("name", &name)]), &v.title); } } } @@ -109,11 +109,11 @@ impl App { let lid = format!("pl-{}-{}", now_secs(), self.lists.len()); self.lists.push(LocalList { id: lid, name: name.clone(), videos, offline: false }); save_lists(&self.lists); - self.toast(format!("Imported “{name}” with {n} videos")); + self.toast(trf("Imported “{name}” with {count} videos", &[("name", &name), ("count", &n.to_string())])); } } - Ok(_) => self.toast("That playlist has no videos (or it is private)".to_string()), - Err(e) => self.toast(format!("Could not import {id}: {e}")), + Ok(_) => self.toast(tr("That playlist has no videos (or it is private)")), + Err(e) => self.toast(trf("Could not import {id}: {error}", &[("id", &id), ("error", &e)])), } if left == 0 { self.import_list = None; @@ -174,7 +174,8 @@ impl App { todo.push(i.key); } save(&self.channels); - self.toast(format!("Imported {added} channel{}", if added == 1 { "" } else { "s" })); + let count = added.to_string(); + self.toast(if added == 1 { trf("Imported {count} channel", &[("count", &count)]) } else { trf("Imported {count} channels", &[("count", &count)]) }); // resolve names / avatars (and @handles) one by one, gently let (tx, ctx) = (self.tx.clone(), self.ctx.clone()); std::thread::spawn(move || { @@ -193,7 +194,7 @@ impl App { Ok(c) => self.cues = c, Err(e) => { self.cc_track = None; - self.toast(format!("Captions unavailable: {e}")); + self.toast(trf("Captions unavailable: {error}", &[("error", &e)])); } } } @@ -243,9 +244,9 @@ impl App { } Msg::OpenChannel(r) => match r { Ok(c) => self.show_channel(c), - Err(e) => self.toast(format!("Could not open the channel: {e}")), + Err(e) => self.toast(trf("Could not open the channel: {error}", &[("error", &e)])), }, - Msg::ExportedSubs(n) => self.toast(format!("Exported {n} channels")), + Msg::ExportedSubs(n) => self.toast(trf("Exported {count} channels", &[("count", &n.to_string())])), Msg::Note(t) => self.toast(t), Msg::Podcast(feed, subscribe, r) => self.apply_podcast(feed, subscribe, r), Msg::PodSearch(q, r) => { @@ -267,13 +268,13 @@ impl App { self.clip.busy = None; match r { Ok(p) => { - self.toast("Clip saved"); + self.toast(tr("Clip saved")); self.clip_finished(p.clone()); self.clip.last = Some(p); } Err(e) if e == "cancelled" => { self.clip.pending = None; - self.toast("Clip cancelled"); + self.toast(tr("Clip cancelled")); } Err(e) => self.clip.err = Some(e), } @@ -311,7 +312,7 @@ impl App { self.sel = Sel::Downloads; } } else if !was && up { - self.toast("Back online"); + self.toast(tr("Back online")); if matches!(self.ffmpeg, FfmpegState::Failed(_)) && ffmpeg_setup::source_for_this_system().is_some() { self.start_ffmpeg_setup(); } @@ -335,7 +336,7 @@ impl App { apply_settings(&self.settings); self.save_settings(); self.library = download::list(); - self.toast("Download folder updated"); + self.toast(tr("Download folder updated")); } } Msg::Picked(p) => { @@ -347,7 +348,7 @@ impl App { Msg::LocalProbe(path, r) => match r { Ok((streams, title, artist)) => self.play_file(&path, streams, title, artist), Err(e) => { - self.dl_err = Some(format!("Could not open {path}: {e}")); + self.dl_err = Some(trf("Could not open {path}: {error}", &[("path", &path), ("error", &e)])); self.sel = Sel::Downloads; } }, @@ -372,7 +373,7 @@ impl App { Some(j) => { self.dl_tries.remove(&id); self.dl_gaveup.insert(j.retry.0.id.clone()); - self.toast(format!("Could not download “{}”", j.retry.0.title)); + self.toast(trf("Could not download “{title}”", &[("title", &j.retry.0.title)])); self.dl_errs.push(format!("{}: {e}", j.retry.0.title)); } None => self.dl_errs.push(e), diff --git a/src/app/play.rs b/src/app/play.rs index 8caca7f..9cfe819 100644 --- a/src/app/play.rs +++ b/src/app/play.rs @@ -219,8 +219,8 @@ impl App { .parent() .and_then(|p| p.file_name()) .and_then(|n| n.to_str()) - .unwrap_or("Local file") - .to_string(); + .map(str::to_owned) + .unwrap_or_else(|| tr("Local file")); self.watching = Some(Video { id: format!("local:{path}"), title, @@ -258,9 +258,9 @@ impl App { let (tx, ctx) = (self.tx.clone(), self.ctx.clone()); std::thread::spawn(move || { let mut d = rfd::FileDialog::new() - .set_title("Open media file") - .add_filter("Media files", media::EXTENSIONS) - .add_filter("All files", &["*"]); + .set_title(tr("Open media file")) + .add_filter(tr("Media files"), media::EXTENSIONS) + .add_filter(tr("All files"), &["*"]); if let Some(dir) = dir { d = d.set_directory(dir); } @@ -410,7 +410,7 @@ impl App { self.cache.remove(&w.id); self.inflight.insert(w.id.clone()); self.player.set_loading(); - self.toast("Trying another way to play this video…"); + self.toast(tr("Trying another way to play this video…")); let (tx, ctx, id) = (self.tx.clone(), self.ctx.clone(), w.id.clone()); std::thread::spawn(move || { let r = yt::streams_alt(&id); @@ -572,7 +572,7 @@ impl App { } if matches!(self.sleep, Some(SleepMode::EndOfVideo)) { self.sleep = None; - self.toast("Sleep timer: stopped after this video"); + self.toast(tr("Sleep timer: stopped after this video")); return; } if self.settings.autoplay && self.queue_next() { @@ -598,7 +598,7 @@ impl App { if self.queue_idx.is_none() && self.watching.is_none() { self.queue_idx = Some(0); } - self.toast(if next { "Playing next" } else { "Added to queue" }); + self.toast(tr(if next { "Playing next" } else { "Added to queue" })); } /// Loads the caption track `idx` of the playing video so it can be drawn. @@ -663,7 +663,7 @@ impl App { self.last_skip = Some(i); let (end, cat) = (self.sponsor[i].end, self.sponsor[i].category.clone()); self.player.seek(end + 0.05); - self.toast(format!("Skipped {cat}")); + self.toast(trf("Skipped {category}", &[("category", &cat)])); } } else if self.last_skip.is_some_and(|i| pos < self.sponsor.get(i).map_or(0.0, |s| s.start - 1.0)) { self.last_skip = None; diff --git a/src/app/updater.rs b/src/app/updater.rs index 2810dac..f23d7bd 100644 --- a/src/app/updater.rs +++ b/src/app/updater.rs @@ -50,24 +50,24 @@ impl App { Some(rel) => { // a skipped version stays quiet unless the user asked if manual || rel.version != self.settings.skipped_version { - self.update_note = Some(format!("Version {} is available", rel.version)); + self.update_note = Some(trf("Version {version} is available", &[("version", &rel.version)])); if self.update.as_ref().map(|u| &u.version) != Some(&rel.version) { self.update_state = UpdateState::Idle; } self.update = Some(rel); } else { - self.update_note = Some(format!("Version {} is available (you skipped it)", rel.version)); + self.update_note = Some(trf("Version {version} is available (you skipped it)", &[("version", &rel.version)])); } } None => { self.update = None; - self.update_note = Some(format!("You have the latest version ({})", update::CURRENT)); + self.update_note = Some(trf("You have the latest version ({version})", &[("version", update::CURRENT)])); } } } Err(e) => { if manual { - self.update_note = Some(format!("Could not check for updates: {e}")); + self.update_note = Some(trf("Could not check for updates: {error}", &[("error", &e)])); } } } diff --git a/src/data/settings.rs b/src/data/settings.rs index fbf9e72..7da1f17 100644 --- a/src/data/settings.rs +++ b/src/data/settings.rs @@ -54,6 +54,8 @@ pub(crate) struct Settings { pub(crate) accent_custom: [u8; 3], /// 0 dark, 1 light, 2 follow the system pub(crate) theme: u8, + /// UI language preference: system, en, or a language catalog code. + pub(crate) language: String, pub(crate) font_scale: f32, /// 0 compact, 1 comfortable, 2 spacious pub(crate) density: u8, @@ -97,6 +99,7 @@ impl Default for Settings { last_update_check: 0, accent_custom: [255, 154, 31], theme: 0, + language: "system".into(), font_scale: 1.0, density: 1, view_mode: 0, @@ -139,8 +142,18 @@ pub(crate) fn save_settings(s: &Settings) { /// Push settings that are read from global state (accent colour, download folder). pub(crate) fn apply_settings(s: &Settings) { - ACCENT_IDX.store(s.accent.min(ACCENTS.len()), std::sync::atomic::Ordering::Relaxed); + ACCENT_IDX.store( + s.accent.min(ACCENTS.len()), + std::sync::atomic::Ordering::Relaxed, + ); let c = s.accent_custom; - ACCENT_CUSTOM.store(((c[0] as u32) << 16) | ((c[1] as u32) << 8) | c[2] as u32, std::sync::atomic::Ordering::Relaxed); - download::set_dir(if s.download_dir.trim().is_empty() { None } else { Some(s.download_dir.clone().into()) }); + ACCENT_CUSTOM.store( + ((c[0] as u32) << 16) | ((c[1] as u32) << 8) | c[2] as u32, + std::sync::atomic::Ordering::Relaxed, + ); + download::set_dir(if s.download_dir.trim().is_empty() { + None + } else { + Some(s.download_dir.clone().into()) + }); } diff --git a/src/locale_format.rs b/src/locale_format.rs new file mode 100644 index 0000000..8af21c9 --- /dev/null +++ b/src/locale_format.rs @@ -0,0 +1,119 @@ +//! The message grammar shared by catalog validation and runtime interpolation. + +enum Token<'a> { + Text(&'a str), + Placeholder(&'a str), + Brace(char), +} + +/// Parse named placeholders and doubled literal braces without interpreting inserted values. +fn tokens(text: &str) -> Result>, String> { + let bytes = text.as_bytes(); + let mut result = Vec::new(); + let mut start = 0; + let mut i = 0; + while i < bytes.len() { + if bytes[i] != b'{' && bytes[i] != b'}' { + i += 1; + continue; + } + if start < i { + result.push(Token::Text(&text[start..i])); + } + let brace = bytes[i]; + if bytes.get(i + 1) == Some(&brace) { + result.push(Token::Brace(brace as char)); + i += 2; + } else if brace == b'{' { + let end = text[i + 1..] + .find('}') + .map(|offset| i + 1 + offset) + .ok_or_else(|| format!("unclosed placeholder at byte {i}"))?; + let name = &text[i + 1..end]; + let mut letters = name.bytes(); + let valid_start = letters + .next() + .is_some_and(|c| c.is_ascii_alphabetic() || c == b'_'); + if !valid_start || !letters.all(|c| c.is_ascii_alphanumeric() || c == b'_') { + return Err(format!("invalid placeholder at byte {i}")); + } + result.push(Token::Placeholder(name)); + i = end + 1; + } else { + return Err(format!("unmatched closing brace at byte {i}")); + } + start = i; + } + if start < text.len() { + result.push(Token::Text(&text[start..])); + } + Ok(result) +} + +/// Return sorted names, preserving repeated placeholders; reject malformed message syntax. +#[allow(dead_code)] // Used by the build script and app tests, rather than normal app execution. +pub(crate) fn placeholder_names(text: &str) -> Result, String> { + let mut names = tokens(text)? + .into_iter() + .filter_map(|token| match token { + Token::Placeholder(name) => Some(name.to_owned()), + _ => None, + }) + .collect::>(); + names.sort(); + Ok(names) +} + +/// Substitute values once and decode doubled braces in message text. +#[allow(dead_code)] // The build script uses validation, while the app also renders messages. +pub(crate) fn render(text: &str, values: &[(&str, &str)]) -> Result { + let mut output = String::new(); + for token in tokens(text)? { + match token { + Token::Text(text) => output.push_str(text), + Token::Brace(brace) => output.push(brace), + Token::Placeholder(name) => { + if let Some((_, value)) = values.iter().find(|(key, _)| *key == name) { + output.push_str(value); + } else { + output.push('{'); + output.push_str(name); + output.push('}'); + } + } + } + } + Ok(output) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn grammar_matches_shared_python_fixtures() { + let cases: Vec = + serde_json::from_str(include_str!("../tests/fixtures/locale-placeholders.json")) + .unwrap(); + for case in cases { + let text = case["text"].as_str().unwrap(); + let actual = placeholder_names(text); + if case["names"].is_null() { + assert!(actual.is_err(), "accepted malformed message {text:?}"); + } else { + let expected: Vec = serde_json::from_value(case["names"].clone()).unwrap(); + assert_eq!(actual.unwrap(), expected, "message {text:?}"); + } + } + } + + #[test] + fn interpolation_preserves_values_and_decodes_escaped_braces() { + assert_eq!(render("{{{count}}}", &[("count", "2")]).unwrap(), "{2}"); + assert_eq!( + render("{title} {count}", &[("title", "A {count}"), ("count", "2")]).unwrap(), + "A {count} 2" + ); + assert_eq!(render("{missing}", &[]).unwrap(), "{missing}"); + } +} diff --git a/src/main.rs b/src/main.rs index 6df549c..0673f49 100644 --- a/src/main.rs +++ b/src/main.rs @@ -16,6 +16,7 @@ mod app; mod data; mod library; +mod locale_format; mod platform; mod playback; mod ui; diff --git a/src/ui/cards.rs b/src/ui/cards.rs index 6a59fb5..2106a55 100644 --- a/src/ui/cards.rs +++ b/src/ui/cards.rs @@ -39,13 +39,13 @@ pub(crate) fn video_card(ui: &mut egui::Ui, rect: Rect, th: f32, v: &Video, info p.rect_filled(b, CornerRadius::same(6), LIVE); let pulse = 0.55 + 0.45 * (ui.input(|i| i.time) * 3.0).sin().abs() as f32; p.circle_filled(b.left_center() + vec2(12.0, 0.0), 4.0, Color32::WHITE.gamma_multiply(pulse)); - p.text(b.center() + vec2(7.0, 0.0), Align2::CENTER_CENTER, "LIVE", FontId::proportional(12.0), Color32::WHITE); + p.text(b.center() + vec2(7.0, 0.0), Align2::CENTER_CENTER, tr("LIVE"), FontId::proportional(12.0), Color32::WHITE); ui.ctx().request_repaint_after(Duration::from_millis(33)); } Kind::Upcoming => { let b = Rect::from_min_size(img.min + vec2(8.0, 8.0), vec2(88.0, 22.0)); p.rect_filled(b, CornerRadius::same(6), accent()); - p.text(b.center(), Align2::CENTER_CENTER, "UPCOMING", FontId::proportional(12.0), ON_ACCENT); + p.text(b.center(), Align2::CENTER_CENTER, tr("UPCOMING"), FontId::proportional(12.0), ON_ACCENT); } Kind::Video if !v.duration.is_empty() => { let g = ui.fonts_mut(|f| f.layout_no_wrap(v.duration.clone(), FontId::proportional(12.0), Color32::WHITE)); @@ -68,7 +68,7 @@ pub(crate) fn video_card(ui: &mut egui::Ui, rect: Rect, th: f32, v: &Video, info if info.is_new { let b = Rect::from_min_size(Pos2::new(img.max.x - 52.0, img.min.y + 8.0), vec2(44.0, 20.0)); p.rect_filled(b, CornerRadius::same(6), accent()); - p.text(b.center(), Align2::CENTER_CENTER, "NEW", FontId::proportional(11.0), ON_ACCENT); + p.text(b.center(), Align2::CENTER_CENTER, tr("NEW"), FontId::proportional(11.0), ON_ACCENT); } if let Some(wf) = info.watched { let pp = ui.painter(); @@ -109,26 +109,26 @@ pub(crate) fn video_card(ui: &mut egui::Ui, rect: Rect, th: f32, v: &Video, info let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand); let mut act: Option = None; resp.context_menu(|ui| { - if ui.button("Play audio only").clicked() { + if ui.button(tr("Play audio only")).clicked() { act = Some(CardAction::PlayAudio); ui.close(); } if v.kind != Kind::Live { - if ui.button("Play next").clicked() { + if ui.button(tr("Play next")).clicked() { act = Some(CardAction::PlayNext); ui.close(); } - if ui.button("Add to queue").clicked() { + if ui.button(tr("Add to queue")).clicked() { act = Some(CardAction::AddToQueue); ui.close(); } } if v.kind != Kind::Live { if info.video_saved { - ui.add_enabled(false, egui::Button::new("Video downloaded")); + ui.add_enabled(false, egui::Button::new(tr("Video downloaded"))); } else { - ui.menu_button("Download video", |ui| { - for (label, q) in [("Best available", 2160u32), ("1080p", 1080), ("720p", 720), ("480p", 480), ("360p", 360)] { + ui.menu_button(tr("Download video"), |ui| { + for (label, q) in [(tr("Best available"), 2160u32), ("1080p".to_string(), 1080), ("720p".to_string(), 720), ("480p".to_string(), 480), ("360p".to_string(), 360)] { if ui.button(label).clicked() { act = Some(CardAction::Download(false, q)); ui.close(); @@ -137,8 +137,8 @@ pub(crate) fn video_card(ui: &mut egui::Ui, rect: Rect, th: f32, v: &Video, info }); } if info.audio_saved { - ui.add_enabled(false, egui::Button::new("Audio downloaded")); - } else if ui.button("Download audio only").clicked() { + ui.add_enabled(false, egui::Button::new(tr("Audio downloaded"))); + } else if ui.button(tr("Download audio only")).clicked() { act = Some(CardAction::Download(true, 0)); ui.close(); } @@ -146,41 +146,41 @@ pub(crate) fn video_card(ui: &mut egui::Ui, rect: Rect, th: f32, v: &Video, info } { let in_wl = info.lists.iter().any(|l| l.id == "watchlater" && l.videos.iter().any(|x| x.id == v.id)); - if ui.button(if in_wl { "Remove from Watch later" } else { "Watch later" }).clicked() { + if ui.button(tr(if in_wl { "Remove from Watch later" } else { "Watch later" })).clicked() { act = Some(CardAction::ToggleList("watchlater".into())); ui.close(); } } - ui.menu_button("Add to playlist", |ui| { + ui.menu_button(tr("Add to playlist"), |ui| { for l in info.lists { let has = l.videos.iter().any(|x| x.id == v.id); - if ui.selectable_label(has, l.name.clone()).clicked() { + if ui.selectable_label(has, playlist_label(l)).clicked() { act = Some(CardAction::ToggleList(l.id.clone())); ui.close(); } } ui.separator(); - if ui.button("+ New playlist…").clicked() { + if ui.button(tr("+ New playlist…")).clicked() { act = Some(CardAction::NewList); ui.close(); } }); if matches!(v.kind, Kind::Video) && !info.in_history_view { ui.separator(); - if ui.button("Not interested").clicked() { + if ui.button(tr("Not interested")).clicked() { act = Some(CardAction::NotInterested); ui.close(); } - if !v.channel_id.is_empty() && ui.button("Recommend less from this channel").clicked() { + if !v.channel_id.is_empty() && ui.button(tr("Recommend less from this channel")).clicked() { act = Some(CardAction::FewerFromChannel); ui.close(); } } - if info.in_history_view && ui.button("Remove from history").clicked() { + if info.in_history_view && ui.button(tr("Remove from history")).clicked() { act = Some(CardAction::RemoveFromHistory); ui.close(); } - if info.current_list.is_some() && ui.button("Remove from this playlist").clicked() { + if info.current_list.is_some() && ui.button(tr("Remove from this playlist")).clicked() { act = Some(CardAction::RemoveFromList); ui.close(); } diff --git a/src/ui/channel_view.rs b/src/ui/channel_view.rs index 58c5832..edb1566 100644 --- a/src/ui/channel_view.rs +++ b/src/ui/channel_view.rs @@ -34,29 +34,29 @@ impl App { // refresh / play all / "updated": next to the name on a wide window, under it on a narrow one let narrow_hdr = w < 920.0; let actions = |app: &mut App, ui: &mut egui::Ui| { - if icon_btn(ui, "refresh", "Refresh", None, ink(), false, true).clicked() { + if icon_btn(ui, "refresh", &tr("Refresh"), None, ink(), false, true).clicked() { app.refresh(&ch); app.ensure_tab(true); } if matches!(app.chan_tab, ChanTab::Videos | ChanTab::Live | ChanTab::Shorts) { - if icon_btn(ui, "play", "Play all", Some(accent()), ON_ACCENT, false, true).clicked() { + if icon_btn(ui, "play", &tr("Play all"), Some(accent()), ON_ACCENT, false, true).clicked() { app.play_all_visible(false); } } // the first press asks, the second one unsubscribes let sure = app.confirm_unsub; - let label = if sure { "Confirm unsubscribe" } else { "Unsubscribe" }; - if icon_btn(ui, "", label, if sure { Some(LIVE) } else { None }, if sure { Color32::WHITE } else { ink() }, false, true).clicked() { + let label = tr(if sure { "Confirm unsubscribe" } else { "Unsubscribe" }); + if icon_btn(ui, "", &label, if sure { Some(LIVE) } else { None }, if sure { Color32::WHITE } else { ink() }, false, true).clicked() { if sure { app.confirm_unsub = false; app.remove_channel(&ch.id); - app.toast(format!("Unsubscribed from {}", ch.name)); + app.toast(trf("Unsubscribed from {channel}", &[("channel", &ch.name)])); } else { app.confirm_unsub = true; } } if let Some(ts) = app.fcache.updated.get(&ch.id) { - ui.label(egui::RichText::new(format!("updated {}", ago(*ts))).size(13.0).color(muted())); + ui.label(egui::RichText::new(trf("Updated {time}", &[("time", &localized_ago(*ts))])).size(13.0).color(muted())); } }; ui.horizontal(|ui| { @@ -101,14 +101,14 @@ impl App { // tabs ui.horizontal_wrapped(|ui| { for (t, label) in [ - (ChanTab::Videos, "Videos"), - (ChanTab::Live, "Live"), - (ChanTab::Shorts, "Shorts"), - (ChanTab::Playlists, "Playlists"), - (ChanTab::About, "About"), + (ChanTab::Videos, tr("Videos")), + (ChanTab::Live, tr("Live")), + (ChanTab::Shorts, tr("Shorts")), + (ChanTab::Playlists, tr("Playlists")), + (ChanTab::About, tr("About")), ] { let on = self.chan_tab == t; - let g = ui.fonts_mut(|f| f.layout_no_wrap(label.to_string(), FontId::proportional(16.0), ink())); + let g = ui.fonts_mut(|f| f.layout_no_wrap(label.clone(), FontId::proportional(16.0), ink())); let (r, resp) = ui.allocate_exact_size(vec2(g.size().x + 28.0, 36.0), Sense::click()); let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand); let hv = ui.ctx().animate_bool_with_time(resp.id, resp.hovered(), 0.12); @@ -126,7 +126,7 @@ impl App { if w >= 820.0 { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let width = 330.0_f32.min(ui.available_width()); - let hint = format!("Search in {}", ch.name); + let hint = trf("Search in {channel}", &[("channel", &ch.name)]); let f = text_field(ui, &mut self.chan_q, &hint, width, 40.0, "search", None, false); if f.submit { self.start_chan_search(); @@ -139,7 +139,7 @@ impl App { }); if w < 820.0 { ui.add_space(6.0); - let hint = format!("Search in {}", ch.name); + let hint = trf("Search in {channel}", &[("channel", &ch.name)]); let f = text_field(ui, &mut self.chan_q, &hint, w, 40.0, "search", None, false); if f.submit { self.start_chan_search(); @@ -167,11 +167,11 @@ impl App { ui.add_space(6.0); ui.horizontal(|ui| { let msg = if loading { - format!("Searching “{q}”…") + trf("Searching “{query}”…", &[("query", &q)]) } else if let Some(e) = &failed { - format!("Search failed: {e}") + trf("Search failed: {error}", &[("error", e)]) } else { - format!("Results for “{q}” • {n_v} videos, {n_p} playlists") + trf("Results for “{query}” • {videos} videos, {playlists} playlists", &[("query", &q), ("videos", &n_v.to_string()), ("playlists", &n_p.to_string())]) }; ui.label(egui::RichText::new(msg).size(13.0).color(if failed.is_some() { LIVE } else { muted() })); }); @@ -201,20 +201,20 @@ impl App { }; if !a.description.is_empty() { card(ui, &mut |ui| { - ui.label(egui::RichText::new("Description").size(13.0).color(muted()).strong()); + ui.label(egui::RichText::new(tr("Description")).size(13.0).color(muted()).strong()); ui.add_space(4.0); ui.add(egui::Label::new(egui::RichText::new(&a.description).size(15.0)).wrap()); }); } card(ui, &mut |ui| { - ui.label(egui::RichText::new("Stats").size(13.0).color(muted()).strong()); + ui.label(egui::RichText::new(tr("Stats")).size(13.0).color(muted()).strong()); ui.add_space(4.0); for (k, v) in [ - ("Subscribers", &a.subs), - ("Videos", &a.videos), - ("Views", &a.views), - ("Joined", &a.joined), - ("Country", &a.country), + (tr("Subscribers"), &a.subs), + (tr("Videos"), &a.videos), + (tr("Views"), &a.views), + (tr("Joined"), &a.joined), + (tr("Country"), &a.country), ] { if !v.is_empty() { ui.horizontal(|ui| { @@ -226,7 +226,7 @@ impl App { }); if !a.links.is_empty() { card(ui, &mut |ui| { - ui.label(egui::RichText::new("Links").size(13.0).color(muted()).strong()); + ui.label(egui::RichText::new(tr("Links")).size(13.0).color(muted()).strong()); ui.add_space(4.0); for (title, url) in &a.links { ui.horizontal(|ui| { diff --git a/src/ui/dialogs.rs b/src/ui/dialogs.rs index 08f2ba9..6c4f54a 100644 --- a/src/ui/dialogs.rs +++ b/src/ui/dialogs.rs @@ -7,23 +7,23 @@ impl App { pub(crate) fn new_group_dialog(&mut self, ctx: &egui::Context) { let Some((name, _)) = self.new_group.as_mut() else { return }; let (mut create, mut cancel) = (false, false); - egui::Window::new("New group") + egui::Window::new(tr("New group")) .collapsible(false) .resizable(false) .anchor(Align2::CENTER_CENTER, vec2(0.0, 0.0)) .show(ctx, |ui| { ui.set_width(300.0); - let f = text_field(ui, name, "Group name, e.g. Music", 300.0, 42.0, "folder", None, false); + let f = text_field(ui, name, &tr("Group name, e.g. Music"), 300.0, 42.0, "folder", None, false); f.resp.request_focus(); if f.submit { create = true; } ui.add_space(6.0); ui.horizontal(|ui| { - if ui.add(egui::Button::new(egui::RichText::new("Create").strong()).fill(accent())).clicked() { + if ui.add(egui::Button::new(egui::RichText::new(tr("Create")).strong()).fill(accent())).clicked() { create = true; } - if ui.button("Cancel").clicked() { + if ui.button(tr("Cancel")).clicked() { cancel = true; } }); @@ -53,26 +53,26 @@ impl App { let Some((name, pending)) = self.new_list.as_mut() else { return }; let mut create = false; let mut cancel = false; - egui::Window::new("New playlist") + egui::Window::new(tr("New playlist")) .collapsible(false) .resizable(false) .anchor(Align2::CENTER_CENTER, vec2(0.0, 0.0)) .show(ctx, |ui| { ui.set_width(300.0); - let f = text_field(ui, name, "Playlist name", 300.0, 42.0, "list", None, false); + let f = text_field(ui, name, &tr("Playlist name"), 300.0, 42.0, "list", None, false); f.resp.request_focus(); if f.submit { create = true; } if let Some(v) = pending.as_ref() { - ui.label(egui::RichText::new(format!("“{}” will be added to it.", v.title)).size(12.0).color(muted())); + ui.label(egui::RichText::new(trf("“{title}” will be added to it.", &[("title", &v.title)])).size(12.0).color(muted())); } ui.add_space(6.0); ui.horizontal(|ui| { - if ui.add(egui::Button::new(egui::RichText::new("Create").strong()).fill(accent())).clicked() { + if ui.add(egui::Button::new(egui::RichText::new(tr("Create")).strong()).fill(accent())).clicked() { create = true; } - if ui.button("Cancel").clicked() { + if ui.button(tr("Cancel")).clicked() { cancel = true; } }); @@ -126,7 +126,7 @@ impl App { } if self.show_help { let mut open = true; - egui::Window::new("Keyboard shortcuts") + egui::Window::new(tr("Keyboard shortcuts")) .open(&mut open) .collapsible(false) .resizable(false) @@ -134,24 +134,24 @@ impl App { .show(ctx, |ui| { ui.set_width(430.0); let rows = [ - ("Space / K", "Play or pause"), - ("← →", "Seek 5 seconds"), - ("J / L", "Seek 10 seconds"), - ("↑ ↓", "Volume"), - ("M", "Mute"), - ("[ / ]", "Slower / faster"), - ("N / P", "Next / previous in queue"), - ("A", "Audio only on or off"), - ("I", "Mini player on or off"), - ("B", "Ambient mode on or off"), - ("W", "Watch later on or off"), - ("C", "Comments"), - ("Y", "Lyrics (music)"), - ("F", "Fullscreen"), - ("Esc", "Back (keeps playing in PiP)"), - ("Ctrl+O", "Open a file"), - ("Ctrl+B", "Collapse the sidebar"), - ("?", "This sheet"), + ("Space / K", tr("Play or pause")), + ("← →", tr("Seek 5 seconds")), + ("J / L", tr("Seek 10 seconds")), + ("↑ ↓", tr("Volume")), + ("M", tr("Mute")), + ("[ / ]", tr("Slower / faster")), + ("N / P", tr("Next / previous in queue")), + ("A", tr("Audio only on or off")), + ("I", tr("Mini player on or off")), + ("B", tr("Ambient mode on or off")), + ("W", tr("Watch later on or off")), + ("C", tr("Comments")), + ("Y", tr("Lyrics (music)")), + ("F", tr("Fullscreen")), + ("Esc", tr("Back (keeps playing in PiP)")), + ("Ctrl+O", tr("Open a file")), + ("Ctrl+B", tr("Collapse the sidebar")), + ("?", tr("This sheet")), ]; for (k, d) in rows { ui.horizontal(|ui| { @@ -175,13 +175,13 @@ impl App { let mut cancel = false; let ids = playlist_ids(text); let busy = *loading > 0; - egui::Window::new("Import playlists from YouTube") + egui::Window::new(tr("Import playlists from YouTube")) .collapsible(false) .resizable(false) .anchor(Align2::CENTER_CENTER, vec2(0.0, 0.0)) .show(ctx, |ui| { ui.set_width(420.0); - ui.label(egui::RichText::new("Paste one or more playlist links (or ids). Each becomes a playlist you can edit, download and keep offline.").size(12.5).color(muted())); + ui.label(egui::RichText::new(tr("Paste one or more playlist links (or ids). Each becomes a playlist you can edit, download and keep offline.")).size(12.5).color(muted())); ui.add_space(6.0); let f = text_field(ui, text, "https://www.youtube.com/playlist?list=…", 420.0, 42.0, "list", None, false); if !busy { @@ -192,22 +192,23 @@ impl App { } ui.add_space(4.0); let note = if busy { - format!("Importing… {loading} left") + trf("Importing… {count} left", &[("count", &loading.to_string())]) } else if text.trim().is_empty() { String::new() } else if ids.is_empty() { - "No playlist link found yet. Private playlists cannot be imported.".to_string() + tr("No playlist link found yet. Private playlists cannot be imported.") } else { - format!("{} playlist{} found", ids.len(), if ids.len() == 1 { "" } else { "s" }) + let count = ids.len().to_string(); + if ids.len() == 1 { trf("{count} playlist found", &[("count", &count)]) } else { trf("{count} playlists found", &[("count", &count)]) } }; ui.label(egui::RichText::new(note).size(12.0).color(muted())); ui.add_space(6.0); ui.horizontal(|ui| { - let b = egui::Button::new(egui::RichText::new("Import").strong()).fill(accent()); + let b = egui::Button::new(egui::RichText::new(tr("Import")).strong()).fill(accent()); if ui.add_enabled(!ids.is_empty() && !busy, b).clicked() { go = true; } - if ui.button(if busy { "Close" } else { "Cancel" }).clicked() { + if ui.button(tr(if busy { "Close" } else { "Cancel" })).clicked() { cancel = true; } }); diff --git a/src/ui/downloads_view.rs b/src/ui/downloads_view.rs index d99216e..e9abc85 100644 --- a/src/ui/downloads_view.rs +++ b/src/ui/downloads_view.rs @@ -28,7 +28,7 @@ impl App { ui.add_space(8.0); let narrow = ui.available_width() < 900.0; ui.horizontal_wrapped(|ui| { - ui.label(egui::RichText::new("Downloads").size(26.0).strong()); + ui.label(egui::RichText::new(tr("Downloads")).size(26.0).strong()); ui.label( egui::RichText::new(download::dir().display().to_string()) .size(12.0) @@ -38,21 +38,22 @@ impl App { ui.end_row(); } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center).with_main_wrap(true), |ui| { - if ui.add(egui::Button::new("Open folder")).clicked() { + if ui.add(egui::Button::new(tr("Open folder"))).clicked() { let _ = std::fs::create_dir_all(download::dir()); crate::platform::open_path(&download::dir()); } if !self.library.is_empty() { if self.dl_sel.is_some() { let n = self.dl_sel.as_ref().map_or(0, |s| s.len()); - if ui.add(egui::Button::new("Done")).clicked() { + if ui.add(egui::Button::new(tr("Done"))).clicked() { self.dl_sel = None; self.dl_confirm = false; } + let count = n.to_string(); let label = if self.dl_confirm { - format!("Confirm delete ({n})") + trf("Confirm delete ({count})", &[("count", &count)]) } else { - format!("Delete ({n})") + trf("Delete ({count})", &[("count", &count)]) }; let b = egui::Button::new(egui::RichText::new(label).color(if n > 0 { Color32::WHITE } else { muted() })) .fill(if n > 0 { LIVE } else { card() }); @@ -71,7 +72,7 @@ impl App { } } let all = !shown.is_empty() && self.dl_sel.as_ref().is_some_and(|s| shown.iter().all(|d| s.contains(&d.file))); - if ui.add(egui::Button::new(if all { "Select none" } else { "Select all" })).clicked() { + if ui.add(egui::Button::new(tr(if all { "Select none" } else { "Select all" }))).clicked() { self.dl_confirm = false; if all { self.dl_sel = Some(HashSet::new()); @@ -79,19 +80,25 @@ impl App { self.dl_sel = Some(shown.iter().map(|d| d.file.clone()).collect()); } } - } else if ui.add(egui::Button::new("Select")).clicked() { + } else if ui.add(egui::Button::new(tr("Select"))).clicked() { self.dl_sel = Some(HashSet::new()); } } }); }); if let Some(e) = &self.dl_err { - ui.colored_label(LIVE, format!("Download failed: {e}")); + ui.colored_label(LIVE, trf("Download failed: {error}", &[("error", e)])); } if !self.dl_errs.is_empty() { ui.horizontal(|ui| { - ui.colored_label(LIVE, format!("{} download{} failed:", self.dl_errs.len(), if self.dl_errs.len() == 1 { "" } else { "s" })); - if ui.small_button("Dismiss").clicked() { + let count = self.dl_errs.len().to_string(); + let summary = if self.dl_errs.len() == 1 { + trf("{count} download failed:", &[("count", &count)]) + } else { + trf("{count} downloads failed:", &[("count", &count)]) + }; + ui.colored_label(LIVE, summary); + if ui.small_button(tr("Dismiss")).clicked() { self.dl_errs.clear(); } }); @@ -102,13 +109,13 @@ impl App { ui.add_space(8.0); if !self.library.is_empty() { let w = ui.available_width(); - text_field(ui, &mut self.lib_filter, "Search downloads", w, 38.0, "search", None, false); + text_field(ui, &mut self.lib_filter, &tr("Search downloads"), w, 38.0, "search", None, false); ui.add_space(6.0); ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 6.0; - for (label, v) in [("Newest", 0u8), ("Largest", 1), ("Oldest", 2), ("A–Z", 3)] { + for (label, v) in [(tr("Newest"), 0u8), (tr("Largest"), 1), (tr("Oldest"), 2), (tr("A–Z"), 3)] { let on = self.dl_sort == v; - if icon_btn(ui, "", label, Some(if on { accent() } else { card() }), if on { ON_ACCENT } else { ink() }, false, true).clicked() { + if icon_btn(ui, "", &label, Some(if on { accent() } else { card() }), if on { ON_ACCENT } else { ink() }, false, true).clicked() { self.dl_sort = v; } } @@ -116,7 +123,7 @@ impl App { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { self.view_toggle(ui); ui.label( - egui::RichText::new(format!("{} items • {} • {} free", self.library.len(), fmt_size(total), fmt_size(free_space(&download::dir())))) + egui::RichText::new(trf("{count} items • {used} • {free} free", &[("count", &self.library.len().to_string()), ("used", &fmt_size(total)), ("free", &fmt_size(free_space(&download::dir()))) ])) .size(12.5) .color(muted()), ); @@ -139,7 +146,7 @@ impl App { let (r, _) = ui.allocate_exact_size(vec2(56.0, 56.0), Sense::hover()); icons::draw(ui.painter(), r.center(), "download", 48.0, muted()); ui.label( - egui::RichText::new("Nothing downloaded yet. Use the Download button in the player, or right-click any video.") + egui::RichText::new(tr("Nothing downloaded yet. Use the Download button in the player, or right-click any video.")) .size(16.0) .color(muted()), ); @@ -177,15 +184,15 @@ impl App { let mb = j.bytes as f64 / 1_048_576.0; let speed = mb / secs; let eta = if j.progress > 0.02 { secs * (1.0 - j.progress as f64) / j.progress as f64 } else { 0.0 }; - let mut line = format!("{}% • {:.1} MB", (j.progress * 100.0) as u32, mb); + let mut line = trf("{percent}% • {size} MB", &[("percent", &((j.progress * 100.0) as u32).to_string()), ("size", &format!("{mb:.1}"))]); if is_paused { - line += " • Paused"; + line += &trf(" • {status}", &[("status", &tr("Paused"))]); } else { if speed > 0.0 { - line += &format!(" • {:.1} MB/s", speed); + line += &trf(" • {speed} MB/s", &[("speed", &format!("{speed:.1}"))]); } if eta > 0.0 { - line += &format!(" • about {} left", fmt_time(eta)); + line += &trf(" • about {time} left", &[("time", &fmt_time(eta))]); } } ui.painter().text(Pos2::new(tx, rect.min.y + 64.0), Align2::LEFT_CENTER, line, FontId::proportional(13.0), muted()); @@ -193,13 +200,13 @@ impl App { let br = Rect::from_center_size(Pos2::new(rect.max.x - 56.0, rect.center().y), vec2(88.0, 32.0)); let resp = ui.interact(br, uid(("dlc", &j.id)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand); ui.painter().rect_filled(br, CornerRadius::same(16), if resp.hovered() { LIVE } else { card_hi() }); - ui.painter().text(br.center(), Align2::CENTER_CENTER, "Cancel", FontId::proportional(14.0), Color32::WHITE); + ui.painter().text(br.center(), Align2::CENTER_CENTER, tr("Cancel"), FontId::proportional(14.0), Color32::WHITE); if resp.clicked() { cancel = Some(j.id.clone()); } // pause / resume let pr = Rect::from_center_size(Pos2::new(br.min.x - 28.0, rect.center().y), vec2(36.0, 32.0)); - let presp = ui.interact(pr, uid(("dlp", &j.id)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text(if is_paused { "Resume" } else { "Pause" }); + let presp = ui.interact(pr, uid(("dlp", &j.id)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text(tr(if is_paused { "Resume" } else { "Pause" })); ui.painter().rect_filled(pr, CornerRadius::same(16), if is_paused { accent() } else if presp.hovered() { card_hi() } else { card() }); icons::draw(ui.painter(), pr.center(), if is_paused { "play" } else { "pause" }, 15.0, if is_paused { ON_ACCENT } else { ink() }); if presp.clicked() { @@ -240,7 +247,7 @@ impl App { if rows.is_empty() && !self.library.is_empty() { ui.add_space(40.0); ui.vertical_centered(|ui| { - ui.label(egui::RichText::new("No downloads match your search.").size(16.0).color(muted())); + ui.label(egui::RichText::new(tr("No downloads match your search.")).size(16.0).color(muted())); }); } macro_rules! flush_cards { @@ -258,9 +265,9 @@ impl App { let uri = if std::path::Path::new(&d.thumb).exists() { crate::platform::file_uri(&d.thumb) } else { String::new() }; let size = std::fs::metadata(&d.file).map(|x| x.len()).unwrap_or(0) as f64 / 1_048_576.0; let sub = if d.audio_only { - format!("{} • audio • {:.0} MB", d.channel, size) + trf("{channel} • {kind} • {size} MB", &[("channel", &d.channel), ("kind", &tr("Audio")), ("size", &format!("{size:.0}"))]) } else { - format!("{} • {}p • {:.0} MB", d.channel, d.height, size) + trf("{channel} • {quality}p • {size} MB", &[("channel", &d.channel), ("quality", &d.height.to_string()), ("size", &format!("{size:.0}"))]) }; let img = views::media_card(ui, rect, m, &uri, &d.title, &sub, hv); views::pill_label(ui, img.right_bottom(), &fmt_time(d.duration)); @@ -304,7 +311,12 @@ impl App { let hv = ui.ctx().animate_bool_with_time(resp.id, resp.hovered(), 0.12); let uri = members.iter().find(|x| std::path::Path::new(&x.thumb).exists()).map(|x| crate::platform::file_uri(&x.thumb)).unwrap_or_default(); let mb: f64 = members.iter().map(|x| std::fs::metadata(&x.file).map(|f| f.len()).unwrap_or(0) as f64).sum::() / 1_048_576.0; - let sub = format!("{} item{} • {:.0} MB", members.len(), if members.len() == 1 { "" } else { "s" }, mb); + let count = members.len().to_string(); + let sub = if members.len() == 1 { + trf("{count} item • {size} MB", &[("count", &count), ("size", &format!("{mb:.0}"))]) + } else { + trf("{count} items • {size} MB", &[("count", &count), ("size", &format!("{mb:.0}"))]) + }; let img = views::media_card(ui, rect, m, &uri, name, &sub, hv); // a folder badge with the track count let b = Rect::from_min_size(img.min + vec2(7.0, 7.0), vec2(48.0, 22.0)); @@ -380,10 +392,16 @@ impl App { let mb: f64 = members.iter().map(|m| std::fs::metadata(&m.file).map(|x| x.len()).unwrap_or(0) as f64).sum::() / 1_048_576.0; let name_t = truncate(ui, &name, FontId::proportional(17.0), w - 230.0, 1); ui.painter().text(Pos2::new(rect.min.x + 58.0, rect.center().y - 10.0), Align2::LEFT_CENTER, name_t, FontId::proportional(17.0), ink()); + let count = members.len().to_string(); + let summary = if members.len() == 1 { + trf("{count} item • {size} MB", &[("count", &count), ("size", &format!("{mb:.0}"))]) + } else { + trf("{count} items • {size} MB", &[("count", &count), ("size", &format!("{mb:.0}"))]) + }; ui.painter().text( Pos2::new(rect.min.x + 58.0, rect.center().y + 12.0), Align2::LEFT_CENTER, - format!("{} item{} • {:.0} MB", members.len(), if members.len() == 1 { "" } else { "s" }, mb), + summary, FontId::proportional(13.0), muted(), ); @@ -438,9 +456,9 @@ impl App { let title = truncate(ui, &d.title, FontId::proportional(16.0), w - 320.0, 1); let size = std::fs::metadata(&d.file).map(|m| m.len()).unwrap_or(0) as f64 / 1_048_576.0; let sub = if d.audio_only { - format!("{} • audio • {} • {:.0} MB", d.channel, fmt_time(d.duration), size) + trf("{channel} • {kind} • {time} • {size} MB", &[("channel", &d.channel), ("kind", &tr("Audio")), ("time", &fmt_time(d.duration)), ("size", &format!("{size:.0}"))]) } else { - format!("{} • {}p • {} • {:.0} MB", d.channel, d.height, fmt_time(d.duration), size) + trf("{channel} • {quality}p • {time} • {size} MB", &[("channel", &d.channel), ("quality", &d.height.to_string()), ("time", &fmt_time(d.duration)), ("size", &format!("{size:.0}"))]) }; ui.painter().text(Pos2::new(tx, rect.center().y - 11.0), Align2::LEFT_CENTER, title, FontId::proportional(16.0), ink()); ui.painter().text(Pos2::new(tx, rect.center().y + 12.0), Align2::LEFT_CENTER, sub, FontId::proportional(13.0), muted()); diff --git a/src/ui/grid.rs b/src/ui/grid.rs index 9b07a1d..ecfc4c8 100644 --- a/src/ui/grid.rs +++ b/src/ui/grid.rs @@ -8,31 +8,31 @@ impl App { self.sync_lib_filter(); let videos = self.visible_videos(); let title = match &self.sel { - Sel::Downloads => "Downloads".to_string(), - Sel::Settings => "Settings".to_string(), - Sel::Stats => "Insights".to_string(), - Sel::Clips => "Clips".to_string(), - Sel::Podcasts => "Podcasts".to_string(), - Sel::Podcast(_) => "Podcast".to_string(), - Sel::Music | Sel::MusicAlbum(_) | Sel::MusicArtist(_) => "Music".to_string(), + Sel::Downloads => tr("Downloads"), + Sel::Settings => tr("Settings"), + Sel::Stats => tr("Insights"), + Sel::Clips => tr("Clips"), + Sel::Podcasts => tr("Podcasts"), + Sel::Podcast(_) => tr("Podcast"), + Sel::Music | Sel::MusicAlbum(_) | Sel::MusicArtist(_) => tr("Music"), Sel::Group(gid) => self.groups.iter().find(|g| &g.id == gid).map(|g| g.name.clone()).unwrap_or_default(), - Sel::History => "History".to_string(), + Sel::History => tr("History"), Sel::Local(id) => self .lists .iter() .find(|l| &l.id == id) - .map(|l| l.name.clone()) + .map(playlist_label) .unwrap_or_default(), - Sel::Home => "Latest from your channels".to_string(), - Sel::Search => format!("Results for “{}”", self.search_query), - Sel::Live => "Live now".to_string(), + Sel::Home => tr("Latest from your channels"), + Sel::Search => trf("Results for “{query}”", &[("query", &self.search_query)]), + Sel::Live => tr("Live now"), Sel::Playlist(_) => self .playlist .as_ref() .and_then(|p| p.1.as_ref()) .and_then(|r| r.as_ref().ok()) .map(|(t, _)| t.clone()) - .unwrap_or_else(|| "Playlist".into()), + .unwrap_or_else(|| tr("Playlist")), Sel::Channel(id) => self .channels .iter() @@ -74,7 +74,7 @@ impl App { let (r, resp) = ui.allocate_exact_size(vec2(46.0, 46.0), Sense::click()); let resp = resp .on_hover_cursor(egui::CursorIcon::PointingHand) - .on_hover_text("Back (Alt+←)"); + .on_hover_text(tr("Back (Alt+←)")); let hv = ui.ctx().animate_bool_with_time(resp.id, resp.hovered(), 0.12); ui.painter().add(surface::capsule(r, 1.0, if hv > 0.05 { Some(accent()) } else { None }, false)); icons::draw(ui.painter(), r.center(), "arrow_left", 19.0, if hv > 0.5 { accent() } else { ink() }); @@ -85,12 +85,11 @@ impl App { } text_field( ui, - &mut self.search_input, - "Search YouTube — videos and channels", + &mut self.search_input, &tr("Search YouTube — videos and channels"), ui.available_width(), 46.0, "search", - Some("Search"), + Some(&tr("Search")), false, ) }) @@ -147,7 +146,7 @@ impl App { .show(ui, |ui| { ui.set_width(width - 12.0); if show_recent { - ui.label(egui::RichText::new("RECENT SEARCHES").size(11.0).color(muted()).strong()); + ui.label(egui::RichText::new(tr("RECENT SEARCHES")).size(11.0).color(muted()).strong()); } for sg in &rows { let (rect, resp) = @@ -215,7 +214,7 @@ impl App { if self.batch_total > 1 && matches!(self.sel, Sel::Home) { let done = self.batch_total.saturating_sub(self.batch.len()); let frac = done as f32 / self.batch_total as f32; - progress_pill(ui, frac, &format!("Refreshing {done} / {}", self.batch_total), 210.0); + progress_pill(ui, frac, &trf("Refreshing {done} / {total}", &[("done", &done.to_string()), ("total", &self.batch_total.to_string())]), 210.0); ui.ctx().request_repaint_after(Duration::from_millis(200)); } else if busy { ui.add(egui::Spinner::new().size(18.0)); @@ -227,7 +226,7 @@ impl App { _ => None, }; if let Some(ts) = ts { - ui.label(egui::RichText::new(format!("updated {}", ago(ts))).size(13.0).color(muted())); + ui.label(egui::RichText::new(trf("Updated {time}", &[("time", &localized_ago(ts))])).size(13.0).color(muted())); } } // on a narrow window the buttons drop to their own line, and wrap if they still do not fit @@ -236,11 +235,11 @@ impl App { } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center).with_main_wrap(true), |ui| { if let Sel::Group(gid) = self.sel.clone() { - if icon_btn(ui, "", "Delete group", None, ink(), false, true).clicked() { + if icon_btn(ui, "",&tr("Delete group"), None, ink(), false, true).clicked() { self.groups.retain(|g| g.id != gid); save_groups(&self.groups); self.sel = Sel::Home; - } else if icon_btn(ui, "refresh", "Refresh", None, ink(), false, true).clicked() { + } else if icon_btn(ui, "refresh",&tr("Refresh"), None, ink(), false, true).clicked() { let members: Vec = self.groups.iter().find(|g| g.id == gid).map(|g| g.channels.clone()).unwrap_or_default(); for c in self.channels.clone().into_iter().filter(|c| members.contains(&c.id)) { self.refresh(&c); @@ -248,22 +247,23 @@ impl App { } } if matches!(self.sel, Sel::Playlist(_) | Sel::Local(_)) && !videos.is_empty() { - let sh = icon_btn(ui, "shuffle", "Shuffle", None, ink(), false, true); + let sh = icon_btn(ui, "shuffle",&tr("Shuffle"), None, ink(), false, true); if sh.clicked() { self.play_all_visible(true); } - if icon_btn(ui, "play", "Play all", Some(accent()), ON_ACCENT, false, true).clicked() { + if icon_btn(ui, "play",&tr("Play all"), Some(accent()), ON_ACCENT, false, true).clicked() { self.play_all_visible(false); } let have = self.offline_count(&videos); - let label = if have == videos.len() { "Downloaded".to_string() } else { format!("Download all ({have}/{})", videos.len()) }; + let label = if have == videos.len() { tr("Downloaded") } else { trf("Download all ({downloaded}/{total})", &[("downloaded", &have.to_string()), ("total", &videos.len().to_string())]) }; if icon_btn(ui, if have < videos.len() { "download" } else { "check" }, &label, None, ink(), false, have < videos.len()).clicked() { download_visible = true; } if let Sel::Local(id) = self.sel.clone() { let on = self.lists.iter().any(|l| l.id == id && l.offline); - let b = icon_btn(ui, if on { "check" } else { "download" }, if on { "Kept offline" } else { "Keep offline" }, Some(if on { accent() } else { card() }), if on { ON_ACCENT } else { ink() }, false, true); - if b.on_hover_text("Keep every item of this playlist downloaded, including ones added later").clicked() { + let label = tr(if on { "Kept offline" } else { "Keep offline" }); + let b = icon_btn(ui, if on { "check" } else { "download" }, &label, Some(if on { accent() } else { card() }), if on { ON_ACCENT } else { ink() }, false, true); + if b.on_hover_text(tr("Keep every item of this playlist downloaded, including ones added later")).clicked() { if let Some(l) = self.lists.iter_mut().find(|l| l.id == id) { l.offline = !l.offline; save_lists(&self.lists); @@ -273,13 +273,13 @@ impl App { } } // a YouTube playlist can be kept as an editable local one - if matches!(self.sel, Sel::Playlist(_)) && ui.add(egui::Button::new("Save as playlist")).clicked() { + if matches!(self.sel, Sel::Playlist(_)) && ui.add(egui::Button::new(tr("Save as playlist"))).clicked() { save_as_local = true; } } if self.sel == Sel::History { if !self.history.is_empty() { - let label = if self.hist_confirm { "Confirm clear" } else { "Clear history" }; + let label = tr(if self.hist_confirm { "Confirm clear" } else { "Clear history" }); let b = egui::Button::new(egui::RichText::new(label).color(if self.hist_confirm { Color32::WHITE } else { ink() })) .fill(if self.hist_confirm { LIVE } else { card() }); if ui.add(b).clicked() { @@ -293,7 +293,7 @@ impl App { } } } else if let Sel::Local(id) = self.sel.clone() { - if icon_btn(ui, "", "Delete playlist", None, ink(), false, true).clicked() { + if icon_btn(ui, "",&tr("Delete playlist"), None, ink(), false, true).clicked() { self.lists.retain(|l| l.id != id); if !self.lists.iter().any(|l| l.id == "favorites") { self.lists.insert(0, LocalList { id: "favorites".into(), name: "Favorites".into(), videos: vec![], offline: false }); @@ -308,22 +308,22 @@ impl App { .filter_map(|r| r.as_ref().ok()) .flatten() .any(|v| !self.seen.contains(&v.id)); - any_new && icon_btn(ui, "check", "Mark all as seen", None, ink(), false, true).clicked() + any_new && icon_btn(ui, "check",&tr("Mark all as seen"), None, ink(), false, true).clicked() } { self.mark_all_seen(); - } else if !matches!(self.sel, Sel::Group(_)) && icon_btn(ui, "refresh", "Refresh", None, ink(), false, true).clicked() { + } else if !matches!(self.sel, Sel::Group(_)) && icon_btn(ui, "refresh",&tr("Refresh"), None, ink(), false, true).clicked() { self.refresh_all(); if self.sel == Sel::Live { self.load_live(); } } ui.add_space(8.0); - for (f, label) in [(Filter::Videos, "Videos"), (Filter::Live, "Live"), (Filter::New, "New"), (Filter::All, "All")] { + for (f, label) in [(Filter::Videos, tr("Videos")), (Filter::Live, tr("Live")), (Filter::New, tr("New")), (Filter::All, tr("All"))] { if own_line { break; } let on = self.filter == f; - if icon_btn(ui, "", label, Some(if on { accent() } else { card() }), if on { ON_ACCENT } else { muted() }, false, true).clicked() { + if icon_btn(ui, "", &label, Some(if on { accent() } else { card() }), if on { ON_ACCENT } else { muted() }, false, true).clicked() { self.filter = f; } } @@ -339,7 +339,7 @@ impl App { }; if has_items { let w = ui.available_width().min(460.0); - text_field(ui, &mut self.lib_filter, "Search this list", w, 38.0, "search", None, false); + text_field(ui, &mut self.lib_filter,&tr("Search this list"), w, 38.0, "search", None, false); ui.add_space(6.0); } @@ -349,47 +349,47 @@ impl App { && !(matches!(self.sel, Sel::Channel(_)) && self.chan_tab == ChanTab::About); // sort and filter chips for a channel's videos and for playlists if self.has_list_tools() && (shows_videos || self.list_sort != 0 || self.list_date != 0 || self.list_len != 0) { - let sorts = ["Default order", "Newest", "Oldest", "Most viewed", "Least viewed", "Longest", "Shortest", "Title A–Z"]; - let dates = ["Any time", "Today", "This week", "This month", "This year"]; - let lens = ["Any length", "Under 4 min", "4–20 min", "Over 20 min"]; + let sorts = [tr("Default order"), tr("Newest"), tr("Oldest"), tr("Most viewed"), tr("Least viewed"), tr("Longest"), tr("Shortest"), tr("Title A–Z")]; + let dates = [tr("Any time"), tr("Today"), tr("This week"), tr("This month"), tr("This year")]; + let lens = [tr("Any length"), tr("Under 4 min"), tr("4–20 min"), tr("Over 20 min")]; ui.horizontal_wrapped(|ui| { let chip = |ui: &mut egui::Ui, label: String, active: bool| -> egui::Response { icon_btn(ui, "", &label, Some(if active { accent() } else { card() }), if active { ON_ACCENT } else { ink() }, true, true) }; - let r1 = chip(ui, format!("Sort: {}", sorts[self.list_sort as usize % 8]), self.list_sort != 0); + let r1 = chip(ui, trf("Sort: {value}", &[("value", &sorts[self.list_sort as usize % 8])]), self.list_sort != 0); egui::Popup::menu(&r1).show(|ui| { for (i, n) in sorts.iter().enumerate() { - if ui.selectable_label(self.list_sort as usize == i, *n).clicked() { + if ui.selectable_label(self.list_sort as usize == i, n).clicked() { self.list_sort = i as u8; ui.close(); } } }); - let r2 = chip(ui, dates[self.list_date as usize % 5].to_string(), self.list_date != 0); + let r2 = chip(ui, dates[self.list_date as usize % 5].clone(), self.list_date != 0); egui::Popup::menu(&r2).show(|ui| { for (i, n) in dates.iter().enumerate() { - if ui.selectable_label(self.list_date as usize == i, *n).clicked() { + if ui.selectable_label(self.list_date as usize == i, n).clicked() { self.list_date = i as u8; ui.close(); } } }); - let r3 = chip(ui, lens[self.list_len as usize % 4].to_string(), self.list_len != 0); + let r3 = chip(ui, lens[self.list_len as usize % 4].clone(), self.list_len != 0); egui::Popup::menu(&r3).show(|ui| { for (i, n) in lens.iter().enumerate() { - if ui.selectable_label(self.list_len as usize == i, *n).clicked() { + if ui.selectable_label(self.list_len as usize == i, n).clicked() { self.list_len = i as u8; ui.close(); } } }); - if (self.list_sort != 0 || self.list_date != 0 || self.list_len != 0) && icon_btn(ui, "", "Reset", None, muted(), false, true).clicked() { + if (self.list_sort != 0 || self.list_date != 0 || self.list_len != 0) && icon_btn(ui, "",&tr("Reset"), None, muted(), false, true).clicked() { self.list_sort = 0; self.list_date = 0; self.list_len = 0; } if matches!(self.sel, Sel::Channel(_)) { - ui.label(egui::RichText::new("applies to the videos loaded so far").size(12.0).color(muted())); + ui.label(egui::RichText::new(tr("applies to the videos loaded so far")).size(12.0).color(muted())); } }); ui.add_space(4.0); @@ -400,10 +400,10 @@ impl App { let mut for_you = self.settings.home_for_you; ui.horizontal(|ui| { if self.sel == Sel::Home { - for (label, on_v) in [("Latest", false), ("For you", true)] { + for (label, on_v) in [(tr("Latest"), false), (tr("For you"), true)] { let on = for_you == on_v; - let b = icon_btn(ui, "", label, Some(if on { accent() } else { card() }), if on { ON_ACCENT } else { ink() }, false, true); - if b.on_hover_text(if on_v { "Ordered by what you watch and listen to" } else { "Newest first" }).clicked() { + let b = icon_btn(ui, "", &label, Some(if on { accent() } else { card() }), if on { ON_ACCENT } else { ink() }, false, true); + if b.on_hover_text(tr(if on_v { "Ordered by what you watch and listen to" } else { "Newest first" })).clicked() { for_you = on_v; } } @@ -423,25 +423,25 @@ impl App { if self.sel == Sel::Search { let mut changed = false; ui.horizontal(|ui| { - let sort = ["Relevance", "Rating", "Upload date", "View count"]; - let date = [(0u8, "Any time"), (2, "Today"), (3, "This week"), (4, "This month"), (5, "This year")]; - let dur = [(0u8, "Any length"), (1, "Under 4 min"), (3, "4–20 min"), (2, "Over 20 min")]; + let sort = [tr("Relevance"), tr("Rating"), tr("Upload date"), tr("View count")]; + let date = [(0u8, tr("Any time")), (2, tr("Today")), (3, tr("This week")), (4, tr("This month")), (5, tr("This year"))]; + let dur = [(0u8, tr("Any length")), (1, tr("Under 4 min")), (3, tr("4–20 min")), (2, tr("Over 20 min"))]; let o = &mut self.search_opts; let chip = |ui: &mut egui::Ui, label: String, active: bool| -> egui::Response { icon_btn(ui, "", &label, Some(if active { accent() } else { card() }), if active { ON_ACCENT } else { ink() }, true, true) }; - let r1 = chip(ui, format!("Sort: {}", sort[o.sort as usize % 4]), o.sort != 0); + let r1 = chip(ui, trf("Sort: {value}", &[("value", &sort[o.sort as usize % 4])]), o.sort != 0); egui::Popup::menu(&r1).show(|ui| { for (i, n) in sort.iter().enumerate() { - if ui.selectable_label(o.sort as usize == i, *n).clicked() { + if ui.selectable_label(o.sort as usize == i, n).clicked() { o.sort = i as u8; changed = true; ui.close(); } } }); - let dl = date.iter().find(|d| d.0 == o.date).map_or("Any time", |d| d.1); - let r2 = chip(ui, dl.to_string(), o.date != 0); + let dl = date.iter().find(|d| d.0 == o.date).map_or_else(|| tr("Any time"), |d| d.1.clone()); + let r2 = chip(ui, dl, o.date != 0); egui::Popup::menu(&r2).show(|ui| { for (v, n) in date { if ui.selectable_label(o.date == v, n).clicked() { @@ -451,8 +451,8 @@ impl App { } } }); - let ll = dur.iter().find(|d| d.0 == o.duration).map_or("Any length", |d| d.1); - let r3 = chip(ui, ll.to_string(), o.duration != 0); + let ll = dur.iter().find(|d| d.0 == o.duration).map_or_else(|| tr("Any length"), |d| d.1.clone()); + let r3 = chip(ui, ll, o.duration != 0); egui::Popup::menu(&r3).show(|ui| { for (v, n) in dur { if ui.selectable_label(o.duration == v, n).clicked() { @@ -472,7 +472,7 @@ impl App { if let Sel::Channel(id) = &self.sel { if let Some(e) = self.tab_err.get(&format!("{id}:{}", self.chan_tab.key())) { - ui.colored_label(LIVE, format!("Could not load this tab: {e}")); + ui.colored_label(LIVE, trf("Could not load this tab: {error}", &[("error", e)])); } if self.chan_tab == ChanTab::About { let about = self.fcache.about.get(id).cloned(); @@ -482,17 +482,17 @@ impl App { } if let Some((_, Some(Err(e)))) = &self.playlist { if matches!(self.sel, Sel::Playlist(_)) { - ui.colored_label(LIVE, format!("Could not load playlist: {e}")); + ui.colored_label(LIVE, trf("Could not load playlist: {error}", &[("error", e)])); } } if let Some(Err(e)) = &self.live { if self.sel == Sel::Live { - ui.colored_label(LIVE, format!("Could not load live streams: {e}")); + ui.colored_label(LIVE, trf("Could not load live streams: {error}", &[("error", e)])); } } if self.sel == Sel::Search { if let Some(Err(e)) = &self.svideos { - ui.colored_label(LIVE, format!("Search failed: {e}")); + ui.colored_label(LIVE, trf("Search failed: {error}", &[("error", e)])); } } let hits: Vec = if self.sel == Sel::Search && self.filter != Filter::Videos { @@ -533,7 +533,7 @@ impl App { ui.add_space(60.0); ui.vertical_centered(|ui| { ui.label(egui::RichText::new("◌").size(48.0).color(muted())); - ui.label(egui::RichText::new(if has_items && !self.lib_filter.trim().is_empty() { + ui.label(egui::RichText::new(tr(if has_items && !self.lib_filter.trim().is_empty() { "Nothing in this list matches your search." } else if self.sel == Sel::History { "Nothing watched yet. Videos you open will show up here, and pick up where you left off." @@ -543,7 +543,7 @@ impl App { "Add your favourite channels to see their videos and live streams here." } else { "No videos to show." - }).size(16.0).color(muted())); + })).size(16.0).color(muted())); }); return; } @@ -606,7 +606,7 @@ impl App { .show_viewport(ui, |ui, view| { let origin = ui.cursor().min.y; if !hits.is_empty() { - ui.label(egui::RichText::new("CHANNELS").size(11.0).color(muted()).strong()); + ui.label(egui::RichText::new(tr("CHANNELS")).size(11.0).color(muted()).strong()); for h in &hits { let (rect, resp) = ui.allocate_exact_size(vec2(avail, 68.0), Sense::click()); let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand); @@ -637,7 +637,7 @@ impl App { let bresp = ui.interact(br, resp.id.with("add"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand); let fill = if added { card_hi() } else if bresp.hovered() { accent2() } else { accent() }; ui.painter().rect_filled(br, CornerRadius::same(17), fill); - icon_label(ui, br.center(), if added { "check" } else { "plus" }, if added { "Added" } else { "Add" }, if added { ink() } else { ON_ACCENT }, false); + icon_label(ui, br.center(), if added { "check" } else { "plus" }, &tr(if added { "Added" } else { "Add" }), if added { ink() } else { ON_ACCENT }, false); if bresp.clicked() && !added { add_hit = Some(h.channel.clone()); } else if resp.clicked() && !bresp.hovered() { @@ -647,7 +647,7 @@ impl App { ui.add_space(14.0); } if !plhits.is_empty() { - ui.label(egui::RichText::new("PLAYLISTS").size(11.0).color(muted()).strong()); + ui.label(egui::RichText::new(tr("PLAYLISTS")).size(11.0).color(muted()).strong()); for h in &plhits { let (rect, resp) = ui.allocate_exact_size(vec2(avail, 76.0), Sense::click()); let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand); @@ -674,7 +674,7 @@ impl App { ui.add_space(14.0); } if (!hits.is_empty() || !plhits.is_empty()) && !videos.is_empty() { - ui.label(egui::RichText::new("VIDEOS").size(11.0).color(muted()).strong()); + ui.label(egui::RichText::new(tr("VIDEOS")).size(11.0).color(muted()).strong()); } let total = rows as f32 * (ch + gap); let (area, _) = ui.allocate_exact_size(vec2(avail, total), Sense::hover()); @@ -716,7 +716,7 @@ impl App { if more_busy { ui.put(Rect::from_center_size(r.center(), vec2(28.0, 28.0)), egui::Spinner::new().color(accent())); } else { - let b = egui::Button::new(egui::RichText::new(if more_failed { "Retry" } else { "Load more" }).strong()) + let b = egui::Button::new(egui::RichText::new(tr(if more_failed { "Retry" } else { "Load more" })).strong()) .fill(card_hi()) .corner_radius(CornerRadius::same(18)) .min_size(vec2(140.0, 36.0)); @@ -770,8 +770,8 @@ impl App { .and_then(|p| p.1.as_ref()) .and_then(|r| r.as_ref().ok()) .map(|(t, _)| t.clone()) - .unwrap_or_else(|| "Playlist".into()), - _ => "Playlist".into(), + .unwrap_or_else(|| tr("Playlist")), + _ => tr("Playlist"), }; self.save_playlist_locally(name, videos.clone()); } diff --git a/src/ui/i18n.rs b/src/ui/i18n.rs new file mode 100644 index 0000000..234a85e --- /dev/null +++ b/src/ui/i18n.rs @@ -0,0 +1,329 @@ +//! UI language catalogs. Caption and content language settings are intentionally separate. +use std::collections::HashMap; +use std::sync::{OnceLock, RwLock}; + +include!(concat!(env!("OUT_DIR"), "/locales.rs")); + +static CATALOGS: OnceLock>> = OnceLock::new(); +static ACTIVE_LANGUAGE: OnceLock> = OnceLock::new(); + +fn catalogs() -> &'static HashMap> { + CATALOGS.get_or_init(|| { + CATALOG_SOURCES + .iter() + .filter_map(|(language, json)| { + serde_json::from_str(json) + .ok() + .map(|catalog| ((*language).to_owned(), catalog)) + }) + .collect() + }) +} + +fn active_language() -> &'static RwLock { + ACTIVE_LANGUAGE.get_or_init(|| RwLock::new("en".to_owned())) +} + +/// Normalize a locale tag to its base language, then select it if a catalog exists. +pub(crate) fn set_language(preference: &str) { + let requested = if preference == "system" { + system_language() + } else { + preference.to_owned() + }; + let language = requested + .split(['-', '_', '.', ':']) + .next() + .unwrap_or("en") + .to_ascii_lowercase(); + let language = if catalogs().contains_key(&language) { + language + } else { + "en".to_owned() + }; + if let Ok(mut active) = active_language().write() { + *active = language; + } +} + +/// Read the standard locale environment variables used by Linux, macOS, and Windows runtimes. +fn system_language() -> String { + #[cfg(windows)] + if let Some(locale) = windows_user_language() { + return locale; + } + #[cfg(target_os = "macos")] + if let Ok(output) = std::process::Command::new("defaults") + .args(["read", "-g", "AppleLocale"]) + .output() + { + let locale = String::from_utf8_lossy(&output.stdout).trim().to_owned(); + if output.status.success() && !locale.is_empty() { + return locale; + } + } + ["LC_ALL", "LC_MESSAGES", "LANG", "LANGUAGE"] + .iter() + .find_map(|key| std::env::var(key).ok().filter(|value| !value.is_empty())) + .unwrap_or_else(|| "en".to_owned()) +} + +#[cfg(windows)] +fn windows_user_language() -> Option { + #[link(name = "kernel32")] + unsafe extern "system" { + fn GetUserDefaultLocaleName(locale_name: *mut u16, count: i32) -> i32; + } + let mut buffer = [0u16; 85]; + // The Windows API writes a null-terminated locale name when the buffer is large enough. + let written = unsafe { GetUserDefaultLocaleName(buffer.as_mut_ptr(), buffer.len() as i32) }; + (written > 1).then(|| String::from_utf16_lossy(&buffer[..(written - 1) as usize])) +} + +/// Locale codes and translator-provided names for the language selector. +pub(crate) fn language_options() -> Vec<(String, String)> { + let mut options = catalogs() + .iter() + .map(|(code, catalog)| { + let name = catalog + .get("__language_name") + .filter(|name| !name.trim().is_empty()) + .cloned() + .unwrap_or_else(|| code.clone()); + (code.clone(), name) + }) + .collect::>(); + options.sort_by(|a, b| a.0.cmp(&b.0)); + options +} + +/// Display a saved playlist name in the current UI language. +pub(crate) fn playlist_label(list: &crate::LocalList) -> String { + match (list.id.as_str(), list.name.as_str()) { + ("favorites", "Favorites") => tr("Favorites"), + ("watchlater", "Watch later") => tr("Watch later"), + ("liked", "Liked songs") => tr("Liked songs"), + _ => list.name.clone(), + } +} + +/// Resolve the raw catalog message before decoding braces or substituting values. +fn message(key: &str) -> String { + let language = active_language() + .read() + .map(|active| active.clone()) + .unwrap_or_else(|_| "en".to_owned()); + lookup(catalogs(), &language, key) +} + +/// Return translated UI text, decoding literal braces and falling back to English. +pub(crate) fn tr(key: &str) -> String { + let text = message(key); + if !text.bytes().any(|byte| matches!(byte, b'{' | b'}')) { + return text; + } + crate::locale_format::render(&text, &[]).unwrap_or(text) +} + +fn lookup( + catalogs: &HashMap>, + language: &str, + key: &str, +) -> String { + catalogs + .get(language) + .and_then(|catalog| catalog.get(key)) + .filter(|value| !value.trim().is_empty()) + .or_else(|| { + catalogs + .get("en") + .and_then(|catalog| catalog.get(key)) + .filter(|value| !value.trim().is_empty()) + }) + .cloned() + .unwrap_or_else(|| key.to_owned()) +} + +/// Translate a string and substitute named values after lookup, so catalog text stays external. +pub(crate) fn trf(key: &str, values: &[(&str, &str)]) -> String { + crate::locale_format::render(&message(key), values).unwrap_or_else(|_| { + let english = lookup(catalogs(), "en", key); + crate::locale_format::render(&english, values).unwrap_or(english) + }) +} + +/// Catalog validation shared by automated tests and contributor checks. +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn english_is_complete_and_locales_have_known_keys_and_valid_placeholders() { + let english = catalogs().get("en").expect("English catalog is required"); + let indonesian = catalogs() + .get("id") + .expect("Indonesian catalog is required"); + assert_eq!(indonesian.len(), english.len()); + assert!(english.keys().all(|key| { + indonesian + .get(key) + .is_some_and(|text| !text.trim().is_empty()) + })); + let total = english + .keys() + .filter(|key| key.as_str() != "__language_name") + .count(); + assert!( + english + .iter() + .filter(|(key, _)| key.as_str() != "__language_name") + .all(|(_, value)| !value.trim().is_empty()), + "English source values must be complete" + ); + for (language, catalog) in catalogs() { + let mut translated = 0; + for (key, value) in catalog { + if key == "__language_name" { + continue; + } + let source = english + .get(key) + .unwrap_or_else(|| panic!("{language}.json has unknown key {key:?}")); + if value.trim().is_empty() { + continue; + } + translated += 1; + assert_eq!( + crate::locale_format::placeholder_names(source).unwrap(), + crate::locale_format::placeholder_names(value) + .unwrap_or_else(|error| panic!("{language}.json for {key:?}: {error}")), + "invalid placeholders in {language}.json for {key:?}" + ); + } + eprintln!( + "{language}: {translated}/{total} UI strings translated ({:.1}%)", + translated as f64 * 100.0 / total as f64 + ); + } + } + + #[test] + fn unsupported_and_regional_languages_fall_back_safely() { + let lists = [ + ("favorites", "Favorites"), + ("watchlater", "Watch later"), + ("liked", "Liked songs"), + ("pl-custom", "Watch later"), + ("favorites", "My favorites"), + ] + .map(|(id, name)| crate::LocalList { + id: id.into(), + name: name.into(), + videos: vec![], + offline: false, + }); + let saved_lists = serde_json::to_string(&lists).unwrap(); + set_language("en"); + assert_eq!( + lists.each_ref().map(playlist_label), + [ + "Favorites", + "Watch later", + "Liked songs", + "Watch later", + "My favorites" + ] + ); + assert_eq!(trf("{count} items", &[("count", "2")]), "2 items"); + let escaped = ["{{", "count", "}}"].concat(); + assert_eq!(tr(&escaped), "{count}"); + assert_eq!(trf(&escaped, &[("count", "2")]), "{count}"); + let now = 1_000_000; + let boundaries = [0, 59, 60, 3599, 3600, 86399, 86400]; + for (seconds, expected) in boundaries.into_iter().zip([ + "just now", + "just now", + "1 min ago", + "59 min ago", + "1 h ago", + "23 h ago", + "1 d ago", + ]) { + assert_eq!(crate::util::ago_at(now - seconds, now), expected); + } + assert_eq!(crate::util::ago_at(now + 60, now), "just now"); + set_language("id-ID"); + assert_eq!( + lists.each_ref().map(playlist_label), + [ + "Favorit", + "Tonton nanti", + "Lagu yang disukai", + "Watch later", + "My favorites" + ] + ); + assert_eq!(serde_json::to_string(&lists).unwrap(), saved_lists); + assert_eq!( + crate::util::ago(crate::util::now_secs()), + "just now", + "persisted podcast metadata keeps its original language" + ); + assert_eq!(tr("Settings"), "Pengaturan"); + assert_eq!(trf("{count} items", &[("count", "2")]), "2 item"); + for (seconds, expected) in boundaries.into_iter().zip([ + "baru saja", + "baru saja", + "1 mnt lalu", + "59 mnt lalu", + "1 jam lalu", + "23 jam lalu", + "1 hari lalu", + ]) { + assert_eq!(crate::util::ago_at(now - seconds, now), expected); + } + assert_eq!( + trf( + "Everything plays through it. In use: {ffmpeg}", + &[("ffmpeg", "ffmpeg")] + ), + "Semua media diputar dengannya. Sedang digunakan: ffmpeg" + ); + set_language("xx-ZZ"); + assert_eq!(tr("Settings"), "Settings"); + let uncatalogued = ["Uncatalogued", " text"].concat(); + assert_eq!(tr(&uncatalogued), uncatalogued); + } + + #[test] + fn saved_language_is_backward_compatible() { + let mut settings: crate::Settings = serde_json::from_value(serde_json::json!({})).unwrap(); + assert_eq!(settings.language, "system"); + settings.language = "id".into(); + let serialized = serde_json::to_string(&settings).unwrap(); + let restored: crate::Settings = serde_json::from_str(&serialized).unwrap(); + assert_eq!(restored.language, "id"); + } + + #[test] + fn partial_locales_fall_back_for_missing_and_blank_values() { + let catalogs = HashMap::from([ + ( + "en".to_owned(), + HashMap::from([ + ("Settings".to_owned(), "Settings".to_owned()), + ("Downloads".to_owned(), "Downloads".to_owned()), + ]), + ), + ( + "fr".to_owned(), + HashMap::from([ + ("Settings".to_owned(), "Paramètres".to_owned()), + ("Downloads".to_owned(), String::new()), + ]), + ), + ]); + assert_eq!(lookup(&catalogs, "fr", "Settings"), "Paramètres"); + assert_eq!(lookup(&catalogs, "fr", "Downloads"), "Downloads"); + } +} diff --git a/src/ui/keys.rs b/src/ui/keys.rs index 812964c..95c2c08 100644 --- a/src/ui/keys.rs +++ b/src/ui/keys.rs @@ -45,13 +45,13 @@ impl App { if pressed(B) { self.settings.ambient = !self.settings.ambient; self.save_settings(); - self.toast(if self.settings.ambient { "Ambient mode on" } else { "Ambient mode off" }); + self.toast(tr(if self.settings.ambient { "Ambient mode on" } else { "Ambient mode off" })); } if pressed(W) { if let Some(w) = self.watching.clone().filter(|w| !w.id.starts_with("local:")) { self.toggle_in_list("watchlater", &w); let on = self.lists.iter().any(|l| l.id == "watchlater" && l.videos.iter().any(|x| x.id == w.id)); - self.toast(if on { "Added to Watch later" } else { "Removed from Watch later" }); + self.toast(tr(if on { "Added to Watch later" } else { "Removed from Watch later" })); } } if pressed(Y) && self.watching.as_ref().is_some_and(|w| w.music) { @@ -68,14 +68,14 @@ impl App { self.player.set_speed(v); self.settings.speed = v; self.save_settings(); - self.toast(format!("Speed {v}×")); + self.toast(trf("Speed {speed}×", &[("speed", &v.to_string())])); } if pressed(CloseBracket) { let v = (self.player.speed + 0.25).min(2.0); self.player.set_speed(v); self.settings.speed = v; self.save_settings(); - self.toast(format!("Speed {v}×")); + self.toast(trf("Speed {speed}×", &[("speed", &v.to_string())])); } if pressed(I) { let on = !self.mini; diff --git a/src/ui/mod.rs b/src/ui/mod.rs index 2611761..018caf2 100644 --- a/src/ui/mod.rs +++ b/src/ui/mod.rs @@ -22,10 +22,12 @@ pub mod music_ui; pub mod side_tools; pub mod podcasts_view; pub mod update_view; +pub mod i18n; #[allow(unused_imports)] pub(crate) use theme::*; pub(crate) use images::*; pub(crate) use widgets::*; pub(crate) use captions::*; +pub(crate) use i18n::*; pub(crate) use cards::*; diff --git a/src/ui/music_ui.rs b/src/ui/music_ui.rs index 6a0a18a..d6f9ba1 100644 --- a/src/ui/music_ui.rs +++ b/src/ui/music_ui.rs @@ -39,14 +39,14 @@ impl App { let cards = |v: &[Video]| -> Vec { v.iter().map(ytmusic::song_card).collect() }; let mut shelves: Vec<(String, Vec)> = vec![]; if !liked.is_empty() { - shelves.push(("Liked songs".into(), cards(&liked[..liked.len().min(20)]))); + shelves.push((tr("Liked songs"), cards(&liked[..liked.len().min(20)]))); } if !artists.is_empty() { let cs = artists .iter() - .map(|a| Card { kind: CardKind::Artist, id: a.id.clone(), title: a.name.clone(), sub: "Following".into(), thumb: a.thumb.clone() }) + .map(|a| Card { kind: CardKind::Artist, id: a.id.clone(), title: a.name.clone(), sub: tr("Following"), thumb: a.thumb.clone() }) .collect(); - shelves.push(("Your artists".into(), cs)); + shelves.push((tr("Your artists"), cs)); // newest releases of the followed artists (YouTube lists them newest first) let mut fresh: Vec<(u32, Card)> = vec![]; for a in artists.iter().take(10) { @@ -66,11 +66,11 @@ impl App { fresh.sort_by(|a, b| b.0.cmp(&a.0)); let cs: Vec = fresh.into_iter().map(|(_, c)| c).take(20).collect(); if !cs.is_empty() { - shelves.push(("New from artists you follow".into(), cs)); + shelves.push((tr("New from artists you follow"), cs)); } } if !recent.is_empty() { - shelves.push(("Jump back in".into(), cards(&recent))); + shelves.push((tr("Jump back in"), cards(&recent))); } // radios: seeds are your liked songs first, then what you played lately let mut seeds: Vec<&Video> = liked.iter().take(2).collect(); @@ -87,7 +87,7 @@ impl App { r.retain(|v| !recent.iter().any(|x| x.id == v.id) && !liked.iter().any(|x| x.id == v.id)); r.truncate(20); if !r.is_empty() { - shelves.push((format!("Because you like {}", seed.title), cards(&r))); + shelves.push((trf("Because you like {title}", &[("title", &seed.title)]), cards(&r))); } } } @@ -165,7 +165,7 @@ impl App { /// The Music search box with its suggestions. fn music_search_bar(&mut self, ui: &mut egui::Ui) { let w = ui.available_width(); - let f = text_field(ui, &mut self.music_q, "Search songs, albums, artists", w, 46.0, "search", Some("Search"), false); + let f = text_field(ui, &mut self.music_q, &tr("Search songs, albums, artists"), w, 46.0, "search", Some(&tr("Search")), false); let mut go = f.submit || f.action; if f.cleared { self.music_active = None; @@ -314,14 +314,14 @@ impl App { ui.add_space(8.0); let Some(w) = self.watching.clone() else { return }; if w.id.starts_with("local:") { - ui.label(egui::RichText::new("Lyrics are only looked up for YouTube songs.").color(muted())); + ui.label(egui::RichText::new(tr("Lyrics are only looked up for YouTube songs.")).color(muted())); return; } if !w.music && self.lyrics_forced != w.id { ui.add_space(16.0); - ui.label(egui::RichText::new("This doesn't look like a song, so lyrics are not looked up automatically.").size(14.0).color(muted())); + ui.label(egui::RichText::new(tr("This doesn't look like a song, so lyrics are not looked up automatically.")).size(14.0).color(muted())); ui.add_space(8.0); - if ui.button("Look up lyrics anyway").clicked() { + if ui.button(tr("Look up lyrics anyway")).clicked() { self.lyrics_forced = w.id.clone(); } return; @@ -385,7 +385,7 @@ impl App { ui.add_space(8.0); } ui.add_space(20.0); - ui.label(egui::RichText::new(format!("Lyrics: {}", l.source)).size(11.0).color(muted())); + ui.label(egui::RichText::new(trf("Lyrics: {source}", &[("source", &l.source)])).size(11.0).color(muted())); }); if l.synced { ui.ctx().request_repaint_after(Duration::from_millis(120)); @@ -405,7 +405,7 @@ impl App { ui.horizontal(|ui| { if self.can_go_back() { let (r, resp) = ui.allocate_exact_size(vec2(46.0, 46.0), Sense::click()); - let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text("Back (Alt+←)"); + let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text(tr("Back (Alt+←)")); let hv = ui.ctx().animate_bool_with_time(resp.id, resp.hovered(), 0.12); ui.painter().add(surface::capsule(r, 1.0, if hv > 0.05 { Some(accent()) } else { None }, false)); icons::draw(ui.painter(), r.center(), "arrow_left", 19.0, if hv > 0.5 { accent() } else { ink() }); @@ -433,10 +433,10 @@ impl App { // result tabs ui.horizontal(|ui| { for (k, l) in [ - (SearchKind::Songs, "Songs"), - (SearchKind::Albums, "Albums"), - (SearchKind::Artists, "Artists"), - (SearchKind::Playlists, "Playlists"), + (SearchKind::Songs, tr("Songs")), + (SearchKind::Albums, tr("Albums")), + (SearchKind::Artists, tr("Artists")), + (SearchKind::Playlists, tr("Playlists")), ] { let on = kind == k; let b = egui::Button::new(egui::RichText::new(l).color(if on { ON_ACCENT } else { ink() })) @@ -457,7 +457,7 @@ impl App { }); } Some((rq, rk, Err(e))) if *rq == q && *rk == kind => { - ui.colored_label(LIVE, format!("Search failed: {e}")); + ui.colored_label(LIVE, trf("Search failed: {error}", &[("error", e)])); } Some((rq, rk, Ok(res))) if *rq == q && *rk == kind => { egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { @@ -467,7 +467,7 @@ impl App { card_grid(ui, &res.cards, &mut open); } if res.songs.is_empty() && res.cards.is_empty() { - ui.label(egui::RichText::new("Nothing found.").color(muted())); + ui.label(egui::RichText::new(tr("Nothing found.")).color(muted())); } }); } @@ -482,18 +482,18 @@ impl App { }); } Some(Err(e)) => { - ui.colored_label(LIVE, format!("Could not load YouTube Music: {e}")); + ui.colored_label(LIVE, trf("Could not load YouTube Music: {error}", &[("error", e)])); } Some(Ok(page)) => { egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { - ui.label(egui::RichText::new("YouTube Music").size(26.0).strong()); + ui.label(egui::RichText::new(tr("YouTube Music")).size(26.0).strong()); ui.add_space(6.0); for (title, cards) in self.for_you.iter().flatten() { shelf(ui, title, cards, &mut open, &mut play); } if self.for_you.as_ref().is_some_and(|f| f.is_empty()) { ui.label( - egui::RichText::new("Play some songs and your own picks will appear here.") + egui::RichText::new(tr("Play some songs and your own picks will appear here.")) .size(13.0) .color(muted()), ); @@ -527,7 +527,7 @@ impl App { }); } Some(Err(e)) => { - ui.colored_label(LIVE, format!("Could not load: {e}")); + ui.colored_label(LIVE, trf("Could not load: {error}", &[("error", e)])); } Some(Ok(page)) => { egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { @@ -549,18 +549,19 @@ impl App { ui.add_space(10.0); if !page.tracks.is_empty() { ui.horizontal_wrapped(|ui| { - if icon_btn(ui, "play", "Play", Some(accent()), ON_ACCENT, false, true).clicked() { + if icon_btn(ui, "play",&tr("Play"), Some(accent()), ON_ACCENT, false, true).clicked() { play_all = Some(false); } - if icon_btn(ui, "shuffle", "Shuffle", None, ink(), false, true).clicked() { + if icon_btn(ui, "shuffle",&tr("Shuffle"), None, ink(), false, true).clicked() { play_all = Some(true); } if is_artist { let following = self.followed.iter().any(|a| a.id == id); + let follow_label = tr(if following { "Following" } else { "Follow" }); let fb = icon_btn( ui, if following { "check" } else { "plus" }, - if following { "Following" } else { "Follow" }, + &follow_label, Some(if following { card_hi() } else { accent() }), if following { ink() } else { ON_ACCENT }, false, @@ -572,7 +573,7 @@ impl App { } let have = self.offline_count(&page.tracks); let all = have == page.tracks.len(); - let label = if all { "Downloaded".to_string() } else { format!("Download ({have}/{})", page.tracks.len()) }; + let label = if all { tr("Downloaded") } else { trf("Download ({downloaded}/{total})", &[("downloaded", &have.to_string()), ("total", &page.tracks.len().to_string())]) }; if icon_btn(ui, if all { "check" } else { "download" }, &label, None, ink(), false, !all).clicked() { download_page = true; } @@ -583,7 +584,7 @@ impl App { ui.add_space(14.0); if !page.tracks.is_empty() { if is_artist { - ui.label(egui::RichText::new("Songs").size(18.0).strong()); + ui.label(egui::RichText::new(tr("Songs")).size(18.0).strong()); ui.add_space(4.0); } song_rows(ui, &page.tracks, &self.lists, &mut act, &mut play); @@ -610,11 +611,11 @@ impl App { match self.followed.iter().position(|a| a.id == id) { Some(i) => { self.followed.remove(i); - self.toast(format!("Unfollowed {name}")); + self.toast(trf("Unfollowed {name}", &[("name", &name)])); } None => { self.followed.push(FollowedArtist { id: id.to_string(), name: name.clone(), thumb }); - self.toast(format!("Following {name}")); + self.toast(trf("Following {name}", &[("name", &name)])); } } save_followed(&self.followed); @@ -704,18 +705,18 @@ fn song_rows( } } resp.context_menu(|ui| { - if ui.button("Play next").clicked() { + if ui.button(tr("Play next")).clicked() { *act = Some((v.clone(), MAct::PlayNext)); ui.close(); } - if ui.button("Add to queue").clicked() { + if ui.button(tr("Add to queue")).clicked() { *act = Some((v.clone(), MAct::Queue)); ui.close(); } - ui.menu_button("Add to playlist", |ui| { + ui.menu_button(tr("Add to playlist"), |ui| { for l in lists { let has = l.videos.iter().any(|x| x.id == v.id); - if ui.selectable_label(has, l.name.clone()).clicked() { + if ui.selectable_label(has, playlist_label(l)).clicked() { *act = Some((v.clone(), MAct::Toggle(l.id.clone()))); ui.close(); } diff --git a/src/ui/panels.rs b/src/ui/panels.rs index 6b4bed0..514470f 100644 --- a/src/ui/panels.rs +++ b/src/ui/panels.rs @@ -8,9 +8,9 @@ impl App { ui.add_space(8.0); if self.queue.is_empty() { ui.add_space(24.0); - ui.label(egui::RichText::new("The queue is empty.").size(15.0).color(muted())); + ui.label(egui::RichText::new(tr("The queue is empty.")).size(15.0).color(muted())); ui.label( - egui::RichText::new("Use “Play all” on a playlist or channel, or right-click a video and choose “Add to queue”.") + egui::RichText::new(tr("Use “Play all” on a playlist or channel, or right-click a video and choose “Add to queue”.")) .size(13.0) .color(muted()), ); @@ -22,12 +22,18 @@ impl App { let mut save_queue = false; let mut moved: Option<(usize, usize)> = None; ui.horizontal(|ui| { - ui.label(egui::RichText::new(format!("{} items • drag to reorder", self.queue.len())).size(13.0).color(muted())); + let count = self.queue.len().to_string(); + let summary = if self.queue.len() == 1 { + trf("{count} item • drag to reorder", &[("count", &count)]) + } else { + trf("{count} items • drag to reorder", &[("count", &count)]) + }; + ui.label(egui::RichText::new(summary).size(13.0).color(muted())); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.add(egui::Button::new("Clear")).clicked() { + if ui.add(egui::Button::new(tr("Clear"))).clicked() { clear = true; } - if ui.add(egui::Button::new("Save as playlist")).clicked() { + if ui.add(egui::Button::new(tr("Save as playlist"))).clicked() { save_queue = true; } }); @@ -117,13 +123,18 @@ impl App { }) .collect(); if videos.is_empty() { - self.toast("Nothing in the queue can be saved as a playlist"); + self.toast(tr("Nothing in the queue can be saved as a playlist")); } else { let id = format!("l-{}", now_secs()); - let name = format!("Saved queue ({} items)", videos.len()); + let count = videos.len().to_string(); + let name = if videos.len() == 1 { + trf("Saved queue ({count} item)", &[("count", &count)]) + } else { + trf("Saved queue ({count} items)", &[("count", &count)]) + }; self.lists.push(LocalList { id: id.clone(), name: name.clone(), videos, offline: false }); save_lists(&self.lists); - self.toast(format!("Saved “{name}” — find it under Playlists")); + self.toast(trf("Saved “{name}” — find it under Playlists", &[("name", &name)])); } } if clear { @@ -145,7 +156,7 @@ impl App { pub(crate) fn related_body(&mut self, ui: &mut egui::Ui) { ui.add_space(8.0); let Some(w) = self.watching.clone().filter(|w| !non_yt(&w.id)) else { - ui.label(egui::RichText::new("Related videos are only available for YouTube videos.").size(14.0).color(muted())); + ui.label(egui::RichText::new(tr("Related videos are only available for YouTube videos.")).size(14.0).color(muted())); return; }; if self.related.as_ref().is_none_or(|r| r.0 != w.id) { @@ -217,13 +228,13 @@ impl App { ui.spacing_mut().item_spacing = vec2(6.0, 6.0); let notes_n = self.watching.as_ref().and_then(|w| self.bookmarks.get(&w.id)).map_or(0, |b| b.len()); let tabs = [ - (SideTab::Comments, "Comments".to_string()), - (SideTab::Lyrics, "Lyrics".to_string()), - (SideTab::Queue, format!("Queue{}", if self.queue.is_empty() { String::new() } else { format!(" {}", self.queue.len()) })), - (SideTab::Related, "Related".to_string()), - (SideTab::Transcript, "Transcript".to_string()), - (SideTab::Notes, format!("Notes{}", if notes_n == 0 { String::new() } else { format!(" {notes_n}") })), - (SideTab::Clip, "Clip".to_string()), + (SideTab::Comments, tr("Comments")), + (SideTab::Lyrics, tr("Lyrics")), + (SideTab::Queue, if self.queue.is_empty() { tr("Queue") } else { trf("Queue ({count})", &[("count", &self.queue.len().to_string())]) }), + (SideTab::Related, tr("Related")), + (SideTab::Transcript, tr("Transcript")), + (SideTab::Notes, if notes_n == 0 { tr("Notes") } else { trf("Notes ({count})", &[("count", ¬es_n.to_string())]) }), + (SideTab::Clip, tr("Clip")), ]; for (t, label) in tabs { let on = self.side_tab == t; @@ -337,7 +348,7 @@ impl App { let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand); let hv = ui.ctx().animate_bool_with_time(resp.id, resp.hovered(), 0.12); ui.painter().rect_filled(r, CornerRadius::same(13), accent().gamma_multiply(0.15 + 0.2 * hv)); - icon_label(ui, r.center(), "chevron_down", "Show more replies", accent2(), false); + icon_label(ui, r.center(), "chevron_down", &tr("Show more replies"), accent2(), false); if resp.clicked() { more_reply = Some((c.id.clone(), next.clone())); } @@ -355,7 +366,7 @@ impl App { if self.comments_next.is_some() { if self.comments_busy { ui.add(egui::Spinner::new()); - } else if ui.add(egui::Button::new("Load more comments").fill(card())).clicked() { + } else if ui.add(egui::Button::new(tr("Load more comments")).fill(card())).clicked() { more = true; } } diff --git a/src/ui/player_view.rs b/src/ui/player_view.rs index d8b97de..b0eec6c 100644 --- a/src/ui/player_view.rs +++ b/src/ui/player_view.rs @@ -175,7 +175,7 @@ impl App { } } } else { - icon_label(ui, area.center_bottom() + vec2(0.0, 6.0), "note", "Audio", muted(), false); + icon_label(ui, area.center_bottom() + vec2(0.0, 6.0), "note", &tr("Audio"), muted(), false); } } } @@ -218,16 +218,16 @@ impl App { let sp = Rect::from_center_size(center - vec2(38.0, 0.0), vec2(24.0, 24.0)); ui.put(sp, egui::Spinner::new().size(24.0).color(accent())); ui.painter().text(center + vec2(14.0, 0.0), Align2::LEFT_CENTER, - if state == State::Buffering { "Buffering" } else { "Loading" }, + tr(if state == State::Buffering { "Buffering" } else { "Loading" }), FontId::proportional(16.0), ink()); } State::Error(e) => { let r = Rect::from_center_size(center, vec2(460.0_f32.min(full.width() - 40.0), 150.0)); ui.painter().rect_filled(r, CornerRadius::same(16), Color32::from_black_alpha(200)); - ui.painter().text(r.center_top() + vec2(0.0, 28.0), Align2::CENTER_CENTER, "Can't play this video", FontId::proportional(20.0), LIVE); + ui.painter().text(r.center_top() + vec2(0.0, 28.0), Align2::CENTER_CENTER, tr("Can't play this video"), FontId::proportional(20.0), LIVE); let shown = if e.contains("opening input") || e.contains("Input/output error") { let d = proxy::last_error(); - format!("YouTube did not hand over this video{}.", if d.is_empty() { String::new() } else { format!(" ({d})") }) + if d.is_empty() { tr("YouTube did not hand over this video.") } else { trf("YouTube did not hand over this video ({detail}).", &[("detail", &d)]) } } else { e.clone() }; @@ -237,14 +237,14 @@ impl App { let br = Rect::from_center_size(r.center() + vec2(0.0, 52.0), vec2(120.0, 32.0)); let bresp = ui.interact(br, uid("err-retry"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand); ui.painter().rect_filled(br, CornerRadius::same(16), if bresp.hovered() { accent2() } else { accent() }); - ui.painter().text(br.center(), Align2::CENTER_CENTER, "Try again", FontId::proportional(14.0), ON_ACCENT); + ui.painter().text(br.center(), Align2::CENTER_CENTER, tr("Try again"), FontId::proportional(14.0), ON_ACCENT); if bresp.clicked() { self.want_retry = true; } } State::Ended => { icons::draw(ui.painter(), center + vec2(-56.0, 0.0), "refresh", 30.0, ink()); - ui.painter().text(center + vec2(-34.0, 0.0), Align2::LEFT_CENTER, "Replay", FontId::proportional(28.0), ink()); + ui.painter().text(center + vec2(-34.0, 0.0), Align2::LEFT_CENTER, tr("Replay"), FontId::proportional(28.0), ink()); } _ => {} } @@ -343,13 +343,22 @@ impl App { let dur = self.player.duration(); let seek = Rect::from_min_size(Pos2::new(full.min.x + 24.0, full.max.y - 88.0), vec2(full.width() - 48.0, 16.0)); if live { - // red "LIVE" while in step with the broadcast, grey "N s behind" once playback has fallen back + // Show the broadcast state and let the viewer jump back to the live edge. let behind = self.player.live_behind(); let late = behind >= 4.0; - let label = if late { { + let label = if late { let b = behind.round() as u64; - if b < 60 { format!("● {b}s behind") } else { format!("● {}m {:02}s behind", b / 60, b % 60) } - } } else { "● LIVE".to_string() }; + if b < 60 { + trf("● {seconds}s behind", &[("seconds", &b.to_string())]) + } else { + trf( + "● {minutes}m {seconds}s behind", + &[("minutes", &(b / 60).to_string()), ("seconds", &format!("{:02}", b % 60))], + ) + } + } else { + tr("● LIVE") + }; let bw = if late { 116.0 } else { 58.0 }; let c = Rect::from_min_size(seek.left_center() - vec2(0.0, 11.0), vec2(bw, 22.0)); let fill = if late { ov(60) } else { LIVE }; @@ -358,15 +367,23 @@ impl App { let mut x = c.right() + 10.0; if late { let b = Rect::from_min_size(Pos2::new(x, c.min.y), vec2(76.0, 22.0)); - let r = ui.interact(b, uid("golive"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text("Jump to the live broadcast"); + let r = ui.interact(b, uid("golive"), Sense::click()) + .on_hover_cursor(egui::CursorIcon::PointingHand) + .on_hover_text(tr("Jump to the live broadcast")); ui.painter().rect_filled(b, CornerRadius::same(11), if r.hovered() { accent2() } else { accent() }.gamma_multiply(t)); - ui.painter().text(b.center(), Align2::CENTER_CENTER, "Go live", FontId::proportional(12.5), ON_ACCENT.gamma_multiply(t)); + ui.painter().text(b.center(), Align2::CENTER_CENTER, tr("Go live"), FontId::proportional(12.5), ON_ACCENT.gamma_multiply(t)); if r.clicked() { self.player.go_live(); } x = b.right() + 12.0; } - ui.painter().text(Pos2::new(x, c.center().y), Align2::LEFT_CENTER, format!("watching for {}", fmt_time(pos)), FontId::proportional(13.0), muted().gamma_multiply(t)); + ui.painter().text( + Pos2::new(x, c.center().y), + Align2::LEFT_CENTER, + trf("Watching for {time}", &[("time", &fmt_time(pos))]), + FontId::proportional(13.0), + muted().gamma_multiply(t), + ); } else { let id = uid("seek"); let sr = ui @@ -473,8 +490,8 @@ impl App { self.watching.as_ref().is_some_and(|w| w.id == c.video.id) && ht >= c.start && ht <= c.end }); let chapter = match (chapter, in_clip) { - (Some(ch), Some(c)) => Some(format!("{ch} • clip {}–{}", fmt_time(c.start), fmt_time(c.end))), - (None, Some(c)) => Some(format!("Clip {}–{}", fmt_time(c.start), fmt_time(c.end))), + (Some(ch), Some(c)) => Some(trf("{channel} • clip {start}–{end}", &[("channel", &ch), ("start", &fmt_time(c.start)), ("end", &fmt_time(c.end))])), + (None, Some(c)) => Some(trf("Clip {start}–{end}", &[("start", &fmt_time(c.start)), ("end", &fmt_time(c.end))])), (ch, None) => ch, }; let label = chapter @@ -671,7 +688,7 @@ impl App { let base = if resp.hovered() { fill.gamma_multiply(1.5) } else { fill }; ui.painter().rect_filled(r, CornerRadius::same(8), base.gamma_multiply(t)); let txt = if fill == accent() { ON_ACCENT } else { ink() }; - if compact && !icon.is_empty() && label != "Audio" { + if compact && !icon.is_empty() && label != tr("Audio") { icon_label(ui, r.center(), icon, "", txt.gamma_multiply(t), false); resp.on_hover_text(label) } else { @@ -708,7 +725,7 @@ impl App { egui::Popup::menu(&spresp).show(|ui| { ui.set_min_width(110.0); for v in [0.5f32, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0] { - let name = if v == 1.0 { "Normal".to_string() } else { format!("{v}×") }; + let name = if v == 1.0 { tr("Normal") } else { format!("{v}×") }; if ui.selectable_label((sp - v).abs() < 0.01, name).clicked() { new_speed = Some(v); ui.close(); @@ -720,8 +737,8 @@ impl App { { let ar = slot("audio"); let on = self.player.audio_mode; - let aresp = pill(ui, ar, "audiomode", "note", "Audio", false, if on { accent() } else { idle }, t) - .on_hover_text("Play audio only (A)"); + let aresp = pill(ui, ar, "audiomode", "note", &tr("Audio"), false, if on { accent() } else { idle }, t) + .on_hover_text(tr("Play audio only (A)")); if aresp.clicked() { toggle_audio = true; } @@ -734,7 +751,7 @@ impl App { let ccresp = pill(ui, ccr, "ccpill", "cc", "", false, if on { accent() } else { idle }, t); egui::Popup::menu(&ccresp).show(|ui| { ui.set_min_width(200.0); - if ui.selectable_label(self.cc_track.is_none(), "Off").clicked() { + if ui.selectable_label(self.cc_track.is_none(), tr("Off")).clicked() { set_cc = Some(None); ui.close(); } @@ -746,13 +763,13 @@ impl App { } if is_pod { ui.separator(); - if ui.button("Open the full transcript").clicked() { + if ui.button(tr("Open the full transcript")).clicked() { toggle_transcript = true; ui.close(); } } else if !is_local_file(&ctracks) { ui.separator(); - ui.menu_button("Translate to…", |ui| { + ui.menu_button(tr("Translate to…"), |ui| { for (code, name) in TRANSLATE_TO { if ui.selectable_label(self.cc_translated.as_deref() == Some(*code), *name).clicked() { translate = Some((*code, *name)); @@ -771,65 +788,65 @@ impl App { ui.set_min_width(220.0); if let Some(w) = self.watching.clone().filter(|w| w.music) { let liked = self.lists.iter().any(|l| l.id == "liked" && l.videos.iter().any(|x| x.id == w.id)); - if ui.selectable_label(liked, "Like this song").clicked() { + if ui.selectable_label(liked, tr("Like this song")).clicked() { list_toggle = Some(("liked".to_string(), w)); ui.close(); } } if let Some(w) = self.watching.clone().filter(|w| !w.id.starts_with("local:")) { let in_wl = self.lists.iter().any(|l| l.id == "watchlater" && l.videos.iter().any(|x| x.id == w.id)); - if ui.selectable_label(in_wl, "Watch later (W)").clicked() { + if ui.selectable_label(in_wl, tr("Watch later (W)")).clicked() { list_toggle = Some(("watchlater".to_string(), w)); ui.close(); } } - if !self.player.is_live() && ui.button("Clip this moment…").clicked() { + if !self.player.is_live() && ui.button(tr("Clip this moment…")).clicked() { open_clip = true; ui.close(); } - if ui.selectable_label(self.settings.ambient, "Ambient mode (B)").clicked() { + if ui.selectable_label(self.settings.ambient, tr("Ambient mode (B)")).clicked() { toggle_ambient = true; ui.close(); } - if ui.selectable_label(self.player.audio_mode, "Audio only (A)").clicked() { + if ui.selectable_label(self.player.audio_mode, tr("Audio only (A)")).clicked() { toggle_audio = true; ui.close(); } ui.separator(); - ui.label(egui::RichText::new("REPEAT").size(11.0).color(muted()).strong()); - for (r, l) in [(Repeat::Off, "Off"), (Repeat::One, "Repeat this video"), (Repeat::All, "Repeat the queue")] { + ui.label(egui::RichText::new(tr("REPEAT")).size(11.0).color(muted()).strong()); + for (r, l) in [(Repeat::Off, tr("Off")), (Repeat::One, tr("Repeat this video")), (Repeat::All, tr("Repeat the queue"))] { if ui.selectable_label(self.settings.repeat == r, l).clicked() { new_repeat = Some(r); } } ui.separator(); - if ui.selectable_label(self.settings.shuffle, "Shuffle the queue").clicked() { + if ui.selectable_label(self.settings.shuffle, tr("Shuffle the queue")).clicked() { toggle_shuffle = true; } ui.separator(); - ui.label(egui::RichText::new("SLEEP TIMER").size(11.0).color(muted()).strong()); + ui.label(egui::RichText::new(tr("SLEEP TIMER")).size(11.0).color(muted()).strong()); let active = match &self.sleep { - Some(SleepMode::At(t)) => format!("Stops in {}", fmt_time(t.saturating_duration_since(Instant::now()).as_secs_f64())), - Some(SleepMode::EndOfVideo) => "Stops after this video".to_string(), - None => "Off".to_string(), + Some(SleepMode::At(t)) => trf("Stops in {time}", &[("time", &fmt_time(t.saturating_duration_since(Instant::now()).as_secs_f64()))]), + Some(SleepMode::EndOfVideo) => tr("Stops after this video"), + None => tr("Off"), }; ui.label(egui::RichText::new(active).size(12.0).color(muted())); - for (label, mins) in [("15 minutes", 15u64), ("30 minutes", 30), ("45 minutes", 45), ("1 hour", 60)] { + for (label, mins) in [(tr("15 minutes"), 15u64), (tr("30 minutes"), 30), (tr("45 minutes"), 45), (tr("1 hour"), 60)] { if ui.button(label).clicked() { set_sleep = Some(Some(SleepMode::At(Instant::now() + Duration::from_secs(mins * 60)))); ui.close(); } } - if ui.button("End of this video").clicked() { + if ui.button(tr("End of this video")).clicked() { set_sleep = Some(Some(SleepMode::EndOfVideo)); ui.close(); } - if self.sleep.is_some() && ui.button("Turn off").clicked() { + if self.sleep.is_some() && ui.button(tr("Turn off")).clicked() { set_sleep = Some(None); ui.close(); } ui.separator(); - if ui.button("Keyboard shortcuts").clicked() { + if ui.button(tr("Keyboard shortcuts")).clicked() { show_help = true; ui.close(); } @@ -844,12 +861,13 @@ impl App { } else { ("Comments", SideTab::Comments) }; + let lbl = tr(lbl); let cresp = pill( ui, cr, "cm", if music { "note" } else { "comment" }, - lbl, + &lbl, false, if self.comments_open && self.side_tab == tab { accent() } else { idle }, t, @@ -866,7 +884,7 @@ impl App { if self.queue.len() > 1 { let qr = slot("queue"); let on = self.comments_open && self.side_tab == SideTab::Queue; - let qresp = pill(ui, qr, "queuepill", "queue", &format!("Queue {}", self.queue.len()), false, if on { accent() } else { idle }, t); + let qresp = pill(ui, qr, "queuepill", "queue", &trf("Queue ({count})", &[("count", &self.queue.len().to_string())]), false, if on { accent() } else { idle }, t); if qresp.clicked() { open_queue = true; } @@ -880,9 +898,9 @@ impl App { let da = self.is_downloaded(&w.id, true); let (dicon, label, chev) = match (prog, dv, da) { (Some(p), _, _) => ("download", format!("{}%", (p * 100.0) as u32), false), - (None, true, _) => ("check", "Saved".to_string(), false), - (None, false, true) => ("check", if is_pod { "Saved" } else { "Audio saved" }.to_string(), false), - _ => ("download", "Download".to_string(), !is_pod), + (None, true, _) => ("check", tr("Saved"), false), + (None, false, true) => ("check", tr(if is_pod { "Saved" } else { "Audio saved" }), false), + _ => ("download", tr("Download"), !is_pod), }; let fill = if dv || da { TEAL } else { idle }; let dresp = pill(ui, dr, "dlbtn", dicon, &label, chev, fill, t); @@ -899,9 +917,9 @@ impl App { egui::Popup::menu(&dresp).show(|ui| { ui.set_min_width(200.0); if dv { - ui.add_enabled(false, egui::Button::new("Video downloaded")); + ui.add_enabled(false, egui::Button::new(tr("Video downloaded"))); } else { - ui.label(egui::RichText::new("VIDEO (mp4)").size(11.0).color(muted()).strong()); + ui.label(egui::RichText::new(tr("VIDEO (mp4)")).size(11.0).color(muted()).strong()); let mut qs = self.player.qualities(); qs.sort_unstable_by(|a, b| b.cmp(a)); for q in qs { @@ -913,8 +931,8 @@ impl App { } ui.separator(); if da { - ui.add_enabled(false, egui::Button::new("Audio downloaded")); - } else if ui.button("Audio only (m4a)").clicked() { + ui.add_enabled(false, egui::Button::new(tr("Audio downloaded"))); + } else if ui.button(tr("Audio only (m4a)")).clicked() { start_dl = Some((w.clone(), true, 0)); ui.close(); } @@ -923,12 +941,13 @@ impl App { } let sr = slot("playlist"); let in_any = self.lists.iter().any(|l| l.videos.iter().any(|x| x.id == w.id)); + let playlist_button_label = tr(if in_any { "Saved" } else { "Playlist" }); let sresp = pill( ui, sr, "plbtn", if in_any { "heart_fill" } else { "playlist_add" }, - if in_any { "Saved" } else { "Playlist" }, + &playlist_button_label, true, if in_any { accent() } else { idle }, t, @@ -937,13 +956,13 @@ impl App { ui.set_min_width(190.0); for l in &self.lists { let has = l.videos.iter().any(|x| x.id == w.id); - if ui.selectable_label(has, l.name.clone()).clicked() { + if ui.selectable_label(has, playlist_label(l)).clicked() { list_toggle = Some((l.id.clone(), w.clone())); ui.close(); } } ui.separator(); - if ui.button("+ New playlist…").clicked() { + if ui.button(tr("+ New playlist…")).clicked() { new_list_for = Some(w.clone()); ui.close(); } @@ -976,7 +995,7 @@ impl App { let _ = tx.send(Msg::Cues(vid, usize::MAX, r)); ctx.request_repaint(); }); - self.toast(format!("Translating captions to {name}")); + self.toast(trf("Translating captions to {name}", &[("name", &name)])); } } if let Some(c) = set_cc { @@ -1028,7 +1047,7 @@ impl App { } if let Some(m) = set_sleep { self.sleep = m; - self.toast(if self.sleep.is_some() { "Sleep timer set" } else { "Sleep timer off" }); + self.toast(tr(if self.sleep.is_some() { "Sleep timer set" } else { "Sleep timer off" })); } if show_help { self.show_help = true; @@ -1101,7 +1120,7 @@ impl App { let title = truncate(ui, &w.title, FontId::proportional(15.0), tw, 1); let up_next = self.queue_idx.and_then(|i| self.queue.get(i + 1)).map(|q| q.title()); let sub_full = match up_next { - Some(n) => format!("{} • Up next: {n}", w.channel_name), + Some(n) => trf("{channel} • Up next: {title}", &[("channel", &w.channel_name), ("title", &n)]), None => w.channel_name.clone(), }; let sub = truncate(ui, &sub_full, FontId::proportional(12.5), tw, 1); @@ -1164,7 +1183,7 @@ impl App { let aspect = self.player.aspect().clamp(0.5, 3.0); let w = 480.0; let builder = egui::ViewportBuilder::default() - .with_title("TubeGlass — Picture in Picture") + .with_title(tr("TubeGlass — Picture in Picture")) .with_inner_size([w, w / aspect]) .with_min_inner_size([240.0, 140.0]) .with_always_on_top() diff --git a/src/ui/podcasts_view.rs b/src/ui/podcasts_view.rs index 8978818..a6766e0 100644 --- a/src/ui/podcasts_view.rs +++ b/src/ui/podcasts_view.rs @@ -8,19 +8,19 @@ use crate::podcasts::Saved; pub(crate) fn ep_menu(resp: &egui::Response, saved: bool, prog: Option, is_new: bool) -> Option { let mut act = None; resp.context_menu(|ui| { - if ui.button("Play next").clicked() { + if ui.button(tr("Play next")).clicked() { act = Some(EpAct::Next); ui.close(); } - if ui.button("Add to queue").clicked() { + if ui.button(tr("Add to queue")).clicked() { act = Some(EpAct::Queue); ui.close(); } - if !saved && prog.is_none() && ui.button("Download").clicked() { + if !saved && prog.is_none() && ui.button(tr("Download")).clicked() { act = Some(EpAct::Download); ui.close(); } - if is_new && ui.button("Mark as played").clicked() { + if is_new && ui.button(tr("Mark as played")).clicked() { act = Some(EpAct::Seen); ui.close(); } @@ -67,7 +67,7 @@ impl App { if is_new { let b = Rect::from_min_size(img.min + vec2(7.0, 7.0), vec2(38.0, 17.0)); ui.painter().rect_filled(b, CornerRadius::same(5), accent()); - ui.painter().text(b.center(), Align2::CENTER_CENTER, "NEW", FontId::proportional(10.5), ON_ACCENT); + ui.painter().text(b.center(), Align2::CENTER_CENTER, tr("NEW"), FontId::proportional(10.5), ON_ACCENT); } if let Some(h) = hist.filter(|h| h.duration > 0.0 && h.position > 5.0) { let f = (h.position / h.duration).clamp(0.0, 1.0) as f32; @@ -157,7 +157,7 @@ impl App { if is_new { let b = Rect::from_min_size(Pos2::new(th_r.min.x + 4.0, th_r.min.y + 4.0), vec2(38.0, 17.0)); ui.painter().rect_filled(b, CornerRadius::same(5), accent()); - ui.painter().text(b.center(), Align2::CENTER_CENTER, "NEW", FontId::proportional(10.5), ON_ACCENT); + ui.painter().text(b.center(), Align2::CENTER_CENTER, tr("NEW"), FontId::proportional(10.5), ON_ACCENT); } let title = truncate(ui, &e.title, FontId::proportional(15.5), w - (tx - rect.min.x) - right, 2); ui.painter().text(Pos2::new(tx, rect.min.y + 10.0), Align2::LEFT_TOP, title, FontId::proportional(15.5), ink()); @@ -250,7 +250,7 @@ impl App { ui.horizontal(|ui| { if self.can_go_back() { let (r, resp) = ui.allocate_exact_size(vec2(46.0, 46.0), Sense::click()); - let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text("Back (Alt+←)"); + let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text(tr("Back (Alt+←)")); let hv = ui.ctx().animate_bool_with_time(resp.id, resp.hovered(), 0.12); ui.painter().add(surface::capsule(r, 1.0, if hv > 0.05 { Some(accent()) } else { None }, false)); icons::draw(ui.painter(), r.center(), "arrow_left", 19.0, if hv > 0.5 { accent() } else { ink() }); @@ -258,7 +258,7 @@ impl App { ui.add_space(4.0); } let w = ui.available_width(); - let f = text_field(ui, &mut self.pod_input, "Search podcasts, or paste a feed or Apple Podcasts link", w, 46.0, "search", Some("Search"), false); + let f = text_field(ui, &mut self.pod_input, &tr("Search podcasts, or paste a feed or Apple Podcasts link"), w, 46.0, "search", Some(&tr("Search")), false); go = f.submit || f.action; cleared = f.cleared; }); @@ -334,7 +334,7 @@ impl App { .corner_radius(CornerRadius::same((side / 2.0) as u8)) .paint_at(ui, art); } - icon_label(ui, Pos2::new(c.x, c.y + big + 20.0), "mic", "Podcast", muted(), false); + icon_label(ui, Pos2::new(c.x, c.y + big + 20.0), "mic", &tr("Podcast"), muted(), false); ui.ctx().request_repaint(); } @@ -344,14 +344,14 @@ impl App { return; } ui.horizontal_wrapped(|ui| { - ui.label(egui::RichText::new("Podcasts").size(26.0).strong()); + ui.label(egui::RichText::new(tr("Podcasts")).size(26.0).strong()); if !self.pod_busy.is_empty() { ui.add(egui::Spinner::new().size(18.0).color(accent())); } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center).with_main_wrap(true), |ui| { if !self.pods.is_empty() { self.view_toggle(ui); - if icon_btn(ui, "refresh", "Refresh", None, ink(), false, true).clicked() { + if icon_btn(ui, "refresh",&tr("Refresh"), None, ink(), false, true).clicked() { self.refresh_all_pods(); } } @@ -370,17 +370,17 @@ impl App { let w = ui.available_width() - 6.0; // search results if let Some((q, res)) = &self.pod_hits { - ui.label(egui::RichText::new(format!("RESULTS FOR “{}”", q.to_uppercase())).size(11.0).color(muted()).strong()); + ui.label(egui::RichText::new(trf("Results for “{query}”", &[("query", &q.to_uppercase())])).size(11.0).color(muted()).strong()); match res { None => { ui.add_space(8.0); ui.add(egui::Spinner::new().size(22.0).color(accent())); } Some(Err(e)) => { - ui.colored_label(LIVE, format!("Search failed: {e}")); + ui.colored_label(LIVE, trf("Search failed: {error}", &[("error", e)])); } Some(Ok(hits)) if hits.is_empty() => { - ui.label(egui::RichText::new("No podcasts found.").color(muted())); + ui.label(egui::RichText::new(tr("No podcasts found.")).color(muted())); } Some(Ok(hits)) => { for h in hits { @@ -403,7 +403,7 @@ impl App { let br = Rect::from_center_size(Pos2::new(rect.max.x - 70.0, rect.center().y), vec2(112.0, 34.0)); let bresp = ui.interact(br, resp.id.with("sub"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand); ui.painter().rect_filled(br, CornerRadius::same(17), if have { card_hi() } else if bresp.hovered() { accent2() } else { accent() }); - icon_label(ui, br.center(), if have { "check" } else { "plus" }, if have { "Subscribed" } else { "Subscribe" }, if have { ink() } else { ON_ACCENT }, false); + icon_label(ui, br.center(), if have { "check" } else { "plus" }, &tr(if have { "Subscribed" } else { "Subscribe" }), if have { ink() } else { ON_ACCENT }, false); if bresp.clicked() && !have { subscribe = Some(h.feed.clone()); } else if resp.clicked() && have { @@ -418,14 +418,14 @@ impl App { if self.pods.is_empty() && self.pod_hits.is_none() { ui.add_space(50.0); ui.vertical_centered(|ui| { - ui.label(egui::RichText::new("No podcasts yet.").size(18.0).color(muted())); - ui.label(egui::RichText::new("Search above, or paste a podcast's feed address (RSS) or its Apple Podcasts link.").color(muted())); + ui.label(egui::RichText::new(tr("No podcasts yet.")).size(18.0).color(muted())); + ui.label(egui::RichText::new(tr("Search above, or paste a podcast's feed address (RSS) or its Apple Podcasts link.")).color(muted())); }); return; } // your shows if !self.pods.is_empty() { - ui.label(egui::RichText::new("YOUR SHOWS").size(11.0).color(muted()).strong()); + ui.label(egui::RichText::new(tr("YOUR SHOWS")).size(11.0).color(muted()).strong()); if self.settings.view_mode == 2 { // list: one row per show for p in &self.pods { @@ -441,14 +441,20 @@ impl App { } let tx = th_r.max.x + 14.0; let t = truncate(ui, &p.show.title, FontId::proportional(16.0), w - 230.0, 1); - let a = truncate(ui, &format!("{} • {} episodes", p.show.author, p.episodes.len()), FontId::proportional(13.0), w - 230.0, 1); + let count = p.episodes.len().to_string(); + let summary = if p.episodes.len() == 1 { + trf("{author} • {count} episode", &[("author", &p.show.author), ("count", &count)]) + } else { + trf("{author} • {count} episodes", &[("author", &p.show.author), ("count", &count)]) + }; + let a = truncate(ui, &summary, FontId::proportional(13.0), w - 230.0, 1); ui.painter().text(Pos2::new(tx, rect.center().y - 10.0), Align2::LEFT_CENTER, t, FontId::proportional(16.0), ink()); ui.painter().text(Pos2::new(tx, rect.center().y + 11.0), Align2::LEFT_CENTER, a, FontId::proportional(13.0), muted()); let n = self.pod_new_count(p); if n > 0 { let b = Rect::from_center_size(Pos2::new(rect.max.x - 60.0, rect.center().y), vec2(78.0, 24.0)); ui.painter().rect_filled(b, CornerRadius::same(12), accent()); - ui.painter().text(b.center(), Align2::CENTER_CENTER, format!("{n} new"), FontId::proportional(12.5), ON_ACCENT); + ui.painter().text(b.center(), Align2::CENTER_CENTER, trf("{count} new", &[("count", &n.to_string())]), FontId::proportional(12.5), ON_ACCENT); } if resp.clicked() { open = Some(p.show.feed.clone()); @@ -497,7 +503,7 @@ impl App { } // newest episodes of every show ui.add_space(8.0); - ui.label(egui::RichText::new("LATEST EPISODES").size(11.0).color(muted()).strong()); + ui.label(egui::RichText::new(tr("LATEST EPISODES")).size(11.0).color(muted()).strong()); let mut all: Vec<(&Saved, &Episode)> = self.pods.iter().flat_map(|p| p.episodes.iter().map(move |e| (p, e))).collect(); all.sort_by(|a, b| b.1.published.cmp(&a.1.published)); let list: Vec<(&str, &Show, &Episode)> = all.into_iter().take(25).map(|(p, e)| (p.show.feed.as_str(), &p.show, e)).collect(); @@ -525,7 +531,7 @@ impl App { } let Some(p) = self.pods.iter().find(|p| p.show.feed == feed).cloned() else { ui.add_space(40.0); - ui.label(egui::RichText::new("You are not subscribed to this show.").color(muted())); + ui.label(egui::RichText::new(tr("You are not subscribed to this show.")).color(muted())); return; }; ui.add_space(6.0); @@ -548,23 +554,29 @@ impl App { ui.add(egui::Spinner::new().size(18.0).color(accent())); } }); - ui.label(egui::RichText::new(format!("{} • {} episodes", p.show.author, p.episodes.len())).size(13.5).color(muted())); + let count = p.episodes.len().to_string(); + let summary = if p.episodes.len() == 1 { + trf("{author} • {count} episode", &[("author", &p.show.author), ("count", &count)]) + } else { + trf("{author} • {count} episodes", &[("author", &p.show.author), ("count", &count)]) + }; + ui.label(egui::RichText::new(summary).size(13.5).color(muted())); let d = truncate(ui, &p.show.description, FontId::proportional(13.5), (ui.available_width() - 20.0).max(240.0), 2); ui.label(egui::RichText::new(d).size(13.5).color(muted())); ui.add_space(4.0); ui.horizontal_wrapped(|ui| { self.view_toggle(ui); - if icon_btn(ui, "play", "Play latest", Some(accent()), ON_ACCENT, false, true).clicked() { + if icon_btn(ui, "play",&tr("Play latest"), Some(accent()), ON_ACCENT, false, true).clicked() { play_latest = true; } - if icon_btn(ui, "refresh", "Refresh", None, ink(), false, true).clicked() { + if icon_btn(ui, "refresh",&tr("Refresh"), None, ink(), false, true).clicked() { refresh = true; } - if self.pod_new_count(&p) > 0 && icon_btn(ui, "check", "Mark all as played", None, ink(), false, true).clicked() { + if self.pod_new_count(&p) > 0 && icon_btn(ui, "check",&tr("Mark all as played"), None, ink(), false, true).clicked() { mark_all = true; } - let label = if self.pod_unsub_confirm { "Confirm unsubscribe" } else { "Unsubscribe" }; - let b = icon_btn(ui, "", label, if self.pod_unsub_confirm { Some(LIVE) } else { None }, if self.pod_unsub_confirm { Color32::WHITE } else { ink() }, false, true); + let label = tr(if self.pod_unsub_confirm { "Confirm unsubscribe" } else { "Unsubscribe" }); + let b = icon_btn(ui, "", &label, if self.pod_unsub_confirm { Some(LIVE) } else { None }, if self.pod_unsub_confirm { Color32::WHITE } else { ink() }, false, true); if b.clicked() { if self.pod_unsub_confirm { unsub = true; @@ -592,7 +604,7 @@ impl App { } if shown < p.episodes.len() { ui.add_space(6.0); - ui.vertical_centered(|ui| ui.label(egui::RichText::new(format!("Showing {shown} of {} episodes", p.episodes.len())).size(12.5).color(muted()))); + ui.vertical_centered(|ui| ui.label(egui::RichText::new(trf("Showing {shown} of {total} episodes", &[("shown", &shown.to_string()), ("total", &p.episodes.len().to_string())])).size(12.5).color(muted()))); ui.add_space(20.0); } }); diff --git a/src/ui/settings_view.rs b/src/ui/settings_view.rs index 7209d39..4f396cb 100644 --- a/src/ui/settings_view.rs +++ b/src/ui/settings_view.rs @@ -6,7 +6,7 @@ impl App { /// Draws the Settings page. pub(crate) fn settings_view(&mut self, ui: &mut egui::Ui) { ui.add_space(8.0); - ui.label(egui::RichText::new("Settings").size(26.0).strong()); + ui.label(egui::RichText::new(tr("Settings")).size(26.0).strong()); ui.add_space(8.0); let mut changed = false; let mut pick_dir = false; @@ -26,7 +26,7 @@ impl App { } egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { let section = |ui: &mut egui::Ui, title: &str, f: &mut dyn FnMut(&mut egui::Ui)| { - ui.label(egui::RichText::new(title).size(12.0).color(muted()).strong()); + ui.label(egui::RichText::new(tr(title)).size(12.0).color(muted()).strong()); egui::Frame::new() .fill(card()) .corner_radius(CornerRadius::same(16)) @@ -39,9 +39,9 @@ impl App { }; let row = |ui: &mut egui::Ui, label: &str, hint: &str, add: &mut dyn FnMut(&mut egui::Ui)| { let texts = |ui: &mut egui::Ui| { - ui.label(egui::RichText::new(label).size(15.0)); + ui.label(egui::RichText::new(tr(label)).size(15.0)); if !hint.is_empty() { - ui.label(egui::RichText::new(hint).size(12.0).color(muted())); + ui.label(egui::RichText::new(tr(hint)).size(12.0).color(muted())); } }; if ui.available_width() >= 640.0 { @@ -87,7 +87,7 @@ impl App { changed |= switch(ui, &mut self.settings.gapless); }); row(ui, "Crossfade", "Blend the end of a song into the next (needs gapless)", &mut |ui| { - for (label, secs) in [("6 s", 6u32), ("3 s", 3), ("Off", 0)] { + for (label, secs) in [(tr("6 s"), 6u32), (tr("3 s"), 3), (tr("Off"), 0)] { let on = self.settings.crossfade == secs; let b = egui::Button::new(egui::RichText::new(label).color(if on { ON_ACCENT } else { ink() })) .fill(if on { accent() } else { card_hi() }); @@ -106,7 +106,7 @@ impl App { }); section(ui, "AUDIO", &mut |ui| { row(ui, "Equalizer", "Presets or your own bass / mid / treble", &mut |ui| { - for (label, b, m, t) in [("Vocal", -2.0f32, 3.0, 1.0), ("Treble", -1.0, 0.0, 5.0), ("Bass", 6.0, 0.0, -1.0), ("Flat", 0.0, 0.0, 0.0)] { + for (label, b, m, t) in [(tr("Vocal"), -2.0f32, 3.0, 1.0), (tr("Treble"), -1.0, 0.0, 5.0), (tr("Bass"), 6.0, 0.0, -1.0), (tr("Flat"), 0.0, 0.0, 0.0)] { let on = (self.settings.eq_bass, self.settings.eq_mid, self.settings.eq_treble) == (b, m, t); let btn = egui::Button::new(egui::RichText::new(label).color(if on { ON_ACCENT } else { ink() })) .fill(if on { accent() } else { card_hi() }); @@ -140,12 +140,18 @@ impl App { }); section(ui, "STORAGE", &mut |ui| { if let Some(st) = &self.storage { + let item_count = st.items.to_string(); + let item_label = if st.items == 1 { + trf("{count} item", &[("count", &item_count)]) + } else { + trf("{count} items", &[("count", &item_count)]) + }; let rows = [ - ("Downloads", format!("{} • {} item{}", fmt_size(st.downloads), st.items, if st.items == 1 { "" } else { "s" })), - ("Clips", fmt_size(st.clips)), - ("Thumbnails and avatars", fmt_size(st.images)), - ("Saved feeds", fmt_size(st.feeds)), - ("Free on this disk", fmt_size(st.free)), + (tr("Downloads"), format!("{} • {item_label}", fmt_size(st.downloads))), + (tr("Clips"), fmt_size(st.clips)), + (tr("Thumbnails and avatars"), fmt_size(st.images)), + (tr("Saved feeds"), fmt_size(st.feeds)), + (tr("Free on this disk"), fmt_size(st.free)), ]; for (k, v) in rows { ui.horizontal(|ui| { @@ -164,11 +170,13 @@ impl App { let mut go = false; ui.horizontal(|ui| { ui.vertical(|ui| { - ui.label(egui::RichText::new(label).size(15.0)); - ui.label(egui::RichText::new(hint).size(12.0).color(muted())); + ui.label(egui::RichText::new(tr(label)).size(15.0)); + if !hint.is_empty() { + ui.label(egui::RichText::new(tr(hint)).size(12.0).color(muted())); + } }); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let b = egui::Button::new(egui::RichText::new(if sure { "Confirm" } else { "Delete…" }).color(if sure { Color32::WHITE } else { ink() })) + let b = egui::Button::new(egui::RichText::new(tr(if sure { "Confirm" } else { "Delete…" })).color(if sure { Color32::WHITE } else { ink() })) .fill(if sure { LIVE } else { card_hi() }); if ui.add(b).clicked() { go = sure; @@ -179,13 +187,13 @@ impl App { ui.add_space(6.0); go }; - if ask(ui, 1, "Finished downloads", "Videos and songs you have already watched or listened to all the way") { + if ask(ui, 1, &tr("Finished downloads"), &tr("Videos and songs you have already watched or listened to all the way")) { free_finished = true; } - if ask(ui, 2, "Downloads older than 30 days", "Frees the most space when you download a lot") { + if ask(ui, 2, &tr("Downloads older than 30 days"), &tr("Frees the most space when you download a lot")) { free_older = Some(30); } - if ask(ui, 3, "Downloads older than 90 days", "") { + if ask(ui, 3, &tr("Downloads older than 90 days"), "") { free_older = Some(90); } }); @@ -207,10 +215,10 @@ impl App { }); section(ui, "DOWNLOADS", &mut |ui| { row(ui, "Folder", &download::dir().display().to_string(), &mut |ui| { - if ui.button("Choose…").clicked() { + if ui.button(tr("Choose…")).clicked() { pick_dir = true; } - if !self.settings.download_dir.is_empty() && ui.button("Reset").clicked() { + if !self.settings.download_dir.is_empty() && ui.button(tr("Reset")).clicked() { self.settings.download_dir.clear(); apply_settings(&self.settings); self.library = download::list(); @@ -219,8 +227,31 @@ impl App { }); }); section(ui, "APPEARANCE", &mut |ui| { + row(ui, "Interface language", "Choose the language used for TubeGlass controls", &mut |ui| { + let options = language_options(); + let selected = if self.settings.language == "system" { + tr("Use system language") + } else { + options.iter().find(|(code, _)| code == &self.settings.language) + .map(|(_, name)| name.clone()).unwrap_or_else(|| self.settings.language.clone()) + }; + egui::ComboBox::from_id_salt("ui-language") + .selected_text(selected) + .show_ui(ui, |ui| { + if ui.selectable_value(&mut self.settings.language, "system".to_owned(), tr("Use system language")).changed() { + i18n::set_language(&self.settings.language); + changed = true; + } + for (code, label) in options { + if ui.selectable_value(&mut self.settings.language, code, label).changed() { + i18n::set_language(&self.settings.language); + changed = true; + } + } + }); + }); row(ui, "Theme", "Dark, light, or follow the system (the video page stays dark)", &mut |ui| { - for (label, v) in [("System", 2u8), ("Light", 1), ("Dark", 0)] { + for (label, v) in [(tr("System"), 2u8), (tr("Light"), 1), (tr("Dark"), 0)] { let on = self.settings.theme == v; let b = egui::Button::new(egui::RichText::new(label).color(if on { ON_ACCENT } else { ink() })) .fill(if on { accent() } else { card_hi() }); @@ -233,7 +264,7 @@ impl App { row(ui, "Text size", "Scales the whole interface", &mut |ui| { for (label, v) in [("130%", 1.3f32), ("115%", 1.15), ("100%", 1.0), ("90%", 0.9)] { let on = (self.settings.font_scale - v).abs() < 0.01; - let b = egui::Button::new(egui::RichText::new(label).color(if on { ON_ACCENT } else { ink() })) + let b = egui::Button::new(egui::RichText::new(tr(label)).color(if on { ON_ACCENT } else { ink() })) .fill(if on { accent() } else { card_hi() }); if ui.add(b).clicked() { self.settings.font_scale = v; @@ -242,7 +273,7 @@ impl App { } }); row(ui, "Density", "How big and how far apart video cards are", &mut |ui| { - for (label, v) in [("Spacious", 2u8), ("Comfortable", 1), ("Compact", 0)] { + for (label, v) in [(tr("Spacious"), 2u8), (tr("Comfortable"), 1), (tr("Compact"), 0)] { let on = self.settings.density == v; let b = egui::Button::new(egui::RichText::new(label).color(if on { ON_ACCENT } else { ink() })) .fill(if on { accent() } else { card_hi() }); @@ -264,12 +295,12 @@ impl App { changed = true; } if on { - ui.label(egui::RichText::new("custom").size(12.0).color(muted())); + ui.label(egui::RichText::new(tr("custom")).size(12.0).color(muted())); } }); for (i, (name, c, _)) in ACCENTS.iter().enumerate().rev() { let (r, resp) = ui.allocate_exact_size(vec2(28.0, 28.0), Sense::click()); - let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text(*name); + let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text(tr(name)); ui.painter().circle_filled(r.center(), 11.0, *c); if self.settings.accent == i { ui.painter().circle_stroke(r.center(), 14.0, Stroke::new(2.0, ink())); @@ -284,12 +315,12 @@ impl App { }); section(ui, "SUBSCRIPTIONS", &mut |ui| { row(ui, "Import", "NewPipe export, YouTube Takeout CSV, OPML, or a list of links", &mut |ui| { - if ui.button("Import…").clicked() { + if ui.button(tr("Import…")).clicked() { import_subs = true; } }); row(ui, "Export", "Saves a NewPipe-compatible subscriptions file", &mut |ui| { - if ui.button("Export…").clicked() { + if ui.button(tr("Export…")).clicked() { export_subs = true; } }); @@ -301,33 +332,33 @@ impl App { }); section(ui, "DATA", &mut |ui| { row(ui, "Back up everything", "Channels, playlists, history, liked songs, groups and settings in one file", &mut |ui| { - if ui.button("Back up…").clicked() { + if ui.button(tr("Back up…")).clicked() { backup = true; } }); row(ui, "Restore a backup", "Replaces what is here with the file's contents, then restarts", &mut |ui| { - if ui.button("Restore…").clicked() { + if ui.button(tr("Restore…")).clicked() { restore = true; } }); row(ui, "Check for updates automatically", "Looks at the project's GitHub releases now and then (nothing else is sent)", &mut |ui| { changed |= switch(ui, &mut self.settings.update_check); }); - let note = self.update_note.clone().unwrap_or_else(|| format!("You have version {}", update::CURRENT)); + let note = self.update_note.clone().unwrap_or_else(|| trf("You have version {version}", &[("version", update::CURRENT)])); row(ui, "Check for updates now", ¬e, &mut |ui| { if self.update_checking { ui.add(egui::Spinner::new().size(16.0).color(accent())); - } else if ui.button("Check now").clicked() { + } else if ui.button(tr("Check now")).clicked() { check_update = true; } }); let ff = crate::platform::ffmpeg_in_use(); let ffm = &mut self.ffmpeg; let mut redo = false; - row(ui, "ffmpeg", &format!("Everything plays through it. In use: {ff}"), &mut |ui| { + row(ui, "ffmpeg", &trf("Everything plays through it. In use: {ffmpeg}", &[("ffmpeg", &ff)]), &mut |ui| { if matches!(ffm, FfmpegState::Downloading(_)) { ui.add(egui::Spinner::new().size(16.0).color(accent())); - } else if ui.button("Download a fresh copy").clicked() { + } else if ui.button(tr("Download a fresh copy")).clicked() { redo = true; } }); @@ -337,7 +368,7 @@ impl App { row(ui, "Check YouTube access", "Tests search, playback, comments and music, to see what broke if something stops working", &mut |ui| { if self.diag_running { ui.add(egui::Spinner::new().size(16.0).color(accent())); - } else if ui.button("Run check").clicked() { + } else if ui.button(tr("Run check")).clicked() { diagnose = true; } }); @@ -345,18 +376,18 @@ impl App { for (name, ok, note) in d { ui.horizontal(|ui| { ui.colored_label(if *ok { Color32::from_rgb(110, 200, 120) } else { LIVE }, "●"); - ui.label(egui::RichText::new(format!("{name} — {note}")).size(13.0).color(if *ok { muted() } else { ink() })); + ui.label(egui::RichText::new(trf("{name} — {note}", &[("name", name), ("note", note)])).size(13.0).color(if *ok { muted() } else { ink() })); }); } ui.add_space(6.0); } row(ui, "Clear image cache", "Thumbnails and avatars are downloaded again when needed", &mut |ui| { - if ui.button("Clear").clicked() { + if ui.button(tr("Clear")).clicked() { clear_cache = true; } }); row(ui, "Clear watch history", "Also forgets where you left each video", &mut |ui| { - if ui.button("Clear").clicked() { + if ui.button(tr("Clear")).clicked() { clear_history = true; } }); @@ -368,7 +399,9 @@ impl App { if pick_dir { let (tx, ctx) = (self.tx.clone(), self.ctx.clone()); std::thread::spawn(move || { - let p = rfd::FileDialog::new().set_title("Download folder").pick_folder(); + let p = rfd::FileDialog::new() + .set_title(tr("Download folder")) + .pick_folder(); let _ = tx.send(Msg::DirPicked(p.map(|p| p.display().to_string()))); ctx.request_repaint(); }); @@ -377,9 +410,9 @@ impl App { let (tx, ctx) = (self.tx.clone(), self.ctx.clone()); std::thread::spawn(move || { let picked = rfd::FileDialog::new() - .set_title("Import subscriptions") - .add_filter("Subscriptions", &["json", "csv", "opml", "xml", "txt"]) - .add_filter("All files", &["*"]) + .set_title(tr("Import subscriptions")) + .add_filter(tr("Subscriptions"), &["json", "csv", "opml", "xml", "txt"]) + .add_filter(tr("All files"), &["*"]) .pick_file(); if let Some(p) = picked { if let Ok(text) = std::fs::read_to_string(p) { @@ -396,9 +429,9 @@ impl App { let (tx, ctx) = (self.tx.clone(), self.ctx.clone()); std::thread::spawn(move || { let picked = rfd::FileDialog::new() - .set_title("Export subscriptions") + .set_title(tr("Export subscriptions")) .set_file_name("newpipe_subscriptions.json") - .add_filter("JSON", &["json"]) + .add_filter(tr("JSON"), &["json"]) .save_file(); if let Some(p) = picked { let _ = std::fs::write(&p, json); @@ -412,14 +445,14 @@ impl App { let (tx, ctx) = (self.tx.clone(), self.ctx.clone()); std::thread::spawn(move || { if let Some(p) = rfd::FileDialog::new() - .set_title("Back up TubeGlass") + .set_title(tr("Back up TubeGlass")) .set_file_name("tubeglass-backup.json") - .add_filter("JSON", &["json"]) + .add_filter(tr("JSON"), &["json"]) .save_file() { let msg = match std::fs::write(&p, bundle) { - Ok(_) => format!("Backup saved to {}", p.display()), - Err(e) => format!("Could not save the backup: {e}"), + Ok(_) => trf("Backup saved to {path}", &[("path", &p.display().to_string())]), + Err(e) => trf("Could not save the backup: {error}", &[("error", &e.to_string())]), }; let _ = tx.send(Msg::Note(msg)); ctx.request_repaint(); @@ -429,11 +462,17 @@ impl App { if restore { let (tx, ctx) = (self.tx.clone(), self.ctx.clone()); std::thread::spawn(move || { - let Some(p) = rfd::FileDialog::new().set_title("Restore a backup").add_filter("JSON", &["json"]).pick_file() else { return }; + let Some(p) = rfd::FileDialog::new() + .set_title(tr("Restore a backup")) + .add_filter(tr("JSON"), &["json"]) + .pick_file() + else { + return; + }; let text = std::fs::read_to_string(&p).unwrap_or_default(); let sure = rfd::MessageDialog::new() - .set_title("Restore backup") - .set_description("This replaces your current channels, playlists, history and settings with the backup, then restarts TubeGlass.") + .set_title(tr("Restore backup")) + .set_description(tr("This replaces your current channels, playlists, history and settings with the backup, then restarts TubeGlass.")) .set_buttons(rfd::MessageButtons::YesNo) .show() == rfd::MessageDialogResult::Yes; @@ -445,7 +484,7 @@ impl App { let _ = tx.send(Msg::Restored); } Err(e) => { - let _ = tx.send(Msg::Note(format!("Could not restore: {e}"))); + let _ = tx.send(Msg::Note(trf("Could not restore: {error}", &[("error", &e.to_string())]))); } } ctx.request_repaint(); @@ -456,7 +495,9 @@ impl App { let finished: HashSet = self .history .iter() - .filter(|h| h.duration > 0.0 && (h.position == 0.0 || h.position >= h.duration - 10.0)) + .filter(|h| { + h.duration > 0.0 && (h.position == 0.0 || h.position >= h.duration - 10.0) + }) .map(|h| h.video.id.clone()) .collect(); let mut n = 0; @@ -476,7 +517,13 @@ impl App { } } self.library = download::list(); - self.toast(format!("Removed {n} download{}, freed {}", if n == 1 { "" } else { "s" }, fmt_size(bytes))); + let count = n.to_string(); + let size = fmt_size(bytes); + self.toast(if n == 1 { + trf("Removed {count} download, freed {size}", &[("count", &count), ("size", &size)]) + } else { + trf("Removed {count} downloads, freed {size}", &[("count", &count), ("size", &size)]) + }); self.refresh_storage(); } if check_update { @@ -497,12 +544,12 @@ impl App { let _ = std::fs::remove_dir_all(d.join("img")); let _ = std::fs::create_dir_all(d.join("img")); } - self.toast("Image cache cleared (restart to refetch avatars)"); + self.toast(tr("Image cache cleared (restart to refetch avatars)")); } if clear_history { self.history.clear(); save_history(&self.history); - self.toast("Watch history cleared"); + self.toast(tr("Watch history cleared")); } } } diff --git a/src/ui/side_tools.rs b/src/ui/side_tools.rs index 2cca06f..a22a6a0 100644 --- a/src/ui/side_tools.rs +++ b/src/ui/side_tools.rs @@ -162,7 +162,7 @@ impl App { // podcasts bring their own transcript (when the feed has one) self.ensure_pod_transcript(); } else if tracks.is_empty() { - ui.label(egui::RichText::new("This video has no captions, so there is no transcript.").size(14.0).color(muted())); + ui.label(egui::RichText::new(tr("This video has no captions, so there is no transcript.")).size(14.0).color(muted())); return; } if !is_pod && self.tr.as_ref().is_none_or(|t| t.0 != w.id) { @@ -187,13 +187,13 @@ impl App { return; } Some(Err(e)) => { - ui.label(egui::RichText::new(format!("Could not load the transcript: {e}")).color(muted())); + ui.label(egui::RichText::new(trf("Could not load the transcript: {error}", &[("error", e)])).color(muted())); return; } Some(Ok(c)) => c.clone(), }; let w_field = ui.available_width(); - text_field(ui, &mut self.tr_filter, "Search the transcript", w_field, 36.0, "search", None, false); + text_field(ui, &mut self.tr_filter, &tr("Search the transcript"), w_field, 36.0, "search", None, false); ui.add_space(6.0); let needle = fold(self.tr_filter.trim()); let rows: Vec = (0..cues.len()).filter(|i| needle.is_empty() || fold(&cues[*i].text).contains(&needle)).collect(); @@ -243,16 +243,16 @@ impl App { let mut add = false; ui.horizontal(|ui| { let fw = ui.available_width() - 130.0; - let f = text_field(ui, &mut self.note_input, "Add a note at this moment", fw, 38.0, "search", None, false); + let f = text_field(ui, &mut self.note_input, &tr("Add a note at this moment"), fw, 38.0, "search", None, false); add |= f.submit; - if ui.add(egui::Button::new(egui::RichText::new(format!("Add {}", fmt_time(pos))).color(ON_ACCENT).strong()).fill(accent())).clicked() { + if ui.add(egui::Button::new(egui::RichText::new(trf("Add {time}", &[("time", &fmt_time(pos))])).color(ON_ACCENT).strong()).fill(accent())).clicked() { add = true; } }); if add { let text = self.note_input.trim().to_string(); let list = self.bookmarks.entry(w.id.clone()).or_default(); - list.push(Bookmark { t: pos, text: if text.is_empty() { "Bookmark".to_string() } else { text } }); + list.push(Bookmark { t: pos, text: if text.is_empty() { tr("Bookmark") } else { text } }); list.sort_by(|a, b| a.t.total_cmp(&b.t)); self.note_input.clear(); save_bookmarks(&self.bookmarks); @@ -260,7 +260,7 @@ impl App { ui.add_space(8.0); let list = self.bookmarks.get(&w.id).cloned().unwrap_or_default(); if list.is_empty() { - ui.label(egui::RichText::new("Notes and bookmarks you add show up here and as dots on the seek bar.").size(13.5).color(muted())); + ui.label(egui::RichText::new(tr("Notes and bookmarks you add show up here and as dots on the seek bar.")).size(13.5).color(muted())); return; } let mut seek: Option = None; @@ -328,20 +328,20 @@ impl App { ui.add_space(8.0); let Some(w) = self.watching.clone() else { return }; if self.player.is_live() { - ui.label(egui::RichText::new("Live streams can't be clipped.").color(muted())); + ui.label(egui::RichText::new(tr("Live streams can't be clipped.")).color(muted())); return; } if self.clip.vid != w.id { self.open_clip_tab(); } let (pos, dur) = (self.player.position(), self.player.duration().max(1.0)); - ui.label(egui::RichText::new("Cut a piece out of this video and save it as a file.").size(13.5).color(muted())); + ui.label(egui::RichText::new(tr("Cut a piece out of this video and save it as a file.")).size(13.5).color(muted())); ui.add_space(10.0); // chapters: pick a segment instead of finding its start and end by hand let chapters = self.player.streams.as_ref().map(|st| st.chapters.clone()).unwrap_or_default(); if !chapters.is_empty() { - ui.label(egui::RichText::new("SEGMENTS").size(11.0).color(muted()).strong()); + ui.label(egui::RichText::new(tr("SEGMENTS")).size(11.0).color(muted()).strong()); ui.add_space(4.0); let mut pick: Option<(f64, f64, bool)> = None; egui::ScrollArea::vertical().id_salt("clip_segments").max_height(190.0).auto_shrink([false, true]).show(ui, |ui| { @@ -361,7 +361,7 @@ impl App { let btn = Rect::from_center_size(Pos2::new(r.max.x - 34.0, r.center().y), vec2(60.0, 24.0)); let bresp = ui.interact(btn, resp.id.with("save"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand); ui.painter().rect_filled(btn, CornerRadius::same(12), if bresp.hovered() { accent2() } else { accent() }); - ui.painter().text(btn.center(), Align2::CENTER_CENTER, "Clip", FontId::proportional(12.5), ON_ACCENT); + ui.painter().text(btn.center(), Align2::CENTER_CENTER, tr("Clip"), FontId::proportional(12.5), ON_ACCENT); let time = format!("{} – {}", fmt_time(c.start), fmt_time(end)); ui.painter().text(Pos2::new(r.min.x + 10.0, r.center().y), Align2::LEFT_CENTER, &time, FontId::monospace(11.5), muted()); let tx = r.min.x + 10.0 + 11.0 * time.chars().count() as f32 * 0.62 + 12.0; @@ -419,7 +419,7 @@ impl App { for which in 0..2 { ui.horizontal(|ui| { - ui.add_sized([46.0, 30.0], egui::Label::new(egui::RichText::new(if which == 0 { "Start" } else { "End" }).size(14.0).color(muted()))); + ui.add_sized([46.0, 30.0], egui::Label::new(egui::RichText::new(tr(if which == 0 { "Start" } else { "End" })).size(14.0).color(muted()))); let txt = if which == 0 { &mut self.clip.start_txt } else { &mut self.clip.end_txt }; let r = ui.add(egui::TextEdit::singleline(txt).desired_width(86.0)); if r.lost_focus() { @@ -434,7 +434,7 @@ impl App { self.clip.start_txt = fmt_time(self.clip.start); self.clip.end_txt = fmt_time(self.clip.end); } - if ui.button(format!("Use {}", fmt_time(pos))).clicked() { + if ui.button(trf("Use {time}", &[("time", &fmt_time(pos))])).clicked() { if which == 0 { self.clip.start = pos.min(self.clip.end - 0.5).max(0.0); } else { @@ -446,21 +446,21 @@ impl App { }); } let len = self.clip.end - self.clip.start; - ui.label(egui::RichText::new(format!("Length {}", fmt_time(len))).size(13.0).color(muted())); + ui.label(egui::RichText::new(trf("Length {time}", &[("time", &fmt_time(len))])).size(13.0).color(muted())); ui.add_space(8.0); ui.horizontal(|ui| { - for (label, v) in [("Video", 0u8), ("Audio", 1), ("GIF", 2)] { - if pill_button(ui, label, self.clip.format == v) { + for (label, v) in [(tr("Video"), 0u8), (tr("Audio"), 1), (tr("GIF"), 2)] { + if pill_button(ui, &label, self.clip.format == v) { self.clip.format = v; } } }); if self.clip.format == 2 && len > 20.0 { - ui.label(egui::RichText::new("GIFs get big fast; 20 seconds or less works best.").size(12.5).color(muted())); + ui.label(egui::RichText::new(tr("GIFs get big fast; 20 seconds or less works best.")).size(12.5).color(muted())); } ui.add_space(10.0); ui.horizontal(|ui| { - if ui.button("Preview").clicked() { + if ui.button(tr("Preview")).clicked() { self.player.seek(self.clip.start); if self.player.paused { self.player.toggle_pause(); @@ -469,7 +469,7 @@ impl App { } if self.clip.busy.is_some() { // progress is drawn below, on its own row - } else if ui.add(egui::Button::new(egui::RichText::new("Save clip").color(ON_ACCENT).strong()).fill(accent())).clicked() { + } else if ui.add(egui::Button::new(egui::RichText::new(tr("Save clip")).color(ON_ACCENT).strong()).fill(accent())).clicked() { self.start_clip(); } }); @@ -494,14 +494,14 @@ impl App { let secs = self.clip.since.map_or(0.0, |t| t.elapsed().as_secs_f64()); let label = if self.clip.started && target > 0.03 { let left = secs * (1.0 - target as f64) / target as f64; - format!("Cutting… {}% • about {} left", (self.clip.shown * 100.0).round() as u32, fmt_time(left.max(1.0))) + trf("Cutting… {percent}% • about {time} left", &[("percent", &((self.clip.shown * 100.0).round() as u32).to_string()), ("time", &fmt_time(left.max(1.0)))]) } else { - "Opening the video…".to_string() + tr("Opening the video…") }; ui.horizontal(|ui| { ui.label(egui::RichText::new(label).size(13.0).color(muted())); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.add(egui::Button::new(egui::RichText::new("Cancel").color(Color32::WHITE)).fill(LIVE)).clicked() { + if ui.add(egui::Button::new(egui::RichText::new(tr("Cancel")).color(Color32::WHITE)).fill(LIVE)).clicked() { self.clip.cancel.store(true, std::sync::atomic::Ordering::SeqCst); } }); @@ -515,19 +515,19 @@ impl App { let mine: Vec = self.clips.iter().filter(|c| c.video.id == w.id).cloned().collect(); if !mine.is_empty() { ui.add_space(14.0); - ui.label(egui::RichText::new("CLIPS OF THIS VIDEO").size(11.0).color(muted()).strong()); + ui.label(egui::RichText::new(tr("CLIPS OF THIS VIDEO")).size(11.0).color(muted()).strong()); let mut play: Option = None; let mut del: Option = None; for c in &mine { let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 38.0), Sense::click()); - let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text("Play this clip"); + let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text(tr("Play this clip")); if resp.hovered() { ui.painter().rect_filled(r, CornerRadius::same(10), ov(16)); } ui.painter().text( Pos2::new(r.min.x + 8.0, r.center().y), Align2::LEFT_CENTER, - format!("{} – {} {}", fmt_time(c.start), fmt_time(c.end), c.kind()), + trf("{start} – {end} {kind}", &[("start", &fmt_time(c.start)), ("end", &fmt_time(c.end)), ("kind", &tr(c.kind()))]), FontId::proportional(13.5), ink(), ); @@ -547,13 +547,13 @@ impl App { } if let Some(p) = self.clip.last.clone() { ui.add_space(8.0); - ui.label(egui::RichText::new(format!("Saved {}", p.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default())).size(13.0).color(muted())); + ui.label(egui::RichText::new(trf("Saved {name}", &[("name", &p.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default())])).size(13.0).color(muted())); let mut play_here = false; ui.horizontal(|ui| { - if ui.button("Play").clicked() { + if ui.button(tr("Play")).clicked() { play_here = true; } - if ui.button("Show folder").clicked() { + if ui.button(tr("Show folder")).clicked() { crate::platform::open_path(&clip::dir()); } }); @@ -656,10 +656,10 @@ impl App { pub fn clips_view(&mut self, ui: &mut egui::Ui) { ui.add_space(8.0); ui.horizontal(|ui| { - ui.label(egui::RichText::new("Clips").size(26.0).strong()); + ui.label(egui::RichText::new(tr("Clips")).size(26.0).strong()); ui.label(egui::RichText::new(clip::dir().display().to_string()).size(12.0).color(muted())); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.button("Open folder").clicked() { + if ui.button(tr("Open folder")).clicked() { let _ = std::fs::create_dir_all(clip::dir()); crate::platform::open_path(&clip::dir()); } @@ -670,8 +670,8 @@ impl App { if self.clips.is_empty() { ui.add_space(60.0); ui.vertical_centered(|ui| { - ui.label(egui::RichText::new("No clips yet.").size(18.0).color(muted())); - ui.label(egui::RichText::new("Open a video, choose the Clip tab (or “Clip this moment…” in the … menu) and save a section.").color(muted())); + ui.label(egui::RichText::new(tr("No clips yet.")).size(18.0).color(muted())); + ui.label(egui::RichText::new(tr("Open a video, choose the Clip tab (or “Clip this moment…” in the … menu) and save a section.")).color(muted())); }); return; } @@ -700,7 +700,7 @@ impl App { // kind badge, length, and the delete button that appears on hover let badge = Rect::from_min_size(img.min + vec2(7.0, 7.0), vec2(46.0, 18.0)); ui.painter().rect_filled(badge, CornerRadius::same(6), Color32::from_black_alpha(190)); - ui.painter().text(badge.center(), Align2::CENTER_CENTER, c.kind(), FontId::proportional(11.0), Color32::WHITE); + ui.painter().text(badge.center(), Align2::CENTER_CENTER, tr(c.kind()), FontId::proportional(11.0), Color32::WHITE); if c.end > c.start { views::pill_label(ui, img.right_bottom(), &fmt_time(c.end - c.start)); } @@ -718,11 +718,11 @@ impl App { icons::draw(ui.painter(), xr.center(), "close", 13.0, Color32::WHITE.gamma_multiply(hv)); } resp.context_menu(|ui| { - if !c.video.id.is_empty() && ui.button("Open the source video").clicked() { + if !c.video.id.is_empty() && ui.button(tr("Open the source video")).clicked() { source = Some((c.video.clone(), c.start)); ui.close(); } - if ui.button("Delete clip").clicked() { + if ui.button(tr("Delete clip")).clicked() { del = Some(c.file.clone()); ui.close(); } @@ -752,7 +752,7 @@ impl App { } let badge = Rect::from_min_size(th_r.min + vec2(6.0, 6.0), vec2(46.0, 18.0)); ui.painter().rect_filled(badge, CornerRadius::same(6), Color32::from_black_alpha(190)); - ui.painter().text(badge.center(), Align2::CENTER_CENTER, c.kind(), FontId::proportional(11.0), Color32::WHITE); + ui.painter().text(badge.center(), Align2::CENTER_CENTER, tr(c.kind()), FontId::proportional(11.0), Color32::WHITE); let tx = th_r.max.x + 14.0; let size = std::fs::metadata(&c.file).map(|m| m.len()).unwrap_or(0); let title = truncate(ui, &c.video.title, FontId::proportional(16.0), w - 400.0, 1); @@ -781,7 +781,7 @@ impl App { let has_source = !c.video.id.is_empty(); if has_source { ui.painter().rect_filled(sr, CornerRadius::same(16), if over_s { accent() } else { card_hi() }); - ui.painter().text(sr.center(), Align2::CENTER_CENTER, "Source video", FontId::proportional(13.0), if over_s { ON_ACCENT } else { ink() }); + ui.painter().text(sr.center(), Align2::CENTER_CENTER, tr("Source video"), FontId::proportional(13.0), if over_s { ON_ACCENT } else { ink() }); } let over_s = over_s && has_source; if over_x || over_s { diff --git a/src/ui/sidebar.rs b/src/ui/sidebar.rs index 1a8a294..7969fc6 100644 --- a/src/ui/sidebar.rs +++ b/src/ui/sidebar.rs @@ -17,7 +17,9 @@ pub(crate) fn sidebar_row( if compact { resp = resp.on_hover_text(label); } - let h = ui.ctx().animate_bool_with_time(resp.id, resp.hovered(), 0.12); + let h = ui + .ctx() + .animate_bool_with_time(resp.id, resp.hovered(), 0.12); let row = rect.shrink2(vec2(0.0, 1.0)); let p = ui.painter(); if selected { @@ -28,7 +30,10 @@ pub(crate) fn sidebar_row( let tile = if compact { Rect::from_center_size(row.center(), vec2(36.0, 36.0)) } else { - Rect::from_min_size(Pos2::new(row.min.x + 6.0, row.center().y - 18.0), vec2(36.0, 36.0)) + Rect::from_min_size( + Pos2::new(row.min.x + 6.0, row.center().y - 18.0), + vec2(36.0, 36.0), + ) }; match avatar { Some(url) if !url.is_empty() => { @@ -41,7 +46,8 @@ pub(crate) fn sidebar_row( .paint_at(ui, Rect::from_center_size(c, vec2(32.0, 32.0))); } if selected { - ui.painter().circle_stroke(c, 18.0, Stroke::new(2.0, ON_ACCENT)); + ui.painter() + .circle_stroke(c, 18.0, Stroke::new(2.0, ON_ACCENT)); } } _ => { @@ -51,7 +57,13 @@ pub(crate) fn sidebar_row( ov((12.0 + 14.0 * h) as u8) }; p.rect_filled(tile, CornerRadius::same(11), fill); - let col = if selected { ON_ACCENT } else if h > 0.4 { ink() } else { icons::muted_icon() }; + let col = if selected { + ON_ACCENT + } else if h > 0.4 { + ink() + } else { + icons::muted_icon() + }; icons::draw(ui.painter(), tile.center(), icon, 20.0, col); } } @@ -63,7 +75,11 @@ pub(crate) fn sidebar_row( Align2::LEFT_CENTER, s, FontId::proportional(15.0), - if selected { ON_ACCENT } else { ink().gamma_multiply(0.86) }, + if selected { + ON_ACCENT + } else { + ink().gamma_multiply(0.86) + }, ); } if live { @@ -73,7 +89,8 @@ pub(crate) fn sidebar_row( } else { Pos2::new(row.max.x - 16.0, row.center().y) }; - ui.painter().circle_filled(dot, 4.5, LIVE.gamma_multiply(pulse)); + ui.painter() + .circle_filled(dot, 4.5, LIVE.gamma_multiply(pulse)); ui.ctx().request_repaint_after(Duration::from_millis(33)); } resp @@ -82,11 +99,13 @@ pub(crate) fn sidebar_row( impl App { /// Draws the sidebar: pages, playlists, groups and channels. pub(crate) fn sidebar(&mut self, ui: &mut egui::Ui, compact: bool) { - let live_ids: HashSet = self .feeds .iter() - .filter(|(_, r)| r.as_ref().is_ok_and(|v| v.iter().any(|x| x.kind == Kind::Live))) + .filter(|(_, r)| { + r.as_ref() + .is_ok_and(|v| v.iter().any(|x| x.kind == Kind::Live)) + }) .map(|(k, _)| k.clone()) .collect(); @@ -101,10 +120,23 @@ impl App { let (r, resp) = ui.allocate_exact_size(vec2(32.0, 32.0), Sense::click()); let resp = resp .on_hover_cursor(egui::CursorIcon::PointingHand) - .on_hover_text(if compact { "Expand sidebar (Ctrl+B)" } else { "Collapse sidebar (Ctrl+B)" }); - let hv = ui.ctx().animate_bool_with_time(resp.id, resp.hovered(), 0.12); - ui.painter().rect_filled(r, CornerRadius::same(10), ov((10.0 + 22.0 * hv) as u8)); - icons::draw(ui.painter(), r.center(), icon, 17.0, if hv > 0.5 { ink() } else { icons::muted_icon() }); + .on_hover_text(tr(if compact { + "Expand sidebar (Ctrl+B)" + } else { + "Collapse sidebar (Ctrl+B)" + })); + let hv = ui + .ctx() + .animate_bool_with_time(resp.id, resp.hovered(), 0.12); + ui.painter() + .rect_filled(r, CornerRadius::same(10), ov((10.0 + 22.0 * hv) as u8)); + icons::draw( + ui.painter(), + r.center(), + icon, + 17.0, + if hv > 0.5 { ink() } else { icons::muted_icon() }, + ); resp.clicked() }; if compact { @@ -133,11 +165,11 @@ impl App { let f = text_field( ui, &mut self.input, - "@handle or link", + &tr("@handle or link"), ui.available_width(), 40.0, "plus", - Some("Add"), + Some(&tr("Add")), self.adding, ); let submit = f.submit || f.action; @@ -148,7 +180,12 @@ impl App { ui.colored_label(LIVE, egui::RichText::new(e).size(12.0)); } ui.add_space(6.0); - ui.label(egui::RichText::new("LIBRARY").size(11.0).color(muted()).strong()); + ui.label( + egui::RichText::new(tr("LIBRARY")) + .size(11.0) + .color(muted()) + .strong(), + ); } let sel = self.sel.clone(); @@ -156,40 +193,130 @@ impl App { let mut remove = None; let mut open_file = false; let active = self.jobs.len(); - if sidebar_row(ui, "Home", None, "home", sel == Sel::Home, false, compact).clicked() { + if sidebar_row( + ui, + &tr("Home"), + None, + "home", + sel == Sel::Home, + false, + compact, + ) + .clicked() + { new_sel = Some(Sel::Home); } - if sidebar_row(ui, "Live now", None, "live", sel == Sel::Live, false, compact).clicked() { + if sidebar_row( + ui, + &tr("Live now"), + None, + "live", + sel == Sel::Live, + false, + compact, + ) + .clicked() + { new_sel = Some(Sel::Live); } - if sidebar_row(ui, "Music", None, "note", matches!(sel, Sel::Music | Sel::MusicAlbum(_) | Sel::MusicArtist(_)), false, compact).clicked() { + if sidebar_row( + ui, + &tr("Music"), + None, + "note", + matches!(sel, Sel::Music | Sel::MusicAlbum(_) | Sel::MusicArtist(_)), + false, + compact, + ) + .clicked() + { new_sel = Some(Sel::Music); } - if sidebar_row(ui, "Podcasts", None, "mic", matches!(sel, Sel::Podcasts | Sel::Podcast(_)), self.pods.iter().any(|p| self.pod_new_count(p) > 0), compact).clicked() { + if sidebar_row( + ui, + &tr("Podcasts"), + None, + "mic", + matches!(sel, Sel::Podcasts | Sel::Podcast(_)), + self.pods.iter().any(|p| self.pod_new_count(p) > 0), + compact, + ) + .clicked() + { new_sel = Some(Sel::Podcasts); } let dl_label = if active > 0 { let avg = self.jobs.iter().map(|j| j.progress).sum::() / active as f32; - format!("Downloads ({active} • {}%)", (avg * 100.0) as u32) + trf("Downloads ({active} • {percent}%)", &[("active", &active.to_string()), ("percent", &((avg * 100.0) as u32).to_string())]) } else { - "Downloads".to_string() + tr("Downloads") }; - if sidebar_row(ui, "History", None, "history", sel == Sel::History, false, compact).clicked() { + if sidebar_row( + ui, + &tr("History"), + None, + "history", + sel == Sel::History, + false, + compact, + ) + .clicked() + { new_sel = Some(Sel::History); } - if sidebar_row(ui, "Insights", None, "chart", sel == Sel::Stats, false, compact).clicked() { + if sidebar_row( + ui, + &tr("Insights"), + None, + "chart", + sel == Sel::Stats, + false, + compact, + ) + .clicked() + { new_sel = Some(Sel::Stats); } - if sidebar_row(ui, &dl_label, None, "download", sel == Sel::Downloads, active > 0, compact).clicked() { + if sidebar_row( + ui, + &dl_label, + None, + "download", + sel == Sel::Downloads, + active > 0, + compact, + ) + .clicked() + { new_sel = Some(Sel::Downloads); } - if sidebar_row(ui, "Clips", None, "scissors", sel == Sel::Clips, false, compact).clicked() { + if sidebar_row( + ui, + &tr("Clips"), + None, + "scissors", + sel == Sel::Clips, + false, + compact, + ) + .clicked() + { new_sel = Some(Sel::Clips); } - if sidebar_row(ui, "Open file…", None, "open", false, false, compact).clicked() { + if sidebar_row(ui, &tr("Open file…"), None, "open", false, false, compact).clicked() { open_file = true; } - if sidebar_row(ui, "Settings", None, "settings", sel == Sel::Settings, false, compact).clicked() { + if sidebar_row( + ui, + &tr("Settings"), + None, + "settings", + sel == Sel::Settings, + false, + compact, + ) + .clicked() + { new_sel = Some(Sel::Settings); } ui.add_space(4.0); @@ -206,12 +333,12 @@ impl App { ui.separator(); } else { ui.horizontal(|ui| { - ui.label(egui::RichText::new("PLAYLISTS").size(11.0).color(muted()).strong()); + ui.label(egui::RichText::new(tr("PLAYLISTS")).size(11.0).color(muted()).strong()); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let (r, resp) = ui.allocate_exact_size(vec2(24.0, 24.0), Sense::click()); let resp = resp .on_hover_cursor(egui::CursorIcon::PointingHand) - .on_hover_text("New playlist"); + .on_hover_text(tr("New playlist")); let hv = ui.ctx().animate_bool_with_time(resp.id, resp.hovered(), 0.12); ui.painter().rect_filled(r, CornerRadius::same(8), ov((10.0 + 25.0 * hv) as u8)); icons::draw(ui.painter(), r.center(), "plus", 13.0, if hv > 0.5 { ink() } else { icons::muted_icon() }); @@ -219,7 +346,7 @@ impl App { let (r, resp) = ui.allocate_exact_size(vec2(24.0, 24.0), Sense::click()); let resp = resp .on_hover_cursor(egui::CursorIcon::PointingHand) - .on_hover_text("Import playlists from YouTube"); + .on_hover_text(tr("Import playlists from YouTube")); let hv = ui.ctx().animate_bool_with_time(resp.id, resp.hovered(), 0.12); ui.painter().rect_filled(r, CornerRadius::same(8), ov((10.0 + 25.0 * hv) as u8)); icons::draw(ui.painter(), r.center(), "download", 13.0, if hv > 0.5 { ink() } else { icons::muted_icon() }); @@ -234,14 +361,14 @@ impl App { "watchlater" => "clock", _ => "list", }; - let label = format!("{} ({})", l.name, l.videos.len()); + let label = format!("{} ({})", playlist_label(l), l.videos.len()); let r = sidebar_row(ui, &label, None, icon, is_sel, false, compact); if r.clicked() { new_sel = Some(Sel::Local(l.id.clone())); } if !is_builtin_list(&l.id) { r.context_menu(|ui| { - if ui.button("Delete playlist").clicked() { + if ui.button(tr("Delete playlist")).clicked() { delete_list = Some(l.id.clone()); ui.close(); } @@ -256,10 +383,10 @@ impl App { } } else { ui.horizontal(|ui| { - ui.label(egui::RichText::new("GROUPS").size(11.0).color(muted()).strong()); + ui.label(egui::RichText::new(tr("GROUPS")).size(11.0).color(muted()).strong()); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let (r, resp) = ui.allocate_exact_size(vec2(24.0, 24.0), Sense::click()); - let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text("New group"); + let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text(tr("New group")); let hv = ui.ctx().animate_bool_with_time(resp.id, resp.hovered(), 0.12); ui.painter().rect_filled(r, CornerRadius::same(8), ov((10.0 + 25.0 * hv) as u8)); icons::draw(ui.painter(), r.center(), "plus", 13.0, if hv > 0.5 { ink() } else { icons::muted_icon() }); @@ -267,7 +394,7 @@ impl App { }); }); if self.groups.is_empty() { - ui.label(egui::RichText::new("Group channels, e.g. Music or News. Right-click a channel to add it.").size(12.0).color(muted())); + ui.label(egui::RichText::new(tr("Group channels, e.g. Music or News. Right-click a channel to add it.")).size(12.0).color(muted())); } } for g in &self.groups { @@ -278,7 +405,7 @@ impl App { new_sel = Some(Sel::Group(g.id.clone())); } r.context_menu(|ui| { - if ui.button("Delete group").clicked() { + if ui.button(tr("Delete group")).clicked() { delete_group = Some(g.id.clone()); ui.close(); } @@ -288,10 +415,10 @@ impl App { if compact { ui.separator(); } else { - ui.label(egui::RichText::new("CHANNELS").size(11.0).color(muted()).strong()); + ui.label(egui::RichText::new(tr("CHANNELS")).size(11.0).color(muted()).strong()); if !self.channels.is_empty() { let w = ui.available_width(); - text_field(ui, &mut self.chan_filter, "Filter channels", w, 36.0, "search", None, false); + text_field(ui, &mut self.chan_filter,&tr("Filter channels"), w, 36.0, "search", None, false); ui.add_space(4.0); } } @@ -299,7 +426,7 @@ impl App { if !needle.is_empty() && !compact { let n = self.channels.iter().filter(|c| fold(&c.name).contains(&needle)).count(); if n == 0 { - ui.label(egui::RichText::new("No channels match.").color(muted()).size(13.0)); + ui.label(egui::RichText::new(tr("No channels match.")).color(muted()).size(13.0)); } } for c in self.channels.iter().filter(|c| needle.is_empty() || fold(&c.name).contains(&needle)) { @@ -335,7 +462,7 @@ impl App { new_sel = Some(Sel::Channel(c.id.clone())); } r.context_menu(|ui| { - ui.menu_button("Add to group", |ui| { + ui.menu_button(tr("Add to group"), |ui| { for g in &self.groups { let has = g.channels.contains(&c.id); if ui.selectable_label(has, g.name.clone()).clicked() { @@ -346,14 +473,14 @@ impl App { if !self.groups.is_empty() { ui.separator(); } - if ui.button("+ New group…").clicked() { + if ui.button(tr("+ New group…")).clicked() { new_group_for = Some(c.id.clone()); ui.close(); } }); - ui.menu_button("Notifications", |ui| { + ui.menu_button(tr("Notifications"), |ui| { let cur = self.settings.chan_prefs.get(&c.id).map_or(0, |p| p.notify); - for (v, label) in [(0u8, "Live streams only"), (1, "Live streams and new uploads"), (2, "Off for this channel")] { + for (v, label) in [(0u8, tr("Live streams only")), (1, tr("Live streams and new uploads")), (2, tr("Off for this channel"))] { if ui.selectable_label(cur == v, label).clicked() { chan_notify = Some((c.id.clone(), v)); ui.close(); @@ -361,14 +488,14 @@ impl App { } }); ui.separator(); - if ui.button("Remove channel").clicked() { + if ui.button(tr("Remove channel")).clicked() { remove = Some(c.id.clone()); ui.close(); } }); } if self.channels.is_empty() && !compact { - ui.label(egui::RichText::new("Nothing here yet. Add a channel above to get started.").color(muted()).size(13.0)); + ui.label(egui::RichText::new(tr("Nothing here yet. Add a channel above to get started.")).color(muted()).size(13.0)); } }); if open_file { @@ -390,7 +517,7 @@ impl App { self.settings.chan_prefs.entry(cid).or_default().notify = v; self.save_settings(); if !self.settings.notifications { - self.toast("Turn on notifications in Settings to receive them"); + self.toast(tr("Turn on notifications in Settings to receive them")); } } if let Some((gid, cid)) = group_toggle { @@ -413,7 +540,15 @@ impl App { if let Some(id) = delete_list { self.lists.retain(|l| l.id != id); if !self.lists.iter().any(|l| l.id == "favorites") { - self.lists.insert(0, LocalList { id: "favorites".into(), name: "Favorites".into(), videos: vec![], offline: false }); + self.lists.insert( + 0, + LocalList { + id: "favorites".into(), + name: "Favorites".into(), + videos: vec![], + offline: false, + }, + ); } save_lists(&self.lists); if self.sel == Sel::Local(id) { @@ -433,7 +568,11 @@ impl App { self.music_q.clear(); self.music_open_home(); } - if s == Sel::Live && (self.live.is_none() || now_secs().saturating_sub(self.fcache.live_updated) > 180) && !self.live_loading { + if s == Sel::Live + && (self.live.is_none() + || now_secs().saturating_sub(self.fcache.live_updated) > 180) + && !self.live_loading + { self.load_live(); } if let Sel::Channel(cid) = &s { diff --git a/src/ui/update_view.rs b/src/ui/update_view.rs index b3f866a..b0e62f5 100644 --- a/src/ui/update_view.rs +++ b/src/ui/update_view.rs @@ -23,25 +23,25 @@ impl App { .show(ui, |ui| { ui.horizontal_centered(|ui| match &state { FfmpegState::Downloading(p) => { - ui.label(egui::RichText::new("Setting up ffmpeg (once, about 30 MB) so video and audio can play…").strong().size(14.0)); + ui.label(egui::RichText::new(tr("Setting up ffmpeg (once, about 30 MB) so video and audio can play…")).strong().size(14.0)); progress_pill(ui, *p, &format!("{}%", (p * 100.0) as u32), 180.0); } FfmpegState::Failed(e) => { - ui.label(egui::RichText::new("ffmpeg is not available, so nothing can play yet.").strong().size(14.0)); + ui.label(egui::RichText::new(tr("ffmpeg is not available, so nothing can play yet.")).strong().size(14.0)); // the explanation gives way (with an ellipsis) so the buttons always stay visible let room = (ui.available_width() - 330.0).max(80.0); let msg = format!("{e} {}", crate::platform::ffmpeg_hint()); ui.allocate_ui(vec2(room, 24.0), |ui| { ui.add(egui::Label::new(egui::RichText::new(msg).size(13.0).color(muted())).truncate()); }); - if icon_btn(ui, "refresh", "Try again", Some(accent()), ON_ACCENT, false, true).clicked() { + if icon_btn(ui, "refresh", &tr("Try again"), Some(accent()), ON_ACCENT, false, true).clicked() { retry = true; } - if icon_btn(ui, "", "Get ffmpeg", None, ink(), false, true).clicked() { + if icon_btn(ui, "", &tr("Get ffmpeg"), None, ink(), false, true).clicked() { open = true; } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if icon_btn(ui, "close", "", None, ink(), false, true).on_hover_text("Hide").clicked() { + if icon_btn(ui, "close", "", None, ink(), false, true).on_hover_text(tr("Hide")).clicked() { hide = true; } }); @@ -79,40 +79,40 @@ impl App { ui.add_space(26.0); match self.update_state.clone() { UpdateState::Idle | UpdateState::Failed(_) => { - ui.label(egui::RichText::new(format!("TubeGlass {} is available", rel.version)).strong().size(14.5)); - ui.label(egui::RichText::new(format!("(you have {})", update::CURRENT)).size(13.0).color(muted())); + ui.label(egui::RichText::new(trf("TubeGlass {version} is available", &[("version", &rel.version)])).strong().size(14.5)); + ui.label(egui::RichText::new(trf("(you have {version})", &[("version", update::CURRENT)])).size(13.0).color(muted())); if let UpdateState::Failed(e) = &self.update_state { ui.colored_label(LIVE, truncate(ui, e, FontId::proportional(13.0), 360.0, 1)); } let have_file = update::pick_asset(&rel.assets, update::detect_install(), std::env::consts::ARCH).is_some(); - if icon_btn(ui, "download", if have_file { "Update" } else { "Open release page" }, Some(accent()), ON_ACCENT, false, true).clicked() { + if icon_btn(ui, "download", &tr(if have_file { "Update" } else { "Open release page" }), Some(accent()), ON_ACCENT, false, true).clicked() { start = true; } - if !rel.notes.is_empty() && icon_btn(ui, "", "What's new", None, ink(), false, true).clicked() { + if !rel.notes.is_empty() && icon_btn(ui, "",&tr("What's new"), None, ink(), false, true).clicked() { notes = true; } - if icon_btn(ui, "", "Skip this version", None, ink(), false, true).clicked() { + if icon_btn(ui, "",&tr("Skip this version"), None, ink(), false, true).clicked() { skip = true; } } UpdateState::Downloading(p) => { - ui.label(egui::RichText::new(format!("Downloading TubeGlass {}…", rel.version)).size(14.0)); + ui.label(egui::RichText::new(trf("Downloading TubeGlass {version}…", &[("version", &rel.version)])).size(14.0)); progress_pill(ui, p, &format!("{}%", (p * 100.0) as u32), 200.0); } UpdateState::Done(path, installed) => { if installed { - ui.label(egui::RichText::new(format!("TubeGlass {} is installed. Restart to use it.", rel.version)).strong().size(14.5)); - if icon_btn(ui, "refresh", "Restart now", Some(accent()), ON_ACCENT, false, true).clicked() { + ui.label(egui::RichText::new(trf("TubeGlass {version} is installed. Restart to use it.", &[("version", &rel.version)])).strong().size(14.5)); + if icon_btn(ui, "refresh",&tr("Restart now"), Some(accent()), ON_ACCENT, false, true).clicked() { restart = true; } } else { - ui.label(egui::RichText::new(format!("Saved to {}", path.display())).size(13.5)); + ui.label(egui::RichText::new(trf("Saved to {path}", &[("path", &path.display().to_string())])).size(13.5)); } } } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let (r, resp) = ui.allocate_exact_size(vec2(28.0, 28.0), Sense::click()); - let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text("Hide for now"); + let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text(tr("Hide for now")); if resp.hovered() { ui.painter().circle_filled(r.center(), 14.0, ov(30)); } @@ -141,14 +141,14 @@ impl App { } if self.update_notes_open { let mut open = true; - egui::Window::new(format!("What's new in {}", rel.version)) + egui::Window::new(trf("What's new in {version}", &[("version", &rel.version)])) .open(&mut open) .default_width(460.0) .show(ui.ctx(), |ui| { egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| { ui.label(egui::RichText::new(&rel.notes).size(13.5)); }); - if !rel.page.is_empty() && ui.link("Open the release page").clicked() { + if !rel.page.is_empty() && ui.link(tr("Open the release page")).clicked() { crate::platform::open_url(&rel.page); } }); diff --git a/src/ui/views.rs b/src/ui/views.rs index a028dbd..e8af74f 100644 --- a/src/ui/views.rs +++ b/src/ui/views.rs @@ -35,7 +35,7 @@ pub fn metrics(settings: &Settings, avail: f32, square: bool) -> Metrics { /// The three layout icons. Returns true when the choice changed. pub fn view_switch(ui: &mut egui::Ui, mode: &mut u8) -> bool { let before = *mode; - for (icon, m, tip) in [("view_list", 2u8, "List"), ("view_compact", 1, "Compact grid"), ("view_grid", 0, "Grid")] { + for (icon, m, tip) in [("view_list", 2u8, tr("List")), ("view_compact", 1, tr("Compact grid")), ("view_grid", 0, tr("Grid"))] { let (r, resp) = ui.allocate_exact_size(vec2(34.0, 30.0), Sense::click()); let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text(tip); let on = *mode == m; diff --git a/src/ui/widgets.rs b/src/ui/widgets.rs index c043b48..a2310c1 100644 --- a/src/ui/widgets.rs +++ b/src/ui/widgets.rs @@ -180,11 +180,11 @@ pub(crate) fn comment_row(ui: &mut egui::Ui, c: &Comment, small: bool, replies_o if c.reply_token.is_some() { ui.add_space(10.0); let label = if c.replies.is_empty() || c.replies == "0" { - "Replies".to_string() + tr("Replies") } else if c.replies == "1" { - "1 reply".to_string() + trf("{count} reply", &[("count", &c.replies)]) } else { - format!("{} replies", c.replies) + trf("{count} replies", &[("count", &c.replies)]) }; let tw = ui.fonts_mut(|f| { f.layout_no_wrap(label.clone(), FontId::proportional(13.0), ink()).size().x diff --git a/src/util.rs b/src/util.rs index e11e9ff..0c38e25 100644 --- a/src/util.rs +++ b/src/util.rs @@ -27,6 +27,22 @@ pub(crate) fn ago(ts: u64) -> String { } } +/// Localized relative age for app-authored UI labels. +pub(crate) fn localized_ago(ts: u64) -> String { + ago_at(ts, now_secs()) +} + +/// Format a relative age with an explicit clock, including future timestamps. +pub(crate) fn ago_at(ts: u64, now: u64) -> String { + let d = now.saturating_sub(ts); + match d { + 0..=59 => tr("just now"), + 60..=3599 => trf("{count} min ago", &[("count", &(d / 60).to_string())]), + 3600..=86399 => trf("{count} h ago", &[("count", &(d / 3600).to_string())]), + _ => trf("{count} d ago", &[("count", &(d / 86400).to_string())]), + } +} + /// How old a video is, in seconds, from the text YouTube shows ("3d ago", "2 weeks ago", /// "Streamed 5mo ago", "12 min ago"). Videos with no such text count as the oldest. pub(crate) fn age_secs(meta: &str) -> u64 { diff --git a/tests/fixtures/locale-placeholders.json b/tests/fixtures/locale-placeholders.json new file mode 100644 index 0000000..f3b2230 --- /dev/null +++ b/tests/fixtures/locale-placeholders.json @@ -0,0 +1,94 @@ +[ + { + "text": "plain text", + "names": [] + }, + { + "text": "Teks {count}", + "names": [ + "count" + ] + }, + { + "text": "{second} {first} {second}", + "names": [ + "first", + "second", + "second" + ] + }, + { + "text": "{_name2}", + "names": [ + "_name2" + ] + }, + { + "text": "é {count}", + "names": [ + "count" + ] + }, + { + "text": "{{count}}", + "names": [] + }, + { + "text": "{{{count}}}", + "names": [ + "count" + ] + }, + { + "text": "{{ and }}", + "names": [] + }, + { + "text": "{count} {", + "names": null + }, + { + "text": "Paramètres {oops", + "names": null + }, + { + "text": "{count}}", + "names": null + }, + { + "text": "}", + "names": null + }, + { + "text": "{", + "names": null + }, + { + "text": "{}", + "names": null + }, + { + "text": "{count", + "names": null + }, + { + "text": "{a{b}}", + "names": null + }, + { + "text": "{count:02}", + "names": null + }, + { + "text": "{1}", + "names": null + }, + { + "text": "{two words}", + "names": null + }, + { + "text": "{é}", + "names": null + } +] diff --git a/tests/locale_build.rs b/tests/locale_build.rs new file mode 100644 index 0000000..802b056 --- /dev/null +++ b/tests/locale_build.rs @@ -0,0 +1,136 @@ +//! Exercise the real build audit with JSON variants and successive source edits. + +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; + +struct Fixture(PathBuf); + +impl Fixture { + fn new() -> Self { + let nonce = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(); + let root = std::env::temp_dir().join(format!( + "tubeglass-locale-audit-{}-{nonce}", + std::process::id() + )); + for directory in ["src/ui", "src/app", "locales", "packaging/windows"] { + fs::create_dir_all(root.join(directory)).unwrap(); + } + let repo = Path::new(env!("CARGO_MANIFEST_DIR")); + fs::copy(repo.join("build.rs"), root.join("build.rs")).unwrap(); + fs::copy( + repo.join("src/locale_format.rs"), + root.join("src/locale_format.rs"), + ) + .unwrap(); + fs::write(root.join("packaging/windows/tubeglass.ico"), b"fixture").unwrap(); + let mut manifest = String::from( + "[package]\nname='locale-audit-fixture'\nversion='0.0.0'\nedition='2024'\n[build-dependencies]\nserde_json='1.0.154'\n", + ); + // Match the app's platform-specific build dependency when running this test on Windows. + if cfg!(windows) { + manifest.push_str("winresource='0.1'\n"); + } + fs::write(root.join("Cargo.toml"), manifest).unwrap(); + fs::write(root.join("src/main.rs"), "fn main() {}\n").unwrap(); + fs::write(root.join("src/util.rs"), "").unwrap(); + Self(root) + } + + fn write(&self, path: &str, text: &str) { + fs::write(self.0.join(path), text).unwrap(); + } + + fn check(&self) -> Output { + Command::new(env!("CARGO")) + .args(["check", "--offline", "--quiet"]) + .env("CARGO_TARGET_DIR", self.0.join("target")) + .current_dir(&self.0) + .output() + .unwrap() + } + + fn passes(&self) { + let output = self.check(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + } + + fn rejects(&self, expected: &str) { + let output = self.check(); + let error = String::from_utf8_lossy(&output.stderr); + assert!(!output.status.success(), "audit unexpectedly passed"); + assert!( + error.contains(expected), + "expected {expected:?}, got {error}" + ); + } +} + +impl Drop for Fixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +#[test] +fn audit_handles_json_and_reruns_for_source_edits() { + let fixture = Fixture::new(); + let source = "fn example() { tr(\"Settings\"); tr(\"Say \\\"hello\\\"\"); }\n"; + fixture.write("src/ui/example.rs", source); + fixture.write( + "locales/en.json", + r#"{"Settings":"Settings","Say \"hello\"":"Say \"hello\""}"#, + ); + fixture.passes(); + + // Valid JSON whitespace must not affect key decoding. + fixture.write( + "locales/en.json", + "{\n \"Settings\" : \"Settings\",\n \"Say \\\"hello\\\"\" : \"Say \\\"hello\\\"\"\n}\n", + ); + fixture.passes(); + + fixture.write( + "src/ui/example.rs", + "fn example() { tr(\"Missing UI key\"); }\n", + ); + fixture.rejects("missing source key"); + fixture.write("src/ui/example.rs", source); + fixture.passes(); + + fixture.write( + "src/app/notification.rs", + "fn example() { tr(\"Missing app key\"); }\n", + ); + fixture.rejects("missing source key"); + fs::remove_file(fixture.0.join("src/app/notification.rs")).unwrap(); + fixture.passes(); + + fixture.write( + "src/util.rs", + "fn example() { tr(\"Missing helper key\"); }\n", + ); + fixture.rejects("missing source key"); + fixture.write("src/util.rs", ""); + fixture.passes(); + + // Partial catalogs remain valid, including minified JSON. + fixture.write( + "locales/fr.json", + r#"{"__language_name":"Français","Settings":""}"#, + ); + fixture.passes(); + fixture.write("locales/fr.json", r#"{"Unknown":"Texte"}"#); + fixture.rejects("unknown translation key"); + fixture.write("locales/fr.json", r#"{"Settings":"Paramètres {oops"}"#); + fixture.rejects("invalid placeholders"); + fixture.write("locales/fr.json", "{"); + fixture.rejects("invalid catalog"); +}