diff --git a/AGENT_DOCUMENTATION.md b/AGENT_DOCUMENTATION.md index ccda723..6a8c287 100644 --- a/AGENT_DOCUMENTATION.md +++ b/AGENT_DOCUMENTATION.md @@ -25,6 +25,7 @@ Versioned examples and sanitized fixtures remain beside their contracts and in | --- | --- | | [Project](docs/interfaces/canvas-pilot.md) | Project schema, versions and migrations | | [Settings](docs/interfaces/canvas-pilot-settings.md) | User preferences and settings compatibility | +| [Language packs](docs/interfaces/language-packs.md) | Runtime ZIP catalogs, installation and fallback | | [Recovery](docs/interfaces/canvas-pilot-recovery.md) | Recovery storage and restoration | | [Layer clipboard](docs/interfaces/canvas-pilot-clipboard.md) | Versioned geometry, crop, fit and blanking payload | | [Geometry exchange](docs/interfaces/canvas-pilot-exchange.md) | Precision, omissions and round trips | diff --git a/Cargo.lock b/Cargo.lock index 394be45..2dc59d2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -548,7 +548,7 @@ dependencies = [ [[package]] name = "canvas-pilot" -version = "0.9.6" +version = "0.9.7" dependencies = [ "base64", "craft-dwg", diff --git a/Cargo.toml b/Cargo.toml index 451bec3..68c83d6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ default-members = ["crates/canvas-pilot"] resolver = "3" [workspace.package] -version = "0.9.6" +version = "0.9.7" edition = "2024" license = "MIT" repository = "https://proxy.dandaedre.com/gitea/idle-org/canvas-pilot" diff --git a/crates/canvas-pilot/examples/text_shaping.rs b/crates/canvas-pilot/examples/text_shaping.rs index a1ce3ce..2737f60 100644 --- a/crates/canvas-pilot/examples/text_shaping.rs +++ b/crates/canvas-pilot/examples/text_shaping.rs @@ -3,9 +3,16 @@ //! in a browser or Pango. Editing the samples never modifies a project. use eframe::egui; +#[path = "../src/language_packs.rs"] +#[allow(dead_code)] +mod language_packs; #[path = "../src/localization.rs"] mod localization; -rust_i18n::i18n!("locales", fallback = "en"); +rust_i18n::i18n!( + "locales", + fallback = "en", + backend = language_packs::Backend +); struct Probe { language: localization::Language, @@ -46,13 +53,14 @@ impl eframe::App for Probe { egui::CentralPanel::default().show(ui, |ui| { ui.heading("Canvas Pilot — text shaping"); ui.label("Offline diagnostic: compare labels, wrapping and editable Unicode text. No device connection."); - let before = self.language; + let before = self.language.clone(); egui::ComboBox::from_id_salt("probe-language") .height(440.0) .selected_text(self.language.name(ui.ctx())) .show_ui(ui, |ui| { for language in localization::Language::ALL { - ui.selectable_value(&mut self.language, language, language.name(ui.ctx())); + let name = language.name(ui.ctx()); + ui.selectable_value(&mut self.language, language, name); } }); if before != self.language { self.language.apply(ui.ctx()); } diff --git a/crates/canvas-pilot/locales/en.json b/crates/canvas-pilot/locales/en.json index 9607b8a..9704cf5 100644 --- a/crates/canvas-pilot/locales/en.json +++ b/crates/canvas-pilot/locales/en.json @@ -479,5 +479,6 @@ "language.name.ne": "Nepali", "language.name.th": "Thai", "language.name.hi": "Hindi", - "language.name.tok": "Toki Pona" + "language.name.tok": "Toki Pona", + "language.install-pack": "Install language pack…" } diff --git a/crates/canvas-pilot/locales/eo.json b/crates/canvas-pilot/locales/eo.json index ab55fc0..ce0693a 100644 --- a/crates/canvas-pilot/locales/eo.json +++ b/crates/canvas-pilot/locales/eo.json @@ -479,5 +479,6 @@ "language.name.ne": "Nepala", "language.name.th": "Taja", "language.name.hi": "Hindia", - "language.name.tok": "Tokipono" + "language.name.tok": "Tokipono", + "language.install-pack": "Instali lingvopakaĵon…" } diff --git a/crates/canvas-pilot/locales/es.json b/crates/canvas-pilot/locales/es.json index 06f8bc6..bd43271 100644 --- a/crates/canvas-pilot/locales/es.json +++ b/crates/canvas-pilot/locales/es.json @@ -479,5 +479,6 @@ "language.name.ne": "Nepalí", "language.name.th": "Tailandés", "language.name.hi": "Hindi", - "language.name.tok": "Toki Pona" + "language.name.tok": "Toki Pona", + "language.install-pack": "Instalar paquete de idiomas…" } diff --git a/crates/canvas-pilot/locales/fr.json b/crates/canvas-pilot/locales/fr.json index fc3c45d..733fa22 100644 --- a/crates/canvas-pilot/locales/fr.json +++ b/crates/canvas-pilot/locales/fr.json @@ -479,5 +479,6 @@ "language.name.ne": "Népalais", "language.name.th": "Thaï", "language.name.hi": "Hindi", - "language.name.tok": "Toki Pona" + "language.name.tok": "Toki Pona", + "language.install-pack": "Installer un pack de langues…" } diff --git a/crates/canvas-pilot/locales/grc.json b/crates/canvas-pilot/locales/grc.json index b9d232e..abc46ba 100644 --- a/crates/canvas-pilot/locales/grc.json +++ b/crates/canvas-pilot/locales/grc.json @@ -479,5 +479,6 @@ "language.name.ne": "Νεπαλικὴ", "language.name.th": "Ταϊκὴ", "language.name.hi": "Ἰνδικὴ", - "language.name.tok": "Τόκι Πόνα" + "language.name.tok": "Τόκι Πόνα", + "language.install-pack": "Install language pack…" } diff --git a/crates/canvas-pilot/locales/hi.json b/crates/canvas-pilot/locales/hi.json index 6d43d4c..4b1af8d 100644 --- a/crates/canvas-pilot/locales/hi.json +++ b/crates/canvas-pilot/locales/hi.json @@ -479,5 +479,6 @@ "language.name.ne": "नेपाली", "language.name.th": "थाई", "language.name.hi": "हिन्दी", - "language.name.tok": "टोकी पोना" + "language.name.tok": "टोकी पोना", + "language.install-pack": "भाषा पैक स्थापित करें…" } diff --git a/crates/canvas-pilot/locales/ja.json b/crates/canvas-pilot/locales/ja.json index 19e38c8..509e951 100644 --- a/crates/canvas-pilot/locales/ja.json +++ b/crates/canvas-pilot/locales/ja.json @@ -479,5 +479,6 @@ "language.name.ne": "ネパール語", "language.name.th": "タイ語", "language.name.hi": "ヒンディー語", - "language.name.tok": "トキポナ" + "language.name.tok": "トキポナ", + "language.install-pack": "言語パックをインストール…" } diff --git a/crates/canvas-pilot/locales/ne.json b/crates/canvas-pilot/locales/ne.json index 33dfe14..bcb65f9 100644 --- a/crates/canvas-pilot/locales/ne.json +++ b/crates/canvas-pilot/locales/ne.json @@ -479,5 +479,6 @@ "language.name.ne": "नेपाली", "language.name.th": "थाई", "language.name.hi": "हिन्दी", - "language.name.tok": "टोकी पोना" + "language.name.tok": "टोकी पोना", + "language.install-pack": "भाषा प्याक स्थापना गर्नुहोस्…" } diff --git a/crates/canvas-pilot/locales/pt-PT.json b/crates/canvas-pilot/locales/pt-PT.json index 7dea0b9..39f1c42 100644 --- a/crates/canvas-pilot/locales/pt-PT.json +++ b/crates/canvas-pilot/locales/pt-PT.json @@ -479,5 +479,6 @@ "language.name.ne": "Nepalês", "language.name.th": "Tailandês", "language.name.hi": "Hindi", - "language.name.tok": "Toki Pona" + "language.name.tok": "Toki Pona", + "language.install-pack": "Instalar pacote de idiomas…" } diff --git a/crates/canvas-pilot/locales/th.json b/crates/canvas-pilot/locales/th.json index c93bd40..0550c59 100644 --- a/crates/canvas-pilot/locales/th.json +++ b/crates/canvas-pilot/locales/th.json @@ -479,5 +479,6 @@ "language.name.ne": "เนปาล", "language.name.th": "ไทย", "language.name.hi": "ฮินดี", - "language.name.tok": "โทกิโพนา" + "language.name.tok": "โทกิโพนา", + "language.install-pack": "ติดตั้งชุดภาษา…" } diff --git a/crates/canvas-pilot/locales/tok.json b/crates/canvas-pilot/locales/tok.json index e2f5f21..bcb94e8 100644 --- a/crates/canvas-pilot/locales/tok.json +++ b/crates/canvas-pilot/locales/tok.json @@ -479,5 +479,6 @@ "language.name.ne": "toki Nepali", "language.name.th": "toki Tawi", "language.name.hi": "toki Insi", - "language.name.tok": "toki pona" + "language.name.tok": "toki pona", + "language.install-pack": "o pana e kulupu toki…" } diff --git a/crates/canvas-pilot/locales/zh-CN.json b/crates/canvas-pilot/locales/zh-CN.json index 25f4c13..4281e60 100644 --- a/crates/canvas-pilot/locales/zh-CN.json +++ b/crates/canvas-pilot/locales/zh-CN.json @@ -479,5 +479,6 @@ "language.name.ne": "尼泊尔语", "language.name.th": "泰语", "language.name.hi": "印地语", - "language.name.tok": "道本语" + "language.name.tok": "道本语", + "language.install-pack": "安装语言包…" } diff --git a/crates/canvas-pilot/src/device_ui.rs b/crates/canvas-pilot/src/device_ui.rs index 6b7fc9b..5d42533 100644 --- a/crates/canvas-pilot/src/device_ui.rs +++ b/crates/canvas-pilot/src/device_ui.rs @@ -77,7 +77,7 @@ impl TransferScope { Self::Selected => tr(ctx, "ui.only-selected-layers"), Self::Folder(folder) => rust_i18n::t!( "scope.folder", - locale = localization::locale(ctx), + locale = &localization::locale(ctx), name = folder ) .into_owned(), diff --git a/crates/canvas-pilot/src/format_ui.rs b/crates/canvas-pilot/src/format_ui.rs index a82eb55..ece6f79 100644 --- a/crates/canvas-pilot/src/format_ui.rs +++ b/crates/canvas-pilot/src/format_ui.rs @@ -360,7 +360,7 @@ impl Editor { } let i = d.layer; let mut open = true; - egui::Window::new(rust_i18n::t!("layer.properties-title", locale = localization::locale(ctx), name = self.layout.layer_label(i)).into_owned()).id(egui::Id::new(("layer-properties", self.layout.layer_info(i).id))).open(&mut open).default_width(540.0).default_height(720.0).min_height(380.0).vscroll(true).show(ctx,|ui| { + egui::Window::new(rust_i18n::t!("layer.properties-title", locale = &localization::locale(ctx), name = self.layout.layer_label(i)).into_owned()).id(egui::Id::new(("layer-properties", self.layout.layer_info(i).id))).open(&mut open).default_width(540.0).default_height(720.0).min_height(380.0).vscroll(true).show(ctx,|ui| { ui.horizontal(|ui| { ui.selectable_value(&mut self.property_tab,PropertyTab::Source,tr(ui.ctx(), "ui.source")); ui.selectable_value(&mut self.property_tab,PropertyTab::Layer,tr(ui.ctx(), "ui.layer-ac9ffc")); diff --git a/crates/canvas-pilot/src/gui.rs b/crates/canvas-pilot/src/gui.rs index 164b370..1357f8f 100644 --- a/crates/canvas-pilot/src/gui.rs +++ b/crates/canvas-pilot/src/gui.rs @@ -120,7 +120,7 @@ impl ImportScope { Self::Selected => tr(ctx, "ui.selected-layers"), Self::Folder(name) => rust_i18n::t!( "scope.folder", - locale = localization::locale(ctx), + locale = &localization::locale(ctx), name = name ) .into_owned(), @@ -572,6 +572,7 @@ impl Editor { pub(super) fn with_saved_settings(ctx: &egui::Context) -> Self { let (store, saved) = settings::Store::open(); let mut editor = Self::with_settings(ctx, store, saved); + let startup_error = std::mem::take(&mut editor.error); if let Some(path) = editor .settings .path @@ -581,6 +582,12 @@ impl Editor { { editor.restore_recovery(ctx, path); } + if !startup_error.is_empty() { + if !editor.error.is_empty() { + editor.error.push('\n'); + } + editor.error.push_str(&startup_error); + } editor.device.try_startup_connection(ctx); editor } @@ -591,6 +598,12 @@ impl Editor { ) -> Self { theme::Theme::restore_recent(ctx, saved.recent_themes.clone()); saved.theme.apply(ctx); + let pack_errors = store + .path + .as_ref() + .and_then(|p| p.parent()) + .map(|directory| crate::language_packs::load(ctx, &directory.join("language-packs"))) + .unwrap_or_default(); saved.language.apply(ctx); preferences_ui::apply_scaling(ctx, saved.ui_scale, saved.text_scale); let mut device = device_ui::DeviceUi::with_connection_preferences( @@ -602,6 +615,7 @@ impl Editor { Self { device, settings: store, + error: pack_errors.join("\n"), language: saved.language, ui_scale: saved.ui_scale, text_scale: saved.text_scale, @@ -619,7 +633,7 @@ impl Editor { language: self .language_preview .as_ref() - .map_or(self.language, |preview| preview.previous), + .map_or_else(|| self.language.clone(), |preview| preview.previous.clone()), midra_host: self.device.host.clone(), recent_midra_hosts: self.device.recent_hosts.clone(), autoconnect_at_startup: self.device.autoconnect_at_startup, @@ -1917,7 +1931,7 @@ impl Editor { ); let label = rust_i18n::t!( "position.from-to", - locale = localization::locale(ui.ctx()), + locale = &localization::locale(ui.ctx()), from = position_point_name(ui.ctx(), self.corner), to = position_point_name(ui.ctx(), self.position_layer_point.unwrap_or(self.corner)) ) diff --git a/crates/canvas-pilot/src/language_packs.rs b/crates/canvas-pilot/src/language_packs.rs new file mode 100644 index 0000000..3d59e86 --- /dev/null +++ b/crates/canvas-pilot/src/language_packs.rs @@ -0,0 +1,446 @@ +//! Versioned, bounded runtime catalogs. Contract: docs/interfaces/language-packs.md. +use eframe::egui; +use serde::{Deserialize, Serialize}; +use std::{ + borrow::Cow, + collections::{BTreeMap, BTreeSet}, + io::{Read, Write}, + path::Path, + sync::{LazyLock, RwLock}, +}; + +const MAX_ARCHIVE: u64 = 2 * 1024 * 1024; +const MAX_EXPANDED: u64 = 4 * 1024 * 1024; +const MAX_PACKS: usize = 32; + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct Manifest { + version: u32, + id: String, + languages: Vec, +} +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Description { + pub locale: String, + pub name: String, + pub native_name: String, +} +#[derive(Clone)] +struct Pack { + manifest: Manifest, + catalogs: BTreeMap>, +} + +// The backend stores catalogs, never the selected locale. Each context selects explicitly. +static CATALOGS: LazyLock>>> = + LazyLock::new(Default::default); +pub struct Backend; +impl rust_i18n::Backend for Backend { + fn available_locales(&self) -> Vec> { + CATALOGS + .read() + .unwrap() + .keys() + .cloned() + .map(Cow::Owned) + .collect() + } + fn translate(&self, locale: &str, key: &str) -> Option> { + CATALOGS + .read() + .unwrap() + .get(locale)? + .get(key) + .cloned() + .map(Cow::Owned) + } + fn messages_for_locale(&self, locale: &str) -> Option, Cow<'_, str>)>> { + Some( + CATALOGS + .read() + .unwrap() + .get(locale)? + .iter() + .map(|(k, v)| (Cow::Owned(k.clone()), Cow::Owned(v.clone()))) + .collect(), + ) + } +} +pub fn valid_id(id: &str) -> bool { + !id.is_empty() + && id.len() <= 63 + && id + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') + && !id.starts_with('-') + && !id.ends_with('-') +} +pub fn available(ctx: &egui::Context) -> Vec { + ctx.data(|data| data.get_temp::>(egui::Id::new("language-packs"))) + .unwrap_or_default() +} +fn register(ctx: &egui::Context, pack: &Pack) { + let mut languages = available(ctx); + let mut backend = CATALOGS.write().unwrap(); + for language in &pack.manifest.languages { + backend.insert( + format!("pack:{}", language.locale), + pack.catalogs[&language.locale].clone(), + ); + languages.push(language.clone()); + } + languages.sort_by(|a, b| a.locale.cmp(&b.locale)); + ctx.data_mut(|data| data.insert_temp(egui::Id::new("language-packs"), languages)); +} +fn placeholders(text: &str) -> Result, String> { + text.split("%{") + .skip(1) + .map(|part| { + part.split_once('}') + .map(|(key, _)| key) + .filter(|key| !key.is_empty()) + .ok_or_else(|| "Malformed placeholder".into()) + }) + .collect() +} +fn parse(bytes: &[u8]) -> Result { + if bytes.len() as u64 > MAX_ARCHIVE { + return Err("Language pack exceeds 2 MiB".into()); + } + let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).map_err(|e| e.to_string())?; + if zip.is_empty() || zip.len() > 17 { + return Err("Expected manifest and at most 16 catalogs".into()); + } + let mut entries = BTreeMap::new(); + let mut total = 0; + for index in 0..zip.len() { + let mut entry = zip.by_index(index).map_err(|e| e.to_string())?; + let name = entry.name().to_owned(); + if name.contains(['/', '\\']) + || !name.ends_with(".json") + || entry.is_dir() + || entry + .unix_mode() + .is_some_and(|mode| mode & 0o170000 == 0o120000) + { + return Err("Pack entries must be regular JSON files at the ZIP root".into()); + } + let mut data = Vec::new(); + (&mut entry) + .take(MAX_EXPANDED - total + 1) + .read_to_end(&mut data) + .map_err(|e| e.to_string())?; + total += data.len() as u64; + if total > MAX_EXPANDED { + return Err("Expanded language pack exceeds 4 MiB".into()); + } + if entries.insert(name, data).is_some() { + return Err("Duplicate ZIP entry".into()); + } + } + let manifest: Manifest = serde_json::from_slice( + &entries + .remove("manifest.json") + .ok_or("Missing manifest.json")?, + ) + .map_err(|e| e.to_string())?; + if manifest.version != 1 + || !valid_id(&manifest.id) + || manifest.languages.is_empty() + || manifest.languages.len() > 16 + { + return Err("Invalid language-pack manifest or unsupported version".into()); + } + let english: BTreeMap = + serde_json::from_str(include_str!("../locales/en.json")).map_err(|e| e.to_string())?; + let mut catalogs = BTreeMap::new(); + for language in &manifest.languages { + if !valid_id(&language.locale) + || language.locale == "system" + || [ + "en", "fr", "ja", "zh-cn", "es", "grc", "eo", "pt-pt", "ne", "th", "hi", "tok", + ] + .contains(&language.locale.as_str()) + { + return Err("Invalid or built-in locale identifier".into()); + } + for name in [&language.name, &language.native_name] { + if name.trim().is_empty() || name.len() > 160 || name.chars().any(char::is_control) { + return Err("Invalid language display name".into()); + } + } + let messages: BTreeMap = serde_json::from_slice( + &entries + .remove(&format!("{}.json", language.locale)) + .ok_or("Missing or repeated language catalog")?, + ) + .map_err(|e| e.to_string())?; + if messages.is_empty() { + return Err("Empty language catalog".into()); + } + for (key, value) in &messages { + let source = english + .get(key) + .ok_or_else(|| format!("Unknown translation key: {key}"))?; + if value.trim().is_empty() + || value.len() > 16384 + || value + .chars() + .any(|c| c.is_control() && c != '\n' && c != '\t') + || placeholders(source)? != placeholders(value)? + { + return Err(format!("Invalid text or mismatched placeholders: {key}")); + } + } + catalogs.insert(language.locale.clone(), messages); + } + if !entries.is_empty() { + return Err("Unexpected files in language pack".into()); + } + Ok(Pack { manifest, catalogs }) +} +fn read(path: &Path) -> Result, String> { + let mut bytes = Vec::new(); + std::fs::File::open(path) + .map_err(|e| e.to_string())? + .take(MAX_ARCHIVE + 1) + .read_to_end(&mut bytes) + .map_err(|e| e.to_string())?; + Ok(bytes) +} +fn check_collisions(ctx: &egui::Context, pack: &Pack) -> Result<(), String> { + let existing = available(ctx); + if pack + .manifest + .languages + .iter() + .any(|new| existing.iter().any(|old| old.locale == new.locale)) + { + return Err("A language in this pack is already installed; remove its old ZIP and restart before replacing it".into()); + } + Ok(()) +} +/// Load once at application startup; invalid files do not prevent startup. +pub fn load(ctx: &egui::Context, directory: &Path) -> Vec { + ctx.data_mut(|data| { + data.insert_temp(egui::Id::new("language-packs"), Vec::::new()) + }); + let entries = match std::fs::read_dir(directory) { + Ok(entries) => entries, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return vec![], + Err(error) => return vec![error.to_string()], + }; + let mut paths = Vec::new(); + let mut errors = Vec::new(); + for entry in entries { + match entry { + Ok(entry) if entry.path().extension().is_some_and(|ext| ext == "zip") => { + paths.push(entry.path()) + } + Ok(_) => (), + Err(error) => errors.push(error.to_string()), + } + if paths.len() > MAX_PACKS { + errors.push("Too many language packs (maximum 32)".into()); + break; + } + } + paths.sort(); + for path in paths.into_iter().take(MAX_PACKS) { + let result = read(&path) + .and_then(|bytes| parse(&bytes)) + .and_then(|pack| { + check_collisions(ctx, &pack)?; + register(ctx, &pack); + Ok(()) + }); + if let Err(error) = result { + errors.push(format!("{}: {error}", path.display())); + } + } + errors +} +/// Validate the entire pack, persist without replacing existing files, then register. +pub fn install(ctx: &egui::Context, directory: &Path, source: &Path) -> Result<(), String> { + let bytes = read(source)?; + let pack = parse(&bytes)?; + check_collisions(ctx, &pack)?; + std::fs::create_dir_all(directory).map_err(|e| e.to_string())?; + if std::fs::read_dir(directory) + .map_err(|e| e.to_string())? + .filter_map(Result::ok) + .filter(|e| e.path().extension().is_some_and(|ext| ext == "zip")) + .count() + >= MAX_PACKS + { + return Err("Too many language packs (maximum 32)".into()); + } + let mut file = tempfile::NamedTempFile::new_in(directory).map_err(|e| e.to_string())?; + file.write_all(&bytes).map_err(|e| e.to_string())?; + file.as_file().sync_all().map_err(|e| e.to_string())?; + file.persist_noclobber(directory.join(format!("{}.zip", pack.manifest.id))) + .map_err(|e| e.to_string())?; + register(ctx, &pack); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::localization::{Language, tr}; + const EXAMPLE: &[u8] = include_bytes!("../../../docs/language-packs/language-pack.zip"); + fn archive(files: &[(&str, &[u8])]) -> Vec { + let mut writer = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for (name, data) in files { + writer + .start_file( + *name, + zip::write::SimpleFileOptions::default() + .compression_method(zip::CompressionMethod::Deflated), + ) + .unwrap(); + writer.write_all(data).unwrap(); + } + writer.finish().unwrap().into_inner() + } + fn modified(manifest: serde_json::Value, messages: serde_json::Value) -> Vec { + archive(&[ + ("manifest.json", &serde_json::to_vec(&manifest).unwrap()), + ("uk.json", &serde_json::to_vec(&messages).unwrap()), + ]) + } + fn manifest() -> serde_json::Value { + serde_json::json!({"version":1,"id":"test","languages":[{"locale":"uk","name":"Ukrainian","native_name":"Українська"}]}) + } + #[test] + fn example_matches_sources_installs_restarts_and_falls_back() { + let mut zip = zip::ZipArchive::new(std::io::Cursor::new(EXAMPLE)).unwrap(); + for (name, text) in [ + ( + "manifest.json", + include_str!("../../../docs/language-packs/example/manifest.json"), + ), + ( + "uk.json", + include_str!("../../../docs/language-packs/example/uk.json"), + ), + ( + "bho.json", + include_str!("../../../docs/language-packs/example/bho.json"), + ), + ] { + let mut actual = String::new(); + zip.by_name(name) + .unwrap() + .read_to_string(&mut actual) + .unwrap(); + assert_eq!(actual, text); + } + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("source.zip"); + std::fs::write(&source, EXAMPLE).unwrap(); + let destination = dir.path().join("packs"); + let ctx = egui::Context::default(); + assert!(load(&ctx, &destination).is_empty()); + install(&ctx, &destination, &source).unwrap(); + assert_eq!(available(&ctx).len(), 2); + Language::Pack("uk".into()).apply(&ctx); + assert_eq!(tr(&ctx, "ui.settings"), "Налаштування"); + assert_eq!( + rust_i18n::t!( + "theme.current", + locale = &crate::localization::locale(&ctx), + name = "Test" + ), + "Поточна тема: Test" + ); + assert_eq!(tr(&ctx, "language.name.en"), "English"); + let original = std::fs::read(destination.join("example-uk-bho.zip")).unwrap(); + assert!(install(&ctx, &destination, &source).is_err()); + assert_eq!( + original, + std::fs::read(destination.join("example-uk-bho.zip")).unwrap() + ); + let restarted = egui::Context::default(); + assert!(load(&restarted, &destination).is_empty()); + Language::Pack("bho".into()).apply(&restarted); + assert_eq!(tr(&restarted, "ui.close"), "बंद करीं"); + assert_eq!(tr(&ctx, "ui.close"), "Закрити"); + std::fs::remove_file(destination.join("example-uk-bho.zip")).unwrap(); + assert!(load(&restarted, &destination).is_empty()); + Language::Pack("bho".into()).apply(&restarted); + assert_eq!(tr(&restarted, "ui.close"), "Close"); + } + #[test] + fn invalid_packs_never_install_and_startup_skips_bad_files() { + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("source.zip"); + let destination = dir.path().join("packs"); + let ctx = egui::Context::default(); + let mut cases = vec![ + b"not a ZIP".to_vec(), + vec![0; MAX_ARCHIVE as usize + 1], + archive(&[("../escape.json", b"{}")]), + archive(&[("manifest.json", b"broken")]), + archive(&[("other.json", b"{}")]), + archive(&[("manifest.json", &vec![b'x'; MAX_EXPANDED as usize + 1])]), + ]; + for messages in [ + serde_json::json!({}), + serde_json::json!({"unknown.key":"bad"}), + serde_json::json!({"ui.close":""}), + serde_json::json!({"ui.close":4}), + serde_json::json!({"ui.close":"%{extra}"}), + serde_json::json!({"theme.current":"missing placeholder"}), + serde_json::json!({"theme.current":"%{name"}), + serde_json::json!({"ui.close":"bad\u{0000}"}), + ] { + cases.push(modified(manifest(), messages)); + } + for (field, value) in [ + ("version", serde_json::json!(2)), + ("id", serde_json::json!("../escape")), + ("languages", serde_json::json!([])), + ("extra", serde_json::json!(true)), + ] { + let mut m = manifest(); + m[field] = value; + cases.push(modified(m, serde_json::json!({"ui.close":"Закрити"}))); + } + for locale in ["en", "system", "uk_UA", "../uk", ""] { + let mut m = manifest(); + m["languages"][0]["locale"] = locale.into(); + cases.push(modified(m, serde_json::json!({"ui.close":"Закрити"}))); + } + let mut m = manifest(); + m["languages"][0]["native_name"] = "\n".into(); + cases.push(modified(m, serde_json::json!({"ui.close":"Закрити"}))); + cases.push(archive(&[ + ("manifest.json", &serde_json::to_vec(&manifest()).unwrap()), + ("uk.json", b"{\"ui.close\":\"Close\"}"), + ("unexpected.json", b"{}"), + ])); + for bytes in cases { + std::fs::write(&source, bytes).unwrap(); + assert!(install(&ctx, &destination, &source).is_err()); + assert!(available(&ctx).is_empty()); + assert!(!destination.exists()); + } + std::fs::create_dir_all(&destination).unwrap(); + std::fs::write(destination.join("broken.zip"), b"bad").unwrap(); + std::fs::write(destination.join("good.zip"), EXAMPLE).unwrap(); + assert_eq!(load(&ctx, &destination).len(), 1); + assert_eq!(available(&ctx).len(), 2); + // A pre-existing target is never overwritten even when it was invalid at startup. + std::fs::write(destination.join("example-uk-bho.zip"), b"preserve").unwrap(); + let fresh = egui::Context::default(); + std::fs::write(&source, EXAMPLE).unwrap(); + assert!(install(&fresh, &destination, &source).is_err()); + assert_eq!( + std::fs::read(destination.join("example-uk-bho.zip")).unwrap(), + b"preserve" + ); + } +} diff --git a/crates/canvas-pilot/src/localization.rs b/crates/canvas-pilot/src/localization.rs index e00e77a..114a9a8 100644 --- a/crates/canvas-pilot/src/localization.rs +++ b/crates/canvas-pilot/src/localization.rs @@ -2,7 +2,7 @@ use eframe::egui; use serde::{Deserialize, Serialize}; -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum Language { #[default] @@ -21,6 +21,7 @@ pub enum Language { Th, Hi, Tok, + Pack(String), } impl Language { pub const ALL: [Self; 13] = [ @@ -39,8 +40,17 @@ impl Language { Self::Tok, ]; - pub fn name(self, ctx: &egui::Context) -> String { + pub fn name(&self, ctx: &egui::Context) -> String { let (native, key) = match self { + Self::Pack(id) => { + return crate::language_packs::available(ctx) + .into_iter() + .find(|p| p.locale == *id) + .map_or_else( + || format!("{id} (pack unavailable — English)"), + |p| format!("{} — {}", p.native_name, p.name), + ); + } Self::System => return tr(ctx, "language.system"), Self::En => ("English", "language.name.en"), Self::Fr => ("Français", "language.name.fr"), @@ -58,8 +68,24 @@ impl Language { format!("{native} — {}", tr(ctx, key)) } - pub fn apply(self, ctx: &egui::Context) { + pub fn apply(&self, ctx: &egui::Context) { let locale = match self { + Self::Pack(id) => { + let locale = if crate::language_packs::available(ctx) + .iter() + .any(|p| p.locale == *id) + { + format!("pack:{id}") + } else { + "en".into() + }; + ctx.set_fonts(font_definitions("en")); + ctx.data_mut(|data| { + data.insert_temp(egui::Id::new("application-locale"), locale.to_owned()) + }); + ctx.request_repaint(); + return; + } Self::En => "en", Self::Fr => "fr", Self::Ja => "ja", @@ -75,7 +101,9 @@ impl Language { Self::System => system_language(sys_locale::get_locale().as_deref()), }; ctx.set_fonts(font_definitions(locale)); - ctx.data_mut(|data| data.insert_temp(egui::Id::new("application-locale"), locale)); + ctx.data_mut(|data| { + data.insert_temp(egui::Id::new("application-locale"), locale.to_owned()) + }); ctx.request_repaint(); } } @@ -156,13 +184,13 @@ fn font_definitions(locale: &str) -> egui::FontDefinitions { fonts } -pub fn locale(ctx: &egui::Context) -> &'static str { - ctx.data(|data| data.get_temp::<&'static str>(egui::Id::new("application-locale"))) - .unwrap_or("en") +pub fn locale(ctx: &egui::Context) -> String { + ctx.data(|data| data.get_temp::(egui::Id::new("application-locale"))) + .unwrap_or_else(|| "en".into()) } pub fn tr(ctx: &egui::Context, key: &str) -> String { - rust_i18n::t!(key, locale = locale(ctx)).into_owned() + rust_i18n::t!(key, locale = &locale(ctx)).into_owned() } #[cfg(test)] @@ -222,6 +250,14 @@ mod tests { #[test] fn embedded_fonts_cover_catalogs_endonyms_and_mixed_text() { let catalogs = [ + ( + Language::Pack("uk".into()), + include_str!("../../../docs/language-packs/example/uk.json"), + ), + ( + Language::Pack("bho".into()), + include_str!("../../../docs/language-packs/example/bho.json"), + ), (Language::PtPt, include_str!("../locales/pt-PT.json")), (Language::Ne, include_str!("../locales/ne.json")), (Language::Th, include_str!("../locales/th.json")), diff --git a/crates/canvas-pilot/src/main.rs b/crates/canvas-pilot/src/main.rs index 5464d57..55b15b3 100644 --- a/crates/canvas-pilot/src/main.rs +++ b/crates/canvas-pilot/src/main.rs @@ -39,7 +39,12 @@ fn main() -> eframe::Result { ) } -rust_i18n::i18n!("locales", fallback = "en"); +rust_i18n::i18n!( + "locales", + fallback = "en", + backend = language_packs::Backend +); +mod language_packs; mod localization; use localization::tr; diff --git a/crates/canvas-pilot/src/preferences_ui.rs b/crates/canvas-pilot/src/preferences_ui.rs index 610b666..aa5e814 100644 --- a/crates/canvas-pilot/src/preferences_ui.rs +++ b/crates/canvas-pilot/src/preferences_ui.rs @@ -57,7 +57,7 @@ impl Section { } pub(super) struct LanguagePreview { pub(super) previous: localization::Language, - previous_locale: &'static str, + previous_locale: String, deadline: std::time::Instant, } @@ -69,17 +69,17 @@ impl Editor { let previous = self .language_preview .as_ref() - .map_or(self.language, |p| p.previous); + .map_or_else(|| self.language.clone(), |p| p.previous.clone()); let previous_locale = self .language_preview .as_ref() - .map_or(localization::locale(ctx), |p| p.previous_locale); + .map_or_else(|| localization::locale(ctx), |p| p.previous_locale.clone()); self.language_preview = Some(LanguagePreview { previous, previous_locale, deadline: std::time::Instant::now() + std::time::Duration::from_secs(20), }); - self.language = language; + self.language = language.clone(); language.apply(ctx); } @@ -113,7 +113,7 @@ impl Editor { ui.label( rust_i18n::t!( "language.rollback", - locale = localization::locale(ctx), + locale = &localization::locale(ctx), seconds = remaining.as_secs() + 1 ) .into_owned(), @@ -123,7 +123,7 @@ impl Editor { ui.label( rust_i18n::t!( "language.rollback", - locale = preview.previous_locale, + locale = &preview.previous_locale, seconds = remaining.as_secs() + 1 ) .into_owned(), @@ -132,7 +132,8 @@ impl Editor { let keep = ui.button(tr(ctx, "language.keep")).clicked(); let cancel = ui .button( - rust_i18n::t!("language.cancel", locale = preview.previous_locale).into_owned(), + rust_i18n::t!("language.cancel", locale = &preview.previous_locale) + .into_owned(), ) .clicked(); (keep, cancel) @@ -162,7 +163,7 @@ impl Editor { .height(440.0) .selected_text(self.language.name(ctx)) .show_ui(ui, |ui| { - for language in localization::Language::ALL { + for language in localization::Language::ALL.into_iter().chain(crate::language_packs::available(ctx).into_iter().map(|p| localization::Language::Pack(p.locale))) { let name = language.name(ctx); if ui.selectable_label(self.language == language, name).clicked() { self.preview_language(ctx, language); @@ -178,6 +179,11 @@ impl Editor { apply_scaling(ctx, self.ui_scale, self.text_scale); } }); + if ui.button(tr(ctx, "language.install-pack")).clicked() + && let Some(path) = rfd::FileDialog::new().add_filter("Language pack", &["zip"]).pick_file() { + let result = self.settings.path.as_ref().and_then(|p| p.parent()).ok_or_else(|| "Settings directory unavailable".to_owned()).and_then(|directory| crate::language_packs::install(ctx, &directory.join("language-packs"), &path)); + match result { Ok(()) => self.language.apply(ctx), Err(error) => self.error = error } + } ui.weak(tr(ctx, "language.preview")); ui.separator(); egui::ScrollArea::vertical().id_salt("settings-body") @@ -210,7 +216,7 @@ impl Editor { if scaling_before != (self.ui_scale, self.text_scale) { apply_scaling(ctx, self.ui_scale, self.text_scale); } if ui.button(tr(ctx, "access.contrast")).clicked() { theme::Theme::HighContrast.apply(ctx); } ui.separator(); - ui.label(rust_i18n::t!("theme.current", locale = localization::locale(ctx), name = theme::Theme::current(ctx).name()).into_owned()); + ui.label(rust_i18n::t!("theme.current", locale = &localization::locale(ctx), name = theme::Theme::current(ctx).name()).into_owned()); if ui.button(tr(ui.ctx(), "ui.browse-all-themes")).clicked() { self.themes_open = true; } ui.label(tr(ui.ctx(), "ui.recently-used")); for choice in theme::Theme::recent(ctx) { @@ -445,7 +451,7 @@ mod tests { .skip(2) .chain(std::iter::once(localization::Language::En)) { - let previous = app.language; + let previous = app.language.clone(); let current_name = app.language.name(&ctx); click_label(&mut app, &ctx, ¤t_name); click_label(&mut app, &ctx, &language.name(&ctx)); @@ -523,6 +529,53 @@ mod tests { assert_eq!(app.project().to_json().unwrap(), project); } + #[test] + fn installed_languages_use_confirmation_preserve_project_and_restart() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("settings.json"); + let (store, saved) = settings::Store::at(path.clone()); + let ctx = egui::Context::default(); + let mut app = Editor::with_settings(&ctx, store, saved); + let source = dir.path().join("source.zip"); + std::fs::write( + &source, + include_bytes!("../../../docs/language-packs/language-pack.zip"), + ) + .unwrap(); + crate::language_packs::install(&ctx, &dir.path().join("language-packs"), &source).unwrap(); + let original = app.project(); + app.preferences_open = true; + // The combo scrolls once installed languages extend the built-in list. + app.preview_language(&ctx, localization::Language::Pack("uk".into())); + let yes = tr(&ctx, "language.keep"); + click_label(&mut app, &ctx, &yes); + assert_eq!( + settings::Store::at(path.clone()).1.language, + localization::Language::Pack("uk".into()) + ); + app.preview_language(&ctx, localization::Language::Pack("bho".into())); + assert_eq!( + app.application_settings(&ctx).language, + localization::Language::Pack("uk".into()) + ); + app.language_preview.as_mut().unwrap().deadline = std::time::Instant::now(); + frame(&mut app, &ctx, vec![]); + assert_eq!(localization::locale(&ctx), "pack:uk"); + assert_eq!(app.project(), original); + let (store, saved) = settings::Store::at(path.clone()); + let restarted_ctx = egui::Context::default(); + let restored = Editor::with_settings(&restarted_ctx, store, saved); + assert_eq!(tr(&restarted_ctx, "ui.settings"), "Налаштування"); + assert_eq!(restored.project(), original); + std::fs::remove_file(dir.path().join("language-packs/example-uk-bho.zip")).unwrap(); + let (store, saved) = settings::Store::at(path); + let missing_ctx = egui::Context::default(); + let missing = Editor::with_settings(&missing_ctx, store, saved); + assert_eq!(localization::locale(&missing_ctx), "en"); + assert_eq!(missing.language, localization::Language::Pack("uk".into())); + assert!(missing.language.name(&missing_ctx).contains("unavailable")); + } + #[test] fn opening_project_preserves_language_scaling_and_pending_preview() { let dir = tempfile::tempdir().unwrap(); @@ -558,7 +611,7 @@ mod tests { apply_scaling(&ctx, 1.0, Some(1.5)); let screen = Rect::from_min_size(Pos2::ZERO, Vec2::new(500.0, 360.0)); let mut app = Editor { - language, + language: language.clone(), ui_scale: 2.0, text_scale: Some(1.5), preferences_open: true, @@ -599,7 +652,7 @@ mod tests { let ctx = egui::Context::default(); language.apply(&ctx); let mut app = Editor { - language, + language: language.clone(), preferences_open: true, preferences_section: section, ..Editor::default() diff --git a/crates/canvas-pilot/src/project_ui.rs b/crates/canvas-pilot/src/project_ui.rs index c6d3c25..471abba 100644 --- a/crates/canvas-pilot/src/project_ui.rs +++ b/crates/canvas-pilot/src/project_ui.rs @@ -170,7 +170,7 @@ impl Editor { device: std::mem::take(&mut self.device), capture, settings: std::mem::take(&mut self.settings), - language: self.language, + language: self.language.clone(), language_preview: self.language_preview.take(), ui_scale: self.ui_scale, text_scale: self.text_scale, diff --git a/crates/canvas-pilot/src/settings.rs b/crates/canvas-pilot/src/settings.rs index 8fe6449..4515cc6 100644 --- a/crates/canvas-pilot/src/settings.rs +++ b/crates/canvas-pilot/src/settings.rs @@ -24,7 +24,7 @@ pub struct Settings { impl Default for Settings { fn default() -> Self { Self { - version: 12, + version: 13, ui_scale: 1.0, text_scale: None, language: Default::default(), @@ -154,14 +154,28 @@ impl Settings { if value["version"] == 12 && value.get("text_scale").is_none() { return Err("Missing text_scale in version 12 settings".into()); } + if value["version"] == 12 { + if !value["language"].is_string() { + return Err("Installed languages require settings version 13".into()); + } + value["version"] = 13.into(); + } + if value["version"] == 13 && value.get("text_scale").is_none() { + return Err("Missing text_scale in version 13 settings".into()); + } let settings: Self = serde_json::from_value(value).map_err(|e| e.to_string())?; settings.validate()?; Ok(settings) } fn validate(&self) -> Result<(), String> { - if self.version != 12 { + if self.version != 13 { return Err(format!("unsupported settings version {}", self.version)); } + if let crate::localization::Language::Pack(id) = &self.language + && !crate::language_packs::valid_id(id) + { + return Err("Invalid installed language identifier".into()); + } if !self.ui_scale.is_finite() || !(0.5..=4.0).contains(&self.ui_scale) || self @@ -365,7 +379,7 @@ mod tests { let old = include_str!("../../../docs/interfaces/canvas-pilot-settings-v8.example.json"); let migrated = Settings::parse(old).unwrap(); assert_eq!(migrated.language, Language::System); - assert_eq!(migrated.version, 12); + assert_eq!(migrated.version, 13); let current = include_str!("../../../docs/interfaces/canvas-pilot-settings-v10.example.json"); assert_eq!(Settings::parse(current).unwrap(), migrated); @@ -374,12 +388,12 @@ mod tests { let mut old: serde_json::Value = serde_json::from_str(v9).unwrap(); old["language"] = old_language.into(); let upgraded = Settings::parse(&old.to_string()).unwrap(); - assert_eq!(upgraded.version, 12); + assert_eq!(upgraded.version, 13); assert_eq!( - serde_json::to_value(upgraded.language).unwrap(), + serde_json::to_value(&upgraded.language).unwrap(), old["language"] ); - old["version"] = 12.into(); + old["version"] = 13.into(); old["ui_scale"] = serde_json::json!(1.0); old["text_scale"] = serde_json::Value::Null; assert_eq!(serde_json::to_value(upgraded).unwrap(), old); @@ -407,6 +421,27 @@ mod tests { assert!(Settings::parse(&value.to_string()).is_err()); } + #[test] + fn installed_language_settings_require_v13_and_preserve_missing_pack_choice() { + let old = include_str!("../../../docs/interfaces/canvas-pilot-settings-v12.example.json"); + let current = + include_str!("../../../docs/interfaces/canvas-pilot-settings-v13.example.json"); + assert_eq!( + Settings::parse(old).unwrap(), + Settings::parse(current).unwrap() + ); + let mut value: serde_json::Value = serde_json::from_str(old).unwrap(); + value["language"] = serde_json::json!({"pack":"uk"}); + assert!(Settings::parse(&value.to_string()).is_err()); + value["version"] = 13.into(); + let saved = Settings::parse(&value.to_string()).unwrap(); + assert_eq!(serde_json::to_value(saved).unwrap(), value); + for id in ["", "../uk", "uk_UA"] { + value["language"] = serde_json::json!({"pack":id}); + assert!(Settings::parse(&value.to_string()).is_err()); + } + } + #[test] fn expanded_languages_require_v12_and_v11_migration_preserves_settings() { let old = include_str!("../../../docs/interfaces/canvas-pilot-settings-v11.example.json"); @@ -434,7 +469,7 @@ mod tests { value["ui_scale"] = 1.5.into(); value["text_scale"] = 1.25.into(); let saved = Settings::parse(&value.to_string()).unwrap(); - value["version"] = 12.into(); + value["version"] = 13.into(); assert_eq!(serde_json::to_value(saved).unwrap(), value); } } @@ -507,7 +542,7 @@ mod tests { for text in [ "broken".to_string(), serde_json::to_string(&Settings { - version: 13, + version: 14, ..Default::default() }) .unwrap(), diff --git a/docs/canvas-pilot/changelog.md b/docs/canvas-pilot/changelog.md index 1090440..89822e7 100644 --- a/docs/canvas-pilot/changelog.md +++ b/docs/canvas-pilot/changelog.md @@ -4,6 +4,20 @@ ## Unreleased +### v0.9.7 + +- Added runtime ZIP language-pack installation in Settings, dynamic language choices, + English fallback and settings v13 migration. Confirmed installed languages persist + across restart; missing packs preserve the choice and fall back to English. +- Added a downloadable Ukrainian/Bhojpuri example and a manual authoring walkthrough. + Both are partial, unreviewed translations using existing bundled fonts. Packs do + not yet supply fonts or reduce application download size. +- Bounded ZIP/catalog validation rejects malformed packs and placeholder mismatches; + installation preserves source archives and never overwrites installed packs. +- Rust gates and manual validation passed, with 91.38% whole-application coverage. + Native clicks verified installed-language selection and confirmation; automated + tests cover installation, restart, removal and rejected packs. + ### v0.9.6 - Added European Portuguese, Nepali, Thai, Hindi and Latin-script Toki Pona UI diff --git a/docs/canvas-pilot/guide/language-packs.md b/docs/canvas-pilot/guide/language-packs.md new file mode 100644 index 0000000..a9dd396 --- /dev/null +++ b/docs/canvas-pilot/guide/language-packs.md @@ -0,0 +1,103 @@ +# Add a language pack + +Language packs add interface translations without rebuilding Canvas Pilot. English +remains the reference language, and missing messages fall back to English. Packs do +not translate project names, device responses or exported geometry. + +## Try the example + +1. Download [language-pack.zip](../../language-packs/language-pack.zip). +2. In Canvas Pilot, open **Menu → Open all settings…**. +3. Click **Install language pack…** and select the ZIP. Leave it zipped. +4. Open **Language / Langue**. The list now includes **Українська — Ukrainian** + and **भोजपुरी — Bhojpuri**, below the built-in languages; scroll if needed. +5. Select one and confirm within 20 seconds. Cancellation and the countdown still + use your previous language. Confirmed choices survive restart. + +The example provides 39 messages per language, including Settings, common controls, +confirmation and a message with a substitution. It is an intentionally partial, +unreviewed machine translation for teaching pack creation. The remaining interface +stays English. Bhojpuri is identified as `bho`, separately from Hindi (`hi`), following +[the ISO language-code list](https://www.loc.gov/standards/iso639-2/php/code_list-utf8.php). +It demonstrates the same Devanagari font support used by Hindi. + +These packs reuse the fonts already bundled with Canvas Pilot. Version 1 packs +contain translations only: they neither install fonts nor reduce the current +application download size. Ukrainian uses the existing Cyrillic coverage. + +## Make your own pack + +Download these three editable example files into the same folder: + +- [manifest.json](../../language-packs/example/manifest.json) +- [uk.json](../../language-packs/example/uk.json) +- [bho.json](../../language-packs/example/bho.json) + +The manifest describes the pack and its languages: + +```json +{ + "version": 1, + "id": "example-uk-bho", + "languages": [ + {"locale": "uk", "name": "Ukrainian", "native_name": "Українська"}, + {"locale": "bho", "name": "Bhojpuri", "native_name": "भोजपुरी"} + ] +} +``` + +Each language has a UTF-8 JSON file named after its `locale`. Use a unique lowercase +language identifier, such as `uk`, and a unique pack `id`. Display names are plain +text; no markup is supported. For another language, change the identifiers, names +and filenames together. New languages do not need a Rust enum entry or a rebuild. + +Start with a few messages, then add more from the +[English source catalog](../../../crates/canvas-pilot/locales/en.json). Copy keys +exactly and translate only their values. Omit messages you have not translated. +Do not copy the whole English catalog merely to appear complete. + +```json +{ + "ui.settings": "Налаштування", + "ui.close": "Закрити", + "theme.current": "Поточна тема: %{name}" +} +``` + +Keep placeholders such as `%{name}` and `%{seconds}` unchanged; their position in the +sentence may change. JSON requires double quotes and no trailing commas. Save as +UTF-8. The importer rejects unknown keys, empty values and mismatched placeholders. +Built-in languages cannot be replaced by packs. + +From the folder containing the three JSON files, create the ZIP with Python: + +```sh +python3 -m zipfile -c language-pack.zip manifest.json uk.json bho.json +``` + +Or use an archive tool: select the files themselves, not their enclosing folder. +The ZIP must contain only `manifest.json` and the declared language JSON files at +its root. Install it through Settings, switch language, and check long labels, +confirmation, fallback messages and text rendering. Ask fluent speakers to review +translations before presenting a pack as ready for everyday use. + +## Storage, updates and removal + +The installer copies the validated ZIP to `language-packs/.zip` beside +`settings.json`. To find that directory, use **Settings → Files & settings** and the +settings-file location displayed there. Keep installed packs there across app +updates. You can also copy a ZIP into this directory while the app is closed; +it is loaded on the next launch. + +An installed pack or duplicate language is never silently overwritten. To update +or remove a pack, close Canvas Pilot, remove its old ZIP from `language-packs`, and +restart. Then install the replacement ZIP if desired. Do not remove `settings.json`. +If your selected pack is absent, the UI uses English and marks the saved choice as +unavailable. Reinstalling that pack restores the requested language. System default +continues to resolve built-in languages; select installed languages explicitly. + +Invalid packs are rejected without installing any of their languages. Startup +skips invalid packs and reports errors. Packs are limited to 2 MiB compressed, +4 MiB expanded and 16 languages each; at most 32 ZIPs are loaded. They do not execute +code, load remote content, or change device settings. The full format is documented +in the [language-pack contract](../../interfaces/language-packs.md). diff --git a/docs/canvas-pilot/guide/preferences.md b/docs/canvas-pilot/guide/preferences.md index d74d883..fddd74e 100644 --- a/docs/canvas-pilot/guide/preferences.md +++ b/docs/canvas-pilot/guide/preferences.md @@ -52,6 +52,11 @@ text for Thai characters such as `ำ` that expand into several glyphs. For thos names, avoid relying on End followed by Backspace; select the whole field to replace it. This limitation concerns text editing, not interface labels. +Additional languages can be installed from ZIP files with **Install language pack…**. +See [Add a language pack](language-packs.md) for the Ukrainian/Bhojpuri example and +instructions for writing a translation. Installed languages appear below the built-in +choices and use the same confirmation. + The book's [French quick start](fr/quickstart.md) now follows the accepted French interface wording and uses French screenshots. It records its machine-translation origin and links to the English manual as the authoritative source. diff --git a/docs/development/localization.md b/docs/development/localization.md index 5375b30..195b343 100644 --- a/docs/development/localization.md +++ b/docs/development/localization.md @@ -47,13 +47,14 @@ The accepted French interface vocabulary does not imply review of other language The desktop UI uses [rust-i18n](https://docs.rs/rust-i18n/) with embedded English, French, Japanese, Simplified Chinese, Spanish, Ancient Greek, Esperanto, European Portuguese, Nepali, Thai, Hindi and Toki Pona JSON catalogs in `crates/canvas-pilot/locales/`. `sys-locale` obtains the desktop -language. There is no custom translation parser, language-file loader, lookup cache -or network translation service. The lockfile pins the dependency versions. +language. Built-in catalogs remain embedded. Runtime ZIP packs use the rust-i18n backend +extension and serde JSON parsing; no network translation service is involved. The lockfile pins the dependency versions. `src/localization.rs` only resolves the supported language preference and passes an explicit locale to rust-i18n. Each egui context holds its own resolved language; there is no process-global `set_locale`, avoiding cross-window/test interference. -Catalogs compile into the binary, so portable releases need no additional files. +Built-in catalogs compile into the binary, so portable releases need no additional +files for those languages. Optional packs persist beside user settings. The build script watches `locales/`, including catalog-only edits and newly added files; translators do not need to touch Rust code to trigger a rebuild. @@ -334,3 +335,32 @@ Begin after the book workflow and glossary have been validated. - [ ] Add translated video captions and transcripts when the planned videos exist. - [ ] Consider a hosted translation platform only when contributor volume makes the repository-based workflow difficult to maintain. + +## Runtime language-pack example (v0.9.7) + +Settings now imports bounded ZIP packs and lists their languages immediately. The +[manual walkthrough](../canvas-pilot/guide/language-packs.md) is the user-facing +authoring tutorial; the [contract](../interfaces/language-packs.md) owns schema, +limits, persistence and compatibility. The example adds Ukrainian and Bhojpuri, +39 messages each, without adding either language to the compiled enum/catalogs. +The same built-in fonts cover both examples. This demonstrates external catalogs; +external font packs and reducing the release size remain future work. + +Settings v13 keeps built-in strings and adds an installed-language object. Missing +packs preserve the requested language while falling back to English. Catalogs +are registered with rust-i18n's runtime backend; the current locale remains per +context. Unknown keys/placeholders, malformed ZIPs and collisions reject the whole +installation. Existing files and projects are preserved. Example translations are +partial and unreviewed. + +Validation: default Rust suite 444 passed / two manual checks ignored; all-features +and restricted suites each 438 passed / one manual check ignored. Formatting, +Clippy in both configurations and warnings-denied rustdoc passed. Whole-application +line coverage: 91.38%. The pinned manual build validates 24 HTML pages and the new +ZIP/JSON downloads. Scripted native X11 clicks scrolled to both installed languages, +selected/confirmed Ukrainian and inspected Bhojpuri with the previous-language +cancellation prompt. Saved settings contained the installed locale in v13 form. +The desktop portal file chooser was unavailable on the isolated display; archive +installation is covered by filesystem tests, and the native walkthrough used the +manual-copy/startup discovery path. Windows/macOS native chooser acceptance remains +unverified. Temporary screenshots/profiles are outside Git. diff --git a/docs/interfaces/canvas-pilot-settings-v13.example.json b/docs/interfaces/canvas-pilot-settings-v13.example.json new file mode 100644 index 0000000..52fc57a --- /dev/null +++ b/docs/interfaces/canvas-pilot-settings-v13.example.json @@ -0,0 +1,29 @@ +{ + "version": 13, + "theme": "midra", + "recent_themes": [ + "midra" + ], + "show_toolbar_icon_names": false, + "keep_aspect_ratio": true, + "show_source_pattern": false, + "snapping": { + "enabled": false, + "pixels": true, + "screen_edges": true, + "layer_edges": true, + "grid": false, + "show_grid": true, + "grid_divisions": [ + 8, + 6 + ] + }, + "midra_host": "", + "allow_sending_to_program": false, + "autoconnect_at_startup": false, + "recent_midra_hosts": [], + "language": "system", + "ui_scale": 1.0, + "text_scale": null +} diff --git a/docs/interfaces/canvas-pilot-settings.md b/docs/interfaces/canvas-pilot-settings.md index f2a36c4..47b8e92 100644 --- a/docs/interfaces/canvas-pilot-settings.md +++ b/docs/interfaces/canvas-pilot-settings.md @@ -1,15 +1,15 @@ -# Canvas Pilot application settings, version 12 +# Canvas Pilot application settings, version 13 Canvas Pilot was formerly named Midra Layout. The rename preserves existing wire-format identifiers, `.midra.json` projects, settings/recovery locations and `MIDRA_VECTORCRAFT_CLI` configuration. No schema version changes are needed. New exports use Canvas Pilot in human-readable titles; legacy files remain readable. Implementation: `crates/canvas-pilot/src/settings.rs`. This per-user JSON file is independent of the [project JSON and SVG contracts](canvas-pilot.md). -[Complete default example](canvas-pilot-settings-v12.example.json). +[Complete default example](canvas-pilot-settings-v13.example.json). Version 1 files migrate automatically: the saved theme becomes the only entry in `recent_themes`, with all other preferences preserved. The [version 1 example](canvas-pilot-settings-v1.example.json) remains a migration fixture. Version 2 files then migrate by adding disabled snapping with all target types enabled. The [version 2 example](canvas-pilot-settings-v2.example.json) -remains a migration fixture too. Version 3 files migrate by adding an empty `midra_host`; the [version 3 example](canvas-pilot-settings-v3.example.json) remains a migration fixture. Version 4 files migrate by adding `allow_sending_to_program: false`; the [version 4 example](canvas-pilot-settings-v4.example.json) remains a migration fixture. Version 5 files migrate with `autoconnect_at_startup: false`; the [version 5 example](canvas-pilot-settings-v5.example.json) remains a migration fixture. Version 6 files migrate with the overlay grid visible, snapping to it disabled, and `grid_divisions: [8, 6]`; the [version 6 example](canvas-pilot-settings-v6.example.json) remains a migration fixture. Version 7 migrates with an empty `recent_midra_hosts` list; the [version 7 example](canvas-pilot-settings-v7.example.json) remains a migration fixture. Version 8 migrates with `language: "system"`; the [version 8 example](canvas-pilot-settings-v8.example.json) remains a migration fixture. Version 9 migrates without changing any preferences; its `system`, `en` and `fr` values remain valid. The [version 9 example](canvas-pilot-settings-v9.example.json) remains a migration fixture. Version 10 adds language choices. Version 11 adds `ui_scale` and `text_scale`; v1–v10 settings migrate to 100% interface scale with separate text scaling disabled, preserving all existing preferences. The [version 10 example](canvas-pilot-settings-v10.example.json) remains a migration fixture. Version 12 adds `pt-PT`, `ne`, `th`, `hi` and `tok`; v1–v11 settings migrate without changing existing preferences. Values outside each old version’s language set are rejected before migration. The [version 11 example](canvas-pilot-settings-v11.example.json) remains a migration fixture. Saving writes version 12, which older applications reject. +remains a migration fixture too. Version 3 files migrate by adding an empty `midra_host`; the [version 3 example](canvas-pilot-settings-v3.example.json) remains a migration fixture. Version 4 files migrate by adding `allow_sending_to_program: false`; the [version 4 example](canvas-pilot-settings-v4.example.json) remains a migration fixture. Version 5 files migrate with `autoconnect_at_startup: false`; the [version 5 example](canvas-pilot-settings-v5.example.json) remains a migration fixture. Version 6 files migrate with the overlay grid visible, snapping to it disabled, and `grid_divisions: [8, 6]`; the [version 6 example](canvas-pilot-settings-v6.example.json) remains a migration fixture. Version 7 migrates with an empty `recent_midra_hosts` list; the [version 7 example](canvas-pilot-settings-v7.example.json) remains a migration fixture. Version 8 migrates with `language: "system"`; the [version 8 example](canvas-pilot-settings-v8.example.json) remains a migration fixture. Version 9 migrates without changing any preferences; its `system`, `en` and `fr` values remain valid. The [version 9 example](canvas-pilot-settings-v9.example.json) remains a migration fixture. Version 10 adds language choices. Version 11 adds `ui_scale` and `text_scale`; v1–v10 settings migrate to 100% interface scale with separate text scaling disabled, preserving all existing preferences. The [version 10 example](canvas-pilot-settings-v10.example.json) remains a migration fixture. Version 12 adds `pt-PT`, `ne`, `th`, `hi` and `tok`; v1–v11 settings migrate without changing existing preferences. Values outside each old version’s language set are rejected before migration. The [version 11 example](canvas-pilot-settings-v11.example.json) remains a migration fixture. Version 13 adds installed language choices; v12 preferences migrate unchanged. The [version 12 example](canvas-pilot-settings-v12.example.json) remains a fixture. Saving writes version 13, which older applications reject. The `directories` 6 crate resolves `ProjectDirs::from("org", "beffroi", "midra-layout")`. The filename is `settings.json` beneath `config_dir()`: @@ -26,10 +26,10 @@ unknown theme names are rejected. There are no numeric coordinates or units. | Field | Values / default | | --- | --- | -| `version` | Integer `12` | +| `version` | Integer `13` | | `ui_scale` | Finite number, 0.5–4.0 inclusive; default 1.0. egui interface zoom relative to the OS display scale. | | `text_scale` | `null` (default, disabled) or finite number 0.5–2.0 inclusive. Additional standard-widget text multiplier. | -| `language` | `"system"` (default), `"en"`, `"fr"`, `"ja"`, `"zh-CN"`, `"es"`, `"grc"`, `"eo"`, `"pt-PT"`, `"ne"`, `"th"`, `"hi"`, `"tok"`. Unknown values are rejected. | +| `language` | `"system"` (default), `"en"`, `"fr"`, `"ja"`, `"zh-CN"`, `"es"`, `"grc"`, `"eo"`, `"pt-PT"`, `"ne"`, `"th"`, `"hi"`, `"tok"`, or `{"pack":"uk"}` for an installed language. Pack identifiers use 1–63 lowercase ASCII letters, digits and hyphens, without a leading/trailing hyphen. Unknown built-in string values are rejected. | | `autoconnect_at_startup` | Boolean; default false. Try one background connection at application startup if the saved address is nonblank. | | `allow_sending_to_program` | Boolean; default false. Enables the Program destination in the exporter. Turning it off restores Preview; applies to quick Apply too. | | `midra_host` | Device IP address text with optional TCP port (e.g. `192.168.10.146:3000`, `[::1]:3000`; default port 80); default `""`. Saved as typed, including incomplete drafts; validated when connecting. | @@ -200,3 +200,8 @@ the saved address, clears old device state/staged input edits, and starts a read connection. The picker is disabled during a pending operation. History belongs to application settings, not project files; migration starts empty because older settings do not record whether their last address connected successfully. + +Installed language choices are described by the [language-pack contract](language-packs.md). +They are allowed only in v13; older versions reject object-valued language fields. +Unavailable packs preserve the identifier and render English rather than discarding +preferences. Installation re-applies a saved missing-pack choice. diff --git a/docs/interfaces/language-packs.md b/docs/interfaces/language-packs.md new file mode 100644 index 0000000..530e30a --- /dev/null +++ b/docs/interfaces/language-packs.md @@ -0,0 +1,78 @@ +# Canvas Pilot language packs, version 1 + +Implementation: `crates/canvas-pilot/src/language_packs.rs`. User instructions and +editable downloads: [Add a language pack](../canvas-pilot/guide/language-packs.md). +[Example archive](../language-packs/language-pack.zip). + +## Archive representation + +ZIP, maximum 2 MiB archive bytes and 4 MiB cumulative uncompressed bytes, checked +while reading. At most 17 entries: `manifest.json` plus 1–16 catalog files. Files +must be at the archive root. Directories, symlinks, duplicate ZIP names, unexpected +files and path separators are rejected. Nothing is extracted. Entry CRC/decompression +errors reject the pack. Unsupported ZIP encryption/compression is rejected by `zip`. + +All JSON uses UTF-8. Manifest version is integer `1`; unknown manifest/description +fields and other versions are rejected. Field order has no meaning. + +| Field | Contract | +| --- | --- | +| `version` | Required integer `1` | +| `id` | Pack identifier; 1–63 lowercase ASCII letters, digits or hyphens; no leading/trailing hyphen | +| `languages` | Required array of 1–16 language descriptions | +| `languages[].locale` | Unique identifier with the same syntax as `id`; reserved built-in identifiers and `system` rejected | +| `languages[].name` | English display name, 1–160 UTF-8 bytes, nonblank, no control characters | +| `languages[].native_name` | Native display name, same constraints | + +Each description requires `.json`, a flat object mapping existing English +catalog keys to translated strings. At least one message is required. Missing keys +fall back to embedded English through rust-i18n; unknown keys reject the whole pack. +Values must be nonblank, at most 16,384 UTF-8 bytes, with no control characters other +than newline/tab. `%{placeholder}` names must match the English message's set; +unterminated/empty placeholders are rejected. Message order is irrelevant. JSON's +ordinary serde map behavior applies: repeated object keys resolve to the last value; +authors must use unique keys. No geometry, numbers, project data or precision fields +are part of this format. + +Version 1 supplies no fonts, language inheritance, executable plugins, network +URLs or automatic downloads. The built-in font repertoire determines rendering. +No override of built-in catalogs is allowed. Catalogs use an internal `pack:` +namespace in the runtime rust-i18n backend; the manifest contains only `uk`, etc. +Catalogs are loaded into memory, not read on every label render. Selection is +explicit per egui context, never a process-global current language. + +## Installation and persistence + +Installation validates all entries and locale collisions before writing. A temporary +file in the destination directory is flushed and persisted without clobbering to +`/language-packs/.zip`; only then are languages registered. +The source ZIP is retained. The installed ZIP preserves original bytes exactly; +there is no re-export or lossy normalization. A pack containing any already-loaded +locale is rejected in full. An existing destination file is never replaced, +including an invalid one. + +Startup reads at most 32 `.zip` files from that directory, sorted by path when +within the limit. If there are more, the first 32 discovered entries are considered, +then sorted, and an error is reported; users must reduce the count. Invalid packs +are skipped with errors. The first valid pack supplying a locale wins; a later +colliding pack is rejected in full. Installation also refuses a 33rd ZIP. Startup +is offline. Manual removal/replacement takes effect after restart. + +The [settings v13 contract](canvas-pilot-settings.md) stores an installed choice as +`"language": {"pack": "uk"}`. Missing packs retain this preference but render in +English, with an unavailable indicator in the selector. Installing the missing +pack re-applies that preference. Existing language confirmation, cancellation and +20-second rollback apply; installation alone does not select another language. +System default resolves only built-in locales. Project/recovery documents contain +no language-pack settings; device/export behavior is unchanged. + +## Compatibility and evidence + +Pack v1 is supported from application v0.9.7. Built-in English keys define the +accepted catalog vocabulary for the running version; removed/renamed keys require +pack updates. Adding an English key does not break partial packs. Older applications +lack pack loading and reject settings v13. Tests cover ZIP/source equality, +install/restart/removal, fallback, placeholder substitution, rejected archives, +non-overwrite, settings migration, confirmation rollback and unchanged project data. +Example catalog characters are checked against the bundled fonts. Example wording +is unreviewed machine translation, not linguistic acceptance. diff --git a/docs/language-packs/example/bho.json b/docs/language-packs/example/bho.json new file mode 100644 index 0000000..e227327 --- /dev/null +++ b/docs/language-packs/example/bho.json @@ -0,0 +1,41 @@ +{ + "language.label": "भाषा / Language", + "language.confirm": "का ई भाषा रउआ खातिर ठीक बा?", + "language.keep": "हाँ", + "language.cancel": "ना, ई भाषा गलती से चुनाइल बा", + "language.rollback": "पक्का ना कइला पर %{seconds} सेकंड में पुरनकी भाषा लवट आई।", + "language.preview": "ई अधूरा अनुवाद के उदाहरण बा। एकर भाषा जाँच नइखे भइल। बाकी संदेश अंग्रेजी में बा।", + "language.install-pack": "भाषा पैक जोड़ीं…", + "language.system": "सिस्टम के भाषा", + "ui.settings": "सेटिंग", + "ui.close": "बंद करीं", + "ui.cancel": "रद्द करीं", + "ui.appearance": "रूप", + "ui.editing": "संपादन", + "ui.reference-images": "संदर्भ चित्र", + "ui.files-settings": "फाइल आ सेटिंग", + "ui.device-integration": "उपकरण से जुड़ाव", + "menu.title": "मेन्यू", + "ui.name": "नाँव", + "ui.visibility": "दिखाई पड़ल", + "ui.protection": "सुरक्षा", + "ui.order": "क्रम", + "ui.select-id": "चुनीं / ID", + "ui.folder-optional": "फोल्डर (वैकल्पिक)", + "ui.no-folder": "कवनो फोल्डर नइखे", + "ui.new-folder": "नया फोल्डर…", + "ui.rename-layer": "परत के नाँव बदलीं…", + "ui.move-to-folder": "फोल्डर में ले जाईं", + "ui.layers-folders": "परत आ फोल्डर", + "ui.layer-values": "परत के मान", + "ui.geometry-file": "ज्यामिति फाइल…", + "ui.clipboard-values": "क्लिपबोर्ड के मान", + "ui.images-input-snapshots": "चित्र आ इनपुट के फोटो", + "ui.reload-layer-list": "परत के सूची फेर लोड करीं", + "ui.rename-folder": "फोल्डर के नाँव बदलीं…", + "ui.select-folder-contents": "फोल्डर के सामान चुनीं", + "access.interface-scale": "इंटरफेस के आकार", + "access.text-scale": "अक्षर के आकार अलग से बदलीं", + "access.reset": "इंटरफेस के आकार रीसेट करीं", + "theme.current": "अभी के थीम: %{name}" +} diff --git a/docs/language-packs/example/manifest.json b/docs/language-packs/example/manifest.json new file mode 100644 index 0000000..6650928 --- /dev/null +++ b/docs/language-packs/example/manifest.json @@ -0,0 +1,16 @@ +{ + "version": 1, + "id": "example-uk-bho", + "languages": [ + { + "locale": "uk", + "name": "Ukrainian", + "native_name": "Українська" + }, + { + "locale": "bho", + "name": "Bhojpuri", + "native_name": "भोजपुरी" + } + ] +} diff --git a/docs/language-packs/example/uk.json b/docs/language-packs/example/uk.json new file mode 100644 index 0000000..9cf2c02 --- /dev/null +++ b/docs/language-packs/example/uk.json @@ -0,0 +1,41 @@ +{ + "language.label": "Мова / Language", + "language.confirm": "Вам підходить ця мова?", + "language.keep": "Так", + "language.cancel": "Ні, цю мову вибрано помилково", + "language.rollback": "Попередня мова повернеться через %{seconds} с, якщо не підтвердити вибір.", + "language.preview": "Приклад часткового перекладу без мовної перевірки. Решта повідомлень — англійською.", + "language.install-pack": "Встановити мовний пакет…", + "language.system": "Системна мова", + "ui.settings": "Налаштування", + "ui.close": "Закрити", + "ui.cancel": "Скасувати", + "ui.appearance": "Вигляд", + "ui.editing": "Редагування", + "ui.reference-images": "Зображення-зразки", + "ui.files-settings": "Файли та налаштування", + "ui.device-integration": "Інтеграція з пристроєм", + "menu.title": "Меню", + "ui.name": "Назва", + "ui.visibility": "Видимість", + "ui.protection": "Захист", + "ui.order": "Порядок", + "ui.select-id": "Вибір / ID", + "ui.folder-optional": "Папка (необов’язково)", + "ui.no-folder": "Без папки", + "ui.new-folder": "Нова папка…", + "ui.rename-layer": "Перейменувати шар…", + "ui.move-to-folder": "Перемістити до папки", + "ui.layers-folders": "Шари та папки", + "ui.layer-values": "Параметри шару", + "ui.geometry-file": "Файл геометрії…", + "ui.clipboard-values": "Значення з буфера обміну", + "ui.images-input-snapshots": "Зображення та знімки входів", + "ui.reload-layer-list": "Оновити список шарів", + "ui.rename-folder": "Перейменувати папку…", + "ui.select-folder-contents": "Вибрати вміст папки", + "access.interface-scale": "Масштаб інтерфейсу", + "access.text-scale": "Окремий масштаб тексту", + "access.reset": "Скинути масштаб інтерфейсу", + "theme.current": "Поточна тема: %{name}" +} diff --git a/docs/language-packs/language-pack.zip b/docs/language-packs/language-pack.zip new file mode 100644 index 0000000..6cfaba9 Binary files /dev/null and b/docs/language-packs/language-pack.zip differ diff --git a/docs/manuals/canvas-pilot/SUMMARY.md b/docs/manuals/canvas-pilot/SUMMARY.md index d8cc56a..8bf2d52 100644 --- a/docs/manuals/canvas-pilot/SUMMARY.md +++ b/docs/manuals/canvas-pilot/SUMMARY.md @@ -20,6 +20,7 @@ - [Formats, crop and precision](../../canvas-pilot/guide/formats-and-crop.md) - [Import, export and project files](../../canvas-pilot/guide/files.md) - [Menus and preferences](../../canvas-pilot/guide/preferences.md) + - [Add a language pack](../../canvas-pilot/guide/language-packs.md) - [Device connection and transfers](../../canvas-pilot/guide/device.md) - [Resolution and cropping model](../../canvas-pilot/resolutions.md) - [Changelog](../../canvas-pilot/changelog.md)