Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(desktop-gpui): add generated localization tables and convert tray, menus and General settings

Richie McIlroy14a794b6e8c0
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 57810c005..eb9a802ee 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -369,6 +369,7 @@ jobs:
cargo +1.95.0 test --manifest-path apps/desktop-gpui/Cargo.toml --locked --target ${{ matrix.settings.target }} --bin cap-gpui
fi
cargo +1.95.0 test --manifest-path apps/desktop-gpui/Cargo.toml --locked --target ${{ matrix.settings.target }} -p cap-gpui-kernels
+ cargo +1.95.0 test --manifest-path apps/desktop-gpui/Cargo.toml --locked --target ${{ matrix.settings.target }} -p cap-i18n-build
tauri-plugins:
name: Verify Tauri plugin versions
diff --git a/apps/desktop-gpui/Cargo.lock b/apps/desktop-gpui/Cargo.lock
index b9df7cbb9..4e856d8fa 100644
--- a/apps/desktop-gpui/Cargo.lock
+++ b/apps/desktop-gpui/Cargo.lock
@@ -1552,6 +1552,7 @@ dependencies = [
"cap-enc-ffmpeg",
"cap-export",
"cap-gpui-kernels",
+ "cap-i18n-build",
"cap-media-info",
"cap-project",
"cap-recording",
@@ -1781,6 +1782,13 @@ dependencies = [
"tracing",
]
+[[package]]
+name = "cap-i18n-build"
+version = "0.1.0"
+dependencies = [
+ "toml 1.1.4+spec-1.1.0",
+]
+
[[package]]
name = "cap-media"
version = "0.1.0"
diff --git a/apps/desktop-gpui/Cargo.toml b/apps/desktop-gpui/Cargo.toml
index f496ed30e..558019442 100644
--- a/apps/desktop-gpui/Cargo.toml
+++ b/apps/desktop-gpui/Cargo.toml
@@ -5,7 +5,7 @@
# wgpu-hal, tao) that only exist for the Tauri app.
[workspace]
resolver = "2"
-members = [".", "kernels"]
+members = [".", "kernels", "i18n-build"]
[package]
name = "cap-desktop-gpui"
@@ -165,6 +165,7 @@ dirs = "6"
whisper-rs = "0.11.0"
[build-dependencies]
+cap-i18n-build = { path = "i18n-build" }
cc = "1.4"
tauri-winres = "0.3.5"
diff --git a/apps/desktop-gpui/build.rs b/apps/desktop-gpui/build.rs
index d23d749a3..151c6bf35 100644
--- a/apps/desktop-gpui/build.rs
+++ b/apps/desktop-gpui/build.rs
@@ -3,6 +3,7 @@ mod diagnostic_build;
fn main() {
diagnostic_build::emit();
+ cap_i18n_build::build("locales");
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos") {
println!("cargo:rerun-if-changed=native/exception_guard.m");
cc::Build::new()
diff --git a/apps/desktop-gpui/dev.sh b/apps/desktop-gpui/dev.sh
index 7e6ce384b..c073cd623 100755
--- a/apps/desktop-gpui/dev.sh
+++ b/apps/desktop-gpui/dev.sh
@@ -10,7 +10,7 @@ STATE_FILE="$PWD/target/dev-restore.json"
BIN="$PWD/target/debug/cap-gpui"
BUILD=cargo
-WATCH_PATHS=(src kernels/src kernels/Cargo.toml assets Cargo.toml ../desktop/src-tauri/sounds)
+WATCH_PATHS=(src kernels/src kernels/Cargo.toml i18n-build/src i18n-build/Cargo.toml locales assets Cargo.toml ../desktop/src-tauri/sounds)
[ -d resources ] && WATCH_PATHS+=(resources)
for crate in camera scap-targets recording timestamp utils project rendering editor export; do
[ -d "../../crates/$crate/src" ] && WATCH_PATHS+=("../../crates/$crate/src")
diff --git a/apps/desktop-gpui/i18n-build/Cargo.toml b/apps/desktop-gpui/i18n-build/Cargo.toml
new file mode 100644
index 000000000..9ba891f50
--- /dev/null
+++ b/apps/desktop-gpui/i18n-build/Cargo.toml
@@ -0,0 +1,12 @@
+[package]
+name = "cap-i18n-build"
+version = "0.1.0"
+edition = "2024"
+license = "AGPL-3.0"
+publish = false
+
+[dependencies]
+toml = "1"
+
+[build-dependencies]
+toml = "1"
diff --git a/apps/desktop-gpui/i18n-build/build.rs b/apps/desktop-gpui/i18n-build/build.rs
new file mode 100644
index 000000000..5808edaed
--- /dev/null
+++ b/apps/desktop-gpui/i18n-build/build.rs
@@ -0,0 +1,22 @@
+#[allow(dead_code)]
+#[path = "src/lib.rs"]
+mod codegen;
+
+use std::path::PathBuf;
+
+fn main() {
+ println!("cargo:rerun-if-changed=src/lib.rs");
+ println!("cargo:rerun-if-changed=tests/fixtures");
+ let manifest_dir =
+ PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR"));
+ let out_dir = PathBuf::from(std::env::var_os("OUT_DIR").expect("OUT_DIR"));
+ let catalogs = codegen::read_catalogs(&manifest_dir.join("tests/fixtures"))
+ .unwrap_or_else(|errors| panic!("{}", errors.join("\n")));
+ let borrowed: Vec<(&str, &str)> = catalogs
+ .iter()
+ .map(|(code, text)| (code.as_str(), text.as_str()))
+ .collect();
+ let output = codegen::generate(&borrowed, false)
+ .unwrap_or_else(|errors| panic!("{}", errors.join("\n")));
+ std::fs::write(out_dir.join("fixture.rs"), output.code).expect("write the fixture tables");
+}
diff --git a/apps/desktop-gpui/i18n-build/src/lib.rs b/apps/desktop-gpui/i18n-build/src/lib.rs
new file mode 100644
index 000000000..b4d88ff0e
--- /dev/null
+++ b/apps/desktop-gpui/i18n-build/src/lib.rs
@@ -0,0 +1,1474 @@
+use std::collections::{BTreeMap, BTreeSet};
+use std::path::{Path, PathBuf};
+
+use toml::{Table, Value};
+
+pub const STRICT_ENV: &str = "CAP_I18N_STRICT";
+
+const MESSAGE_FIELDS: [&str; 8] = [
+ "text", "one", "few", "many", "other", "context", "max_px", "size",
+];
+
+const KEYWORDS: &[&str] = &[
+ "abstract", "as", "async", "await", "become", "box", "break", "const", "continue", "crate",
+ "do", "dyn", "else", "enum", "extern", "false", "final", "fn", "for", "gen", "if", "impl",
+ "in", "let", "loop", "macro", "match", "mod", "move", "mut", "override", "priv", "pub", "ref",
+ "return", "self", "static", "struct", "super", "trait", "true", "try", "type", "typeof",
+ "union", "unsafe", "unsized", "use", "virtual", "where", "while", "yield",
+];
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub enum Category {
+ One,
+ Few,
+ Many,
+ Other,
+}
+
+impl Category {
+ pub const ALL: [Category; 4] = [
+ Category::One,
+ Category::Few,
+ Category::Many,
+ Category::Other,
+ ];
+
+ pub fn name(self) -> &'static str {
+ match self {
+ Category::One => "one",
+ Category::Few => "few",
+ Category::Many => "many",
+ Category::Other => "other",
+ }
+ }
+
+ fn from_name(name: &str) -> Option<Self> {
+ Self::ALL
+ .into_iter()
+ .find(|category| category.name() == name)
+ }
+
+ fn variant(self) -> &'static str {
+ match self {
+ Category::One => "One",
+ Category::Few => "Few",
+ Category::Many => "Many",
+ Category::Other => "Other",
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum OneRule {
+ Never,
+ ExactlyOne,
+ ZeroOrOne,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct PluralRule {
+ pub one: OneRule,
+ pub many_millions: bool,
+}
+
+impl PluralRule {
+ pub fn category(self, n: usize) -> Category {
+ let one = match self.one {
+ OneRule::Never => false,
+ OneRule::ExactlyOne => n == 1,
+ OneRule::ZeroOrOne => n <= 1,
+ };
+ if one {
+ Category::One
+ } else if self.many_millions && n != 0 && n.is_multiple_of(1_000_000) {
+ Category::Many
+ } else {
+ Category::Other
+ }
+ }
+
+ pub fn categories(self) -> Vec<Category> {
+ let mut categories = Vec::new();
+ if self.one != OneRule::Never {
+ categories.push(Category::One);
+ }
+ if self.many_millions {
+ categories.push(Category::Many);
+ }
+ categories.push(Category::Other);
+ categories
+ }
+
+ fn required(self) -> impl Iterator<Item = Category> {
+ self.categories()
+ .into_iter()
+ .filter(|category| *category != Category::Many)
+ }
+}
+
+#[derive(Debug)]
+pub struct LocaleSpec {
+ pub code: &'static str,
+ pub ident: &'static str,
+ pub endonym: &'static str,
+ pub plural: PluralRule,
+}
+
+const ONE_IS_ONE: PluralRule = PluralRule {
+ one: OneRule::ExactlyOne,
+ many_millions: false,
+};
+
+const ZERO_AND_ONE_ARE_ONE: PluralRule = PluralRule {
+ one: OneRule::ZeroOrOne,
+ many_millions: false,
+};
+
+const NO_PLURALS: PluralRule = PluralRule {
+ one: OneRule::Never,
+ many_millions: false,
+};
+
+pub const LOCALES: &[LocaleSpec] = &[
+ LocaleSpec {
+ code: "en",
+ ident: "En",
+ endonym: "English",
+ plural: ONE_IS_ONE,
+ },
+ LocaleSpec {
+ code: "zh-CN",
+ ident: "ZhCn",
+ endonym: "简体中文",
+ plural: NO_PLURALS,
+ },
+ LocaleSpec {
+ code: "ja",
+ ident: "Ja",
+ endonym: "日本語",
+ plural: NO_PLURALS,
+ },
+ LocaleSpec {
+ code: "fr",
+ ident: "Fr",
+ endonym: "Français",
+ plural: PluralRule {
+ one: OneRule::ZeroOrOne,
+ many_millions: true,
+ },
+ },
+ LocaleSpec {
+ code: "es",
+ ident: "Es",
+ endonym: "Español",
+ plural: PluralRule {
+ one: OneRule::ExactlyOne,
+ many_millions: true,
+ },
+ },
+ LocaleSpec {
+ code: "de",
+ ident: "De",
+ endonym: "Deutsch",
+ plural: ONE_IS_ONE,
+ },
+ LocaleSpec {
+ code: "hi",
+ ident: "Hi",
+ endonym: "हिन्दी",
+ plural: ZERO_AND_ONE_ARE_ONE,
+ },
+];
+
+pub struct Output {
+ pub code: String,
+ pub warnings: Vec<String>,
+ pub keys: usize,
+}
+
+pub fn build(locales: impl AsRef<Path>) {
+ let manifest_dir = env_path("CARGO_MANIFEST_DIR");
+ let out_dir = env_path("OUT_DIR");
+ let locales = manifest_dir.join(locales);
+ println!("cargo:rerun-if-changed={}", locales.display());
+ println!("cargo:rerun-if-env-changed={STRICT_ENV}");
+ let strict = std::env::var(STRICT_ENV).is_ok_and(|value| value == "1");
+
+ let catalogs = read_catalogs(&locales).unwrap_or_else(|errors| fail(&errors));
+ let borrowed: Vec<(&str, &str)> = catalogs
+ .iter()
+ .map(|(code, text)| (code.as_str(), text.as_str()))
+ .collect();
+ let output = generate(&borrowed, strict).unwrap_or_else(|errors| fail(&errors));
+ for warning in &output.warnings {
+ for line in warning.lines() {
+ println!("cargo:warning={line}");
+ }
+ }
+ let path = out_dir.join("i18n.rs");
+ if let Err(error) = std::fs::write(&path, output.code) {
+ panic!("cap-i18n-build: cannot write {}: {error}", path.display());
+ }
+}
+
+fn env_path(name: &str) -> PathBuf {
+ std::env::var_os(name)
+ .map(PathBuf::from)
+ .unwrap_or_else(|| panic!("cap-i18n-build: {name} is unset; call build() from build.rs"))
+}
+
+fn fail(errors: &[String]) -> ! {
+ panic!(
+ "cap-i18n-build found {} problem(s) in the locale catalogs:\n{}",
+ errors.len(),
+ errors.join("\n")
+ )
+}
+
+pub fn read_catalogs(dir: &Path) -> Result<Vec<(String, String)>, Vec<String>> {
+ let entries = std::fs::read_dir(dir)
+ .map_err(|error| vec![format!("cannot read {}: {error}", dir.display())])?;
+ let mut catalogs = Vec::new();
+ let mut errors = Vec::new();
+ for entry in entries {
+ let path = match entry {
+ Ok(entry) => entry.path(),
+ Err(error) => {
+ errors.push(format!("cannot read {}: {error}", dir.display()));
+ continue;
+ }
+ };
+ if path.extension().and_then(|extension| extension.to_str()) != Some("toml") {
+ continue;
+ }
+ let Some(code) = path.file_stem().and_then(|stem| stem.to_str()) else {
+ errors.push(format!("{} has a non UTF-8 name", path.display()));
+ continue;
+ };
+ match std::fs::read_to_string(&path) {
+ Ok(text) => catalogs.push((code.to_string(), text)),
+ Err(error) => errors.push(format!("cannot read {}: {error}", path.display())),
+ }
+ }
+ catalogs.sort();
+ if errors.is_empty() {
+ Ok(catalogs)
+ } else {
+ Err(errors)
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+enum Piece {
+ Text(String),
+ Arg(String),
+}
+
+#[derive(Clone, Debug)]
+struct Template {
+ source: String,
+ pieces: Vec<Piece>,
+}
+
+impl Template {
+ fn parse(source: &str) -> Result<Self, String> {
+ let mut pieces = Vec::new();
+ let mut text = String::new();
+ let mut chars = source.chars().peekable();
+ while let Some(c) = chars.next() {
+ match c {
+ '{' if chars.peek() == Some(&'{') => {
+ chars.next();
+ text.push('{');
+ }
+ '}' if chars.peek() == Some(&'}') => {
+ chars.next();
+ text.push('}');
+ }
+ '{' => {
+ let mut name = String::new();
+ loop {
+ match chars.next() {
+ Some('}') => break,
+ Some(c) => name.push(c),
+ None => {
+ return Err(format!(
+ "unclosed `{{` in {source:?}; write `{{{{` for a literal brace"
+ ));
+ }
+ }
+ }
+ if !is_identifier(&name) {
+ return Err(format!(
+ "`{{{name}}}` in {source:?} is not a placeholder; placeholders are \
+ lowercase snake_case names and literal braces are written `{{{{` and `}}}}`"
+ ));
+ }
+ if !text.is_empty() {
+ pieces.push(Piece::Text(std::mem::take(&mut text)));
+ }
+ pieces.push(Piece::Arg(name));
+ }
+ '}' => {
+ return Err(format!(
+ "unmatched `}}` in {source:?}; write `}}}}` for a literal brace"
+ ));
+ }
+ c => text.push(c),
+ }
+ }
+ if !text.is_empty() {
+ pieces.push(Piece::Text(text));
+ }
+ Ok(Self {
+ source: source.to_string(),
+ pieces,
+ })
+ }
+
+ fn args(&self) -> Vec<&str> {
+ let mut args: Vec<&str> = Vec::new();
+ for piece in &self.pieces {
+ if let Piece::Arg(name) = piece
+ && !args.contains(&name.as_str())
+ {
+ args.push(name);
+ }
+ }
+ args
+ }
+
+ fn arg_set(&self) -> BTreeSet<&str> {
+ self.args().into_iter().collect()
+ }
+
+ fn non_count_args(&self) -> BTreeSet<&str> {
+ self.args()
+ .into_iter()
+ .filter(|arg| *arg != "count")
+ .collect()
+ }
+
+ fn plain(&self) -> String {
+ self.pieces
+ .iter()
+ .map(|piece| match piece {
+ Piece::Text(text) => text.as_str(),
+ Piece::Arg(_) => "",
+ })
+ .collect()
+ }
+
+ fn expression(&self) -> String {
+ if self.args().is_empty() {
+ return format!("String::from({:?})", self.plain());
+ }
+ let mut format = String::new();
+ for piece in &self.pieces {
+ match piece {
+ Piece::Text(text) => format.push_str(&text.replace('{', "{{").replace('}', "}}")),
+ Piece::Arg(name) => {
+ format.push('{');
+ format.push_str(name);
+ format.push('}');
+ }
+ }
+ }
+ format!("format!({format:?})")
+ }
+}
+
+fn is_identifier(name: &str) -> bool {
+ let mut chars = name.chars();
+ chars.next().is_some_and(|first| first.is_ascii_lowercase())
+ && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
+ && !KEYWORDS.contains(&name)
+}
+
+fn check_segment(name: &str) -> Result<(), String> {
+ if MESSAGE_FIELDS.contains(&name) {
+ return Err(format!(
+ "`{name}` is reserved for message fields and cannot name a key"
+ ));
+ }
+ if !is_identifier(name) {
+ return Err(format!(
+ "`{name}` is not a valid key segment; use lowercase snake_case that is not a Rust keyword"
+ ));
+ }
+ Ok(())
+}
+
+#[derive(Clone, Debug)]
+enum Raw {
+ Text(String),
+ Plural(BTreeMap<Category, String>),
+}
+
+#[derive(Clone, Debug)]
+struct Entry {
+ raw: Raw,
+ context: Option<String>,
+}
+
+#[derive(Clone, Debug)]
+enum Forms {
+ Text(Template),
+ Plural(BTreeMap<Category, Template>),
+}
+
+struct Message {
+ context: Option<String>,
+ english: Forms,
+ translations: Vec<Option<Forms>>,
+}
+
+fn parse_catalog(
+ code: &str,
+ text: &str,
+ source: bool,
+ errors: &mut Vec<String>,
+) -> BTreeMap<String, Entry> {
+ let file = format!("{code}.toml");
+ let mut entries = BTreeMap::new();
+ match text.parse::<Table>() {
+ Ok(table) => flatten(&file, &table, "", source, &mut entries, errors),
+ Err(error) => errors.push(format!("{file}: {error}")),
+ }
+ entries
+}
+
+fn flatten(
+ file: &str,
+ table: &Table,
+ prefix: &str,
+ source: bool,
+ entries: &mut BTreeMap<String, Entry>,
+ errors: &mut Vec<String>,
+) {
+ for (name, value) in table.iter() {
+ let key = if prefix.is_empty() {
+ name.clone()
+ } else {
+ format!("{prefix}.{name}")
+ };
+ if let Err(error) = check_segment(name) {
+ errors.push(format!("{file}: `{key}`: {error}"));
+ continue;
+ }
+ match value {
+ Value::String(text) => {
+ entries.insert(
+ key,
+ Entry {
+ raw: Raw::Text(text.clone()),
+ context: None,
+ },
+ );
+ }
+ Value::Table(inner)
+ if inner
+ .keys()
+ .any(|field| MESSAGE_FIELDS.contains(&field.as_str())) =>
+ {
+ match parse_message_table(inner, source) {
+ Ok(entry) => {
+ entries.insert(key, entry);
+ }
+ Err(error) => errors.push(format!("{file}: `{key}`: {error}")),
+ }
+ }
+ Value::Table(inner) => flatten(file, inner, &key, source, entries, errors),
+ _ => errors.push(format!("{file}: `{key}`: expected a string or a table")),
+ }
+ }
+}
+
+fn parse_message_table(table: &Table, source: bool) -> Result<Entry, String> {
+ let mut text = None;
+ let mut context = None;
+ let mut forms = BTreeMap::new();
+ for (field, value) in table.iter() {
+ match field.as_str() {
+ "text" if source => text = Some(expect_string(field, value)?),
+ "context" if source => context = Some(expect_string(field, value)?),
+ "max_px" | "size" if source => expect_positive_number(field, value)?,
+ name => match Category::from_name(name) {
+ Some(category) => {
+ forms.insert(category, expect_string(field, value)?);
+ }
+ None if MESSAGE_FIELDS.contains(&name) => {
+ return Err(format!(
+ "`{name}` belongs in en.toml only; translations hold a string or plural forms"
+ ));
+ }
+ None => {
+ return Err(format!(
+ "`{name}` sits beside message fields; a table is either a message \
+ (text, one, few, many, other, context, max_px, size) or a group of keys"
+ ));
+ }
+ },
+ }
+ }
+ let raw = match (text, forms.is_empty()) {
+ (Some(text), true) => Raw::Text(text),
+ (None, false) => Raw::Plural(forms),
+ (Some(_), false) => return Err("has both `text` and plural forms".to_string()),
+ (None, true) => return Err("has neither `text` nor plural forms".to_string()),
+ };
+ Ok(Entry { raw, context })
+}
+
+fn expect_string(field: &str, value: &Value) -> Result<String, String> {
+ match value {
+ Value::String(text) => Ok(text.clone()),
+ _ => Err(format!("`{field}` must be a string")),
+ }
+}
+
+fn expect_positive_number(field: &str, value: &Value) -> Result<(), String> {
+ match value {
+ Value::Integer(number) if *number > 0 => Ok(()),
+ Value::Float(number) if *number > 0.0 => Ok(()),
+ _ => Err(format!("`{field}` must be a positive number")),
+ }
+}
+
+fn leading_whitespace(text: &str) -> &str {
+ &text[..text.len() - text.trim_start().len()]
+}
+
+fn trailing_whitespace(text: &str) -> &str {
+ &text[text.trim_end().len()..]
+}
+
+fn check_value(value: &str, english: Option<&str>) -> Result<Template, String> {
+ if value.trim().is_empty() {
+ return Err("value is empty".to_string());
+ }
+ if let Some(english) = english
+ && (leading_whitespace(value) != leading_whitespace(english)
+ || trailing_whitespace(value) != trailing_whitespace(english))
+ {
+ return Err(format!(
+ "leading or trailing whitespace differs from English {english:?}"
+ ));
+ }
+ Template::parse(value)
+}
+
+fn placeholder_list(args: &BTreeSet<&str>) -> String {
+ if args.is_empty() {
+ return "(none)".to_string();
+ }
+ args.iter()
+ .map(|arg| format!("{{{arg}}}"))
+ .collect::<Vec<_>>()
+ .join(", ")
+}
+
+fn same_placeholders(english: &BTreeSet<&str>, translated: &BTreeSet<&str>) -> Result<(), String> {
+ if english == translated {
+ return Ok(());
+ }
+ Err(format!(
+ "placeholders {} do not match English {}",
+ placeholder_list(translated),
+ placeholder_list(english)
+ ))
+}
+
+fn plural_forms(
+ spec: &LocaleSpec,
+ values: &BTreeMap<Category, String>,
+ english_other: Option<&str>,
+) -> Result<BTreeMap<Category, Template>, String> {
+ let allowed = spec.plural.categories();
+ for category in values.keys() {
+ if !allowed.contains(category) {
+ return Err(format!(
+ "`{}` is not a plural form in {}, which uses {}",
+ category.name(),
+ spec.code,
+ allowed
+ .iter()
+ .map(|category| category.name())
+ .collect::<Vec<_>>()
+ .join(", ")
+ ));
+ }
+ }
+ for category in spec.plural.required() {
+ if !values.contains_key(&category) {
+ return Err(format!("missing the `{}` plural form", category.name()));
+ }
+ }
+ values
+ .iter()
+ .map(|(category, value)| {
+ check_value(value, english_other)
+ .map(|template| (*category, template))
+ .map_err(|error| format!("`{}` form: {error}", category.name()))
+ })
+ .collect()
+}
+
+fn english_forms(raw: &Raw) -> Result<Forms, String> {
+ match raw {
+ Raw::Text(value) => Ok(Forms::Text(check_value(value, None)?)),
+ Raw::Plural(values) => {
+ let forms = plural_forms(&LOCALES[0], values, None)?;
+ let expected = forms[&Category::Other].non_count_args();
+ for (category, template) in &forms {
+ same_placeholders(&expected, &template.non_count_args()).map_err(|error| {
+ format!("`{}` form against `other`: {error}", category.name())
+ })?;
+ }
+ Ok(Forms::Plural(forms))
+ }
+ }
+}
+
+fn translated_forms(spec: &LocaleSpec, english: &Forms, raw: &Raw) -> Result<Forms, String> {
+ match (english, raw) {
+ (Forms::Text(english), Raw::Text(value)) => {
+ let template = check_value(value, Some(english.source.as_str()))?;
+ same_placeholders(&english.arg_set(), &template.arg_set())?;
+ Ok(Forms::Text(template))
+ }
+ (Forms::Plural(english), Raw::Plural(values)) => {
+ let english_other = &english[&Category::Other];
+ let forms = plural_forms(spec, values, Some(english_other.source.as_str()))?;
+ let expected = english_other.non_count_args();
+ for (category, template) in &forms {
+ same_placeholders(&expected, &template.non_count_args())
+ .map_err(|error| format!("`{}` form: {error}", category.name()))?;
+ }
+ Ok(Forms::Plural(forms))
+ }
+ (Forms::Text(_), Raw::Plural(_)) => {
+ Err("English is a single string, so the translation must be one too".to_string())
+ }
+ (Forms::Plural(_), Raw::Text(_)) => Err(
+ "English has plural forms, so the translation needs them too, for example \
+ `{ other = \"...\" }`"
+ .to_string(),
+ ),
+ }
+}
+
+pub fn generate(catalogs: &[(&str, &str)], strict: bool) -> Result<Output, Vec<String>> {
+ let mut errors = Vec::new();
+ let mut warnings = Vec::new();
+
+ let mut found: Vec<(&'static LocaleSpec, &str)> = Vec::new();
+ for &(code, text) in catalogs {
+ match LOCALES.iter().find(|spec| spec.code == code) {
+ Some(_) if found.iter().any(|(spec, _)| spec.code == code) => {
+ errors.push(format!("{code}.toml is listed twice"));
+ }
+ Some(spec) => found.push((spec, text)),
+ None => errors.push(format!(
+ "{code}.toml: unknown locale; expected one of {}",
+ LOCALES
+ .iter()
+ .map(|spec| spec.code)
+ .collect::<Vec<_>>()
+ .join(", ")
+ )),
+ }
+ }
+ found.sort_by_key(|(spec, _)| LOCALES.iter().position(|known| known.code == spec.code));
+ if found.first().is_none_or(|(spec, _)| spec.code != "en") {
+ errors.push("en.toml is missing; English is the source catalog".to_string());
+ return Err(errors);
+ }
+
+ let locales: Vec<&LocaleSpec> = found.iter().map(|(spec, _)| *spec).collect();
+ let catalogs: Vec<BTreeMap<String, Entry>> = found
+ .iter()
+ .enumerate()
+ .map(|(position, (spec, text))| parse_catalog(spec.code, text, position == 0, &mut errors))
+ .collect();
+
+ let mut messages = BTreeMap::new();
+ for (key, entry) in &catalogs[0] {
+ match english_forms(&entry.raw) {
+ Ok(english) => {
+ messages.insert(
+ key.clone(),
+ Message {
+ context: entry.context.clone(),
+ english,
+ translations: vec![None; locales.len()],
+ },
+ );
+ }
+ Err(error) => errors.push(format!("en.toml: `{key}`: {error}")),
+ }
+ }
+
+ let total = messages.len();
+ for (position, spec) in locales.iter().enumerate().skip(1) {
+ let catalog = &catalogs[position];
+ for key in catalog.keys().filter(|key| !messages.contains_key(*key)) {
+ warnings.push(format!(
+ "{}.toml: `{key}` is not in en.toml and is ignored",
+ spec.code
+ ));
+ }
+ let mut missing = Vec::new();
+ for (key, message) in &mut messages {
+ match catalog.get(key) {
+ Some(entry) => match translated_forms(spec, &message.english, &entry.raw) {
+ Ok(forms) => message.translations[position] = Some(forms),
+ Err(error) => errors.push(format!("{}.toml: `{key}`: {error}", spec.code)),
+ },
+ None => missing.push(key.clone()),
+ }
+ }
+ if !missing.is_empty() {
+ let mut preview = missing
+ .iter()
+ .take(8)
+ .map(|key| format!("`{key}`"))
+ .collect::<Vec<_>>()
+ .join(", ");
+ if missing.len() > 8 {
+ preview.push_str(", ...");
+ }
+ let note = format!(
+ "{}.toml: {} of {total} keys fall back to English: {preview}",
+ spec.code,
+ missing.len()
+ );
+ if strict {
+ errors.push(note);
+ } else {
+ warnings.push(note);
+ }
+ }
+ }
+
+ if !errors.is_empty() {
+ return Err(errors);
+ }
+ Ok(Output {
+ code: emit(&locales, &messages),
+ warnings,
+ keys: total,
+ })
+}
+
+#[derive(Default)]
+struct Code {
+ out: String,
+ depth: usize,
+}
+
+impl Code {
+ fn line(&mut self, text: impl AsRef<str>) {
+ let text = text.as_ref();
+ if !text.is_empty() {
+ for _ in 0..self.depth {
+ self.out.push_str(" ");
+ }
+ self.out.push_str(text);
+ }
+ self.out.push('\n');
+ }
+
+ fn open(&mut self, text: impl AsRef<str>) {
+ self.line(text);
+ self.depth += 1;
+ }
+
+ fn close(&mut self, text: impl AsRef<str>) {
+ self.depth -= 1;
+ self.line(text);
+ }
+
+ fn reopen(&mut self, text: impl AsRef<str>) {
+ self.depth -= 1;
+ self.line(text);
+ self.depth += 1;
+ }
+
+ fn arm(&mut self, pattern: &str, lines: &[String]) {
+ let last = lines.len() - 1;
+ for (index, line) in lines.iter().enumerate() {
+ let prefix = if index == 0 {
+ format!("{pattern} => ")
+ } else {
+ String::new()
+ };
+ let suffix = if index == last { "," } else { "" };
+ self.line(format!("{prefix}{line}{suffix}"));
+ }
+ }
+}
+
+#[derive(Default)]
+struct Node<'a> {
+ children: BTreeMap<&'a str, Node<'a>>,
+ leaves: Vec<(&'a str, &'a str)>,
+}
+
+struct Context<'a> {
+ locales: &'a [&'a LocaleSpec],
+ messages: &'a BTreeMap<String, Message>,
+ text_ids: BTreeMap<&'a str, usize>,
+}
+
+fn plain_text(forms: &Forms) -> Option<&Template> {
+ match forms {
+ Forms::Text(template) if template.args().is_empty() => Some(template),
+ _ => None,
+ }
+}
+
+fn plural_fn(spec: &LocaleSpec) -> String {
+ format!("plural_{}", spec.ident.to_ascii_lowercase())
+}
+
+fn emit(locales: &[&LocaleSpec], messages: &BTreeMap<String, Message>) -> String {
+ let mut code = Code::default();
+ code.line(
+ "// @generated by cap-i18n-build from the locale catalogs. Edit those, not this file.",
+ );
+ code.line("");
+ emit_locales(&mut code, locales);
+
+ let texts: Vec<(&str, &Message)> = messages
+ .iter()
+ .filter(|(_, message)| plain_text(&message.english).is_some())
+ .map(|(key, message)| (key.as_str(), message))
+ .collect();
+ if !texts.is_empty() {
+ code.line("");
+ code.line(format!("const LOCALE_COUNT: usize = {};", locales.len()));
+ code.line(format!("const TEXT_COUNT: usize = {};", texts.len()));
+ code.line("");
+ code.open("static TEXT: [[&str; TEXT_COUNT]; LOCALE_COUNT] = [");
+ for position in 0..locales.len() {
+ code.open("[");
+ for (_, message) in &texts {
+ let template = message.translations[position]
+ .as_ref()
+ .and_then(plain_text)
+ .or_else(|| plain_text(&message.english));
+ if let Some(template) = template {
+ code.line(format!("{:?},", template.plain()));
+ }
+ }
+ code.close("],");
+ }
+ code.close("];");
+ code.line("");
+ code.open("fn text(id: usize) -> &'static str {");
+ code.line("TEXT[index()][id]");
+ code.close("}");
+ }
+
+ let mut plural_users = BTreeSet::new();
+ for message in messages.values() {
+ if !matches!(message.english, Forms::Plural(_)) {
+ continue;
+ }
+ for (position, spec) in locales.iter().enumerate() {
+ let has_forms = position == 0 || message.translations[position].is_some();
+ if has_forms && spec.plural.categories().len() > 1 {
+ plural_users.insert(position);
+ }
+ }
+ }
+ if !plural_users.is_empty() {
+ let variants: BTreeSet<Category> = plural_users
+ .iter()
+ .flat_map(|position| locales[*position].plural.categories())
+ .collect();
+ code.line("");
+ code.line("#[derive(Clone, Copy, Debug, PartialEq, Eq)]");
+ code.open("enum Plural {");
+ for variant in &variants {
+ code.line(format!("{},", variant.variant()));
+ }
+ code.close("}");
+ for position in &plural_users {
+ code.line("");
+ emit_rule(&mut code, locales[*position]);
+ }
+ }
+
+ code.line("");
+ code.line("#[cfg(test)]");
+ code.open(format!("pub const KEYS: [&str; {}] = [", messages.len()));
+ for key in messages.keys() {
+ code.line(format!("{key:?},"));
+ }
+ code.close("];");
+
+ let mut root = Node::default();
+ for key in messages.keys() {
+ let segments: Vec<&str> = key.split('.').collect();
+ let Some((name, path)) = segments.split_last() else {
+ continue;
+ };
+ let mut node = &mut root;
+ for segment in path {
+ node = node.children.entry(*segment).or_default();
+ }
+ node.leaves.push((*name, key.as_str()));
+ }
+ let context = Context {
+ locales,
+ messages,
+ text_ids: texts
+ .iter()
+ .enumerate()
+ .map(|(id, (key, _))| (*key, id))
+ .collect(),
+ };
+ code.line("");
+ code.open("pub mod tr {");
+ emit_node(&mut code, &root, 1, &context);
+ code.close("}");
+ code.out
+}
+
+fn emit_locales(code: &mut Code, locales: &[&LocaleSpec]) {
+ code.line("#[allow(dead_code)]");
+ code.line("#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]");
+ code.line("#[repr(u8)]");
+ code.open("pub enum Locale {");
+ for (index, spec) in locales.iter().enumerate() {
+ code.line(format!("{} = {index},", spec.ident));
+ }
+ code.close("}");
+ code.line("");
+ code.line("#[allow(dead_code)]");
+ code.open("impl Locale {");
+ code.line(format!(
+ "pub const ALL: [Locale; {}] = [{}];",
+ locales.len(),
+ locales
+ .iter()
+ .map(|spec| format!("Locale::{}", spec.ident))
+ .collect::<Vec<_>>()
+ .join(", ")
+ ));
+ emit_locale_field(code, locales, "code", |spec| spec.code);
+ emit_locale_field(code, locales, "endonym", |spec| spec.endonym);
+ code.line("");
+ code.open("pub fn from_code(code: &str) -> Option<Self> {");
+ code.open("match code {");
+ for spec in locales {
+ code.line(format!("{:?} => Some(Locale::{}),", spec.code, spec.ident));
+ }
+ code.line("_ => None,");
+ code.close("}");
+ code.close("}");
+ code.close("}");
+}
+
+fn emit_locale_field(
+ code: &mut Code,
+ locales: &[&LocaleSpec],
+ name: &str,
+ field: fn(&LocaleSpec) -> &'static str,
+) {
+ code.line("");
+ code.open(format!("pub const fn {name}(self) -> &'static str {{"));
+ code.open("match self {");
+ for spec in locales {
+ code.line(format!("Locale::{} => {:?},", spec.ident, field(spec)));
+ }
+ code.close("}");
+ code.close("}");
+}
+
+fn emit_rule(code: &mut Code, spec: &LocaleSpec) {
+ code.open(format!("fn {}(n: usize) -> Plural {{", plural_fn(spec)));
+ let mut branches = Vec::new();
+ match spec.plural.one {
+ OneRule::Never => {}
+ OneRule::ExactlyOne => branches.push(("n == 1", Category::One)),
+ OneRule::ZeroOrOne => branches.push(("n <= 1", Category::One)),
+ }
+ if spec.plural.many_millions {
+ branches.push(("n != 0 && n.is_multiple_of(1_000_000)", Category::Many));
+ }
+ if branches.is_empty() {
+ code.line("let _ = n;");
+ code.line("Plural::Other");
+ } else {
+ for (index, (condition, category)) in branches.iter().enumerate() {
+ if index == 0 {
+ code.open(format!("if {condition} {{"));
+ } else {
+ code.reopen(format!("}} else if {condition} {{"));
+ }
+ code.line(format!("Plural::{}", category.variant()));
+ }
+ code.reopen("} else {");
+ code.line("Plural::Other");
+ code.close("}");
+ }
+ code.close("}");
+}
+
+fn emit_node(code: &mut Code, node: &Node, depth: usize, context: &Context) {
+ let mut first = true;
+ for (name, key) in &node.leaves {
+ if !first {
+ code.line("");
+ }
+ first = false;
+ emit_accessor(code, name, key, depth, context);
+ }
+ for (name, child) in &node.children {
+ if !first {
+ code.line("");
+ }
+ first = false;
+ code.open(format!("pub mod {name} {{"));
+ emit_node(code, child, depth + 1, context);
+ code.close("}");
+ }
+}
+
+fn signature_args(forms: &Forms) -> Vec<&str> {
+ match forms {
+ Forms::Text(template) => template.args(),
+ Forms::Plural(forms) => {
+ let mut args = vec!["count"];
+ let ordered = forms
+ .get(&Category::Other)
+ .into_iter()
+ .chain(forms.values());
+ for template in ordered {
+ for arg in template.args() {
+ if !args.contains(&arg) {
+ args.push(arg);
+ }
+ }
+ }
+ args
+ }
+ }
+}
+
+fn expression_lines(forms: &Forms, spec: &LocaleSpec, root: &str) -> Vec<String> {
+ match forms {
+ Forms::Text(template) => vec![template.expression()],
+ Forms::Plural(forms) => {
+ let other = forms[&Category::Other].expression();
+ if spec.plural.categories().len() == 1 {
+ return vec![other];
+ }
+ let mut lines = vec![format!("match {root}{}(count) {{", plural_fn(spec))];
+ for (category, template) in forms {
+ if *category != Category::Other {
+ lines.push(format!(
+ " {root}Plural::{} => {},",
+ category.variant(),
+ template.expression()
+ ));
+ }
+ }
+ lines.push(format!(" _ => {other},"));
+ lines.push("}".to_string());
+ lines
+ }
+ }
+}
+
+fn emit_accessor(code: &mut Code, name: &str, key: &str, depth: usize, context: &Context) {
+ let message = &context.messages[key];
+ let root = "super::".repeat(depth);
+ let mut doc = match &message.english {
+ Forms::Text(template) => format!("`{key}`: {}", template.source),
+ Forms::Plural(forms) => format!(
+ "`{key}`: {}",
+ forms
+ .iter()
+ .map(|(category, template)| format!("{} = {}", category.name(), template.source))
+ .collect::<Vec<_>>()
+ .join("; ")
+ ),
+ };
+ if let Some(note) = &message.context {
+ doc.push_str("\n\n");
+ doc.push_str(note);
+ }
+ code.line(format!("#[doc = {doc:?}]"));
+
+ if let Some(id) = context.text_ids.get(key) {
+ code.open(format!("pub fn {name}() -> &'static str {{"));
+ code.line(format!("{root}text({id})"));
+ code.close("}");
+ return;
+ }
+
+ let params = signature_args(&message.english)
+ .into_iter()
+ .map(|arg| {
+ if arg == "count" {
+ "count: usize".to_string()
+ } else {
+ format!("{arg}: impl ::std::fmt::Display")
+ }
+ })
+ .collect::<Vec<_>>()
+ .join(", ");
+ code.open(format!("pub fn {name}({params}) -> String {{"));
+ let english = expression_lines(&message.english, context.locales[0], &root);
+ let translated: Vec<(usize, Vec<String>)> = message
+ .translations
+ .iter()
+ .enumerate()
+ .filter_map(|(position, forms)| {
+ forms.as_ref().map(|forms| {
+ (
+ position,
+ expression_lines(forms, context.locales[position], &root),
+ )
+ })
+ })
+ .collect();
+ if translated.is_empty() {
+ for line in &english {
+ code.line(line);
+ }
+ } else {
+ code.open(format!("match {root}index() {{"));
+ for (position, lines) in &translated {
+ code.arm(&position.to_string(), lines);
+ }
+ code.arm("_", &english);
+ code.close("}");
+ }
+ code.close("}");
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn run(catalogs: &[(&str, &str)]) -> Result<Output, Vec<String>> {
+ generate(catalogs, false)
+ }
+
+ fn errors(catalogs: &[(&str, &str)]) -> String {
+ match run(catalogs) {
+ Ok(_) => panic!("expected the catalogs to be rejected"),
+ Err(errors) => errors.join("\n"),
+ }
+ }
+
+ fn rule(code: &str) -> PluralRule {
+ LOCALES
+ .iter()
+ .find(|spec| spec.code == code)
+ .map(|spec| spec.plural)
+ .unwrap()
+ }
+
+ #[test]
+ fn plain_strings_become_static_table_entries() {
+ let output = run(&[("en", "[tray]\nopen = \"Open Main Window\"\n")]).unwrap();
+ assert_eq!(output.keys, 1);
+ assert!(output.code.contains("\"Open Main Window\","));
+ assert!(output.code.contains("pub fn open() -> &'static str {"));
+ assert!(output.code.contains("super::super::text(0)"));
+ assert!(output.code.contains("\"tray.open\","));
+ }
+
+ #[test]
+ fn placeholders_become_typed_parameters() {
+ let output = run(&[(
+ "en",
+ "[a]\nversion = \"Cap v{version}\"\nitems = \"{count} items in {place}\"\n",
+ )])
+ .unwrap();
+ assert!(
+ output
+ .code
+ .contains("pub fn version(version: impl ::std::fmt::Display) -> String {")
+ );
+ assert!(output.code.contains("format!(\"Cap v{version}\")"));
+ assert!(
+ output.code.contains(
+ "pub fn items(count: usize, place: impl ::std::fmt::Display) -> String {"
+ )
+ );
+ }
+
+ #[test]
+ fn placeholder_mismatch_is_rejected() {
+ let en = "[a]\ngreeting = \"Hello, {name}!\"\n";
+ let message = errors(&[("en", en), ("fr", "[a]\ngreeting = \"Bonjour, {nom} !\"\n")]);
+ assert!(message.contains("fr.toml: `a.greeting`"), "{message}");
+ assert!(message.contains("{nom}"), "{message}");
+ assert!(message.contains("{name}"), "{message}");
+
+ let message = errors(&[("en", en), ("fr", "[a]\ngreeting = \"Bonjour !\"\n")]);
+ assert!(message.contains("(none)"), "{message}");
+ }
+
+ #[test]
+ fn malformed_braces_are_rejected() {
+ for value in [
+ "Hello {name",
+ "Hello } there",
+ "{0}",
+ "{Name}",
+ "{name:?}",
+ "{}",
+ "{type}",
+ "{a{{b}",
+ ] {
+ let catalog = format!("[a]\nb = {value:?}\n");
+ let message = errors(&[("en", &catalog)]);
+ assert!(message.contains("en.toml: `a.b`"), "{value}: {message}");
+ }
+ }
+
+ #[test]
+ fn doubled_braces_are_literal_braces() {
+ let output = run(&[(
+ "en",
+ "[a]\nplain = \"Use {{name}} here\"\nformatted = \"{{{value}}} and }}\"\n",
+ )])
+ .unwrap();
+ assert!(
+ output.code.contains("\"Use {name} here\","),
+ "{}",
+ output.code
+ );
+ assert!(
+ output.code.contains("format!(\"{{{value}}} and }}\")"),
+ "{}",
+ output.code
+ );
+ }
+
+ #[test]
+ fn plural_rules_select_the_documented_forms() {
+ for code in ["en", "de"] {
+ assert_eq!(rule(code).category(0), Category::Other);
+ assert_eq!(rule(code).category(1), Category::One);
+ assert_eq!(rule(code).category(2), Category::Other);
+ assert_eq!(rule(code).category(1_000_000), Category::Other);
+ }
+ let fr = rule("fr");
+ assert_eq!(fr.category(0), Category::One);
+ assert_eq!(fr.category(1), Category::One);
+ assert_eq!(fr.category(2), Category::Other);
+ assert_eq!(fr.category(1_000_000), Category::Many);
+ assert_eq!(fr.category(3_000_000), Category::Many);
+ assert_eq!(fr.category(1_000_001), Category::Other);
+ let es = rule("es");
+ assert_eq!(es.category(0), Category::Other);
+ assert_eq!(es.category(1), Category::One);
+ assert_eq!(es.category(2_000_000), Category::Many);
+ let hi = rule("hi");
+ assert_eq!(hi.category(0), Category::One);
+ assert_eq!(hi.category(1), Category::One);
+ assert_eq!(hi.category(2), Category::Other);
+ for code in ["zh-CN", "ja"] {
+ for n in [0, 1, 2, 1_000_000] {
+ assert_eq!(rule(code).category(n), Category::Other);
+ }
+ }
+ }
+
+ #[test]
+ fn plural_messages_dispatch_on_count() {
+ let en = "[a]\nclips = { one = \"One clip\", other = \"{count} clips\" }\n";
+ let fr = "[a]\nclips = { one = \"{count} clip\", many = \"{count} de clips\", other = \"{count} clips\" }\n";
+ let ja = "[a]\nclips = { other = \"{count}件のクリップ\" }\n";
+ let output = run(&[("en", en), ("fr", fr), ("ja", ja)]).unwrap();
+ assert!(
+ output
+ .code
+ .contains("pub fn clips(count: usize) -> String {")
+ );
+ assert!(output.code.contains("fn plural_en(n: usize) -> Plural {"));
+ assert!(output.code.contains("fn plural_fr(n: usize) -> Plural {"));
+ assert!(!output.code.contains("fn plural_ja"));
+ assert!(
+ output
+ .code
+ .contains("super::super::Plural::Many => format!(\"{count} de clips\"),")
+ );
+ assert!(
+ output
+ .code
+ .contains("1 => format!(\"{count}件のクリップ\"),")
+ );
+ }
+
+ #[test]
+ fn plural_forms_are_checked_per_locale() {
+ let en = "[a]\nclips = { one = \"One clip\", other = \"{count} clips\" }\n";
+ let message = errors(&[("en", "[a]\nclips = { one = \"One clip\" }\n")]);
+ assert!(
+ message.contains("missing the `other` plural form"),
+ "{message}"
+ );
+
+ let message = errors(&[
+ ("en", en),
+ ("ja", "[a]\nclips = { one = \"1\", other = \"{count}\" }\n"),
+ ]);
+ assert!(
+ message.contains("`one` is not a plural form in ja"),
+ "{message}"
+ );
+
+ let message = errors(&[
+ ("en", en),
+ ("fr", "[a]\nclips = { other = \"{count} clips\" }\n"),
+ ]);
+ assert!(
+ message.contains("missing the `one` plural form"),
+ "{message}"
+ );
+
+ let fr_without_many = "[a]\nclips = { one = \"Un clip\", other = \"{count} clips\" }\n";
+ assert!(run(&[("en", en), ("fr", fr_without_many)]).is_ok());
+
+ let message = errors(&[("en", "[a]\nx = { one = \"{name}\", other = \"{count}\" }\n")]);
+ assert!(message.contains("against `other`"), "{message}");
+ }
+
+ #[test]
+ fn translation_shape_must_match_english() {
+ let message = errors(&[
+ (
+ "en",
+ "[a]\nclips = { one = \"One clip\", other = \"{count} clips\" }\n",
+ ),
+ ("fr", "[a]\nclips = \"{count} clips\"\n"),
+ ]);
+ assert!(message.contains("needs them too"), "{message}");
+
+ let message = errors(&[
+ ("en", "[a]\nsave = \"Save\"\n"),
+ ("fr", "[a]\nsave = { one = \"a\", other = \"b\" }\n"),
+ ]);
+ assert!(message.contains("must be one too"), "{message}");
+
+ let message = errors(&[
+ ("en", "[a]\nsave = \"Save\"\n"),
+ ("fr", "[a]\nsave = { text = \"Enregistrer\" }\n"),
+ ]);
+ assert!(message.contains("belongs in en.toml only"), "{message}");
+ }
+
+ #[test]
+ fn missing_translations_warn_and_fall_back_unless_strict() {
+ let en = "[a]\nsave = \"Save\"\nopen = \"Open\"\n";
+ let fr = "[a]\nsave = \"Enregistrer\"\nstale = \"Vieux\"\n";
+ let output = run(&[("en", en), ("fr", fr)]).unwrap();
+ assert!(
+ output
+ .warnings
+ .iter()
+ .any(|warning| warning.contains("1 of 2 keys fall back to English: `a.open`"))
+ );
+ assert!(
+ output
+ .warnings
+ .iter()
+ .any(|warning| warning.contains("`a.stale` is not in en.toml"))
+ );
+ assert!(output.code.contains("\"Enregistrer\","));
+ assert_eq!(output.code.matches("\"Open\",").count(), 2);
+
+ let strict = generate(&[("en", en), ("fr", fr)], true).unwrap_err();
+ assert!(
+ strict
+ .iter()
+ .any(|error| error.contains("fall back to English"))
+ );
+ }
+
+ #[test]
+ fn keys_and_tables_are_validated() {
+ for (catalog, expected) in [
+ ("[a]\ntype = \"x\"\n", "not a valid key segment"),
+ ("[a]\nOpen = \"x\"\n", "not a valid key segment"),
+ ("other = \"x\"\n", "reserved for message fields"),
+ (
+ "[a]\nb = { text = \"x\", one = \"y\" }\n",
+ "both `text` and plural forms",
+ ),
+ (
+ "[a]\nb = { context = \"x\" }\n",
+ "neither `text` nor plural forms",
+ ),
+ (
+ "[a.b]\ntext = \"x\"\nlabel = \"y\"\n",
+ "sits beside message fields",
+ ),
+ ("[a]\nb = { text = \"x\", max_px = 0 }\n", "positive number"),
+ ("[a]\nb = 3\n", "expected a string or a table"),
+ ("[a]\nb = \" \"\n", "value is empty"),
+ ("[a\n", "en.toml"),
+ ] {
+ let message = errors(&[("en", catalog)]);
+ assert!(message.contains(expected), "{catalog:?}: {message}");
+ }
+ }
+
+ #[test]
+ fn message_tables_carry_metadata() {
+ let output = run(&[(
+ "en",
+ "[a]\ntitle = { text = \"Title\", context = \"Window heading\", max_px = 120, size = 13.5 }\n",
+ )])
+ .unwrap();
+ assert!(output.code.contains("\"Title\","));
+ assert!(output.code.contains("Window heading"));
+ }
+
+ #[test]
+ fn surrounding_whitespace_must_match_english() {
+ let message = errors(&[
+ ("en", "[a]\nb = \"Studio\"\n"),
+ ("fr", "[a]\nb = \" Studio\"\n"),
+ ]);
+ assert!(message.contains("whitespace differs"), "{message}");
+ }
+
+ #[test]
+ fn locale_files_are_checked() {
+ let message = errors(&[("en", "a = \"x\"\n"), ("xx", "a = \"y\"\n")]);
+ assert!(message.contains("xx.toml: unknown locale"), "{message}");
+
+ let message = errors(&[("fr", "a = \"x\"\n")]);
+ assert!(message.contains("en.toml is missing"), "{message}");
+ }
+
+ #[test]
+ fn locale_enum_lists_present_locales_in_registry_order() {
+ let output = run(&[("fr", "a = \"y\"\n"), ("en", "a = \"x\"\n")]).unwrap();
+ assert!(output.code.contains("En = 0,"));
+ assert!(output.code.contains("Fr = 1,"));
+ assert!(output.code.contains("\"fr\" => Some(Locale::Fr),"));
+ assert!(output.code.contains("Locale::Fr => \"Français\","));
+ assert!(!output.code.contains("Ja ="));
+ }
+
+ #[test]
+ fn output_is_deterministic() {
+ let catalogs = [
+ ("en", "[b]\nz = \"Z\"\n[a]\ny = \"Y {n}\"\nx = \"X\"\n"),
+ ("de", "[a]\nx = \"X\"\n"),
+ ];
+ assert_eq!(run(&catalogs).unwrap().code, run(&catalogs).unwrap().code);
+ }
+}
diff --git a/apps/desktop-gpui/i18n-build/tests/fixtures/en.toml b/apps/desktop-gpui/i18n-build/tests/fixtures/en.toml
new file mode 100644
index 000000000..1427f1eb4
--- /dev/null
+++ b/apps/desktop-gpui/i18n-build/tests/fixtures/en.toml
@@ -0,0 +1,12 @@
+[common]
+save = "Save"
+braces = "Use {{name}} in templates"
+greeting = "Hello, {name}!"
+untranslated = "Only in English"
+
+[common.meta]
+title = { text = "Title", context = "Window heading", max_px = 120 }
+
+[editor.selection]
+clips = { one = "One clip", other = "{count} clips" }
+segments = { one = "{count} {kind} segment selected", other = "{count} {kind} segments selected" }
diff --git a/apps/desktop-gpui/i18n-build/tests/fixtures/fr.toml b/apps/desktop-gpui/i18n-build/tests/fixtures/fr.toml
new file mode 100644
index 000000000..f87386470
--- /dev/null
+++ b/apps/desktop-gpui/i18n-build/tests/fixtures/fr.toml
@@ -0,0 +1,11 @@
+[common]
+save = "Enregistrer"
+braces = "Utilisez {{name}} dans les modèles"
+greeting = "Bonjour, {name} !"
+
+[common.meta]
+title = "Titre"
+
+[editor.selection]
+clips = { one = "Un clip", other = "{count} clips" }
+segments = { one = "{count} segment {kind} sélectionné", many = "{count} de segments {kind} sélectionnés", other = "{count} segments {kind} sélectionnés" }
diff --git a/apps/desktop-gpui/i18n-build/tests/fixtures/ja.toml b/apps/desktop-gpui/i18n-build/tests/fixtures/ja.toml
new file mode 100644
index 000000000..461c4dde4
--- /dev/null
+++ b/apps/desktop-gpui/i18n-build/tests/fixtures/ja.toml
@@ -0,0 +1,7 @@
+[common]
+save = "保存"
+greeting = "こんにちは、{name}さん"
+
+[editor.selection]
+clips = { other = "{count}件のクリップ" }
+segments = { other = "{kind}セグメントを{count}件選択" }
diff --git a/apps/desktop-gpui/i18n-build/tests/generated.rs b/apps/desktop-gpui/i18n-build/tests/generated.rs
new file mode 100644
index 000000000..448f0a2da
--- /dev/null
+++ b/apps/desktop-gpui/i18n-build/tests/generated.rs
@@ -0,0 +1,115 @@
+mod i18n {
+ use std::cell::Cell;
+
+ use cap_i18n_build::{Category, LOCALES};
+
+ thread_local! {
+ static INDEX: Cell<usize> = const { Cell::new(0) };
+ }
+
+ fn index() -> usize {
+ INDEX.with(Cell::get)
+ }
+
+ fn set(locale: Locale) {
+ INDEX.with(|index| index.set(locale as usize));
+ }
+
+ include!(concat!(env!("OUT_DIR"), "/fixture.rs"));
+
+ fn build_rule(code: &str) -> cap_i18n_build::PluralRule {
+ LOCALES
+ .iter()
+ .find(|spec| spec.code == code)
+ .map(|spec| spec.plural)
+ .unwrap()
+ }
+
+ fn same(generated: Plural, expected: Category) -> bool {
+ matches!(
+ (generated, expected),
+ (Plural::One, Category::One)
+ | (Plural::Many, Category::Many)
+ | (Plural::Other, Category::Other)
+ )
+ }
+
+ #[test]
+ fn locales_are_generated_from_the_catalog_files() {
+ assert_eq!(Locale::ALL, [Locale::En, Locale::Ja, Locale::Fr]);
+ assert_eq!(Locale::Fr.code(), "fr");
+ assert_eq!(Locale::Ja.endonym(), "日本語");
+ assert_eq!(Locale::from_code("ja"), Some(Locale::Ja));
+ assert_eq!(Locale::from_code("de"), None);
+ assert_eq!(KEYS.len(), 7);
+ assert!(KEYS.windows(2).all(|pair| pair[0] < pair[1]));
+ }
+
+ #[test]
+ fn english_is_the_default() {
+ assert_eq!(tr::common::save(), "Save");
+ assert_eq!(tr::common::braces(), "Use {name} in templates");
+ assert_eq!(tr::common::greeting("Ana"), "Hello, Ana!");
+ assert_eq!(tr::common::meta::title(), "Title");
+ assert_eq!(tr::editor::selection::clips(1), "One clip");
+ assert_eq!(tr::editor::selection::clips(0), "0 clips");
+ assert_eq!(tr::editor::selection::clips(3), "3 clips");
+ assert_eq!(
+ tr::editor::selection::segments(1, "zoom"),
+ "1 zoom segment selected"
+ );
+ assert_eq!(
+ tr::editor::selection::segments(2, "zoom"),
+ "2 zoom segments selected"
+ );
+ }
+
+ #[test]
+ fn switching_locale_switches_text_and_falls_back_to_english() {
+ set(Locale::Fr);
+ assert_eq!(tr::common::save(), "Enregistrer");
+ assert_eq!(tr::common::braces(), "Utilisez {name} dans les modèles");
+ assert_eq!(tr::common::greeting("Ana"), "Bonjour, Ana !");
+ assert_eq!(tr::common::meta::title(), "Titre");
+ assert_eq!(tr::common::untranslated(), "Only in English");
+
+ set(Locale::Ja);
+ assert_eq!(tr::common::save(), "保存");
+ assert_eq!(tr::common::greeting("Ana"), "こんにちは、Anaさん");
+ assert_eq!(tr::common::braces(), "Use {name} in templates");
+ assert_eq!(tr::common::meta::title(), "Title");
+
+ set(Locale::En);
+ assert_eq!(tr::common::save(), "Save");
+ }
+
+ #[test]
+ fn plurals_follow_each_locale_rule() {
+ use self::tr::editor::selection::segments;
+
+ set(Locale::Fr);
+ assert_eq!(segments(0, "zoom"), "0 segment zoom sélectionné");
+ assert_eq!(segments(1, "zoom"), "1 segment zoom sélectionné");
+ assert_eq!(segments(2, "zoom"), "2 segments zoom sélectionnés");
+ assert_eq!(
+ segments(1_000_000, "zoom"),
+ "1000000 de segments zoom sélectionnés"
+ );
+ assert_eq!(tr::editor::selection::clips(0), "Un clip");
+ assert_eq!(tr::editor::selection::clips(2_000_000), "2000000 clips");
+
+ set(Locale::Ja);
+ assert_eq!(segments(1, "ズーム"), "ズームセグメントを1件選択");
+ assert_eq!(tr::editor::selection::clips(1), "1件のクリップ");
+ set(Locale::En);
+ }
+
+ #[test]
+ fn generated_rules_match_the_build_rules() {
+ let samples = (0..2_100).chain([999_999, 1_000_000, 1_000_001, 2_000_000, 7_000_000]);
+ for n in samples {
+ assert!(same(plural_en(n), build_rule("en").category(n)), "en {n}");
+ assert!(same(plural_fr(n), build_rule("fr").category(n)), "fr {n}");
+ }
+ }
+}
diff --git a/apps/desktop-gpui/locales/en.toml b/apps/desktop-gpui/locales/en.toml
new file mode 100644
index 000000000..311f1dae4
--- /dev/null
+++ b/apps/desktop-gpui/locales/en.toml
@@ -0,0 +1,218 @@
+[common]
+add = "Add"
+cancel = "Cancel"
+ok = "OK"
+reset = "Reset"
+reset_to_default = "Reset to Default"
+save = "Save"
+
+[menu.app]
+about = "About Cap"
+hide = "Hide Cap"
+hide_others = "Hide Others"
+quit = "Quit Cap"
+services = "Services"
+
+[menu.file]
+close_window = "Close Window"
+title = "File"
+
+[menu.edit]
+copy = "Copy"
+cut = "Cut"
+paste = "Paste"
+redo = "Redo"
+select_all = "Select All"
+title = "Edit"
+undo = "Undo"
+
+[menu.view]
+enter_full_screen = "Enter Full Screen"
+title = "View"
+
+[menu.window]
+close_window = "Close Window"
+minimize = "Minimize"
+zoom = "Zoom"
+
+[menu.help]
+title = "Help"
+
+[tray]
+import_media = "Import Media..."
+no_recent_items = "No recent items"
+open_main_window = "Open Main Window"
+previous = { text = "Previous", context = "Submenu listing the most recent recordings and screenshots." }
+quit = "Quit Cap"
+record_area = "Record Area"
+record_display = "Record Display"
+record_window = "Record Window"
+request_permissions = "Request Permissions"
+screenshot_area = "Screenshot Area"
+screenshot_display = "Screenshot Display"
+screenshot_window = "Screenshot Window"
+select_mode = "Select Mode"
+settings = "Settings"
+take_screenshot = "Take a Screenshot"
+tooltip_recording = { text = "Cap - Stop Recording", context = "Windows tray tooltip while a recording runs; clicking the icon stops it." }
+upload_logs = "Upload Logs"
+version = { text = "Cap v{version}", context = "Disabled row showing the app version, for example Cap v0.6.1." }
+view_all_recordings = "View all recordings"
+view_all_screenshots = "View all screenshots"
+
+[tray.mode]
+instant = { text = "Instant", context = "Recording mode name." }
+screenshot = { text = "Screenshot", context = "Recording mode name." }
+studio = { text = "Studio", context = "Recording mode name." }
+
+[settings.nav]
+automations = "Automations"
+changelog = "Changelog"
+cli = "CLI"
+experimental = "Experimental"
+feedback = "Feedback"
+general = "General"
+integrations = "Integrations"
+license = "Plan & license"
+quality = "Recording quality"
+recordings = "Recordings"
+screenshots = "Screenshots"
+shortcuts = "Shortcuts"
+transcription = "Transcription"
+
+[settings.general.appearance]
+description = "Match Cap to your system theme or pick a fixed look."
+title = "Appearance"
+
+[settings.general.app]
+description = "Choose how Cap shows up on your system."
+title = "App"
+
+[settings.general.app.dock_icon]
+description = "Keep Cap in the dock even when no windows are open."
+label = "Always show dock icon"
+
+[settings.general.app.notifications]
+description = "Show notifications for clipboard copies, saved files, and more. You may need to allow Cap in your system's notification settings."
+label = "System notifications"
+
+[settings.general.recording]
+description = "Behaviour while you record and after you stop."
+title = "Recording"
+
+[settings.general.recording.countdown]
+description = "Wait before the recording starts."
+label = "Countdown"
+off = "Off"
+seconds_10 = "10 seconds"
+seconds_3 = "3 seconds"
+seconds_5 = "5 seconds"
+
+[settings.general.recording.confirm_without_mic]
+description = "Require confirmation when no microphone is selected or the selected microphone is unavailable."
+label = "Confirm before recording without a microphone"
+
+[settings.general.recording.studio_sound]
+description = "Clean up microphone audio automatically. You can still turn it off for any recording in the editor."
+label = { text = "Studio Sound on new recordings", context = "Studio Sound is the name of Cap's microphone clean-up feature." }
+
+[settings.general.recording.main_window_start]
+description = "What happens to the main window once a recording begins."
+label = "Main window when recording starts"
+
+[settings.general.recording.post_deletion]
+description = "Whether the recording window should reopen."
+label = "After deleting a recording"
+
+[settings.general.recording.delete_after_upload]
+description = "Cap removes the local file once it has uploaded successfully."
+label = "Delete Instant recordings after upload"
+
+[settings.general.recording.crash_recovery]
+description = "Record in fragments that can be recovered after a crash or power loss. Slightly larger files during capture."
+label = "Crash-recoverable recording"
+
+[settings.general.recording.custom_cursor]
+description = "Capture cursor state separately so you can adjust size and smoothing in the editor."
+label = "Custom cursor capture (Studio)"
+
+[settings.general.recording.auto_zoom]
+description = "Automatically add zoom segments around mouse clicks in Studio recordings."
+label = "Auto zoom on clicks"
+
+[settings.general.recording.default_zoom]
+description = "Zoom level for newly created and auto-generated zoom segments."
+label = "Default zoom amount"
+
+[settings.general.recording.capture_keyboard]
+description = "Record key presses so you can add keyboard overlays in the editor."
+label = "Capture keyboard presses"
+
+[settings.general.recording.notch_overlay]
+description = "Automatically restores the notch for new screen and area recordings when the selected region contains the complete notch. External displays, partial areas, and window recordings are left alone. Each recording can override it in the editor."
+label = "Draw the MacBook notch on screen recordings"
+
+[settings.general.recording.max_fps]
+description = "Maximum framerate for screen capture."
+description_high = { text = "Maximum framerate for screen capture. Higher values may cause drops or increased CPU usage on some systems.", context = "Shown instead of the short description when more than 60 FPS is selected." }
+fps_120 = "120 FPS"
+fps_24 = "24 FPS"
+fps_25 = "25 FPS"
+fps_30 = "30 FPS"
+fps_60 = "60 FPS (Recommended)"
+label = "Max capture framerate"
+
+[settings.general.storage]
+choose_folder = "Choose Folder"
+default_location = { text = "Default (Application Support)", context = "Shown in place of a folder path when recordings use the default location." }
+description = "Where Cap saves your recordings."
+title = "Storage"
+
+[settings.general.project_name]
+available_placeholders = "Available placeholders"
+description = "Template used for new recordings and exported files."
+title = "Default project name"
+
+[settings.general.project_name.placeholders]
+date_time = "Date & time"
+date_values = "the recording's date"
+mode_values = { text = "\"studio\", \"instant\", or \"screenshot\"", context = "The quoted words are inserted into file names exactly as written; keep them in English." }
+recording_mode = "Recording mode"
+recording_mode_values = { text = "\"Studio\", \"Instant\", or \"Screenshot\"", context = "The quoted words are inserted into file names exactly as written; keep them in English." }
+target = "Target"
+target_kind_values = { text = "\"Display\", \"Window\", or \"Area\"", context = "The quoted words are inserted into file names exactly as written; keep them in English." }
+target_name_values = "Monitor name or window title."
+time_values = "the recording's time"
+
+[settings.general.excluded_windows]
+description = "Hide windows from recordings."
+empty = "No windows are currently excluded."
+missing_body = { text = "Camera, settings, or recording windows can appear as black boxes in screen recordings. Missing: {names}.", context = "{names} is a comma-separated list of Cap window titles." }
+missing_title = "Recommended Cap windows are not excluded"
+restore = "Restore"
+title = "Excluded windows"
+
+[settings.general.updates]
+description = "Choose which Cap builds you receive."
+nightly_description = "The newest builds, updated automatically in the background when you're not recording or exporting. May be unstable."
+nightly_switch_back = "Switching back to Stable will return you to the latest stable version, which may be older than your current build."
+stable_description = "Versioned releases (recommended)"
+title = "Updates"
+
+[settings.general.updates.channel]
+description = "Which release channel Cap updates from."
+label = "Update channel"
+
+[settings.general.self_host]
+confirm_change = { text = "Are you sure you want to change the server URL to '{origin}'? You will need to sign in again.", context = "{origin} is a URL such as https://cap.example.com." }
+description = "Only change this if you are running your own instance of Cap Web."
+server_url = "Cap Server URL"
+title = "Self-host"
+update = "Update"
+
+[settings.general.privacy]
+title = "Privacy"
+
+[settings.general.privacy.telemetry]
+description = "Cap uses anonymous telemetry to improve reliability and fix bugs. We never collect recording contents, window titles, file paths, or personal information."
+label = "Share anonymous telemetry"
diff --git a/apps/desktop-gpui/src/i18n/mod.rs b/apps/desktop-gpui/src/i18n/mod.rs
new file mode 100644
index 000000000..1a8acea53
--- /dev/null
+++ b/apps/desktop-gpui/src/i18n/mod.rs
@@ -0,0 +1,12 @@
+use std::sync::atomic::{AtomicU8, Ordering};
+
+include!(concat!(env!("OUT_DIR"), "/i18n.rs"));
+
+static CURRENT: AtomicU8 = AtomicU8::new(Locale::En as u8);
+
+fn index() -> usize {
+ CURRENT.load(Ordering::Relaxed) as usize
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/apps/desktop-gpui/src/i18n/tests.rs b/apps/desktop-gpui/src/i18n/tests.rs
new file mode 100644
index 000000000..c041fd646
--- /dev/null
+++ b/apps/desktop-gpui/src/i18n/tests.rs
@@ -0,0 +1,503 @@
+use super::*;
+
+#[test]
+fn english_is_the_default_locale() {
+ assert_eq!(Locale::ALL[index()], Locale::En);
+ assert_eq!(Locale::En.code(), "en");
+ assert_eq!(Locale::from_code("en"), Some(Locale::En));
+}
+
+#[test]
+fn english_matches_the_literals_it_replaced() {
+ let app_name = crate::menus::APP_NAME;
+ let pairs: &[(&str, String)] = &[
+ (tr::common::add(), "Add".into()),
+ (tr::common::cancel(), "Cancel".into()),
+ (tr::common::ok(), "OK".into()),
+ (tr::common::reset(), "Reset".into()),
+ (tr::common::reset_to_default(), "Reset to Default".into()),
+ (tr::common::save(), "Save".into()),
+ (tr::menu::app::about(), format!("About {app_name}")),
+ (tr::menu::app::hide(), format!("Hide {app_name}")),
+ (tr::menu::app::hide_others(), "Hide Others".into()),
+ (tr::menu::app::quit(), format!("Quit {app_name}")),
+ (tr::menu::app::services(), "Services".into()),
+ (tr::menu::file::close_window(), "Close Window".into()),
+ (tr::menu::file::title(), "File".into()),
+ (tr::menu::edit::copy(), "Copy".into()),
+ (tr::menu::edit::cut(), "Cut".into()),
+ (tr::menu::edit::paste(), "Paste".into()),
+ (tr::menu::edit::redo(), "Redo".into()),
+ (tr::menu::edit::select_all(), "Select All".into()),
+ (tr::menu::edit::title(), "Edit".into()),
+ (tr::menu::edit::undo(), "Undo".into()),
+ (
+ tr::menu::view::enter_full_screen(),
+ "Enter Full Screen".into(),
+ ),
+ (tr::menu::view::title(), "View".into()),
+ (tr::menu::window::close_window(), "Close Window".into()),
+ (tr::menu::window::minimize(), "Minimize".into()),
+ (tr::menu::window::zoom(), "Zoom".into()),
+ (tr::menu::help::title(), "Help".into()),
+ (tr::tray::import_media(), "Import Media...".into()),
+ (tr::tray::no_recent_items(), "No recent items".into()),
+ (tr::tray::open_main_window(), "Open Main Window".into()),
+ (tr::tray::previous(), "Previous".into()),
+ (tr::tray::quit(), "Quit Cap".into()),
+ (tr::tray::record_area(), "Record Area".into()),
+ (tr::tray::record_display(), "Record Display".into()),
+ (tr::tray::record_window(), "Record Window".into()),
+ (
+ tr::tray::request_permissions(),
+ "Request Permissions".into(),
+ ),
+ (tr::tray::screenshot_area(), "Screenshot Area".into()),
+ (tr::tray::screenshot_display(), "Screenshot Display".into()),
+ (tr::tray::screenshot_window(), "Screenshot Window".into()),
+ (tr::tray::select_mode(), "Select Mode".into()),
+ (tr::tray::settings(), "Settings".into()),
+ (tr::tray::take_screenshot(), "Take a Screenshot".into()),
+ (tr::tray::tooltip_recording(), "Cap - Stop Recording".into()),
+ (tr::tray::upload_logs(), "Upload Logs".into()),
+ (
+ tr::tray::view_all_recordings(),
+ "View all recordings".into(),
+ ),
+ (
+ tr::tray::view_all_screenshots(),
+ "View all screenshots".into(),
+ ),
+ (tr::tray::mode::instant(), "Instant".into()),
+ (tr::tray::mode::screenshot(), "Screenshot".into()),
+ (tr::tray::mode::studio(), "Studio".into()),
+ (tr::settings::nav::automations(), "Automations".into()),
+ (tr::settings::nav::changelog(), "Changelog".into()),
+ (tr::settings::nav::cli(), "CLI".into()),
+ (tr::settings::nav::experimental(), "Experimental".into()),
+ (tr::settings::nav::feedback(), "Feedback".into()),
+ (tr::settings::nav::general(), "General".into()),
+ (tr::settings::nav::integrations(), "Integrations".into()),
+ (tr::settings::nav::license(), "Plan & license".into()),
+ (tr::settings::nav::quality(), "Recording quality".into()),
+ (tr::settings::nav::recordings(), "Recordings".into()),
+ (tr::settings::nav::screenshots(), "Screenshots".into()),
+ (tr::settings::nav::shortcuts(), "Shortcuts".into()),
+ (tr::settings::nav::transcription(), "Transcription".into()),
+ (
+ tr::settings::general::appearance::description(),
+ "Match Cap to your system theme or pick a fixed look.".into(),
+ ),
+ (
+ tr::settings::general::appearance::title(),
+ "Appearance".into(),
+ ),
+ (
+ tr::settings::general::app::description(),
+ "Choose how Cap shows up on your system.".into(),
+ ),
+ (tr::settings::general::app::title(), "App".into()),
+ (
+ tr::settings::general::app::dock_icon::description(),
+ "Keep Cap in the dock even when no windows are open.".into(),
+ ),
+ (
+ tr::settings::general::app::dock_icon::label(),
+ "Always show dock icon".into(),
+ ),
+ (
+ tr::settings::general::app::notifications::description(),
+ "Show notifications for clipboard copies, saved files, and more. \
+ You may need to allow Cap in your system's notification settings."
+ .into(),
+ ),
+ (
+ tr::settings::general::app::notifications::label(),
+ "System notifications".into(),
+ ),
+ (
+ tr::settings::general::recording::description(),
+ "Behaviour while you record and after you stop.".into(),
+ ),
+ (
+ tr::settings::general::recording::title(),
+ "Recording".into(),
+ ),
+ (
+ tr::settings::general::recording::countdown::description(),
+ "Wait before the recording starts.".into(),
+ ),
+ (
+ tr::settings::general::recording::countdown::label(),
+ "Countdown".into(),
+ ),
+ (
+ tr::settings::general::recording::countdown::off(),
+ "Off".into(),
+ ),
+ (
+ tr::settings::general::recording::countdown::seconds_10(),
+ "10 seconds".into(),
+ ),
+ (
+ tr::settings::general::recording::countdown::seconds_3(),
+ "3 seconds".into(),
+ ),
+ (
+ tr::settings::general::recording::countdown::seconds_5(),
+ "5 seconds".into(),
+ ),
+ (
+ tr::settings::general::recording::confirm_without_mic::description(),
+ "Require confirmation when no microphone is selected or the \
+ selected microphone is unavailable."
+ .into(),
+ ),
+ (
+ tr::settings::general::recording::confirm_without_mic::label(),
+ "Confirm before recording without a microphone".into(),
+ ),
+ (
+ tr::settings::general::recording::studio_sound::description(),
+ "Clean up microphone audio automatically. You can still turn it \
+ off for any recording in the editor."
+ .into(),
+ ),
+ (
+ tr::settings::general::recording::studio_sound::label(),
+ "Studio Sound on new recordings".into(),
+ ),
+ (
+ tr::settings::general::recording::main_window_start::description(),
+ "What happens to the main window once a recording begins.".into(),
+ ),
+ (
+ tr::settings::general::recording::main_window_start::label(),
+ "Main window when recording starts".into(),
+ ),
+ (
+ tr::settings::general::recording::post_deletion::description(),
+ "Whether the recording window should reopen.".into(),
+ ),
+ (
+ tr::settings::general::recording::post_deletion::label(),
+ "After deleting a recording".into(),
+ ),
+ (
+ tr::settings::general::recording::delete_after_upload::description(),
+ "Cap removes the local file once it has uploaded successfully.".into(),
+ ),
+ (
+ tr::settings::general::recording::delete_after_upload::label(),
+ "Delete Instant recordings after upload".into(),
+ ),
+ (
+ tr::settings::general::recording::crash_recovery::description(),
+ "Record in fragments that can be recovered after a crash or power \
+ loss. Slightly larger files during capture."
+ .into(),
+ ),
+ (
+ tr::settings::general::recording::crash_recovery::label(),
+ "Crash-recoverable recording".into(),
+ ),
+ (
+ tr::settings::general::recording::custom_cursor::description(),
+ "Capture cursor state separately so you can adjust size and \
+ smoothing in the editor."
+ .into(),
+ ),
+ (
+ tr::settings::general::recording::custom_cursor::label(),
+ "Custom cursor capture (Studio)".into(),
+ ),
+ (
+ tr::settings::general::recording::auto_zoom::description(),
+ "Automatically add zoom segments around mouse clicks in Studio \
+ recordings."
+ .into(),
+ ),
+ (
+ tr::settings::general::recording::auto_zoom::label(),
+ "Auto zoom on clicks".into(),
+ ),
+ (
+ tr::settings::general::recording::default_zoom::description(),
+ "Zoom level for newly created and auto-generated zoom segments.".into(),
+ ),
+ (
+ tr::settings::general::recording::default_zoom::label(),
+ "Default zoom amount".into(),
+ ),
+ (
+ tr::settings::general::recording::capture_keyboard::description(),
+ "Record key presses so you can add keyboard overlays in the editor.".into(),
+ ),
+ (
+ tr::settings::general::recording::capture_keyboard::label(),
+ "Capture keyboard presses".into(),
+ ),
+ (
+ tr::settings::general::recording::notch_overlay::description(),
+ "Automatically restores the notch for new screen and area \
+ recordings when the selected region contains the complete notch. \
+ External displays, partial areas, and window recordings are left \
+ alone. Each recording can override it in the editor."
+ .into(),
+ ),
+ (
+ tr::settings::general::recording::notch_overlay::label(),
+ "Draw the MacBook notch on screen recordings".into(),
+ ),
+ (
+ tr::settings::general::recording::max_fps::description(),
+ "Maximum framerate for screen capture.".into(),
+ ),
+ (
+ tr::settings::general::recording::max_fps::description_high(),
+ "Maximum framerate for screen capture. Higher values may cause \
+ drops or increased CPU usage on some systems."
+ .into(),
+ ),
+ (
+ tr::settings::general::recording::max_fps::fps_120(),
+ "120 FPS".into(),
+ ),
+ (
+ tr::settings::general::recording::max_fps::fps_24(),
+ "24 FPS".into(),
+ ),
+ (
+ tr::settings::general::recording::max_fps::fps_25(),
+ "25 FPS".into(),
+ ),
+ (
+ tr::settings::general::recording::max_fps::fps_30(),
+ "30 FPS".into(),
+ ),
+ (
+ tr::settings::general::recording::max_fps::fps_60(),
+ "60 FPS (Recommended)".into(),
+ ),
+ (
+ tr::settings::general::recording::max_fps::label(),
+ "Max capture framerate".into(),
+ ),
+ (
+ tr::settings::general::storage::choose_folder(),
+ "Choose Folder".into(),
+ ),
+ (
+ tr::settings::general::storage::default_location(),
+ "Default (Application Support)".into(),
+ ),
+ (
+ tr::settings::general::storage::description(),
+ "Where Cap saves your recordings.".into(),
+ ),
+ (tr::settings::general::storage::title(), "Storage".into()),
+ (
+ tr::settings::general::project_name::available_placeholders(),
+ "Available placeholders".into(),
+ ),
+ (
+ tr::settings::general::project_name::description(),
+ "Template used for new recordings and exported files.".into(),
+ ),
+ (
+ tr::settings::general::project_name::title(),
+ "Default project name".into(),
+ ),
+ (
+ tr::settings::general::project_name::placeholders::date_time(),
+ "Date & time".into(),
+ ),
+ (
+ tr::settings::general::project_name::placeholders::date_values(),
+ "the recording's date".into(),
+ ),
+ (
+ tr::settings::general::project_name::placeholders::mode_values(),
+ "\"studio\", \"instant\", or \"screenshot\"".into(),
+ ),
+ (
+ tr::settings::general::project_name::placeholders::recording_mode(),
+ "Recording mode".into(),
+ ),
+ (
+ tr::settings::general::project_name::placeholders::recording_mode_values(),
+ "\"Studio\", \"Instant\", or \"Screenshot\"".into(),
+ ),
+ (
+ tr::settings::general::project_name::placeholders::target(),
+ "Target".into(),
+ ),
+ (
+ tr::settings::general::project_name::placeholders::target_kind_values(),
+ "\"Display\", \"Window\", or \"Area\"".into(),
+ ),
+ (
+ tr::settings::general::project_name::placeholders::target_name_values(),
+ "Monitor name or window title.".into(),
+ ),
+ (
+ tr::settings::general::project_name::placeholders::time_values(),
+ "the recording's time".into(),
+ ),
+ (
+ tr::settings::general::excluded_windows::description(),
+ "Hide windows from recordings.".into(),
+ ),
+ (
+ tr::settings::general::excluded_windows::empty(),
+ "No windows are currently excluded.".into(),
+ ),
+ (
+ tr::settings::general::excluded_windows::missing_title(),
+ "Recommended Cap windows are not excluded".into(),
+ ),
+ (
+ tr::settings::general::excluded_windows::restore(),
+ "Restore".into(),
+ ),
+ (
+ tr::settings::general::excluded_windows::title(),
+ "Excluded windows".into(),
+ ),
+ (
+ tr::settings::general::updates::description(),
+ "Choose which Cap builds you receive.".into(),
+ ),
+ (
+ tr::settings::general::updates::nightly_description(),
+ "The newest builds, updated automatically in the background when you're \
+ not recording or exporting. May be unstable."
+ .into(),
+ ),
+ (
+ tr::settings::general::updates::nightly_switch_back(),
+ "Switching back to Stable will return you to the latest \
+ stable version, which may be older than your current build."
+ .into(),
+ ),
+ (
+ tr::settings::general::updates::stable_description(),
+ "Versioned releases (recommended)".into(),
+ ),
+ (tr::settings::general::updates::title(), "Updates".into()),
+ (
+ tr::settings::general::updates::channel::description(),
+ "Which release channel Cap updates from.".into(),
+ ),
+ (
+ tr::settings::general::updates::channel::label(),
+ "Update channel".into(),
+ ),
+ (
+ tr::settings::general::self_host::description(),
+ "Only change this if you are running your own instance of Cap Web.".into(),
+ ),
+ (
+ tr::settings::general::self_host::server_url(),
+ "Cap Server URL".into(),
+ ),
+ (
+ tr::settings::general::self_host::title(),
+ "Self-host".into(),
+ ),
+ (tr::settings::general::self_host::update(), "Update".into()),
+ (tr::settings::general::privacy::title(), "Privacy".into()),
+ (
+ tr::settings::general::privacy::telemetry::description(),
+ "Cap uses anonymous telemetry to improve reliability and fix bugs. We \
+ never collect recording contents, window titles, file paths, or \
+ personal information."
+ .into(),
+ ),
+ (
+ tr::settings::general::privacy::telemetry::label(),
+ "Share anonymous telemetry".into(),
+ ),
+ ];
+ for (translated, literal) in pairs {
+ assert_eq!(*translated, literal.as_str());
+ }
+ let plain_keys = KEYS.len() - 3;
+ assert_eq!(
+ pairs.len(),
+ plain_keys,
+ "every plain key has a literal above"
+ );
+}
+
+#[test]
+fn english_messages_format_like_the_literals_they_replaced() {
+ let version = "0.6.1";
+ assert_eq!(tr::tray::version(version), format!("Cap v{version}"));
+ let names = "Cap Camera, Cap Settings".to_string();
+ assert_eq!(
+ tr::settings::general::excluded_windows::missing_body(&names),
+ format!(
+ "Camera, settings, or recording windows can appear as black \
+ boxes in screen recordings. Missing: {names}."
+ )
+ );
+ let origin = "https://cap.example.com";
+ assert_eq!(
+ tr::settings::general::self_host::confirm_change(origin),
+ format!(
+ "Are you sure you want to change the server URL to '{origin}'? You will need \
+ to sign in again."
+ )
+ );
+}
+
+#[test]
+fn prompt_buttons_keep_their_roles() {
+ assert_eq!(
+ gpui::PromptButton::ok(tr::common::ok()),
+ gpui::PromptButton::from("Ok")
+ );
+ assert_eq!(
+ gpui::PromptButton::cancel(tr::common::cancel()),
+ gpui::PromptButton::from("Cancel")
+ );
+}
+
+#[test]
+fn every_key_is_used_outside_the_catalog() {
+ let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
+ let i18n = src.join("i18n");
+ let mut sources = String::new();
+ let mut pending = vec![src];
+ while let Some(dir) = pending.pop() {
+ for entry in std::fs::read_dir(&dir).unwrap() {
+ let path = entry.unwrap().path();
+ if path.is_dir() {
+ if path != i18n {
+ pending.push(path);
+ }
+ } else if path.extension().is_some_and(|extension| extension == "rs") {
+ sources.push_str(&std::fs::read_to_string(&path).unwrap());
+ sources.push('\n');
+ }
+ }
+ }
+ let unused: Vec<&str> = KEYS
+ .iter()
+ .copied()
+ .filter(|key| {
+ let accessor = format!("tr::{}", key.replace('.', "::"));
+ !sources.match_indices(&accessor).any(|(at, _)| {
+ sources[at + accessor.len()..]
+ .chars()
+ .next()
+ .is_none_or(|next| !(next.is_ascii_alphanumeric() || next == '_'))
+ })
+ })
+ .collect();
+ assert!(
+ unused.is_empty(),
+ "keys in locales/en.toml that no code reads: {unused:?}"
+ );
+}
diff --git a/apps/desktop-gpui/src/main.rs b/apps/desktop-gpui/src/main.rs
index 10cdb7b09..457de903f 100644
--- a/apps/desktop-gpui/src/main.rs
+++ b/apps/desktop-gpui/src/main.rs
@@ -41,6 +41,7 @@ mod editor_timeline;
mod editor_window;
mod feeds;
mod hotkeys;
+mod i18n;
mod import;
mod installer;
mod library;
diff --git a/apps/desktop-gpui/src/menus.rs b/apps/desktop-gpui/src/menus.rs
index 8e3996369..60e700b49 100644
--- a/apps/desktop-gpui/src/menus.rs
+++ b/apps/desktop-gpui/src/menus.rs
@@ -26,6 +26,7 @@ use gpui::{
use crate::{
app_windows::{self, AppWindows},
+ i18n::tr,
main_window::MainWindow,
platform,
session::{Phase, RecordingSession},
@@ -34,7 +35,7 @@ use crate::{
};
/// `productName` in `tauri.conf.json`, which is what macOS renames the first
-/// submenu to and what the About/Hide/Quit labels interpolate.
+/// submenu to.
pub const APP_NAME: &str = "Cap";
/// `env!("CARGO_PKG_VERSION")`, exactly as `build_tray_menu` spells it -- this
@@ -123,23 +124,26 @@ pub fn build_menus() -> Vec<Menu> {
name: APP_NAME.into(),
disabled: false,
items: vec![
- MenuItem::action(format!("About {APP_NAME}"), About),
+ MenuItem::action(tr::menu::app::about(), About),
MenuItem::separator(),
- MenuItem::os_submenu("Services", SystemMenuType::Services),
+ MenuItem::os_submenu(tr::menu::app::services(), SystemMenuType::Services),
MenuItem::separator(),
- MenuItem::action(format!("Hide {APP_NAME}"), HideSelf),
- MenuItem::action("Hide Others", HideOthers),
+ MenuItem::action(tr::menu::app::hide(), HideSelf),
+ MenuItem::action(tr::menu::app::hide_others(), HideOthers),
MenuItem::separator(),
- MenuItem::action(format!("Quit {APP_NAME}"), Quit),
+ MenuItem::action(tr::menu::app::quit(), Quit),
],
},
Menu {
- name: "File".into(),
+ name: tr::menu::file::title().into(),
disabled: false,
- items: vec![MenuItem::action("Close Window", CloseWindow)],
+ items: vec![MenuItem::action(
+ tr::menu::file::close_window(),
+ CloseWindow,
+ )],
},
Menu {
- name: "Edit".into(),
+ name: tr::menu::edit::title().into(),
disabled: false,
// The text field's own actions, tagged with the AppKit selector
// that belongs to each. gpui routes `cut:`/`copy:`/`paste:`/
@@ -147,17 +151,21 @@ pub fn build_menus() -> Vec<Menu> {
// `cx.dispatch_action`, so all six land in whatever element holds
// focus -- there is no separate "menu implementation" of copy.
items: vec![
- MenuItem::os_action("Undo", text_input::Undo, OsAction::Undo),
- MenuItem::os_action("Redo", text_input::Redo, OsAction::Redo),
+ MenuItem::os_action(tr::menu::edit::undo(), text_input::Undo, OsAction::Undo),
+ MenuItem::os_action(tr::menu::edit::redo(), text_input::Redo, OsAction::Redo),
MenuItem::separator(),
- MenuItem::os_action("Cut", text_input::Cut, OsAction::Cut),
- MenuItem::os_action("Copy", text_input::Copy, OsAction::Copy),
- MenuItem::os_action("Paste", text_input::Paste, OsAction::Paste),
- MenuItem::os_action("Select All", text_input::SelectAll, OsAction::SelectAll),
+ MenuItem::os_action(tr::menu::edit::cut(), text_input::Cut, OsAction::Cut),
+ MenuItem::os_action(tr::menu::edit::copy(), text_input::Copy, OsAction::Copy),
+ MenuItem::os_action(tr::menu::edit::paste(), text_input::Paste, OsAction::Paste),
+ MenuItem::os_action(
+ tr::menu::edit::select_all(),
+ text_input::SelectAll,
+ OsAction::SelectAll,
+ ),
],
},
Menu {
- name: "View".into(),
+ name: tr::menu::view::title().into(),
disabled: false,
// muda's own string for this item is "Toggle Full Screen"; AppKit
// relabels any item wired to `toggleFullScreen:` to "Enter Full
@@ -165,20 +173,26 @@ pub fn build_menus() -> Vec<Menu> {
// a gpui action rather than that selector, so the title is written
// out -- and, unlike the shipping one, does not flip to "Exit Full
// Screen" while fullscreen (noted deviation).
- items: vec![MenuItem::action("Enter Full Screen", ToggleFullscreen)],
+ items: vec![MenuItem::action(
+ tr::menu::view::enter_full_screen(),
+ ToggleFullscreen,
+ )],
},
Menu {
+ // gpui_macos hands this menu to `setWindowsMenu:` only when its
+ // title is exactly "Window" (platform.rs:274), so it stays English
+ // until the menu is registered by hand.
name: "Window".into(),
disabled: false,
items: vec![
- MenuItem::action("Minimize", Minimize),
- MenuItem::action("Zoom", Zoom),
+ MenuItem::action(tr::menu::window::minimize(), Minimize),
+ MenuItem::action(tr::menu::window::zoom(), Zoom),
MenuItem::separator(),
- MenuItem::action("Close Window", CloseWindow),
+ MenuItem::action(tr::menu::window::close_window(), CloseWindow),
],
},
Menu {
- name: "Help".into(),
+ name: tr::menu::help::title().into(),
disabled: false,
items: vec![],
},
diff --git a/apps/desktop-gpui/src/settings_window.rs b/apps/desktop-gpui/src/settings_window.rs
index 52d2a2fd3..a8a3b088b 100644
--- a/apps/desktop-gpui/src/settings_window.rs
+++ b/apps/desktop-gpui/src/settings_window.rs
@@ -24,6 +24,7 @@ use serde_json::Value;
use crate::{
devices::WindowOption,
+ i18n::tr,
library::{self, RecordingItem, RecordingMode, ScreenshotItem},
main_window::Mode,
sign_in::{SignIn, SignInEvent, SignInOrigin, SignInOutcome},
@@ -115,19 +116,19 @@ impl Page {
/// and the route disagree in the shipping app.
fn label(self) -> &'static str {
match self {
- Self::General => "General",
- Self::Quality => "Recording quality",
- Self::Shortcuts => "Shortcuts",
- Self::Cli => "CLI",
- Self::Recordings => "Recordings",
- Self::Screenshots => "Screenshots",
- Self::Automations => "Automations",
- Self::Transcription => "Transcription",
- Self::Integrations => "Integrations",
- Self::License => "Plan & license",
- Self::Experimental => "Experimental",
- Self::Feedback => "Feedback",
- Self::Changelog => "Changelog",
+ Self::General => tr::settings::nav::general(),
+ Self::Quality => tr::settings::nav::quality(),
+ Self::Shortcuts => tr::settings::nav::shortcuts(),
+ Self::Cli => tr::settings::nav::cli(),
+ Self::Recordings => tr::settings::nav::recordings(),
+ Self::Screenshots => tr::settings::nav::screenshots(),
+ Self::Automations => tr::settings::nav::automations(),
+ Self::Transcription => tr::settings::nav::transcription(),
+ Self::Integrations => tr::settings::nav::integrations(),
+ Self::License => tr::settings::nav::license(),
+ Self::Experimental => tr::settings::nav::experimental(),
+ Self::Feedback => tr::settings::nav::feedback(),
+ Self::Changelog => tr::settings::nav::changelog(),
}
}
@@ -218,20 +219,20 @@ struct OpenMenu {
}
/// `MAX_FPS_OPTIONS` in general.tsx.
-const MAX_FPS_OPTIONS: &[(u32, &str)] = &[
- (24, "24 FPS"),
- (25, "25 FPS"),
- (30, "30 FPS"),
- (60, "60 FPS (Recommended)"),
- (120, "120 FPS"),
+const MAX_FPS_OPTIONS: &[(u32, fn() -> &'static str)] = &[
+ (24, tr::settings::general::recording::max_fps::fps_24),
+ (25, tr::settings::general::recording::max_fps::fps_25),
+ (30, tr::settings::general::recording::max_fps::fps_30),
+ (60, tr::settings::general::recording::max_fps::fps_60),
+ (120, tr::settings::general::recording::max_fps::fps_120),
];
/// The Countdown select's options.
-const COUNTDOWN_OPTIONS: &[(u32, &str)] = &[
- (0, "Off"),
- (3, "3 seconds"),
- (5, "5 seconds"),
- (10, "10 seconds"),
+const COUNTDOWN_OPTIONS: &[(u32, fn() -> &'static str)] = &[
+ (0, tr::settings::general::recording::countdown::off),
+ (3, tr::settings::general::recording::countdown::seconds_3),
+ (5, tr::settings::general::recording::countdown::seconds_5),
+ (10, tr::settings::general::recording::countdown::seconds_10),
];
const STUDIO_QUALITY_TIERS: &[(StudioQuality, &str, &str)] = &[
@@ -276,12 +277,14 @@ enum InstantQualityNotice {
}
/// `UPDATE_CHANNEL_OPTIONS`.
-const UPDATE_CHANNEL_DESCRIPTIONS: &[(UpdateChannel, &str)] = &[
- (UpdateChannel::Stable, "Versioned releases (recommended)"),
+const UPDATE_CHANNEL_DESCRIPTIONS: &[(UpdateChannel, fn() -> &'static str)] = &[
+ (
+ UpdateChannel::Stable,
+ tr::settings::general::updates::stable_description,
+ ),
(
UpdateChannel::Nightly,
- "The newest builds, updated automatically in the background when you're \
- not recording or exporting. May be unstable.",
+ tr::settings::general::updates::nightly_description,
),
];
@@ -1391,12 +1394,12 @@ impl SettingsWindow {
let current = self.settings.recording_countdown.unwrap_or(0);
COUNTDOWN_OPTIONS
.iter()
- .map(|(value, label)| ui::MenuItem::new(*label, *value == current))
+ .map(|(value, label)| ui::MenuItem::new(label(), *value == current))
.collect()
}
MenuKind::MaxFps => MAX_FPS_OPTIONS
.iter()
- .map(|(value, label)| ui::MenuItem::new(*label, *value == self.settings.max_fps))
+ .map(|(value, label)| ui::MenuItem::new(label(), *value == self.settings.max_fps))
.collect(),
MenuKind::MainWindowStart => {
enum_items(self.settings.main_window_recording_start_behaviour)
@@ -3030,8 +3033,8 @@ impl SettingsWindow {
}));
self.section(
- "Appearance",
- Some("Match Cap to your system theme or pick a fixed look."),
+ tr::settings::general::appearance::title(),
+ Some(tr::settings::general::appearance::description()),
None,
vec![self.card(true).child(tiles).into_any_element()],
)
@@ -3040,14 +3043,14 @@ impl SettingsWindow {
/// The macOS-only App section: `hideDockIcon`, `enableNotifications`.
fn render_app_section(&self, cx: &mut Context<Self>) -> impl IntoElement {
self.section(
- "App",
- Some("Choose how Cap shows up on your system."),
+ tr::settings::general::app::title(),
+ Some(tr::settings::general::app::description()),
None,
vec![
self.rows(vec![
self.setting_row(
- "Always show dock icon",
- Some("Keep Cap in the dock even when no windows are open."),
+ tr::settings::general::app::dock_icon::label(),
+ Some(tr::settings::general::app::dock_icon::description()),
// The row is the *inverse* of the stored key.
self.toggle(
"hide-dock-icon",
@@ -3067,11 +3070,8 @@ impl SettingsWindow {
.into_any_element(),
),
self.setting_row(
- "System notifications",
- Some(
- "Show notifications for clipboard copies, saved files, and more. \
- You may need to allow Cap in your system's notification settings.",
- ),
+ tr::settings::general::app::notifications::label(),
+ Some(tr::settings::general::app::notifications::description()),
self.toggle(
"enable-notifications",
self.settings.enable_notifications,
@@ -3386,33 +3386,30 @@ impl SettingsWindow {
let countdown_label = COUNTDOWN_OPTIONS
.iter()
.find(|(value, _)| *value == settings.recording_countdown.unwrap_or(0))
- .map(|(_, label)| (*label).to_string())
+ .map(|(_, label)| label().to_string())
.unwrap_or_else(|| settings.recording_countdown.unwrap_or(0).to_string());
let fps_label = MAX_FPS_OPTIONS
.iter()
.find(|(value, _)| *value == settings.max_fps)
- .map(|(_, label)| (*label).to_string())
+ .map(|(_, label)| label().to_string())
.unwrap_or_else(|| settings.max_fps.to_string());
let zoom = settings.default_zoom_amount.unwrap_or(1.5);
self.section(
- "Recording",
- Some("Behaviour while you record and after you stop."),
+ tr::settings::general::recording::title(),
+ Some(tr::settings::general::recording::description()),
None,
vec![
self.rows(vec![
self.setting_row(
- "Countdown",
- Some("Wait before the recording starts."),
+ tr::settings::general::recording::countdown::label(),
+ Some(tr::settings::general::recording::countdown::description()),
self.select("countdown", countdown_label, MenuKind::Countdown, cx)
.into_any_element(),
),
self.setting_row(
- "Confirm before recording without a microphone",
- Some(
- "Require confirmation when no microphone is selected or the \
- selected microphone is unavailable.",
- ),
+ tr::settings::general::recording::confirm_without_mic::label(),
+ Some(tr::settings::general::recording::confirm_without_mic::description()),
self.toggle(
"confirm-without-mic",
settings.confirm_without_microphone,
@@ -3434,11 +3431,8 @@ impl SettingsWindow {
.into_any_element(),
),
self.setting_row(
- "Studio Sound on new recordings",
- Some(
- "Clean up microphone audio automatically. You can still turn it \
- off for any recording in the editor.",
- ),
+ tr::settings::general::recording::studio_sound::label(),
+ Some(tr::settings::general::recording::studio_sound::description()),
self.toggle(
"studio-sound-default",
settings.studio_sound_by_default,
@@ -3454,8 +3448,8 @@ impl SettingsWindow {
.into_any_element(),
),
self.setting_row(
- "Main window when recording starts",
- Some("What happens to the main window once a recording begins."),
+ tr::settings::general::recording::main_window_start::label(),
+ Some(tr::settings::general::recording::main_window_start::description()),
self.select(
"main-window-start",
settings.main_window_recording_start_behaviour.label(),
@@ -3470,8 +3464,8 @@ impl SettingsWindow {
// `showOverlay` means "reshow the main window"
// (`app_windows.rs`) and is labelled "Show Cap".
self.setting_row(
- "After deleting a recording",
- Some("Whether the recording window should reopen."),
+ tr::settings::general::recording::post_deletion::label(),
+ Some(tr::settings::general::recording::post_deletion::description()),
self.select(
"post-deletion",
settings.post_deletion_behaviour.label(),
@@ -3481,8 +3475,8 @@ impl SettingsWindow {
.into_any_element(),
),
self.setting_row(
- "Delete Instant recordings after upload",
- Some("Cap removes the local file once it has uploaded successfully."),
+ tr::settings::general::recording::delete_after_upload::label(),
+ Some(tr::settings::general::recording::delete_after_upload::description()),
self.toggle(
"delete-after-upload",
settings.delete_instant_recordings_after_upload,
@@ -3497,11 +3491,8 @@ impl SettingsWindow {
.into_any_element(),
),
self.setting_row(
- "Crash-recoverable recording",
- Some(
- "Record in fragments that can be recovered after a crash or power \
- loss. Slightly larger files during capture.",
- ),
+ tr::settings::general::recording::crash_recovery::label(),
+ Some(tr::settings::general::recording::crash_recovery::description()),
self.toggle(
"crash-recovery",
settings.crash_recovery_recording,
@@ -3516,11 +3507,8 @@ impl SettingsWindow {
.into_any_element(),
),
self.setting_row(
- "Custom cursor capture (Studio)",
- Some(
- "Capture cursor state separately so you can adjust size and \
- smoothing in the editor.",
- ),
+ tr::settings::general::recording::custom_cursor::label(),
+ Some(tr::settings::general::recording::custom_cursor::description()),
self.toggle(
"custom-cursor",
settings.custom_cursor_capture,
@@ -3535,11 +3523,8 @@ impl SettingsWindow {
.into_any_element(),
),
self.setting_row(
- "Auto zoom on clicks",
- Some(
- "Automatically add zoom segments around mouse clicks in Studio \
- recordings.",
- ),
+ tr::settings::general::recording::auto_zoom::label(),
+ Some(tr::settings::general::recording::auto_zoom::description()),
self.toggle("auto-zoom", settings.auto_zoom_on_clicks, cx, |this, cx| {
this.settings.auto_zoom_on_clicks = !this.settings.auto_zoom_on_clicks;
let value = this.settings.auto_zoom_on_clicks;
@@ -3548,8 +3533,8 @@ impl SettingsWindow {
.into_any_element(),
),
self.setting_row(
- "Default zoom amount",
- Some("Zoom level for newly created and auto-generated zoom segments."),
+ tr::settings::general::recording::default_zoom::label(),
+ Some(tr::settings::general::recording::default_zoom::description()),
div()
// `flex gap-2 items-center w-52`
.flex()
@@ -3569,8 +3554,8 @@ impl SettingsWindow {
.into_any_element(),
),
self.setting_row(
- "Capture keyboard presses",
- Some("Record key presses so you can add keyboard overlays in the editor."),
+ tr::settings::general::recording::capture_keyboard::label(),
+ Some(tr::settings::general::recording::capture_keyboard::description()),
self.toggle(
"capture-keyboard",
settings.capture_keyboard_events,
@@ -3585,13 +3570,8 @@ impl SettingsWindow {
.into_any_element(),
),
self.setting_row(
- "Draw the MacBook notch on screen recordings",
- Some(
- "Automatically restores the notch for new screen and area \
- recordings when the selected region contains the complete notch. \
- External displays, partial areas, and window recordings are left \
- alone. Each recording can override it in the editor.",
- ),
+ tr::settings::general::recording::notch_overlay::label(),
+ Some(tr::settings::general::recording::notch_overlay::description()),
self.toggle(
"notch-overlay",
settings.macbook_notch_overlay,
@@ -3606,12 +3586,11 @@ impl SettingsWindow {
.into_any_element(),
),
self.setting_row(
- "Max capture framerate",
+ tr::settings::general::recording::max_fps::label(),
Some(if settings.max_fps > 60 {
- "Maximum framerate for screen capture. Higher values may cause \
- drops or increased CPU usage on some systems."
+ tr::settings::general::recording::max_fps::description_high()
} else {
- "Maximum framerate for screen capture."
+ tr::settings::general::recording::max_fps::description()
}),
self.select("max-fps", fps_label, MenuKind::MaxFps, cx)
.into_any_element(),
@@ -3628,14 +3607,15 @@ impl SettingsWindow {
let path = self.settings.recordings_path.clone();
let is_custom = path.is_some();
// `Default (Application Support)`
- let display = path.unwrap_or_else(|| "Default (Application Support)".to_string());
+ let display =
+ path.unwrap_or_else(|| tr::settings::general::storage::default_location().to_string());
let mut actions = div().flex().flex_row().justify_end().gap(px(8.));
if is_custom {
actions = actions.child(self.button(
"recordings-reset",
(ui::ButtonVariant::Gray, None),
- "Reset to Default",
+ tr::common::reset_to_default(),
false,
cx,
|this, _window, cx| {
@@ -3647,7 +3627,7 @@ impl SettingsWindow {
actions = actions.child(self.button(
"recordings-pick",
(ui::ButtonVariant::Dark, None),
- "Choose Folder",
+ tr::settings::general::storage::choose_folder(),
false,
cx,
|_, window, cx| {
@@ -3678,8 +3658,8 @@ impl SettingsWindow {
));
self.section(
- "Storage",
- Some("Where Cap saves your recordings."),
+ tr::settings::general::storage::title(),
+ Some(tr::settings::general::storage::description()),
None,
vec![
self.card(true)
@@ -3740,7 +3720,7 @@ impl SettingsWindow {
.child(self.button(
"project-name-reset",
(ui::ButtonVariant::Gray, None),
- "Reset",
+ tr::common::reset(),
reset_disabled,
cx,
|this, _window, cx| {
@@ -3756,7 +3736,7 @@ impl SettingsWindow {
.child(self.button(
"project-name-save",
(ui::ButtonVariant::Dark, None),
- "Save",
+ tr::common::save(),
save_disabled,
cx,
|this, _window, cx| {
@@ -3769,19 +3749,35 @@ impl SettingsWindow {
let placeholder_rows: Vec<(&str, &str, &str)> = vec![
(
- "Recording mode",
+ tr::settings::general::project_name::placeholders::recording_mode(),
"{recording_mode}",
- "\"Studio\", \"Instant\", or \"Screenshot\"",
+ tr::settings::general::project_name::placeholders::recording_mode_values(),
+ ),
+ (
+ "",
+ "{mode}",
+ tr::settings::general::project_name::placeholders::mode_values(),
),
- ("", "{mode}", "\"studio\", \"instant\", or \"screenshot\""),
(
- "Target",
+ tr::settings::general::project_name::placeholders::target(),
"{target_kind}",
- "\"Display\", \"Window\", or \"Area\"",
+ tr::settings::general::project_name::placeholders::target_kind_values(),
+ ),
+ (
+ "",
+ "{target_name}",
+ tr::settings::general::project_name::placeholders::target_name_values(),
+ ),
+ (
+ tr::settings::general::project_name::placeholders::date_time(),
+ "{date}",
+ tr::settings::general::project_name::placeholders::date_values(),
+ ),
+ (
+ "",
+ "{time}",
+ tr::settings::general::project_name::placeholders::time_values(),
),
- ("", "{target_name}", "Monitor name or window title."),
- ("Date & time", "{date}", "the recording's date"),
- ("", "{time}", "the recording's time"),
];
let body = div()
@@ -3829,7 +3825,7 @@ impl SettingsWindow {
.size(px(14.))
.text_color(theme.settings_muted()),
)
- .child("Available placeholders")
+ .child(tr::settings::general::project_name::available_placeholders())
.on_click(cx.listener(|this, _, _window, cx| {
this.toggle_placeholders(cx);
})),
@@ -3894,8 +3890,8 @@ impl SettingsWindow {
);
self.section(
- "Default project name",
- Some("Template used for new recordings and exported files."),
+ tr::settings::general::project_name::title(),
+ Some(tr::settings::general::project_name::description()),
Some(right),
vec![self.card(true).child(body).into_any_element()],
)
@@ -3914,7 +3910,7 @@ impl SettingsWindow {
.child(self.button(
"exclusions-reset",
(ui::ButtonVariant::Gray, None),
- "Reset",
+ tr::common::reset(),
false,
cx,
|this, _window, cx| {
@@ -3925,7 +3921,7 @@ impl SettingsWindow {
self.button(
"exclusions-add",
(ui::ButtonVariant::Dark, Some("icons/plus.svg")),
- "Add",
+ tr::common::add(),
self.windows.is_empty(),
cx,
|_, _, _| {},
@@ -3944,7 +3940,7 @@ impl SettingsWindow {
div()
.text_size(px(12.))
.text_color(theme.settings_muted())
- .child("No windows are currently excluded.")
+ .child(tr::settings::general::excluded_windows::empty())
.into_any_element()
} else {
div()
@@ -4020,6 +4016,8 @@ impl SettingsWindow {
.map(|entry| entry.primary_label().to_string())
.collect::<Vec<_>>()
.join(", ");
+ let missing_title = tr::settings::general::excluded_windows::missing_title();
+ let missing_body = tr::settings::general::excluded_windows::missing_body(names);
card = card.child(
// `mb-3 rounded-lg border border-amber-6 bg-amber-3/30 px-3 py-2.5`
div()
@@ -4054,17 +4052,19 @@ impl SettingsWindow {
div()
.text_size(px(12.))
.font_weight(FontWeight::MEDIUM)
- .child("Recommended Cap windows are not excluded"),
+ .child(missing_title),
)
- .child(div().text_size(px(10.)).line_height(px(14.)).child(format!(
- "Camera, settings, or recording windows can appear as black \
- boxes in screen recordings. Missing: {names}."
- ))),
+ .child(
+ div()
+ .text_size(px(10.))
+ .line_height(px(14.))
+ .child(missing_body),
+ ),
)
.child(self.button(
"exclusions-restore",
(ui::ButtonVariant::Gray, None),
- "Restore",
+ tr::settings::general::excluded_windows::restore(),
false,
cx,
|this, _window, cx| {
@@ -4075,8 +4075,8 @@ impl SettingsWindow {
}
self.section(
- "Excluded windows",
- Some("Hide windows from recordings."),
+ tr::settings::general::excluded_windows::title(),
+ Some(tr::settings::general::excluded_windows::description()),
Some(right),
vec![card.child(chips).into_any_element()],
)
@@ -4089,7 +4089,7 @@ impl SettingsWindow {
let description = UPDATE_CHANNEL_DESCRIPTIONS
.iter()
.find(|(channel, _)| *channel == current)
- .map(|(_, description)| *description)
+ .map(|(_, description)| description())
.unwrap_or_default();
let body = div()
@@ -4111,13 +4111,17 @@ impl SettingsWindow {
.flex_col()
.gap(px(2.))
.min_w_0()
- .child(div().text_size(px(13.)).child("Update channel"))
+ .child(
+ div()
+ .text_size(px(13.))
+ .child(tr::settings::general::updates::channel::label()),
+ )
.child(
div()
.text_size(px(12.))
.line_height(px(16.))
.text_color(theme.settings_muted())
- .child("Which release channel Cap updates from."),
+ .child(tr::settings::general::updates::channel::description()),
),
)
.child(self.segmented::<UpdateChannel>(
@@ -4146,17 +4150,14 @@ impl SettingsWindow {
.text_size(px(11.))
.line_height(px(15.))
.text_color(theme.settings_muted())
- .child(
- "Switching back to Stable will return you to the latest \
- stable version, which may be older than your current build.",
- ),
+ .child(tr::settings::general::updates::nightly_switch_back()),
)
}),
);
self.section(
- "Updates",
- Some("Choose which Cap builds you receive."),
+ tr::settings::general::updates::title(),
+ Some(tr::settings::general::updates::description()),
None,
vec![self.card(false).child(body).into_any_element()],
)
@@ -4176,7 +4177,11 @@ impl SettingsWindow {
.flex()
.flex_col()
.gap(px(6.))
- .child(div().text_size(px(13.)).child("Cap Server URL"))
+ .child(
+ div()
+ .text_size(px(13.))
+ .child(tr::settings::general::self_host::server_url()),
+ )
.child(self.text_field(Field::ServerUrl, cx)),
)
.child(
@@ -4188,7 +4193,7 @@ impl SettingsWindow {
.child(self.button(
"server-url-reset",
(ui::ButtonVariant::Gray, None),
- "Reset to Default",
+ tr::common::reset_to_default(),
stored == DEFAULT_SERVER_URL && draft == DEFAULT_SERVER_URL,
cx,
|this, window, cx| {
@@ -4206,7 +4211,7 @@ impl SettingsWindow {
.child(self.button(
"server-url-update",
(ui::ButtonVariant::Dark, None),
- "Update",
+ tr::settings::general::self_host::update(),
stored == draft,
cx,
|this, window, cx| {
@@ -4217,8 +4222,8 @@ impl SettingsWindow {
);
self.section(
- "Self-host",
- Some("Only change this if you are running your own instance of Cap Web."),
+ tr::settings::general::self_host::title(),
+ Some(tr::settings::general::self_host::description()),
None,
vec![self.card(true).child(body).into_any_element()],
)
@@ -4232,12 +4237,12 @@ impl SettingsWindow {
};
let answer = window.prompt(
gpui::PromptLevel::Warning,
- &format!(
- "Are you sure you want to change the server URL to '{origin}'? You will need \
- to sign in again."
- ),
+ &tr::settings::general::self_host::confirm_change(&origin),
None,
- &["Ok", "Cancel"],
+ &[
+ gpui::PromptButton::ok(tr::common::ok()),
+ gpui::PromptButton::cancel(tr::common::cancel()),
+ ],
cx,
);
cx.spawn(async move |this, cx| {
@@ -4259,18 +4264,14 @@ impl SettingsWindow {
/// `TelemetryCard` -- `enableTelemetry`.
fn render_privacy(&self, cx: &mut Context<Self>) -> impl IntoElement {
self.section(
- "Privacy",
+ tr::settings::general::privacy::title(),
None,
None,
vec![
self.rows(vec![
self.setting_row(
- "Share anonymous telemetry",
- Some(
- "Cap uses anonymous telemetry to improve reliability and fix bugs. We \
- never collect recording contents, window titles, file paths, or \
- personal information.",
- ),
+ tr::settings::general::privacy::telemetry::label(),
+ Some(tr::settings::general::privacy::telemetry::description()),
self.toggle(
"telemetry",
self.settings.enable_telemetry,
diff --git a/apps/desktop-gpui/src/tray.rs b/apps/desktop-gpui/src/tray.rs
index 001a6d2a8..87dccce5b 100644
--- a/apps/desktop-gpui/src/tray.rs
+++ b/apps/desktop-gpui/src/tray.rs
@@ -23,6 +23,7 @@ use gpui::{App, Global};
use crate::{
app_windows,
+ i18n::tr,
library::{self, MediaKind},
main_window::{Mode, TargetType},
menus,
@@ -241,13 +242,13 @@ pub fn scan_previous(load_thumbnails: bool) -> Vec<PreviousItem> {
fn previous_submenu(previous: &[PreviousItem]) -> Entry {
if previous.is_empty() {
return Entry::Submenu {
- title: "Previous".into(),
+ title: tr::tray::previous().into(),
enabled: false,
- items: vec![Entry::disabled("No recent items")],
+ items: vec![Entry::disabled(tr::tray::no_recent_items())],
};
}
Entry::Submenu {
- title: "Previous".into(),
+ title: tr::tray::previous().into(),
enabled: true,
items: previous
.iter()
@@ -283,32 +284,50 @@ fn mode_submenu(mode: Mode) -> Entry {
)
};
Entry::Submenu {
- title: "Select Mode".into(),
+ title: tr::tray::select_mode().into(),
enabled: true,
items: vec![
- label(Mode::Studio, "Studio"),
- label(Mode::Instant, "Instant"),
- label(Mode::Screenshot, "Screenshot"),
+ label(Mode::Studio, tr::tray::mode::studio()),
+ label(Mode::Instant, tr::tray::mode::instant()),
+ label(Mode::Screenshot, tr::tray::mode::screenshot()),
],
}
}
/// `build_tray_menu`, minus the onboarding-minimal branch.
pub fn build_menu(mode: Mode, previous: &[PreviousItem], version: &str) -> Vec<Entry> {
- let mut entries = vec![Entry::item("Open Main Window", TrayItem::OpenCap)];
+ let mut entries = vec![Entry::item(tr::tray::open_main_window(), TrayItem::OpenCap)];
if mode == Mode::Screenshot {
- entries.push(Entry::item("Screenshot Display", TrayItem::RecordDisplay));
- entries.push(Entry::item("Screenshot Window", TrayItem::RecordWindow));
- entries.push(Entry::item("Screenshot Area", TrayItem::RecordArea));
+ entries.push(Entry::item(
+ tr::tray::screenshot_display(),
+ TrayItem::RecordDisplay,
+ ));
+ entries.push(Entry::item(
+ tr::tray::screenshot_window(),
+ TrayItem::RecordWindow,
+ ));
+ entries.push(Entry::item(
+ tr::tray::screenshot_area(),
+ TrayItem::RecordArea,
+ ));
} else {
- entries.push(Entry::item("Record Display", TrayItem::RecordDisplay));
- entries.push(Entry::item("Record Window", TrayItem::RecordWindow));
- entries.push(Entry::item("Record Area", TrayItem::RecordArea));
- entries.push(Entry::item("Take a Screenshot", TrayItem::TakeScreenshot));
+ entries.push(Entry::item(
+ tr::tray::record_display(),
+ TrayItem::RecordDisplay,
+ ));
+ entries.push(Entry::item(
+ tr::tray::record_window(),
+ TrayItem::RecordWindow,
+ ));
+ entries.push(Entry::item(tr::tray::record_area(), TrayItem::RecordArea));
+ entries.push(Entry::item(
+ tr::tray::take_screenshot(),
+ TrayItem::TakeScreenshot,
+ ));
}
- entries.push(Entry::item("Import Media...", TrayItem::ImportMedia));
+ entries.push(Entry::item(tr::tray::import_media(), TrayItem::ImportMedia));
entries.push(Entry::Separator);
entries.push(mode_submenu(mode));
@@ -316,31 +335,34 @@ pub fn build_menu(mode: Mode, previous: &[PreviousItem], version: &str) -> Vec<E
entries.push(Entry::Separator);
entries.push(Entry::item(
- "View all recordings",
+ tr::tray::view_all_recordings(),
TrayItem::ViewAllRecordings,
));
entries.push(Entry::item(
- "View all screenshots",
+ tr::tray::view_all_screenshots(),
TrayItem::ViewAllScreenshots,
));
- entries.push(Entry::item("Settings", TrayItem::OpenSettings));
+ entries.push(Entry::item(tr::tray::settings(), TrayItem::OpenSettings));
entries.push(Entry::Separator);
// `logging::upload_log_file` needs the auth token and the HTTP client,
// neither of which this app has.
- entries.push(Entry::disabled("Upload Logs"));
- entries.push(Entry::disabled(format!("Cap v{version}")));
- entries.push(Entry::item("Quit Cap", TrayItem::Quit));
+ entries.push(Entry::disabled(tr::tray::upload_logs()));
+ entries.push(Entry::disabled(tr::tray::version(version)));
+ entries.push(Entry::item(tr::tray::quit(), TrayItem::Quit));
entries
}
pub fn build_onboarding_menu(version: &str) -> Vec<Entry> {
vec![
- Entry::item("Request Permissions", TrayItem::RequestPermissions),
+ Entry::item(
+ tr::tray::request_permissions(),
+ TrayItem::RequestPermissions,
+ ),
Entry::Separator,
- Entry::disabled(format!("Cap v{version}")),
- Entry::item("Quit Cap", TrayItem::Quit),
+ Entry::disabled(tr::tray::version(version)),
+ Entry::item(tr::tray::quit(), TrayItem::Quit),
]
}
diff --git a/apps/desktop-gpui/src/tray/windows.rs b/apps/desktop-gpui/src/tray/windows.rs
index 04de18705..1545f480d 100644
--- a/apps/desktop-gpui/src/tray/windows.rs
+++ b/apps/desktop-gpui/src/tray/windows.rs
@@ -12,7 +12,7 @@ use tray_icon::{
use super::{
Entry, PreviousItem, TrayItem, current_menu_entries, handle_item, scan_previous, stop_recording,
};
-use crate::main_window::Mode;
+use crate::{i18n::tr, main_window::Mode};
const TRAY_ID: &str = "cap-gpui-tray";
const DEFAULT_ICON: &[u8] =
@@ -222,7 +222,7 @@ pub fn set_recording(recording: bool, cx: &mut App) {
Err(error) => tracing::warn!("failed to decode the Windows tray icon: {error:#}"),
}
let tooltip = if recording {
- "Cap - Stop Recording"
+ tr::tray::tooltip_recording()
} else {
"Cap"
};