Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

M14: translation catalogs, same system as PhotoCraft (#106)

Simon Leblanca07243c8fff1
diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md
index dc6025140..15aaa8083 100644
--- a/ATTRIBUTION.md
+++ b/ATTRIBUTION.md
@@ -4,10 +4,11 @@
Every asset PdfCraft includes, bundles or uses to build its published material, with its author, source and licence. The policy is in [AGENTS.md](AGENTS.md) §1. The machine-readable list, with SHA-256 hashes, is [ATTRIBUTION.toml](ATTRIBUTION.toml). Licence texts are kept beside the assets and summarised in [NOTICE](NOTICE).
-## In this repository (242)
+## In this repository (243)
| Asset | Title | Author | Licence | Source | Used for |
|---|---|---|---|---|---|
+| `crates/ui-egui/src/i18n/ja.tsv` | Japanese interface translation catalog | PdfCraft contributors | MIT OR Apache-2.0 | Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources | Japanese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs |
| `assets/icons/accessibility.svg` | Lucide icon "accessibility" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/accessibility.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/align-left.svg` | Lucide icon "align-left" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/align-left.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
| `assets/icons/align-center.svg` | Lucide icon "align-center" | Lucide Contributors (portions Cole Bemis, Feather) | ISC | https://github.com/lucide-icons/lucide (npm lucide-static 1.49.0, icons/align-center.svg) | UI icon, embedded via crates/ui-egui/src/icon_data.rs |
diff --git a/ATTRIBUTION.toml b/ATTRIBUTION.toml
index b2008de41..005bde0f4 100644
--- a/ATTRIBUTION.toml
+++ b/ATTRIBUTION.toml
@@ -10,6 +10,17 @@
# licence: SPDX expression from the allowlist in AGENTS.md §1.2. adobe_data = true marks the closed list of
# Adobe-authored non-visual technical data allowed by AGENTS.md §1.1.
+[[asset]]
+path = "crates/ui-egui/src/i18n/ja.tsv"
+title = "Japanese interface translation catalog"
+author = "PdfCraft contributors"
+source = "Contributor-original: clean-room translations of PdfCraft's English UI labels, no proprietary localisation resources"
+licence = "MIT OR Apache-2.0"
+licence_file = "LICENSE-MIT"
+kind = "translation"
+usage = "Japanese UI strings, compiled in by crates/ui-egui/src/i18n/mod.rs"
+sha256 = "404a932baa7943958c56df19c912065ab08b6acc477dde63dc60fcacb2f54be8"
+
[[asset]]
path = "assets/icons/accessibility.svg"
title = "Lucide icon \"accessibility\""
diff --git a/ROADMAP.md b/ROADMAP.md
index dfe157747..8962434d0 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -45,7 +45,7 @@ Read this before choosing work. The feature table above counts what exists; this
| Foundations | Weakest | Rendering is still the bootstrap `hayro`; the inspector is `lopdf`; 18 vendored patches carried |
| Robustness | Early beta | Each 15-minute fuzz run found new out-of-memory crashes or hangs until 2026-10-05 |
| Acrobat fidelity | Unmeasured | No systematic side-by-side comparison with Acrobat, visual or behavioural |
-| Product readiness | 0.2.1 | No code signing, localization, performance budgets or keyboard-only operation yet |
+| Product readiness | 0.2.1 | No code signing, performance budgets or keyboard-only operation yet; localization has its catalog system (English, partial Japanese) but few strings go through it |
**By area** (shipped share of each area's features):
@@ -79,7 +79,7 @@ The gaps that matter most, in priority order. Agents: prefer these over adding P
3. **Measure fidelity against Acrobat.** Build a side-by-side harness (render, text, form behaviour) over synthetic fixtures (`plan/acrobat/`, clean-room rules apply). Until then, parity numbers count features, not quality.
4. **Editing existing content (M7).** Fonts, subsets, reflow and CJK. The most visible gap for Pro users.
5. **Pro workflows.** Signatures with timestamps and LTV (M9), OCR beyond Latin (M10), Office import/export (M10), preflight and PDF/A/X/UA (M11), XFA (M12).
-6. **1.0 polish (M14).** Code-signed installers, localization, keyboard-only operation, a full screen-reader audit.
+6. **1.0 polish (M14).** Code-signed installers, localization (the catalog system is in place; route every dialog and panel string through `tl!`, then add languages), keyboard-only operation, a full screen-reader audit.
Decided against for now (owner, 2026-10-05): self-installing updates and an update check at start. Help ▸ Check for updates is manual only.
@@ -104,6 +104,8 @@ Hours are for a single agent (low–high). "Done" is the estimated fraction of t
| M12 | Accessibility, compare, measure, search, XFA | 200–380 | 20% | 160–305 | Done: new `a11y` crate with the Accessibility Checker (all 32 rules, report, Fix/Skip/Explain, options dialog and results panel, agent tools). Missing: autotag, Tags/Order/Content panels, Reading Order tool, alt-text workflow, compare, measure, search index, XFA |
| M13 | Automation (MCP, Action Wizard, CLI) + AI providers | 60–120 | 45% | 33–66 | Done: MCP resources (document info, text, page images); headless tool table (123 tools incl. signing, optimizing, initial view, links, stamps, data exchange, comment review, forms authoring and scripts, redaction, sanitize, print, add content), opt-in MCP server over stdio, CLI `run`/`tools` (closed stdout pipes exit cleanly), UI control channel with drag. Missing: Action Wizard, AI providers |
| M14 | 1.0 polish: performance, localization, installers | 120–250 | 0% | 120–250 | |
+| M13 | Automation (MCP, Action Wizard, CLI) + AI providers | 60–120 | 45% | 33–66 | Done: MCP resources (document info, text, page images); headless tool table (123 tools incl. signing, optimizing, initial view, links, stamps, data exchange, comment review, forms authoring and scripts, redaction, sanitize, print, add content), opt-in MCP server over stdio, CLI `run`/`tools`, UI control channel with drag. Missing: Action Wizard, AI providers |
+| M14 | 1.0 polish: performance, localization, installers | 120–250 | 2% | 118–245 | Done: PhotoCraft's translation system (`i18n/`: TSV catalogs, `tl!`, command-id and plural entries, system-language detection, catalog tests) with English and the first Japanese strings (menus, Preferences). Missing: dialogs and panels through `tl!`, more languages, Windows language detection, installers, performance budgets |
| | **Total (original plan sizing)** | **2,085–3,840** | **≈ 35%** | **≈ 1,350–2,500 at the planned rate; ≈ 600–1,100 at the measured rate** | |
**Overall progress: about 30–35% of the effort (49.5% of features shipped).** The viewer and the core are far ahead of the editing features, because the viewer was built first so progress could be seen; rendering itself is still borrowed from `hayro`. See [Honest assessment](#honest-assessment-2026-10-05).
@@ -131,6 +133,7 @@ Newest first. One line per session: the date, what moved, and the new overall pe
- **2026-10-08 (community):** Cut and stack in Print > Multiple: single-sided n-up sheets can be cut into cell piles and restacked in selected page order, with aligned gutter marks and blanks kept in their cells. Available through doc_print; duplex is refused. Grid-size overflow returns an error. No change to the parity count or the overall estimate (about 30–35%).
- **2026-10-07 (community, #143):** Windows MSI gets a full-UI welcome dialog with a "Create a desktop shortcut" checkbox (on by default; `INSTALLDESKTOPSHORTCUT=0` for unattended installs), progress, files in use, repair/remove, and a "Setup completed successfully" screen with Finish (plus distinct failed/cancelled screens). Start Menu and desktop shortcuts are now plain links to `pdfcraft.exe` instead of advertised MSI shortcuts. Packaging checks the compiled MSI's shortcut, checkbox and dialog tables; the ARM64 smoke test checks both links' targets, their removal on uninstall, and the opt-out. Installer polish only; feature counts unchanged. ≈ 30–35%.
+- **2026-10-07 (localization):** The interface translates through the same system as PhotoCraft: one TSV catalog per language (`crates/ui-egui/src/i18n/ja.tsv`), the `tl!` macro, entries keyed by command id or with plural forms, and catalog tests (format, duplicates, placeholders, command ids). Catalogs are validated strictly (unknown escapes, reserved contexts, placeholders, ellipses, plural forms), a bad line is skipped and logged at run time, `fmt` substitutes in one pass, the drawing language is per thread, and each `.tsv` is an attributed asset (`kind = "translation"`, checked by `cargo xtask assets`); validation, attribution and the language-switch control test folded in from #175. The 49 existing Japanese strings moved over unchanged, plus `Auto`. The `language` preference now defaults to `auto` (follow the system language; English when it has no catalog); `en`/`ja` still persist, and unknown values are rejected. Not covered: dialogs and panels, Windows system-language detection. ≈ 30–35% (unchanged).
- **2026-10-07 (session 16):** PrintCraft is renamed PdfCraft: repo `storytold/pdfcraft`, crates and binaries `pdfcraft*`, bundle id `ai.storyteller.pdfcraft`. On first launch the app moves the old PrintCraft settings and crash-recovery folders to the new name, so upgrades keep recent files, preferences and unsaved work. No feature change. ≈ 30–35%.
- **2026-10-07 (community, #163):** Fill & Sign shows saved signature/initials previews with add, change and remove controls in the quick picker and left panel. The editor loads the saved typed text or drawn strokes; Apply replaces future placements and Cancel preserves the saved value. Existing annotations stay unchanged. Long typed names shrink to the placement width and include glyph overhangs in preview/PDF bounds. Regression coverage includes persistence, removal/recreation, long names and the opt-in UI control channel. Parity counts and effort estimate unchanged (50.2% shipped, ≈ 30–35% effort).
diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs
index a0aa3cb20..e5783f77a 100644
--- a/crates/ui-egui/src/chrome.rs
+++ b/crates/ui-egui/src/chrome.rs
@@ -146,25 +146,24 @@ pub fn mode_bar(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
}
fn main_menu(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
- let language = app.language;
let t = Tokens::get(ui.ctx());
- let resp = widgets::ghost_button(ui, "panel-left", language.tr("Menu"));
+ let resp = widgets::ghost_button(ui, "panel-left", tl!("Menu"));
egui::Popup::menu(&resp).show(|ui| {
ui.set_min_width(230.0);
- ui.menu_button(language.tr("File"), |ui| crate::commands::registry_menu(app, ui, "File"));
- ui.menu_button(language.tr("Edit"), |ui| crate::commands::registry_menu(app, ui, "Edit"));
- ui.menu_button(language.tr("Pages"), |ui| crate::commands::registry_menu(app, ui, "Pages"));
- ui.menu_button(language.tr("View"), |ui| {
+ ui.menu_button(tl!("File"), |ui| crate::commands::registry_menu(app, ui, "File"));
+ ui.menu_button(tl!("Edit"), |ui| crate::commands::registry_menu(app, ui, "Edit"));
+ ui.menu_button(tl!("Pages"), |ui| crate::commands::registry_menu(app, ui, "Pages"));
+ ui.menu_button(tl!("View"), |ui| {
if let Some(i) = app.active {
let v = &mut app.views[i];
ui.label(egui::RichText::new("Zoom").color(t.text_faint).small());
- if widgets::menu_item(ui, language.tr("Actual size"), "⌘1").clicked() {
+ if widgets::menu_item(ui, tl!("Actual size"), "⌘1").clicked() {
v.set_zoom(1.0);
}
- if widgets::menu_item(ui, language.tr("Zoom to page level"), "⌘0").clicked() {
+ if widgets::menu_item(ui, tl!("Zoom to page level"), "⌘0").clicked() {
v.fit = Fit::Page;
}
- if widgets::menu_item(ui, language.tr("Fit to width"), "⌘2").clicked() {
+ if widgets::menu_item(ui, tl!("Fit to width"), "⌘2").clicked() {
v.fit = Fit::Width;
}
if widgets::menu_item(ui, "Fit to height", "").clicked() {
@@ -212,7 +211,7 @@ fn main_menu(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
ui.separator();
}
crate::commands::registry_menu(app, ui, "View");
- ui.menu_button(language.tr("Display theme"), |ui| {
+ ui.menu_button(tl!("Display theme"), |ui| {
let ctx = ui.ctx().clone();
if ui.radio(app.follow_system_theme, "Use system setting").clicked() {
app.follow_system_theme = true;
@@ -226,7 +225,7 @@ fn main_menu(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
app.set_theme(&ctx, ThemeKind::Dark);
}
});
- ui.menu_button(language.tr("Side panels"), |ui| {
+ ui.menu_button(tl!("Side panels"), |ui| {
for (p, label) in [
(RightPanel::Comments, "Comments"),
(RightPanel::Bookmarks, "Bookmarks"),
@@ -245,7 +244,7 @@ fn main_menu(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
}
});
});
- ui.menu_button(language.tr("Help"), |ui| crate::commands::registry_menu(app, ui, "Help"));
+ ui.menu_button(tl!("Help"), |ui| crate::commands::registry_menu(app, ui, "Help"));
});
}
diff --git a/crates/ui-egui/src/commands.rs b/crates/ui-egui/src/commands.rs
index 6dd10b7e9..a3479781c 100644
--- a/crates/ui-egui/src/commands.rs
+++ b/crates/ui-egui/src/commands.rs
@@ -505,7 +505,7 @@ pub(crate) fn registry_menu(app: &mut PdfCraftApp, ui: &mut egui::Ui, menu: &str
let mac = cfg!(target_os = "macos") || cfg!(target_arch = "wasm32");
for spec in commands::menu(menu) {
let label = commands::current_label(spec, &app.session, app.active_ids().map(|(_, id)| id));
- let label = app.language.tr(&label);
+ let label = crate::i18n::tr_id(crate::i18n::current(), spec.id, &label);
let shortcut = spec.shortcut.map(|s| s.label(mac)).unwrap_or_default();
let enabled = app.command_enabled(spec);
let resp = ui.add_enabled(enabled, egui::Button::new(label).shortcut_text(shortcut));
diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs
deleted file mode 100644
index 0038e84bb..000000000
--- a/crates/ui-egui/src/i18n.rs
+++ /dev/null
@@ -1,124 +0,0 @@
-//! Interface translations. Command ids, document text and file names remain stable.
-//! Untranslated labels fall back to English so coverage can grow incrementally.
-
-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
-#[serde(rename_all = "lowercase")]
-pub enum Language {
- #[default]
- En,
- Ja,
-}
-
-impl Language {
- pub const ALL: [Self; 2] = [Self::En, Self::Ja];
-
- pub fn name(self) -> &'static str {
- match self {
- Self::En => "English",
- Self::Ja => "日本語",
- }
- }
-
- pub fn parse(code: &str) -> Option<Self> {
- match code {
- "en" => Some(Self::En),
- "ja" => Some(Self::Ja),
- _ => None,
- }
- }
-
- pub fn tr(self, text: &str) -> &str {
- if self == Self::Ja
- && let Some((_, japanese)) = JAPANESE.iter().find(|(english, _)| *english == text)
- {
- return japanese;
- }
- text
- }
-}
-
-const JAPANESE: &[(&str, &str)] = &[
- ("Menu", "メニュー"),
- ("File", "ファイル"),
- ("Edit", "編集"),
- ("Pages", "ページ"),
- ("View", "表示"),
- ("Help", "ヘルプ"),
- ("Preferences", "環境設定"),
- ("Preferences…", "環境設定…"),
- ("Interface language", "表示言語"),
- ("Identity", "個人情報"),
- ("Name on new comments", "新しい注釈の作成者名"),
- ("Open…", "開く…"),
- ("New blank PDF", "空白の PDF を作成"),
- ("Create PDF from file…", "ファイルから PDF を作成…"),
- ("Create PDF from images…", "画像から PDF を作成…"),
- ("Create PDF from clipboard", "クリップボードから PDF を作成"),
- ("Combine files…", "ファイルを結合…"),
- ("Save", "保存"),
- ("Save as…", "別名で保存…"),
- ("Close file", "ファイルを閉じる"),
- ("Close all", "すべて閉じる"),
- ("Revert", "保存済みの状態に戻す"),
- ("Print…", "印刷…"),
- ("Document properties…", "文書のプロパティ…"),
- ("Undo", "取り消し"),
- ("Redo", "やり直し"),
- ("Find…", "検索…"),
- ("Advanced search…", "高度な検索…"),
- ("Copy pages", "ページをコピー"),
- ("Cut pages", "ページを切り取り"),
- ("Paste pages", "ページを貼り付け"),
- ("Fit visible", "表示範囲に合わせる"),
- ("Marquee zoom", "範囲指定ズーム"),
- ("Take a snapshot", "スナップショットを作成"),
- ("Full screen mode", "全画面表示"),
- ("Read mode", "閲覧モード"),
- ("Switch light / dark theme", "明るい/暗いテーマを切り替え"),
- ("Comments panel", "コメントパネル"),
- ("Form fields panel", "フォームフィールドパネル"),
- ("Clear form", "フォームをクリア"),
- ("Find tools and commands…", "ツールとコマンドを検索…"),
- ("Zoom", "ズーム"),
- ("Actual size", "実際のサイズ"),
- ("Zoom to page level", "ページ全体を表示"),
- ("Fit to width", "幅に合わせる"),
- ("Display theme", "表示テーマ"),
- ("Side panels", "サイドパネル"),
- ("Enable Acrobat JavaScript", "Acrobat JavaScript を有効にする"),
- ("OK", "OK"),
-];
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn translations_are_unique_and_preserve_unknown_text() {
- for (i, (en, ja)) in JAPANESE.iter().enumerate() {
- assert!(!ja.is_empty());
- assert!(JAPANESE.iter().take(i).all(|(other, _)| en != other));
- assert_eq!(Language::En.tr(en), *en);
- }
- assert_eq!(Language::Ja.tr("File"), "ファイル");
- assert_eq!(Language::Ja.tr("日本語の文書.pdf"), "日本語の文書.pdf");
- assert_eq!(Language::parse("xx"), None);
- }
-
- #[test]
- fn language_persists_and_invalid_input_keeps_current_language() {
- let mut app = crate::PdfCraftApp::default();
- app.set_option("language", "ja").unwrap();
- assert_eq!(app.language, Language::Ja);
- assert!(app.set_option("language", "xx").is_err());
- assert_eq!(app.language, Language::Ja);
- let mut restored = crate::PdfCraftApp::default();
- restored.restore(&app.persist());
- assert_eq!(restored.language, Language::Ja);
- restored.restore(r#"{"language":"xx"}"#);
- assert_eq!(restored.language, Language::Ja);
- let mut legacy = crate::PdfCraftApp::default();
- legacy.restore("{}");
- assert_eq!(legacy.language, Language::En);
- }
-}
diff --git a/crates/ui-egui/src/i18n/catalog.rs b/crates/ui-egui/src/i18n/catalog.rs
new file mode 100644
index 000000000..7bf429666
--- /dev/null
+++ b/crates/ui-egui/src/i18n/catalog.rs
@@ -0,0 +1,175 @@
+//! Parser and lookup tables for translation catalogs (`*.tsv`, format documented in `ja.tsv`).
+//!
+//! Validation is strict (unknown escapes, unknown `@` contexts, placeholder, ellipsis and plural
+//! form mismatches, duplicates), but a bad line is only skipped and reported: the rest of the
+//! catalog still loads and the skipped string shows in English. The tests insist the bundled
+//! catalogs have no errors at all.
+
+use std::collections::{HashMap, HashSet};
+
+/// A catalog entry as read from the file.
+#[derive(Debug, PartialEq, Eq)]
+pub struct Entry {
+ pub context: String,
+ pub source: String,
+ pub translation: String,
+}
+
+/// A parsed catalog. Values are owned for the life of the process (catalogs are built once).
+#[derive(Debug, Default)]
+pub struct Catalog {
+ /// context-free strings: English source → translation (the hot path, looked up every frame)
+ plain: HashMap<String, String>,
+ /// strings with a disambiguating context: context → source → translation
+ contextual: HashMap<String, HashMap<String, String>>,
+ /// command-id keyed strings
+ ids: HashMap<String, String>,
+ /// plural messages: `one|other` → forms
+ plurals: HashMap<String, Vec<String>>,
+}
+
+fn unescape(text: &str) -> Result<String, String> {
+ let mut out = String::with_capacity(text.len());
+ let mut chars = text.chars();
+ while let Some(c) = chars.next() {
+ if c != '\\' {
+ out.push(c);
+ continue;
+ }
+ match chars.next() {
+ Some('n') => out.push('\n'),
+ Some('t') => out.push('\t'),
+ Some('\\') => out.push('\\'),
+ Some(other) => return Err(format!("unknown escape \\{other}; use \\n, \\t or \\\\")),
+ None => return Err("trailing backslash; use \\\\ for a literal backslash".into()),
+ }
+ }
+ Ok(out)
+}
+
+/// `{name}` placeholders of a template, sorted (translators may reorder them).
+pub fn placeholders(text: &str) -> Vec<&str> {
+ let mut names = Vec::new();
+ let mut rest = text;
+ while let Some((_, after_open)) = rest.split_once('{') {
+ let Some((name, after_close)) = after_open.split_once('}') else { break };
+ names.push(name);
+ rest = after_close;
+ }
+ names.sort_unstable();
+ names
+}
+
+/// Check one entry against its English source. `forms` is the language's number of plural forms.
+fn validate(entry: &Entry, forms: usize) -> Result<(), String> {
+ let Entry { context, source, translation } = entry;
+ match context.as_str() {
+ // The source is a command id, not a template; the bundled-catalog tests check the id
+ // exists and compare the translation with that command's English label.
+ "@id" => Ok(()),
+ "@plural" => {
+ let english: Vec<&str> = source.split('|').collect();
+ let [one, other] = english.as_slice() else { return Err("plural source must be one|other".into()) };
+ if one.is_empty() || other.is_empty() || placeholders(one) != placeholders(other) {
+ return Err("English plural forms must be nonempty and have matching placeholders".into());
+ }
+ let translated: Vec<&str> = translation.split('|').collect();
+ if translated.len() != forms || translated.iter().any(|form| form.is_empty()) {
+ return Err(format!("expected {forms} nonempty plural forms"));
+ }
+ if translated.iter().any(|form| placeholders(form) != placeholders(other)) {
+ return Err("plural placeholders differ from the English source".into());
+ }
+ Ok(())
+ }
+ _ if context.starts_with('@') => Err(format!("unknown reserved context {context:?}")),
+ _ => {
+ if placeholders(source) != placeholders(translation) {
+ return Err("placeholders differ from the English source".into());
+ }
+ if source.ends_with('…') != translation.ends_with('…') {
+ return Err("trailing ellipsis differs from the English source".into());
+ }
+ Ok(())
+ }
+ }
+}
+
+fn parse_line(line: &str, forms: usize) -> Result<Entry, String> {
+ let mut columns = line.split('\t');
+ let (Some(context), Some(source), Some(translation), None) = (columns.next(), columns.next(), columns.next(), columns.next()) else {
+ return Err("expected `context<TAB>source<TAB>translation`".into());
+ };
+ let entry = Entry { context: unescape(context)?, source: unescape(source)?, translation: unescape(translation)? };
+ if entry.source.is_empty() || entry.translation.is_empty() {
+ return Err("source and translation must be nonempty".into());
+ }
+ validate(&entry, forms)?;
+ Ok(entry)
+}
+
+/// Read the entries of a catalog file for a language with `forms` plural forms. Malformed lines
+/// and duplicates (the first entry wins) are returned as errors and skipped, so a bad translation
+/// never breaks the UI.
+pub fn parse_entries(text: &str, forms: usize) -> (Vec<Entry>, Vec<String>) {
+ let mut entries = Vec::new();
+ let mut errors = Vec::new();
+ let mut seen = HashSet::new();
+ for (index, line) in text.lines().enumerate() {
+ if line.trim().is_empty() || line.starts_with('#') {
+ continue;
+ }
+ let line_no = index.saturating_add(1);
+ match parse_line(line, forms) {
+ Ok(entry) if !seen.insert((entry.context.clone(), entry.source.clone())) => {
+ errors.push(format!("line {line_no}: duplicate key {:?} / {:?}", entry.context, entry.source));
+ }
+ Ok(entry) => entries.push(entry),
+ Err(error) => errors.push(format!("line {line_no}: {error}")),
+ }
+ }
+ (entries, errors)
+}
+
+impl Catalog {
+ /// Build a catalog from its valid entries; the errors of the skipped lines come back too.
+ pub fn parse(text: &str, forms: usize) -> (Catalog, Vec<String>) {
+ let (entries, errors) = parse_entries(text, forms);
+ let mut c = Catalog::default();
+ for Entry { context, source, translation } in entries {
+ match context.as_str() {
+ "" => {
+ c.plain.insert(source, translation);
+ }
+ "@id" => {
+ c.ids.insert(source, translation);
+ }
+ "@plural" => {
+ c.plurals.insert(source, translation.split('|').map(str::to_string).collect());
+ }
+ _ => {
+ c.contextual.entry(context).or_default().insert(source, translation);
+ }
+ }
+ }
+ (c, errors)
+ }
+
+ pub fn plain(&self, s: &str) -> Option<&str> {
+ self.plain.get(s).map(String::as_str)
+ }
+
+ pub fn contextual(&self, ctx: &str, s: &str) -> Option<&str> {
+ self.contextual.get(ctx)?.get(s).map(String::as_str)
+ }
+
+ pub fn id(&self, id: &str) -> Option<&str> {
+ self.ids.get(id).map(String::as_str)
+ }
+
+ /// The plural form `index` of the message whose English forms are `one|other`.
+ pub fn plural(&self, one: &str, other: &str, index: usize) -> Option<&str> {
+ let forms = self.plurals.get(&format!("{one}|{other}"))?;
+ forms.get(index.min(forms.len().saturating_sub(1))).map(String::as_str)
+ }
+}
diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv
new file mode 100644
index 000000000..573b3d688
--- /dev/null
+++ b/crates/ui-egui/src/i18n/ja.tsv
@@ -0,0 +1,67 @@
+# Japanese (ja) catalog. Columns, separated by a TAB: context <TAB> source <TAB> translation
+#
+# context empty a plain UI string; `source` is the English text in the code
+# @id a command id (e.g. file.saveAs): wins over the English text for
+# that menu item, so one id can read differently from its twin
+# @plural `source` is "one|other" (English forms); the translation lists the
+# language's forms separated by "|" (see `plural` in i18n/mod.rs)
+# anything else a disambiguating context passed to `tr_ctx`
+# escapes \n \t \\ inside a column. `{name}` placeholders must appear in both columns.
+# lines starting with # and blank lines are ignored.
+#
+# Clean-room: every entry was written from the plain meaning of the English label using ordinary
+# Japanese computing vocabulary. No proprietary localisation resource, string table or product UI
+# (Acrobat's included) was consulted or copied; add entries the same way.
+# Product and technology names (PdfCraft, PDF, Acrobat JavaScript ...) stay in Latin letters;
+# the trailing "…" of dialog commands is kept.
+
+ Menu メニュー
+ File ファイル
+ Edit 編集
+ Pages ページ
+ View 表示
+ Help ヘルプ
+ Preferences 環境設定
+ Preferences… 環境設定…
+ Interface language 表示言語
+ Identity 個人情報
+ Name on new comments 新しい注釈の作成者名
+ Open… 開く…
+ New blank PDF 空白の PDF を作成
+ Create PDF from file… ファイルから PDF を作成…
+ Create PDF from images… 画像から PDF を作成…
+ Create PDF from clipboard クリップボードから PDF を作成
+ Combine files… ファイルを結合…
+ Save 保存
+ Save as… 別名で保存…
+ Close file ファイルを閉じる
+ Close all すべて閉じる
+ Revert 保存済みの状態に戻す
+ Print… 印刷…
+ Document properties… 文書のプロパティ…
+ Undo 取り消し
+ Redo やり直し
+ Find… 検索…
+ Advanced search… 高度な検索…
+ Copy pages ページをコピー
+ Cut pages ページを切り取り
+ Paste pages ページを貼り付け
+ Fit visible 表示範囲に合わせる
+ Marquee zoom 範囲指定ズーム
+ Take a snapshot スナップショットを作成
+ Full screen mode 全画面表示
+ Read mode 閲覧モード
+ Switch light / dark theme 明るい/暗いテーマを切り替え
+ Comments panel コメントパネル
+ Form fields panel フォームフィールドパネル
+ Clear form フォームをクリア
+ Find tools and commands… ツールとコマンドを検索…
+ Zoom ズーム
+ Actual size 実際のサイズ
+ Zoom to page level ページ全体を表示
+ Fit to width 幅に合わせる
+ Display theme 表示テーマ
+ Side panels サイドパネル
+ Enable Acrobat JavaScript Acrobat JavaScript を有効にする
+ OK OK
+ Auto 自動
diff --git a/crates/ui-egui/src/i18n/mod.rs b/crates/ui-egui/src/i18n/mod.rs
new file mode 100644
index 000000000..bea872cd6
--- /dev/null
+++ b/crates/ui-egui/src/i18n/mod.rs
@@ -0,0 +1,500 @@
+//! UI localisation. Strings in code stay English and are the default lookup keys; a per-language
+//! catalog (`*.tsv`, see `ja.tsv` for the format) maps them to display text at render time. Command
+//! ids, document text, file names, the control channel, the CLI and MCP never see translated text,
+//! so agents and scripts are unaffected. A string without a translation is shown in English, so
+//! coverage can grow incrementally.
+//!
+//! The system is the one PhotoCraft uses (`photocraft/crates/ui-egui/src/i18n`), so catalogs and
+//! habits carry over between the two apps.
+//!
+//! # Adding a language
+//! 1. Add `xx.tsv` next to `ja.tsv` (copy its header; translate from the *meaning* of the English
+//! text, clean-room, see `ja.tsv`).
+//! 2. Add one row to [`LANGUAGES`] (code, native name, catalog, plural rule).
+//!
+//! That is all: the Preferences dropdown, the system-locale match and the catalog tests (parse,
+//! placeholders, plural forms) pick it up from the registry.
+//!
+//! # Looking strings up
+//! - [`tl!`](crate::tl) / [`t`]: a plain string in the current language. [`tr`]: in a given one.
+//! - [`tr_ctx`]: when one English word needs different translations.
+//! - [`tr_id`]: a command-id keyed string with the English label as fallback (menu items), so a
+//! translation survives rewording of the English text and can differ per command.
+//! - [`trn`]: plural-aware (`{n}` is filled in). [`fmt`]: fill `{name}` placeholders after [`tr`];
+//! translators may reorder placeholders freely.
+
+mod catalog;
+
+use std::cell::Cell;
+use std::sync::OnceLock;
+
+use catalog::Catalog;
+
+/// The `language` preference value that follows the system locale.
+pub const AUTO: &str = "auto";
+
+/// One supported UI language.
+pub struct LangInfo {
+ /// BCP 47 code, lowercase (`ja`, `zh-hans`, `pt-br`). Also the `language` preference value.
+ pub code: &'static str,
+ /// The language's name in itself, shown in the Preferences dropdown.
+ pub name: &'static str,
+ /// Catalog file contents (empty for the built-in English).
+ pub source: &'static str,
+ /// Plural form index for a count (English: 0 = one, 1 = other; Japanese: always 0). A catalog's
+ /// `@plural` entries list one form per index.
+ pub plural: fn(u64) -> usize,
+ catalog: OnceLock<Catalog>,
+}
+
+fn plural_one_other(n: u64) -> usize {
+ usize::from(n != 1)
+}
+
+fn plural_none(_: u64) -> usize {
+ 0
+}
+
+/// The registry. English first: it is the fallback and the source language.
+pub static LANGUAGES: [LangInfo; 2] = [
+ LangInfo { code: "en", name: "English", source: "", plural: plural_one_other, catalog: OnceLock::new() },
+ LangInfo { code: "ja", name: "日本語", source: include_str!("ja.tsv"), plural: plural_none, catalog: OnceLock::new() },
+];
+
+impl LangInfo {
+ /// How many plural forms the language's `@plural` entries list.
+ fn plural_forms(&self) -> usize {
+ (0..=1000).map(self.plural).max().unwrap_or(0).saturating_add(1)
+ }
+
+ fn catalog(&self) -> &Catalog {
+ self.catalog.get_or_init(|| {
+ let (catalog, errors) = Catalog::parse(self.source, self.plural_forms());
+ for error in errors {
+ log::warn!("{} interface catalog: {error}; that entry shows in English", self.code);
+ }
+ catalog
+ })
+ }
+}
+
+/// A language the UI can be shown in (a handle into [`LANGUAGES`]).
+#[derive(Clone, Copy)]
+pub struct Lang(&'static LangInfo);
+
+impl std::fmt::Debug for Lang {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "Lang({})", self.0.code)
+ }
+}
+
+impl PartialEq for Lang {
+ fn eq(&self, other: &Self) -> bool {
+ self.0.code == other.0.code
+ }
+}
+
+impl Eq for Lang {}
+
+impl Lang {
+ pub const EN: Lang = Lang(&LANGUAGES[0]);
+
+ pub fn code(self) -> &'static str {
+ self.0.code
+ }
+
+ /// A language by its exact code.
+ pub fn from_code(code: &str) -> Option<Lang> {
+ LANGUAGES.iter().find(|l| l.code.eq_ignore_ascii_case(code)).map(Lang)
+ }
+
+ /// Resolve the `language` preference: a language code, or [`AUTO`] (and anything unknown,
+ /// e.g. a code from a newer version) to follow the system locale.
+ pub fn from_pref(pref: &str) -> Lang {
+ Lang::from_code(pref).unwrap_or_else(system_lang)
+ }
+
+ /// Every registered language.
+ pub fn all() -> impl Iterator<Item = Lang> {
+ LANGUAGES.iter().map(Lang)
+ }
+
+ pub fn name(self) -> &'static str {
+ self.0.name
+ }
+
+ fn catalog(self) -> &'static Catalog {
+ self.0.catalog()
+ }
+}
+
+/// The canonical `language` preference for user input: [`AUTO`] or a registered code (any case).
+/// `None` for anything else, so callers can keep the current setting.
+pub fn normalize_pref(pref: &str) -> Option<&'static str> {
+ if pref.eq_ignore_ascii_case(AUTO) {
+ return Some(AUTO);
+ }
+ Lang::from_code(pref).map(Lang::code)
+}
+
+/// Candidate language codes for a locale tag, most specific first: `zh_TW.UTF-8` →
+/// `zh-tw`, `zh-hant`, `zh`.
+fn candidates(tag: &str) -> Vec<String> {
+ let base = tag.split(['.', '@']).next().unwrap_or("").replace('_', "-").to_ascii_lowercase();
+ let parts: Vec<&str> = base.split('-').filter(|p| !p.is_empty()).collect();
+ let Some(&primary) = parts.first() else { return Vec::new() };
+ let mut out = Vec::new();
+ for n in (1..=parts.len()).rev() {
+ out.push(parts.get(..n).unwrap_or_default().join("-"));
+ }
+ if primary == "zh" && !parts.iter().any(|p| matches!(*p, "hans" | "hant")) {
+ // Chinese by region when no script is given.
+ let script = if parts.iter().any(|p| matches!(*p, "tw" | "hk" | "mo")) { "zh-hant" } else { "zh-hans" };
+ out.insert(out.len().saturating_sub(1), script.to_string());
+ }
+ out
+}
+
+/// The registered language for a locale tag such as `ja_JP.UTF-8`, `ja-JP`; `None` if the
+/// language isn't supported. `C`/`POSIX` mean English.
+pub fn lang_from_tag(tag: &str) -> Option<Lang> {
+ let cands = candidates(tag);
+ if matches!(cands.first().map(String::as_str), Some("c" | "posix")) {
+ return Some(Lang::EN);
+ }
+ cands.iter().find_map(|c| Lang::from_code(c))
+}
+
+/// The system language (cached). English when it can't be determined.
+pub fn system_lang() -> Lang {
+ // Tests drive the UI by its English labels whatever the developer's locale is.
+ if cfg!(test) {
+ return Lang::EN;
+ }
+ static SYSTEM: OnceLock<Lang> = OnceLock::new();
+ *SYSTEM.get_or_init(detect_system_lang)
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+fn detect_system_lang() -> Lang {
+ for var in ["LC_ALL", "LC_MESSAGES", "LANG"] {
+ if let Some(l) = std::env::var(var).ok().filter(|v| !v.is_empty()).and_then(|v| lang_from_tag(&v)) {
+ return l;
+ }
+ }
+ // Apps started from the Finder don't inherit LANG: use the macOS preferred-languages list.
+ // The absolute path keeps a `defaults` earlier on PATH from running; any failure means English.
+ #[cfg(target_os = "macos")]
+ if let Ok(out) = std::process::Command::new("/usr/bin/defaults").args(["read", "-g", "AppleLanguages"]).output()
+ && out.status.success()
+ && let Some(l) = first_supported(&String::from_utf8_lossy(&out.stdout))
+ {
+ return l;
+ }
+ Lang::EN
+}
+
+/// The first supported language in a `defaults read` list like `(\n "ja-JP",\n "en-US"\n)`.
+#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
+fn first_supported(list: &str) -> Option<Lang> {
+ list.split(['(', ')', ',', '"', '\n']).map(str::trim).filter(|s| !s.is_empty()).find_map(lang_from_tag)
+}
+
+#[cfg(target_arch = "wasm32")]
+fn detect_system_lang() -> Lang {
+ Lang::EN
+}
+
+thread_local! {
+ // Per thread, as in PhotoCraft: independent app and test threads (kittest harnesses run in
+ // parallel) must not change each other's drawing language.
+ static CURRENT: Cell<Lang> = const { Cell::new(Lang::EN) };
+}
+
+/// Set the UI language for drawing (the shell calls this once per frame from the preference), so
+/// widgets can translate without every call site carrying a language around.
+pub fn set_current(lang: Lang) {
+ CURRENT.set(lang);
+}
+
+/// The language the UI is drawn in.
+pub fn current() -> Lang {
+ CURRENT.get()
+}
+
+/// Does `lang` have a catalog entry for this plain string? (English never does: it is the source.)
+pub fn has(lang: Lang, s: &str) -> bool {
+ lang.catalog().plain(s).is_some()
+}
+
+/// Translate an English UI string into the current language ([`tr`] with [`current`]).
+pub fn t(s: &str) -> &str {
+ tr(current(), s)
+}
+
+/// Translate an English UI string; unknown strings come back unchanged.
+pub fn tr(lang: Lang, s: &str) -> &str {
+ lang.catalog().plain(s).unwrap_or(s)
+}
+
+/// Like [`tr`], for an English string that needs a disambiguating `context`.
+pub fn tr_ctx<'a>(lang: Lang, context: &str, s: &'a str) -> &'a str {
+ lang.catalog().contextual(context, s).unwrap_or_else(|| tr(lang, s))
+}
+
+/// A string keyed by its command id, falling back to the translation of the English `label`.
+pub fn tr_id<'a>(lang: Lang, id: &str, label: &'a str) -> &'a str {
+ lang.catalog().id(id).unwrap_or_else(|| tr(lang, label))
+}
+
+/// Fill `{name}` placeholders in one pass. Unknown placeholders are left as written, and inserted
+/// values are never read as templates again, so a file name containing `{n}` stays intact.
+pub fn fmt(template: &str, args: &[(&str, &str)]) -> String {
+ let mut out = String::with_capacity(template.len());
+ let mut rest = template;
+ while let Some((before, after_open)) = rest.split_once('{') {
+ out.push_str(before);
+ let Some((name, after_close)) = after_open.split_once('}') else {
+ out.push('{');
+ out.push_str(after_open);
+ return out;
+ };
+ match args.iter().find(|(key, _)| *key == name) {
+ Some((_, value)) => out.push_str(value),
+ None => {
+ out.push('{');
+ out.push_str(name);
+ out.push('}');
+ }
+ }
+ rest = after_close;
+ }
+ out.push_str(rest);
+ out
+}
+
+/// A plural-aware message: `one`/`other` are the English forms (with `{n}` where the count goes).
+pub fn trn(lang: Lang, n: u64, one: &str, other: &str) -> String {
+ let idx = (lang.0.plural)(n);
+ let text = lang.catalog().plural(one, other, idx).unwrap_or(if n == 1 { one } else { other });
+ fmt(text, &[("n", &n.to_string())])
+}
+
+#[cfg(test)]
+mod tests {
+ use super::catalog::{Entry, parse_entries, placeholders};
+ use super::*;
+
+ const JA: fn() -> Lang = || Lang::from_code("ja").expect("ja registered");
+
+ #[test]
+ fn tags_map_to_languages() {
+ assert_eq!(lang_from_tag("ja_JP.UTF-8"), Some(JA()));
+ assert_eq!(lang_from_tag("ja-JP"), Some(JA()));
+ assert_eq!(lang_from_tag("en_US.UTF-8"), Some(Lang::EN));
+ assert_eq!(lang_from_tag("C"), Some(Lang::EN));
+ assert_eq!(lang_from_tag("POSIX"), Some(Lang::EN));
+ assert_eq!(lang_from_tag("fr_FR"), None);
+ assert_eq!(lang_from_tag("zh-TW"), None);
+ assert_eq!(lang_from_tag(""), None);
+ assert_eq!(lang_from_tag("_"), None);
+ }
+
+ #[test]
+ fn candidates_walk_from_specific_to_general() {
+ assert_eq!(candidates("pt_BR.UTF-8"), ["pt-br", "pt"]);
+ assert_eq!(candidates("zh_TW"), ["zh-tw", "zh-hant", "zh"]);
+ assert_eq!(candidates("zh-CN"), ["zh-cn", "zh-hans", "zh"]);
+ assert_eq!(candidates("zh-Hant-HK"), ["zh-hant-hk", "zh-hant", "zh"]);
+ }
+
+ #[test]
+ fn macos_language_list_is_parsed() {
+ assert_eq!(first_supported("(\n \"ja-JP\",\n \"en-US\"\n)\n"), Some(JA()));
+ assert_eq!(first_supported("(\n \"fr-FR\",\n \"en-US\"\n)\n"), Some(Lang::EN));
+ assert_eq!(first_supported("("), None);
+ }
+
+ #[test]
+ fn preferences_resolve_with_fallback() {
+ assert_eq!(Lang::from_pref("ja"), JA());
+ assert_eq!(Lang::from_pref("JA"), JA());
+ assert_eq!(Lang::from_pref("en"), Lang::EN);
+ // `auto` and unknown codes follow the system (English under test).
+ assert_eq!(Lang::from_pref(AUTO), Lang::EN);
+ assert_eq!(Lang::from_pref("xx-unknown"), Lang::EN);
+ assert_eq!(normalize_pref("JA"), Some("ja"));
+ assert_eq!(normalize_pref("Auto"), Some(AUTO));
+ assert_eq!(normalize_pref("xx"), None);
+ }
+
+ #[test]
+ fn lookups_fall_back_to_english() {
+ assert_eq!(tr(JA(), "no such label"), "no such label");
+ assert_eq!(tr(Lang::EN, "File"), "File");
+ assert_eq!(tr(JA(), "File"), "ファイル");
+ assert_eq!(tr(JA(), "日本語の文書.pdf"), "日本語の文書.pdf");
+ assert_eq!(tr_id(JA(), "no.such.id", "File"), "ファイル");
+ assert_eq!(tr_ctx(JA(), "no such context", "File"), "ファイル");
+ assert!(has(JA(), "Save") && !has(Lang::EN, "Save"));
+ }
+
+ #[test]
+ fn catalog_kinds_are_parsed_and_looked_up() {
+ let (c, errors) = Catalog::parse(
+ "# c\n\tHello\tこんにちは\n@id\tfile.save\t保存する\nmenu\tWindows\tウィンドウ群\n@plural\t{n} file|{n} files\t{n} 個\n\n",
+ 1,
+ );
+ assert!(errors.is_empty(), "{errors:?}");
+ assert_eq!(c.plain("Hello"), Some("こんにちは"));
+ assert_eq!(c.id("file.save"), Some("保存する"));
+ assert_eq!(c.contextual("menu", "Windows"), Some("ウィンドウ群"));
+ assert_eq!(c.contextual("other", "Windows"), None);
+ assert_eq!(c.plural("{n} file", "{n} files", 0), Some("{n} 個"));
+ assert_eq!(c.plural("{n} file", "{n} files", 5), Some("{n} 個"), "an index past the forms clamps");
+ }
+
+ #[test]
+ fn malformed_lines_are_reported_not_fatal() {
+ let (entries, errors) = parse_entries("\tok\tはい\nno tabs here\n\tonly\n\ta\tb\tc\textra\n\t\tempty source\n", 1);
+ assert_eq!(entries.len(), 1);
+ assert_eq!(errors.len(), 4, "{errors:?}");
+ let (entries, errors) = parse_entries("\ta\\tb\tx\\ny\\\\z\n", 1);
+ assert!(errors.is_empty(), "{errors:?}");
+ assert_eq!(entries, [Entry { context: String::new(), source: "a\tb".into(), translation: "x\ny\\z".into() }]);
+ }
+
+ #[test]
+ fn strict_validation_skips_only_the_bad_line() {
+ for (text, forms, error) in [
+ ("\tFile", 1, "context<TAB>"),
+ ("\tFile\t", 1, "nonempty"),
+ ("\tFile\\q\tFiles", 1, "unknown escape"),
+ ("\tFile\tFiles\\", 1, "trailing backslash"),
+ ("\tOpen…\tOpen", 1, "ellipsis"),
+ ("\tOpen {file}\tOpen {name}", 1, "placeholders"),
+ ("@plural\tpage\tPages", 1, "one|other"),
+ ("@plural\t{n} page|{n} pages\t{n} pages", 2, "2 nonempty"),
+ ("@plural\t{n} page|{n} pages\tPages", 1, "placeholders"),
+ ("@unknown\tFile\tFiles", 1, "reserved context"),
+ ] {
+ // The bad line comes first; the good line after it still loads.
+ let (catalog, errors) = Catalog::parse(&format!("{text}\n\tSave\t保存\n"), forms);
+ assert_eq!(errors.len(), 1, "{text:?}: {errors:?}");
+ assert!(errors[0].starts_with("line 1: ") && errors[0].contains(error), "{errors:?}");
+ assert_eq!(catalog.plain("Save"), Some("保存"), "{text:?}");
+ }
+ let (catalog, errors) = Catalog::parse("\tFile\tファイル\n\tFile\t別\n", 1);
+ assert!(errors.len() == 1 && errors[0].contains("line 2: duplicate"), "{errors:?}");
+ assert_eq!(catalog.plain("File"), Some("ファイル"), "the first entry wins");
+ }
+
+ #[test]
+ fn catalogs_handle_escapes_crlf_and_distinct_contexts() {
+ let (catalog, errors) =
+ Catalog::parse("# comment\r\n\r\n\tLine\\nTab\\tPath\\\\\tOther\\nTab\\tPath\\\\\r\nweight\tLight\tThin\r\ntheme\tLight\tPale\r\n", 1);
+ assert!(errors.is_empty(), "{errors:?}");
+ assert_eq!(catalog.plain("Line\nTab\tPath\\"), Some("Other\nTab\tPath\\"));
+ assert_eq!(catalog.contextual("weight", "Light"), Some("Thin"));
+ assert_eq!(catalog.contextual("theme", "Light"), Some("Pale"));
+ }
+
+ #[test]
+ fn broken_catalog_falls_back_to_english() {
+ static BROKEN: LangInfo =
+ LangInfo { code: "broken", name: "Broken test catalog", source: "malformed\n\\", plural: plural_none, catalog: OnceLock::new() };
+ assert_eq!(tr(Lang(&BROKEN), "File"), "File");
+ assert_eq!(trn(Lang(&BROKEN), 2, "{n} page", "{n} pages"), "2 pages");
+ }
+
+ #[test]
+ fn contextual_id_and_plural_lookups_have_english_fallbacks() {
+ static TEST: LangInfo = LangInfo {
+ code: "test",
+ name: "Test catalog",
+ source: "\tLight\tPlain light\nweight\tLight\tThin\n@id\tfile.open\tOpen dialog…\n@plural\t{n} page|{n} pages\tOne page: {n}|Many pages: {n}\n",
+ plural: plural_one_other,
+ catalog: OnceLock::new(),
+ };
+ let l = Lang(&TEST);
+ assert_eq!(tr_ctx(l, "weight", "Light"), "Thin");
+ assert_eq!(tr_ctx(l, "theme", "Light"), "Plain light");
+ assert_eq!(tr_ctx(l, "theme", "Unknown"), "Unknown");
+ assert_eq!(tr_id(l, "file.open", "Reworded English…"), "Open dialog…");
+ assert_eq!(tr_id(l, "unknown", "Light"), "Plain light");
+ assert_eq!(tr_id(l, "unknown", "Unknown"), "Unknown");
+ assert_eq!(trn(l, 1, "{n} page", "{n} pages"), "One page: 1");
+ assert_eq!(trn(l, 0, "{n} page", "{n} pages"), "Many pages: 0");
+ assert_eq!(trn(l, u64::MAX, "{n} page", "{n} pages"), format!("Many pages: {}", u64::MAX));
+ }
+
+ #[test]
+ fn formatting_reorders_parameters_without_reinterpreting_user_text() {
+ let args = [("file", "日本語-{n}.pdf"), ("n", "2")];
+ assert_eq!(fmt("{n}: {file}; {unknown}", &args), "2: 日本語-{n}.pdf; {unknown}");
+ assert_eq!(fmt("{file} / {file}", &args), "日本語-{n}.pdf / 日本語-{n}.pdf");
+ assert_eq!(fmt("text {unfinished", &args), "text {unfinished");
+ assert_eq!(fmt("}{n}{", &args), "}2{");
+ assert_eq!(fmt("unchanged", &[]), "unchanged");
+ }
+
+ #[test]
+ fn current_language_is_per_thread() {
+ set_current(JA());
+ assert_eq!(t("File"), "ファイル");
+ std::thread::spawn(|| assert_eq!(current(), Lang::EN)).join().unwrap();
+ set_current(Lang::EN);
+ assert_eq!(t("File"), "File");
+ }
+
+ #[test]
+ fn plurals_and_placeholders() {
+ assert_eq!(trn(Lang::EN, 1, "{n} item", "{n} items"), "1 item");
+ assert_eq!(trn(Lang::EN, 0, "{n} item", "{n} items"), "0 items");
+ assert_eq!(trn(Lang::EN, 7, "{n} item", "{n} items"), "7 items");
+ // No `@plural` entry yet: Japanese falls back to the English forms.
+ assert_eq!(trn(JA(), 7, "{n} item", "{n} items"), "7 items");
+ assert_eq!(fmt("{b} before {a}", &[("a", "x"), ("b", "y"), ("c", "z")]), "y before x");
+ assert_eq!(fmt("{missing}", &[]), "{missing}");
+ assert_eq!(placeholders("a {x} b {y} {"), ["x", "y"]);
+ }
+
+ #[test]
+ fn language_persists_and_invalid_input_keeps_current_language() {
+ let mut app = crate::PdfCraftApp::default();
+ assert_eq!(app.language, AUTO);
+ app.set_option("language", "JA").unwrap();
+ assert_eq!(app.language, "ja");
+ assert!(app.set_option("language", "xx").is_err());
+ assert_eq!(app.language, "ja");
+ let mut restored = crate::PdfCraftApp::default();
+ restored.restore(&app.persist());
+ assert_eq!(restored.language, "ja");
+ restored.restore(r#"{"language":"xx"}"#);
+ assert_eq!(restored.language, "ja");
+ app.set_option("language", AUTO).unwrap();
+ assert_eq!(app.language, AUTO);
+ // Settings written before the system-locale default (no key) follow the system.
+ let mut legacy = crate::PdfCraftApp::default();
+ legacy.restore("{}");
+ assert_eq!(legacy.language, AUTO);
+ }
+
+ /// Every bundled catalog is well-formed and consistent with its sources.
+ #[test]
+ fn bundled_catalogs_are_consistent() {
+ let mut codes = std::collections::HashSet::new();
+ for l in &LANGUAGES {
+ assert!(codes.insert(l.code), "duplicate code {}", l.code);
+ assert!(l.code == l.code.to_ascii_lowercase() && !l.name.is_empty(), "{}", l.code);
+ let (entries, errors) = parse_entries(l.source, l.plural_forms());
+ assert!(errors.is_empty(), "{}: {errors:?}", l.code);
+ for e in entries.iter().filter(|e| e.context == "@id") {
+ let command = pdfcraft_engine::commands::command(&e.source);
+ let Some(command) = command else { panic!("{}: unknown command id {:?}", l.code, e.source) };
+ assert_eq!(placeholders(&e.translation), placeholders(command.label), "{}: {}", l.code, e.source);
+ assert_eq!(e.translation.ends_with('…'), command.label.ends_with('…'), "{}: ellipsis mismatch: {}", l.code, e.source);
+ }
+ }
+ }
+}
diff --git a/crates/ui-egui/src/js_ui.rs b/crates/ui-egui/src/js_ui.rs
index 5209c4c42..8eb240d52 100644
--- a/crates/ui-egui/src/js_ui.rs
+++ b/crates/ui-egui/src/js_ui.rs
@@ -221,19 +221,21 @@ pub(crate) fn document_js_body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tok
/// Preferences: interface language, identity and JavaScript. Returns `true` to close.
pub(crate) fn preferences_body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) -> bool {
- ui.label(egui::RichText::new(app.language.tr("Preferences")).font(theme::semibold(18.0)));
+ ui.label(egui::RichText::new(tl!("Preferences")).font(theme::semibold(18.0)));
ui.horizontal(|ui| {
- ui.label(app.language.tr("Interface language"));
- egui::ComboBox::from_id_salt("interface-language").selected_text(app.language.name()).show_ui(ui, |ui| {
- for language in crate::i18n::Language::ALL {
- ui.selectable_value(&mut app.language, language, language.name());
+ ui.label(tl!("Interface language"));
+ let selected = crate::i18n::Lang::from_code(&app.language).map_or(tl!("Auto"), crate::i18n::Lang::name);
+ egui::ComboBox::from_id_salt("interface-language").selected_text(selected).show_ui(ui, |ui| {
+ ui.selectable_value(&mut app.language, crate::i18n::AUTO.to_string(), tl!("Auto"));
+ for language in crate::i18n::Lang::all() {
+ ui.selectable_value(&mut app.language, language.code().to_string(), language.name());
}
});
});
ui.add_space(8.0);
- ui.label(egui::RichText::new(app.language.tr("Documents and view")).font(theme::semibold(13.0)));
+ ui.label(egui::RichText::new(tl!("Documents and view")).font(theme::semibold(13.0)));
ui.horizontal(|ui| {
- ui.label(app.language.tr("Default workspace mode"));
+ ui.label(tl!("Default workspace mode"));
for (mode, label) in [
(crate::Mode::AllTools, "All Tools"),
(crate::Mode::Read, "Read"),
@@ -241,19 +243,19 @@ pub(crate) fn preferences_body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tok
(crate::Mode::Convert, "Convert"),
(crate::Mode::Sign, "E-Sign"),
] {
- ui.radio_value(&mut app.default_mode, mode, app.language.tr(label));
+ ui.radio_value(&mut app.default_mode, mode, tl!(label));
}
});
ui.label(
- egui::RichText::new(app.language.tr("Used when opening PDFs. An explicit launch or control mode takes precedence for the session."))
+ egui::RichText::new(tl!("Used when opening PDFs. An explicit launch or control mode takes precedence for the session."))
.small()
.color(t.text_muted),
);
ui.add_space(8.0);
// Identity: the author of new comments (Acrobat: Preferences ▸ Identity).
- ui.label(egui::RichText::new(app.language.tr("Identity")).font(theme::semibold(13.0)));
+ ui.label(egui::RichText::new(tl!("Identity")).font(theme::semibold(13.0)));
ui.horizontal(|ui| {
- let label = ui.label(app.language.tr("Name on new comments"));
+ let label = ui.label(tl!("Name on new comments"));
ui.add(egui::TextEdit::singleline(&mut app.comment_prefs.author).desired_width(220.0).char_limit(crate::MAX_AUTHOR_CHARS))
.labelled_by(label.id);
});
@@ -262,7 +264,7 @@ pub(crate) fn preferences_body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tok
egui::Frame::new().fill(t.hover).corner_radius(egui::CornerRadius::same(6)).inner_margin(egui::Margin::same(10)).show(ui, |ui| {
ui.set_width(ui.available_width());
let mut on = app.session.javascript();
- if ui.checkbox(&mut on, app.language.tr("Enable Acrobat JavaScript")).changed() {
+ if ui.checkbox(&mut on, tl!("Enable Acrobat JavaScript")).changed() {
app.session.set_javascript(on);
}
ui.label(
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 64cbaef4c..864cdff95 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -7,6 +7,13 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
+/// Translate an English UI string into the current language (see [`i18n`]).
+macro_rules! tl {
+ ($s:expr) => {
+ $crate::i18n::t($s)
+ };
+}
+
mod a11y_ui;
mod actions_ui;
pub mod canvas;
@@ -318,7 +325,8 @@ pub struct PdfCraftApp {
/// Comment author, per-tool colours and widths, pin.
pub comment_prefs: comments::CommentPrefs,
pub theme: ThemeKind,
- pub language: i18n::Language,
+ /// Interface language preference: `auto` (follow the system) or a code from [`i18n::LANGUAGES`].
+ pub language: String,
/// Follow the operating system's light/dark setting.
pub follow_system_theme: bool,
pub dialog: Option<Dialog>,
@@ -533,7 +541,7 @@ impl PdfCraftApp {
quick_tool: QuickTool::Select,
comment_prefs: Default::default(),
theme: ThemeKind::Light,
- language: i18n::Language::default(),
+ language: i18n::AUTO.to_string(),
follow_system_theme: false,
dialog: None,
update_source: None,
@@ -992,8 +1000,8 @@ impl PdfCraftApp {
if let Ok(mode) = serde_json::from_value::<Mode>(v["default_mode"].clone()) {
self.default_mode = mode;
}
- if let Ok(language) = serde_json::from_value::<i18n::Language>(v["language"].clone()) {
- self.language = language;
+ if let Some(language) = v["language"].as_str().and_then(i18n::normalize_pref) {
+ self.language = language.to_string();
}
// An empty or missing name keeps the login-name default; settings are untrusted, so the
// name is cut to a sane length.
@@ -1037,7 +1045,11 @@ impl PdfCraftApp {
let view = self.active.and_then(|i| self.views.get_mut(i));
match (key, view) {
("language", _) => {
- self.language = i18n::Language::parse(value).ok_or("language must be en or ja")?;
+ let language = i18n::normalize_pref(value).ok_or_else(|| {
+ let codes: Vec<&str> = std::iter::once(i18n::AUTO).chain(i18n::Lang::all().map(i18n::Lang::code)).collect();
+ format!("language must be one of {}", codes.join(", "))
+ })?;
+ self.language = language.to_string();
}
("theme", _) => {
self.follow_system_theme = value == "system";
@@ -1337,6 +1349,7 @@ impl eframe::App for PdfCraftApp {
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
let ctx = ui.ctx().clone();
+ i18n::set_current(i18n::Lang::from_pref(&self.language));
// Fonts registered via set_fonts only take effect next frame; named families would panic now.
if !self.fonts_ready {
ctx.request_repaint();
diff --git a/crates/ui-egui/tests/control.rs b/crates/ui-egui/tests/control.rs
index 25da10b32..7bffc047f 100644
--- a/crates/ui-egui/tests/control.rs
+++ b/crates/ui-egui/tests/control.rs
@@ -4,6 +4,7 @@
use std::sync::{Arc, Mutex};
use egui_kittest::Harness;
+use egui_kittest::kittest::Queryable;
use pdfcraft_ui_egui::PdfCraftApp;
use pdfcraft_ui_egui::control::{ControlClient, Reply};
use serde_json::{Value, json};
@@ -67,6 +68,40 @@ fn ok(h: &mut Harness<'static, PdfCraftApp>, c: &ControlClient, method: &str, pa
call(h, c, method, params).unwrap_or_else(|e| panic!("{method}: {e}"))
}
+/// Switching the interface language changes labels only: documents, their dirty state and the
+/// command ids agents drive stay exactly the same.
+#[test]
+fn language_switch_preserves_document_and_command_ids() {
+ use pdfcraft_ui_egui::i18n;
+ let (mut h, c) = harness();
+ let doc = h.state().views[0].id;
+ h.state_mut().session.apply(doc, pdfcraft_engine::Edit::RotatePages { pages: vec![0], degrees: 90 }).unwrap();
+ let documents = ok(&mut h, &c, "ui.state", json!({}))["documents"].clone();
+ assert_eq!(documents[0]["dirty"], true);
+ let commands = ok(&mut h, &c, "ui.commands", json!({}));
+ for code in ["ja", "en"] {
+ ok(&mut h, &c, "ui.set", json!({ "key": "language", "value": code }));
+ h.run_steps(2);
+ let state = ok(&mut h, &c, "ui.state", json!({}));
+ assert_eq!(state["language"], code);
+ assert_eq!(state["documents"], documents);
+ assert_eq!(ok(&mut h, &c, "ui.commands", json!({})), commands);
+
+ let lang = i18n::Lang::from_code(code).unwrap();
+ h.get_by_label(i18n::tr(lang, "Menu")).click();
+ h.run_steps(2);
+ h.get_by_label(&format!("{} ⏵", i18n::tr(lang, "File"))).hover();
+ h.run_steps(3);
+ h.get_by_label_contains(i18n::tr(lang, "Open…"));
+ ok(&mut h, &c, "ui.key", json!({ "key": "Escape" }));
+ ok(&mut h, &c, "ui.key", json!({ "key": "Escape" }));
+ h.run_steps(2);
+ }
+ let error = call(&mut h, &c, "ui.set", json!({ "key": "language", "value": "xx" })).unwrap_err();
+ assert!(error.contains("auto, en, ja"), "{error}");
+ assert_eq!(ok(&mut h, &c, "ui.state", json!({}))["language"], "en");
+}
+
#[cfg(target_os = "linux")]
fn start_autoscroll(h: &mut Harness<'static, PdfCraftApp>, c: &ControlClient) -> egui::Pos2 {
let p = h.state().views[0].viewport_rect().center();
diff --git a/docs/localization.md b/docs/localization.md
index 5bd89d325..c33f44b7e 100644
--- a/docs/localization.md
+++ b/docs/localization.md
@@ -1,6 +1,8 @@
# Interface language
-Choose **Edit > Preferences > Interface language** and select **English** or **日本語**. The change applies immediately and persists between launches. Command ids, document contents and file names are unchanged.
+Choose **Edit > Preferences > Interface language** and select **Auto**, **English** or **日本語**. The change applies immediately and persists between launches. Command ids, document contents and file names are unchanged.
+
+**Auto** (the default) follows the system language: `LC_ALL`, `LC_MESSAGES` or `LANG`, then the preferred-languages list on macOS. A system language without a catalog, such as French, shows English. Windows has no system-language detection yet, so **Auto** shows English there unless `LANG` is set.
The control channel exposes the setting through `ui.set`:
@@ -8,8 +10,27 @@ The control channel exposes the setting through `ui.set`:
{"method":"ui.set","params":{"key":"language","value":"ja"}}
```
-`ui.state` reports `language` as `en` or `ja`. Unknown language codes return an error without changing the current setting. Old preferences default to English.
+The value is `auto` or a language code (`en`, `ja`), in any case. `ui.state` reports `language` as written in the preferences (`auto`, `en` or `ja`). Unknown values return an error without changing the current setting. Preferences saved before this setting existed follow the system language.
This first translation pass covers the main menu and core registered menu commands. Untranslated labels use English. Vertical Japanese PDF rendering is an existing viewer feature; this change does not add vertical text editing.
Japanese interface text uses BIZ UDPGothic from [craft-fonts](https://github.com/storytold/craft-fonts), an optional build input that every release includes (`CRAFT_FONTS_DIR`; see the README). A build made without it has no Japanese face, so Japanese labels show replacement boxes.
+
+## How translations work
+
+PdfCraft uses the same system as PhotoCraft (`crates/ui-egui/src/i18n/`):
+
+- Strings in the code stay in English and serve as lookup keys. At draw time, `tl!("Save")` returns the text in the current language, and falls back to English when there is no entry.
+- Each language has a catalog, `crates/ui-egui/src/i18n/<code>.tsv`, with one entry per line: `context<TAB>English<TAB>translation`. An empty context marks a plain string. `@id` keys an entry by command id (for example `file.saveAs`), so one menu item can read differently from another with the same English label. `@plural` holds plural forms. Any other context disambiguates an English word with several meanings (`tr_ctx`). The header of `ja.tsv` documents the format and escapes.
+- Placeholders (`{name}`) must appear in both columns. A trailing `…` must be kept. `i18n::fmt` fills placeholders in one pass, so a value such as a file name containing `{n}` is inserted as written.
+- Catalogs are validated strictly: unknown escapes, unknown `@` contexts, placeholder or ellipsis mismatches, wrong plural form counts and duplicates are errors. The tests require the bundled catalogs to have none; at run time a bad line is skipped (and logged) and that string shows in English.
+- Catalogs are assets: each `.tsv` has an `ATTRIBUTION.toml` entry with `kind = "translation"` and its SHA-256, checked by `cargo xtask assets`.
+- Translations are clean-room: write them from the meaning of the English text, never from another product's string tables.
+
+## Adding a language
+
+1. Copy the header of `ja.tsv` into `xx.tsv` and translate entries.
+2. Add one row to `LANGUAGES` in `crates/ui-egui/src/i18n/mod.rs`: code, native name, catalog and plural rule.
+3. Add an `ATTRIBUTION.toml` entry for the catalog (`kind = "translation"`), then run `cargo xtask assets --write` and `cargo xtask assets`.
+
+The Preferences dropdown, the system-language match and the catalog tests (format, duplicates, placeholders, plural forms, command ids) then pick it up.
diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml
index 86984895f..d78949bc4 100644
--- a/parity/acrobat-features.toml
+++ b/parity/acrobat-features.toml
@@ -9806,8 +9806,8 @@ milestone = "M14"
status = "partial"
commands = []
tools = []
-evidence = ["crates/ui-egui/src/i18n.rs::language_persists_and_invalid_input_keeps_current_language"]
-notes = "Preferences switches English/Japanese and persists; ui.set language en|ja and ui.state expose it. Core menu labels translated; broader dialog/panel translations and additional languages remain open."
+evidence = ["crates/ui-egui/src/i18n/mod.rs::language_persists_and_invalid_input_keeps_current_language", "crates/ui-egui/src/i18n/mod.rs::bundled_catalogs_are_consistent", "crates/ui-egui/tests/control.rs::language_switch_preserves_document_and_command_ids"]
+notes = "Preferences switches Auto (system language)/English/Japanese and persists; ui.set language auto|en|ja and ui.state expose it. TSV catalogs per language (same system as PhotoCraft). Core menu labels translated; dialogs, panels, Windows system-language detection and more languages remain open."
[[feature]]
id = "misc.prefs-reading"
diff --git a/xtask/src/assets.rs b/xtask/src/assets.rs
index 36ef6ac90..43a0af7b2 100644
--- a/xtask/src/assets.rs
+++ b/xtask/src/assets.rs
@@ -46,7 +46,7 @@ pub const ADOBE_DATA_ALLOWED: &[(&str, &str)] = &[("hayro-cmap", "assets/cmaps.b
/// File extensions that count as assets wherever they appear in the repository.
const ASSET_EXTENSIONS: &[&str] = &[
"png", "jpg", "jpeg", "gif", "svg", "ico", "icns", "webp", "bmp", "tif", "tiff", "avif", "heic", "ttf", "otf", "ttc", "woff", "woff2", "pfb",
- "pfa", "afm", "icc", "icm", "pdf", "eps", "ps", "ai", "psd", "mp3", "wav", "ogg", "flac", "mp4", "mov", "webm", "cur", "ani", "brotli",
+ "pfa", "afm", "icc", "icm", "pdf", "eps", "ps", "ai", "psd", "mp3", "wav", "ogg", "flac", "mp4", "mov", "webm", "cur", "ani", "brotli", "tsv",
];
#[derive(Deserialize, Default)]
@@ -221,7 +221,9 @@ fn mentions_adobe(s: &str) -> bool {
pub fn check(root: &Path, m: &Manifest, repo_files: &[String], lock: &BTreeSet<(String, String)>) -> Vec<String> {
let mut problems = Vec::new();
let mut seen = BTreeSet::new();
- let visual = |kind: &str| matches!(kind, "icon" | "image" | "font" | "logo" | "cursor" | "video");
+ // Kinds that may never come from Adobe (AGENTS.md §1.1): visual design, and UI translations
+ // (which must be clean-room, never taken from a product's string tables).
+ let visual = |kind: &str| matches!(kind, "icon" | "image" | "font" | "logo" | "cursor" | "video" | "translation");
let licence_ok = |what: &str, licence: &str, problems: &mut Vec<String>| {
for id in licence_ids(licence) {
if !ALLOWED_LICENCES.contains(&id) {
@@ -483,6 +485,15 @@ mod tests {
assert!(p.iter().any(|p| p.contains("no ATTRIBUTION.toml entry")), "{p:?}");
}
+ #[test]
+ fn translation_catalogs_require_attribution() {
+ assert!(is_asset_path("crates/ui-egui/src/i18n/ja.tsv"));
+ let p = check(&root(), &Manifest::default(), &["crates/ui-egui/src/i18n/ja.tsv".into()], &lock(&[]));
+ assert!(p.iter().any(|p| p.contains("no ATTRIBUTION.toml entry")), "{p:?}");
+ let m = Manifest { asset: vec![asset("crates/ui-egui/src/i18n/ja.tsv", "Adobe", "translation", "MIT")], ..Default::default() };
+ assert!(check(&root(), &m, &[], &lock(&[])).iter().any(|p| p.contains("from Adobe is forbidden")));
+ }
+
#[test]
fn adobe_icons_are_rejected() {
let m = Manifest { asset: vec![asset("assets/icons/x.svg", "Adobe Inc.", "icon", "MIT")], ..Default::default() };