diff --git a/Cargo.lock b/Cargo.lock index e90b4c0..d554ca6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -548,7 +548,7 @@ dependencies = [ [[package]] name = "canvas-pilot" -version = "0.9.15" +version = "0.9.16" dependencies = [ "base64", "craft-dwg", diff --git a/Cargo.toml b/Cargo.toml index 153be0f..d58b525 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ default-members = ["crates/canvas-pilot"] resolver = "3" [workspace.package] -version = "0.9.15" +version = "0.9.16" edition = "2024" license = "MIT" repository = "https://proxy.dandaedre.com/gitea/idle-org/canvas-pilot" diff --git a/crates/canvas-pilot/locales/en.json b/crates/canvas-pilot/locales/en.json index bdadcbf..4d7d29e 100644 --- a/crates/canvas-pilot/locales/en.json +++ b/crates/canvas-pilot/locales/en.json @@ -1,4 +1,7 @@ { + "language.packs": "Language packs", + "language.remove-pack": "Remove pack…", + "language.overwrite-pack": "Overwrite pack", "ui.mask-edges": "Mask edges", "ui.rename-layer": "Rename layer…", "ui.move-to-folder": "Move to folder", diff --git a/crates/canvas-pilot/locales/eo.json b/crates/canvas-pilot/locales/eo.json index b22575c..c987f89 100644 --- a/crates/canvas-pilot/locales/eo.json +++ b/crates/canvas-pilot/locales/eo.json @@ -1,4 +1,7 @@ { + "language.packs": "Lingvopakaĵoj", + "language.remove-pack": "Forigi pakaĵon…", + "language.overwrite-pack": "Anstataŭigi pakaĵon", "ui.mask-edges": "Randoj de maskoj", "ui.rename-layer": "Renomi tavolon…", "ui.move-to-folder": "Movi al dosierujo", diff --git a/crates/canvas-pilot/locales/es.json b/crates/canvas-pilot/locales/es.json index 7f5f7e9..3dd5dd7 100644 --- a/crates/canvas-pilot/locales/es.json +++ b/crates/canvas-pilot/locales/es.json @@ -1,4 +1,7 @@ { + "language.packs": "Paquetes de idiomas", + "language.remove-pack": "Eliminar paquete…", + "language.overwrite-pack": "Sobrescribir paquete", "ui.mask-edges": "Bordes de máscara", "ui.rename-layer": "Renombrar capa…", "ui.move-to-folder": "Mover a carpeta", diff --git a/crates/canvas-pilot/locales/fr.json b/crates/canvas-pilot/locales/fr.json index 1dca677..5853293 100644 --- a/crates/canvas-pilot/locales/fr.json +++ b/crates/canvas-pilot/locales/fr.json @@ -1,4 +1,7 @@ { + "language.packs": "Packs de langues", + "language.remove-pack": "Supprimer le pack…", + "language.overwrite-pack": "Remplacer le pack", "ui.mask-edges": "Bords des masques", "ui.rename-layer": "Renommer le calque…", "ui.move-to-folder": "Déplacer vers un dossier", diff --git a/crates/canvas-pilot/locales/grc.json b/crates/canvas-pilot/locales/grc.json index 3e94145..eaa73ed 100644 --- a/crates/canvas-pilot/locales/grc.json +++ b/crates/canvas-pilot/locales/grc.json @@ -1,4 +1,7 @@ { + "language.packs": "Δέματα γλωσσῶν", + "language.remove-pack": "Ἀφαιρεῖν τὸ δέμα…", + "language.overwrite-pack": "Ἀντικαθιστάναι τὸ δέμα", "ui.mask-edges": "Ἄκρα τῶν καλυμμάτων", "ui.rename-layer": "Μετονόμασον τὸ στρῶμα…", "ui.move-to-folder": "Εἰς φάκελον μετάθεσον", diff --git a/crates/canvas-pilot/locales/hi.json b/crates/canvas-pilot/locales/hi.json index a7e1cad..e8ac06f 100644 --- a/crates/canvas-pilot/locales/hi.json +++ b/crates/canvas-pilot/locales/hi.json @@ -1,4 +1,7 @@ { + "language.packs": "भाषा पैक", + "language.remove-pack": "पैक हटाएँ…", + "language.overwrite-pack": "पैक बदलें", "ui.mask-edges": "मास्क के किनारे", "ui.rename-layer": "परत का नाम बदलें…", "ui.move-to-folder": "फ़ोल्डर में ले जाएँ", diff --git a/crates/canvas-pilot/locales/ja.json b/crates/canvas-pilot/locales/ja.json index fd32a6a..e19403d 100644 --- a/crates/canvas-pilot/locales/ja.json +++ b/crates/canvas-pilot/locales/ja.json @@ -1,4 +1,7 @@ { + "language.packs": "言語パック", + "language.remove-pack": "パックを削除…", + "language.overwrite-pack": "パックを上書き", "ui.mask-edges": "マスクの端", "ui.rename-layer": "レイヤー名を変更…", "ui.move-to-folder": "フォルダーに移動", diff --git a/crates/canvas-pilot/locales/ne.json b/crates/canvas-pilot/locales/ne.json index 7436493..a0ccfe8 100644 --- a/crates/canvas-pilot/locales/ne.json +++ b/crates/canvas-pilot/locales/ne.json @@ -1,4 +1,7 @@ { + "language.packs": "भाषा प्याकहरू", + "language.remove-pack": "प्याक हटाउनुहोस्…", + "language.overwrite-pack": "प्याक बदल्नुहोस्", "ui.mask-edges": "मास्कका किनाराहरू", "ui.rename-layer": "तहको नाम फेर्नुहोस्…", "ui.move-to-folder": "फोल्डरमा सार्नुहोस्", diff --git a/crates/canvas-pilot/locales/pt-PT.json b/crates/canvas-pilot/locales/pt-PT.json index b86532c..c4b49d4 100644 --- a/crates/canvas-pilot/locales/pt-PT.json +++ b/crates/canvas-pilot/locales/pt-PT.json @@ -1,4 +1,7 @@ { + "language.packs": "Pacotes de idiomas", + "language.remove-pack": "Remover pacote…", + "language.overwrite-pack": "Substituir pacote", "ui.mask-edges": "Limites da máscara", "ui.rename-layer": "Mudar nome da camada…", "ui.move-to-folder": "Mover para pasta", diff --git a/crates/canvas-pilot/locales/th.json b/crates/canvas-pilot/locales/th.json index 3911cd4..b30162a 100644 --- a/crates/canvas-pilot/locales/th.json +++ b/crates/canvas-pilot/locales/th.json @@ -1,4 +1,7 @@ { + "language.packs": "ชุดภาษา", + "language.remove-pack": "ลบชุดภาษา…", + "language.overwrite-pack": "เขียนทับชุดภาษา", "ui.mask-edges": "ขอบมาสก์", "ui.rename-layer": "เปลี่ยนชื่อเลเยอร์…", "ui.move-to-folder": "ย้ายไปโฟลเดอร์", diff --git a/crates/canvas-pilot/locales/tok.json b/crates/canvas-pilot/locales/tok.json index ece5368..e89618d 100644 --- a/crates/canvas-pilot/locales/tok.json +++ b/crates/canvas-pilot/locales/tok.json @@ -1,4 +1,7 @@ { + "language.packs": "kulupu toki", + "language.remove-pack": "o weka e kulupu…", + "language.overwrite-pack": "o ante e kulupu", "ui.mask-edges": "poka pi len sitelen", "ui.rename-layer": "o ante e nimi lipu…", "ui.move-to-folder": "o tawa kulupu", diff --git a/crates/canvas-pilot/locales/zh-CN.json b/crates/canvas-pilot/locales/zh-CN.json index da43a63..ec1b43b 100644 --- a/crates/canvas-pilot/locales/zh-CN.json +++ b/crates/canvas-pilot/locales/zh-CN.json @@ -1,4 +1,7 @@ { + "language.packs": "语言包", + "language.remove-pack": "移除语言包…", + "language.overwrite-pack": "覆盖语言包", "ui.mask-edges": "蒙版边缘", "ui.rename-layer": "重命名图层…", "ui.move-to-folder": "移至文件夹", diff --git a/crates/canvas-pilot/src/gui.rs b/crates/canvas-pilot/src/gui.rs index 8aa9935..cf79ab3 100644 --- a/crates/canvas-pilot/src/gui.rs +++ b/crates/canvas-pilot/src/gui.rs @@ -48,6 +48,7 @@ pub struct Editor { text_scale: Option, language: localization::Language, language_preview: Option, + language_pack_action: Option, recovery: recovery_ui::Recovery, themes_open: bool, preferences_open: bool, @@ -371,6 +372,7 @@ impl Default for Editor { text_scale: None, language: localization::Language::default(), language_preview: None, + language_pack_action: None, settings: settings::Store::default(), recovery: recovery_ui::Recovery::default(), themes_open: false, @@ -482,6 +484,7 @@ impl Editor { && !self.reference_open && !self.layer_ui.open && self.language_preview.is_none() + && self.language_pack_action.is_none() && self.files.loading.is_none() && !self.files.new_requested && !self.files.new_after_save @@ -4141,6 +4144,7 @@ impl Editor { self.update_alt_mask(&ctx); self.main_ui(root_ui); self.language_confirmation(&ctx); + self.language_pack_confirmation(&ctx); } fn main_ui(&mut self, root_ui: &mut egui::Ui) { let ctx = &root_ui.ctx().clone(); diff --git a/crates/canvas-pilot/src/language_packs.rs b/crates/canvas-pilot/src/language_packs.rs index 3d59e86..827cec1 100644 --- a/crates/canvas-pilot/src/language_packs.rs +++ b/crates/canvas-pilot/src/language_packs.rs @@ -5,7 +5,7 @@ use std::{ borrow::Cow, collections::{BTreeMap, BTreeSet}, io::{Read, Write}, - path::Path, + path::{Path, PathBuf}, sync::{LazyLock, RwLock}, }; @@ -18,6 +18,8 @@ const MAX_PACKS: usize = 32; struct Manifest { version: u32, id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + revision: Option, languages: Vec, } #[derive(Clone, Debug, Deserialize, Serialize)] @@ -77,22 +79,48 @@ pub fn valid_id(id: &str) -> bool { && !id.starts_with('-') && !id.ends_with('-') } -pub fn available(ctx: &egui::Context) -> Vec { - ctx.data(|data| data.get_temp::>(egui::Id::new("language-packs"))) +#[derive(Clone, Debug)] +pub struct Installed { + pub id: String, + pub revision: u64, + pub languages: Vec, + path: PathBuf, +} +pub fn installed(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); +pub fn available(ctx: &egui::Context) -> Vec { + let mut languages: Vec<_> = installed(ctx) + .into_iter() + .flat_map(|p| p.languages) + .collect(); + languages.sort_by(|a, b| a.locale.cmp(&b.locale)); + languages +} +fn register(ctx: &egui::Context, pack: &Pack, path: &Path) { + let mut packs = installed(ctx); let mut backend = CATALOGS.write().unwrap(); + for old in packs.iter().filter(|p| p.id == pack.manifest.id) { + for language in &old.languages { + backend.remove(&format!("pack:{}", language.locale)); + } + } + packs.retain(|p| p.id != pack.manifest.id); 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)); + packs.push(Installed { + id: pack.manifest.id.clone(), + revision: pack.manifest.revision.unwrap_or(0), + languages: pack.manifest.languages.clone(), + path: path.into(), + }); + packs.sort_by(|a, b| a.id.cmp(&b.id)); + ctx.data_mut(|data| data.insert_temp(egui::Id::new("language-packs"), packs)); } fn placeholders(text: &str) -> Result, String> { text.split("%{") @@ -140,14 +168,20 @@ fn parse(bytes: &[u8]) -> Result { return Err("Duplicate ZIP entry".into()); } } - let manifest: Manifest = serde_json::from_slice( + let manifest_value: serde_json::Value = 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) + if manifest_value["version"] == 1 && manifest_value.get("revision").is_some() { + return Err("Legacy packs cannot contain revision; use manifest version 2".into()); + } + let manifest: Manifest = serde_json::from_value(manifest_value).map_err(|e| e.to_string())?; + if !matches!( + (manifest.version, manifest.revision), + (1, None) | (2, Some(1..)) + ) || !valid_id(&manifest.id) || manifest.languages.is_empty() || manifest.languages.len() > 16 { @@ -210,23 +244,30 @@ fn read(path: &Path) -> Result, String> { .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()); +fn check_collisions(ctx: &egui::Context, pack: &Pack, replacing: bool) -> Result<(), String> { + for old in installed(ctx) { + if old.id == pack.manifest.id { + if replacing { + continue; + } + return Err("Pack identifier is already installed".into()); + } + if pack.manifest.languages.iter().any(|new| { + old.languages + .iter() + .any(|language| language.locale == new.locale) + }) { + return Err(format!( + "A language in this pack belongs to installed pack {}", + old.id + )); + } } 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()) - }); + 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![], @@ -252,8 +293,8 @@ pub fn load(ctx: &egui::Context, directory: &Path) -> Vec { let result = read(&path) .and_then(|bytes| parse(&bytes)) .and_then(|pack| { - check_collisions(ctx, &pack)?; - register(ctx, &pack); + check_collisions(ctx, &pack, false)?; + register(ctx, &pack, &path); Ok(()) }); if let Err(error) = result { @@ -262,29 +303,117 @@ pub fn load(ctx: &egui::Context, directory: &Path) -> Vec { } errors } -/// Validate the entire pack, persist without replacing existing files, then register. -pub fn install(ctx: &egui::Context, directory: &Path, source: &Path) -> Result<(), String> { +/// Validated bytes and the exact destination reviewed by the user. Never re-read the source on confirmation. +pub struct Prepared { + pack: Pack, + bytes: Vec, + path: PathBuf, + previous: Option>, + pub previous_revision: Option, +} +impl Prepared { + pub fn id(&self) -> &str { + &self.pack.manifest.id + } + pub fn revision(&self) -> u64 { + self.pack.manifest.revision.unwrap_or(0) + } + pub fn needs_confirmation(&self) -> bool { + self.previous.is_some() + && self + .previous_revision + .is_none_or(|old| self.revision() <= old) + } +} +fn existing_bytes(path: &Path) -> Result>, String> { + match read(path) { + Ok(bytes) if bytes.len() as u64 <= MAX_ARCHIVE => Ok(Some(bytes)), + Ok(_) => Err("Existing pack exceeds 2 MiB; remove it manually before replacing it".into()), + Err(_error) if !path.exists() => Ok(None), + Err(error) => Err(error), + } +} +pub fn prepare(ctx: &egui::Context, directory: &Path, source: &Path) -> Result { let bytes = read(source)?; let pack = parse(&bytes)?; - check_collisions(ctx, &pack)?; + check_collisions(ctx, &pack, true)?; + let path = installed(ctx) + .into_iter() + .find(|p| p.id == pack.manifest.id) + .map_or_else( + || directory.join(format!("{}.zip", pack.manifest.id)), + |p| p.path, + ); + let previous = existing_bytes(&path)?; + if let Some(old) = previous.as_ref().and_then(|bytes| parse(bytes).ok()) + && old.manifest.id != pack.manifest.id + { + return Err("Destination belongs to a different pack; remove that pack first".into()); + } + let previous_revision = previous + .as_ref() + .and_then(|bytes| parse(bytes).ok()) + .filter(|old| old.manifest.id == pack.manifest.id) + .map(|old| old.manifest.revision.unwrap_or(0)); + Ok(Prepared { + pack, + bytes, + path, + previous, + previous_revision, + }) +} +pub fn commit(ctx: &egui::Context, pending: Prepared, overwrite: bool) -> Result<(), String> { + if pending.needs_confirmation() && !overwrite { + return Err("Replacing this pack requires overwrite confirmation".into()); + } + check_collisions(ctx, &pending.pack, true)?; + if existing_bytes(&pending.path)? != pending.previous { + return Err("Installed pack changed during review; choose the ZIP again".into()); + } + let directory = pending.path.parent().ok_or("Missing pack directory")?; 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 + if pending.previous.is_none() + && 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.write_all(&pending.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); + if pending.previous.is_some() { + file.persist(&pending.path).map_err(|e| e.to_string())?; + } else { + file.persist_noclobber(&pending.path) + .map_err(|e| e.to_string())?; + } + register(ctx, &pending.pack, &pending.path); Ok(()) } +pub fn remove(ctx: &egui::Context, pack: &Installed) -> Result<(), String> { + let current = parse(&read(&pack.path)?)?; + if current.manifest.id != pack.id || current.manifest.revision.unwrap_or(0) != pack.revision { + return Err("Installed pack changed; restart before removing it".into()); + } + std::fs::remove_file(&pack.path).map_err(|e| e.to_string())?; + let mut backend = CATALOGS.write().unwrap(); + for language in &pack.languages { + backend.remove(&format!("pack:{}", language.locale)); + } + let mut packs = installed(ctx); + packs.retain(|p| p.id != pack.id); + ctx.data_mut(|data| data.insert_temp(egui::Id::new("language-packs"), packs)); + Ok(()) +} +#[cfg(test)] +pub fn install(ctx: &egui::Context, directory: &Path, source: &Path) -> Result<(), String> { + commit(ctx, prepare(ctx, directory, source)?, false) +} #[cfg(test)] mod tests { @@ -314,6 +443,154 @@ mod tests { fn manifest() -> serde_json::Value { serde_json::json!({"version":1,"id":"test","languages":[{"locale":"uk","name":"Ukrainian","native_name":"Українська"}]}) } + fn revision_archive(id: &str, locale: &str, revision: Option, text: &str) -> Vec { + let mut m = serde_json::json!({"version":1,"id":id,"languages":[{"locale":locale,"name":"Test","native_name":"Test"}]}); + if let Some(revision) = revision { + m["version"] = 2.into(); + m["revision"] = revision.into(); + } + archive(&[ + ("manifest.json", &serde_json::to_vec(&m).unwrap()), + ( + &format!("{locale}.json"), + &serde_json::to_vec(&serde_json::json!({"ui.close":text})).unwrap(), + ), + ]) + } + + #[test] + fn updates_replace_language_lists_and_work_at_pack_limit_on_original_paths() { + let dir = tempfile::tempdir().unwrap(); + let destination = dir.path().join("packs"); + std::fs::create_dir_all(&destination).unwrap(); + let old = revision_archive("limits", "test-old-list", Some(1), "Old"); + let file = destination.join("custom-name.zip"); + std::fs::write(&file, old).unwrap(); + let ctx = egui::Context::default(); + assert!(load(&ctx, &destination).is_empty()); + for i in 1..MAX_PACKS { + std::fs::write(destination.join(format!("invalid-{i}.zip")), b"bad").unwrap(); + } + let source = dir.path().join("source.zip"); + let updated = revision_archive("limits", "test-new-list", Some(2), "New"); + std::fs::write(&source, &updated).unwrap(); + install(&ctx, &destination, &source).unwrap(); + assert_eq!( + available(&ctx) + .iter() + .map(|p| p.locale.as_str()) + .collect::>(), + ["test-new-list"] + ); + assert_eq!(std::fs::read(&file).unwrap(), updated); + assert!(!destination.join("limits.zip").exists()); + std::fs::write( + &source, + revision_archive("extra", "test-extra-list", Some(1), "Extra"), + ) + .unwrap(); + assert!(install(&ctx, &destination, &source).is_err()); + // A misleading filename is not permission to overwrite a different identity. + std::fs::write( + destination.join("extra.zip"), + revision_archive("unrelated", "test-unrelated-list", Some(1), "Other"), + ) + .unwrap(); + assert!(prepare(&ctx, &destination, &source).is_err()); + } + + #[test] + fn revisions_update_atomically_and_equal_older_or_legacy_require_confirmation() { + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("source.zip"); + let destination = dir.path().join("packs"); + let ctx = egui::Context::default(); + let legacy = revision_archive("revisions", "test-revision", None, "Legacy"); + std::fs::write(&source, &legacy).unwrap(); + install(&ctx, &destination, &source).unwrap(); + let newer = revision_archive("revisions", "test-revision", Some(2), "Updated"); + std::fs::write(&source, &newer).unwrap(); + install(&ctx, &destination, &source).unwrap(); + Language::Pack("test-revision".into()).apply(&ctx); + assert_eq!(tr(&ctx, "ui.close"), "Updated"); + assert_eq!(installed(&ctx)[0].revision, 2); + for revision in [Some(2), Some(1), None] { + std::fs::write( + &source, + revision_archive("revisions", "test-revision", revision, "Replacement"), + ) + .unwrap(); + let pending = prepare(&ctx, &destination, &source).unwrap(); + assert!(pending.needs_confirmation()); + assert!(commit(&ctx, pending, false).is_err()); + assert_eq!( + std::fs::read(destination.join("revisions.zip")).unwrap(), + newer + ); + assert_eq!(tr(&ctx, "ui.close"), "Updated"); + } + let pending = prepare(&ctx, &destination, &source).unwrap(); + // Confirmation uses reviewed bytes, not a newly edited source file. + std::fs::write(&source, b"changed after review").unwrap(); + commit(&ctx, pending, true).unwrap(); + assert_eq!(tr(&ctx, "ui.close"), "Replacement"); + let restarted = egui::Context::default(); + assert!(load(&restarted, &destination).is_empty()); + assert_eq!(installed(&restarted)[0].revision, 0); + remove(&ctx, &installed(&ctx)[0]).unwrap(); + assert!(available(&ctx).is_empty()); + assert!(!destination.join("revisions.zip").exists()); + Language::Pack("test-revision".into()).apply(&ctx); + assert_eq!(tr(&ctx, "ui.close"), "Close"); + assert!(load(&restarted, &destination).is_empty()); + assert!(installed(&restarted).is_empty()); + } + + #[test] + fn changed_destination_collisions_and_invalid_revisions_leave_packs_intact() { + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("source.zip"); + let destination = dir.path().join("packs"); + let ctx = egui::Context::default(); + let original = revision_archive("collision", "test-collision", Some(1), "Original"); + std::fs::write(&source, &original).unwrap(); + install(&ctx, &destination, &source).unwrap(); + std::fs::write( + &source, + revision_archive("other", "test-collision", Some(3), "Collision"), + ) + .unwrap(); + assert!(prepare(&ctx, &destination, &source).is_err()); + std::fs::write( + &source, + revision_archive("collision", "test-collision", Some(2), "Newer"), + ) + .unwrap(); + let pending = prepare(&ctx, &destination, &source).unwrap(); + let file = destination.join("collision.zip"); + std::fs::write(&file, b"external change").unwrap(); + assert!(commit(&ctx, pending, true).is_err()); + assert_eq!(std::fs::read(&file).unwrap(), b"external change"); + assert!(remove(&ctx, &installed(&ctx)[0]).is_err()); + std::fs::write(&file, &original).unwrap(); + let mut m = manifest(); + m["version"] = 2.into(); + for revision in [ + serde_json::Value::Null, + serde_json::json!(0), + serde_json::json!(-1), + serde_json::json!(1.5), + serde_json::json!("2"), + ] { + m["revision"] = revision; + assert!(parse(&modified(m.clone(), serde_json::json!({"ui.close":"Test"}))).is_err()); + } + m["version"] = 1.into(); + m["revision"] = 1.into(); + assert!(parse(&modified(m, serde_json::json!({"ui.close":"Test"}))).is_err()); + assert_eq!(std::fs::read(file).unwrap(), original); + } + #[test] fn example_matches_sources_installs_restarts_and_falls_back() { let mut zip = zip::ZipArchive::new(std::io::Cursor::new(EXAMPLE)).unwrap(); diff --git a/crates/canvas-pilot/src/preferences_ui.rs b/crates/canvas-pilot/src/preferences_ui.rs index 78850fa..0b98516 100644 --- a/crates/canvas-pilot/src/preferences_ui.rs +++ b/crates/canvas-pilot/src/preferences_ui.rs @@ -41,14 +41,16 @@ fn scale_slider(ui: &mut egui::Ui, scale: &mut f32, maximum: f32) -> egui::Respo pub(super) enum Section { #[default] Appearance, + Languages, Editing, Reference, Storage, Device, } impl Section { - const ALL: [(Self, &'static str); 5] = [ + const ALL: [(Self, &'static str); 6] = [ (Self::Appearance, "ui.appearance"), + (Self::Languages, "language.packs"), (Self::Editing, "ui.editing"), (Self::Reference, "ui.reference-images"), (Self::Storage, "ui.files-settings"), @@ -61,6 +63,11 @@ pub(super) struct LanguagePreview { deadline: std::time::Instant, } +pub(super) enum PackAction { + Install(crate::language_packs::Prepared), + Remove(crate::language_packs::Installed), +} + impl Editor { fn preview_language(&mut self, ctx: &egui::Context, language: localization::Language) { if language == self.language { @@ -145,6 +152,115 @@ impl Editor { } } + fn refresh_pack_language( + &mut self, + ctx: &egui::Context, + previous: &[crate::language_packs::Description], + ) { + if let localization::Language::Pack(locale) = &self.language + && previous.iter().any(|p| &p.locale == locale) + && !crate::language_packs::available(ctx) + .iter() + .any(|p| &p.locale == locale) + { + self.language = localization::Language::En; + } + self.language.apply(ctx); + self.settings.save(&self.application_settings(ctx)); + } + + fn prepare_language_pack(&mut self, ctx: &egui::Context, path: &std::path::Path) { + self.finish_language_preview(ctx, false); + 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::prepare(ctx, &directory.join("language-packs"), path) + }); + let previous = crate::language_packs::available(ctx); + match result { + Ok(pending) if pending.needs_confirmation() => { + self.language_pack_action = Some(PackAction::Install(pending)) + } + Ok(pending) => match crate::language_packs::commit(ctx, pending, false) { + Ok(()) => self.refresh_pack_language(ctx, &previous), + Err(error) => self.error = error, + }, + Err(error) => self.error = error, + } + } + + fn language_pack_settings(&mut self, ui: &mut egui::Ui) { + let ctx = ui.ctx().clone(); + ui.heading(tr(&ctx, "language.packs")); + if ui.button(tr(&ctx, "language.install-pack")).clicked() + && let Some(path) = rfd::FileDialog::new() + .add_filter("Language pack", &["zip"]) + .pick_file() + { + self.prepare_language_pack(&ctx, &path); + } + ui.weak("Choose a ZIP to install or update. Newer revisions update immediately; equal or older revisions ask before replacing."); + let packs = crate::language_packs::installed(&ctx); + if packs.is_empty() { + ui.label("No language packs installed."); + } + for pack in packs { + ui.separator(); + ui.label(format!("{} · revision {}", pack.id, pack.revision)); + for language in &pack.languages { + ui.label(format!("{} — {}", language.native_name, language.name)); + } + ui.push_id(&pack.id, |ui| { + if ui.button(tr(&ctx, "language.remove-pack")).clicked() { + self.finish_language_preview(&ctx, false); + self.language_pack_action = Some(PackAction::Remove(pack.clone())); + } + }); + } + } + + pub(super) fn language_pack_confirmation(&mut self, ctx: &egui::Context) { + let Some(action) = &self.language_pack_action else { + return; + }; + let response = egui::Modal::new(egui::Id::new("confirm-language-pack")).show(ctx, |ui| { + ui.set_max_width(460.0); + let label = match action { + PackAction::Install(pack) => { + ui.heading(tr(ctx, "language.overwrite-pack")); + ui.label(format!("{}: installed revision {} → revision {}", pack.id(), pack.previous_revision.map_or_else(|| "unknown".into(), |v| v.to_string()), pack.revision())); + ui.label("This is not a newer revision. Replacing it overwrites the installed translations."); + "language.overwrite-pack" + }, + PackAction::Remove(pack) => { + ui.heading(tr(ctx, "language.remove-pack")); + ui.label(&pack.id); + ui.label(pack.languages.iter().map(|p| p.name.as_str()).collect::>().join(", ")); + ui.label("All languages in this pack will be removed. If the current language is removed, the interface switches to English. You can reinstall the ZIP later."); + "language.remove-pack" + } + }; + (ui.button(tr(ctx, label)).clicked(), ui.button(tr(ctx, "ui.cancel")).clicked()) + }); + if response.inner.1 || response.should_close() { + self.language_pack_action = None; + } else if response.inner.0 { + let previous = crate::language_packs::available(ctx); + let result = match self.language_pack_action.take().unwrap() { + PackAction::Install(pack) => crate::language_packs::commit(ctx, pack, true), + PackAction::Remove(pack) => crate::language_packs::remove(ctx, &pack), + }; + match result { + Ok(()) => self.refresh_pack_language(ctx, &previous), + Err(error) => self.error = error, + } + } + } + pub(super) fn preferences_window(&mut self, ctx: &egui::Context) { if !self.preferences_open { return; @@ -179,11 +295,6 @@ 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") @@ -229,6 +340,7 @@ impl Editor { ui.checkbox(&mut self.show_pattern, tr(ui.ctx(), "ui.show-source-patterns-on-other-layers-while-cropping")); ui.weak(tr(ui.ctx(), "ui.themes-also-apply-to-the-viewport-imported-pictures-retain-their-colors")); } + Section::Languages => self.language_pack_settings(ui), Section::Editing => { ui.heading(tr(ui.ctx(), "ui.editing")); self.resize_ratio_option(ui); @@ -337,6 +449,104 @@ mod tests { ); frame(app, ctx, vec![mouse(pos, false)]); } + fn manager_pack(revision: u64, locale: &str) -> Vec { + use std::io::Write; + let manifest = serde_json::json!({"version":2,"id":"manager-test","revision":revision,"languages":[{"locale":locale,"name":"Manager test","native_name":"Manager test"}]}); + let mut writer = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for (name, value) in [ + ("manifest.json", manifest), + ( + &format!("{locale}.json"), + serde_json::json!({"ui.close":format!("Close revision {revision}")}), + ), + ] { + writer + .start_file(name, zip::write::SimpleFileOptions::default()) + .unwrap(); + writer + .write_all(&serde_json::to_vec(&value).unwrap()) + .unwrap(); + } + writer.finish().unwrap().into_inner() + } + + #[test] + fn pack_manager_updates_confirms_overwrites_and_removes_active_language_live() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("settings.json"); + let source = dir.path().join("pack.zip"); + let (store, mut saved) = settings::Store::at(path.clone()); + saved.language = localization::Language::En; + let ctx = egui::Context::default(); + let mut app = Editor::with_settings(&ctx, store, saved); + app.preferences_open = true; + app.fields[0] = "-".into(); + let project = app.project().to_json().unwrap(); + let draft = app.fields.clone(); + click_label(&mut app, &ctx, "Language packs"); + assert_eq!(app.preferences_section, Section::Languages); + std::fs::write(&source, manager_pack(1, "test-manager")).unwrap(); + app.prepare_language_pack(&ctx, &source); + assert!(app.language_pack_action.is_none()); + app.preview_language(&ctx, localization::Language::Pack("test-manager".into())); + app.finish_language_preview(&ctx, true); + std::fs::write(&source, manager_pack(2, "test-manager")).unwrap(); + app.prepare_language_pack(&ctx, &source); + assert!(app.language_pack_action.is_none()); + assert_eq!(tr(&ctx, "ui.close"), "Close revision 2"); + app.prepare_language_pack(&ctx, &source); + assert!(matches!( + app.language_pack_action, + Some(PackAction::Install(_)) + )); + click_label(&mut app, &ctx, "Cancel"); + assert!(app.language_pack_action.is_none()); + std::fs::write(&source, manager_pack(1, "test-manager")).unwrap(); + app.prepare_language_pack(&ctx, &source); + assert!(matches!( + app.language_pack_action, + Some(PackAction::Install(_)) + )); + click_label(&mut app, &ctx, "Overwrite pack"); + assert_eq!(tr(&ctx, "ui.close"), "Close revision 1"); + click_label(&mut app, &ctx, "Remove pack…"); + click_label(&mut app, &ctx, "Cancel"); + assert_eq!(crate::language_packs::available(&ctx).len(), 1); + click_label(&mut app, &ctx, "Remove pack…"); + click_label(&mut app, &ctx, "Remove pack…"); + assert!(crate::language_packs::available(&ctx).is_empty()); + assert_eq!(app.language, localization::Language::En); + assert_eq!(localization::locale(&ctx), "en"); + assert_eq!( + settings::Store::at(path).1.language, + localization::Language::En + ); + assert!(!dir.path().join("language-packs/manager-test.zip").exists()); + assert_eq!(app.project().to_json().unwrap(), project); + assert_eq!(app.fields, draft); + // An unrelated installation preserves an already-missing preference. + app.language = localization::Language::Pack("missing-manager".into()); + app.language.apply(&ctx); + std::fs::write(&source, manager_pack(2, "test-other-manager")).unwrap(); + app.prepare_language_pack(&ctx, &source); + assert_eq!( + app.language, + localization::Language::Pack("missing-manager".into()) + ); + app.preview_language( + &ctx, + localization::Language::Pack("test-other-manager".into()), + ); + app.finish_language_preview(&ctx, true); + // Updating away the active locale switches to English without confirmation. + std::fs::write(&source, manager_pack(3, "test-manager")).unwrap(); + app.prepare_language_pack(&ctx, &source); + assert!(app.language_pack_action.is_none()); + assert_eq!(app.language, localization::Language::En); + assert_eq!(app.project().to_json().unwrap(), project); + assert_eq!(app.fields, draft); + } + #[test] fn scale_slider_commits_only_after_pointer_release() { for maximum in [200.0, 400.0] { diff --git a/docs/canvas-pilot/changelog.md b/docs/canvas-pilot/changelog.md index 5520ffd..e0ae998 100644 --- a/docs/canvas-pilot/changelog.md +++ b/docs/canvas-pilot/changelog.md @@ -4,6 +4,18 @@ ## Unreleased +### v0.9.16 + +- Added language-pack management in Settings: installed revisions/languages, + confirmed removal and immediate refresh without restarting. Removing the active + language selects and saves English. +- Format-2 ZIP packs carry a positive revision number. Higher revisions update + atomically; equal/older revisions require overwrite confirmation. Legacy packs + remain readable as revision 0; cross-pack locale collisions remain errors. + Updated the Ukrainian/Bhojpuri teaching ZIP and authoring contract. +- Native manager/removal checks, update/overwrite UI regressions and all required + validation passed; whole-application line coverage is 91.68%. + ### v0.9.15 - Removed nested Export and duplicate device mapping/transfer entries from Project; diff --git a/docs/canvas-pilot/guide/language-packs.md b/docs/canvas-pilot/guide/language-packs.md index a9dd396..0560296 100644 --- a/docs/canvas-pilot/guide/language-packs.md +++ b/docs/canvas-pilot/guide/language-packs.md @@ -8,7 +8,7 @@ not translate project names, device responses or exported geometry. 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. +3. Choose **Language packs**, then 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 @@ -21,7 +21,7 @@ stays English. Bhojpuri is identified as `bho`, separately from Hindi (`hi`), fo [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 +These packs reuse the fonts already bundled with Canvas Pilot. Version 1 and 2 packs contain translations only: they neither install fonts nor reduce the current application download size. Ukrainian uses the existing Cyrillic coverage. @@ -37,8 +37,9 @@ The manifest describes the pack and its languages: ```json { - "version": 1, + "version": 2, "id": "example-uk-bho", + "revision": 1, "languages": [ {"locale": "uk", "name": "Ukrainian", "native_name": "Українська"}, {"locale": "bho", "name": "Bhojpuri", "native_name": "भोजपुरी"} @@ -89,12 +90,32 @@ 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. +Use **Settings → Language packs** to see installed packs, their revisions and included languages. +**Remove pack…** asks for confirmation and removes every language bundled in that +pack immediately. Removing the active language switches to English and saves that +choice. Built-in languages cannot be removed. Keep the source ZIP if you want to +reinstall later; removal does not delete your original download. + +To update, choose **Install language pack…** and select the new ZIP: + +- Keep the same pack `id` and increase `revision` for a newer release. A higher + revision replaces the installed pack immediately, including the currently selected + translations. No restart or manual file removal is needed. +- An equal revision (a sidegrade, including the same ZIP) or lower revision asks + before overwriting. Cancel leaves the installed pack unchanged. +- Legacy format-1 packs have revision 0. A format-2 revision 1 pack updates them + directly; installing a legacy pack over another installed pack requires confirmation. +- Languages belonging to a different installed pack cannot be overwritten. Remove + that pack explicitly first. An update can add/remove languages within its own pack; + if it removes the active language, Canvas Pilot switches to English. + +`version` describes the manifest format and stays **2**; `revision` is a positive +integer that you increase for each release (1, 2, 3, …). It is independent of the app +version and file timestamps, so timezone or clock changes do not affect ordering. + +If a pack is removed outside the app, the saved language remains marked unavailable +and renders in English until reinstalled. 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, diff --git a/docs/canvas-pilot/guide/preferences.md b/docs/canvas-pilot/guide/preferences.md index 5d2a767..3e5cd92 100644 --- a/docs/canvas-pilot/guide/preferences.md +++ b/docs/canvas-pilot/guide/preferences.md @@ -60,7 +60,9 @@ 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…**. +Use **Settings → Language packs** to install/update ZIP packs, view their revisions +and languages, or remove them. Newer revisions update immediately; equal or older +revisions ask before overwriting. Removal asks for confirmation. 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. diff --git a/docs/interfaces/language-packs.md b/docs/interfaces/language-packs.md index 530e30a..d0c7a82 100644 --- a/docs/interfaces/language-packs.md +++ b/docs/interfaces/language-packs.md @@ -1,4 +1,4 @@ -# Canvas Pilot language packs, version 1 +# Canvas Pilot language packs, versions 1 and 2 Implementation: `crates/canvas-pilot/src/language_packs.rs`. User instructions and editable downloads: [Add a language pack](../canvas-pilot/guide/language-packs.md). @@ -12,12 +12,13 @@ must be at the archive root. Directories, symlinks, duplicate ZIP names, unexpec 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 +All JSON uses UTF-8. Manifest version is integer `1` or `2`; unknown manifest/description fields and other versions are rejected. Field order has no meaning. | Field | Contract | | --- | --- | -| `version` | Required integer `1` | +| `version` | Required integer `1` (legacy) or `2` | +| `revision` | Format 2: required positive `u64` integer (1–18446744073709551615). Format 1: absent, interpreted as revision 0. Higher numbers mean newer content; no clock/timezone or app-version comparison. | | `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 | @@ -34,7 +35,7 @@ ordinary serde map behavior applies: repeated object keys resolve to the last va 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 +Neither version supplies 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. @@ -43,22 +44,39 @@ 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. +Installation validates every entry and locale collision before writing. Packs are +identified by `id`; locales owned by other installed IDs always reject the operation. +A new pack is persisted without clobbering to `/language-packs/.zip`. +An update replaces that ID's actual loaded path (including a manually named ZIP). +The source is read once, bounded and retained in memory during review. The original +ZIP bytes are preserved exactly, without extraction or re-export. + +A same-ID higher revision updates immediately. Equal/lower revisions, legacy-over- +legacy and a pre-existing unreadable-as-pack destination require explicit overwrite +confirmation. Cancel changes neither disk nor runtime catalogs. A destination over +2 MiB cannot be replaced through this flow. Before committing, destination bytes are +compared against those reviewed; a change requires a fresh selection. A temporary +file in the destination directory is flushed, then atomically persisted/replaced; +runtime catalogs and available-language metadata update only after persistence succeeds. +Updates may add/remove locales; old descriptions are replaced, never appended. +The revision comparison uses the installed file, not only cached metadata. + +Removal confirms the pack ID and all included languages. The installed file is +validated against its recorded ID/revision before deletion; a failure retains the +runtime registration. Successful deletion removes the pack's selector entries +immediately. Source downloads are untouched. Removing/updating away the active +language selects and saves English; other choices are retained. No restart is +required. Built-in catalogs cannot be removed or overridden. 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. +colliding pack or duplicate ID is rejected in full. Installation also refuses a +33rd ZIP, but replacing an existing ZIP is allowed at the limit. Startup is offline. +Manual removal/replacement takes effect after restart. -The [settings v13 contract](canvas-pilot-settings.md) stores an installed choice as +The [settings 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 @@ -68,11 +86,13 @@ 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 +Pack v1 is supported from application v0.9.7. Pack v2 and live management are +supported from v0.9.16; older applications reject format 2 rather than ignoring +its revision. The example archive is format 2, revision 1. 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, +pack updates. Adding an English key does not break partial packs. Applications before +v0.9.7 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. +revision ordering, confirmed overwrite, canceled/stale review, live removal, 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/manifest.json b/docs/language-packs/example/manifest.json index 6650928..ddc016a 100644 --- a/docs/language-packs/example/manifest.json +++ b/docs/language-packs/example/manifest.json @@ -1,6 +1,7 @@ { - "version": 1, + "version": 2, "id": "example-uk-bho", + "revision": 1, "languages": [ { "locale": "uk", diff --git a/docs/language-packs/language-pack.zip b/docs/language-packs/language-pack.zip index 6cfaba9..e17ecb4 100644 Binary files a/docs/language-packs/language-pack.zip and b/docs/language-packs/language-pack.zip differ