From e8507bfc8cb85dc2b8882f049b1caaecd7104382 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 28 Nov 2026 22:31:06 +0100 Subject: [PATCH 1/3] Web size: bake the UI string catalogs compressed and unpack a language when it is first read (#2720) --- Cargo.lock | 1 + crates/ui-egui/Cargo.toml | 3 + crates/ui-egui/build.rs | 100 +++++++++++++++++++--------- crates/ui-egui/src/field_tests.rs | 2 +- crates/ui-egui/src/i18n.rs | 102 ++++++++++++++++++++++++++--- crates/ui-egui/src/i18n/tests.rs | 61 ++++++++++------- crates/ui-egui/src/naming_tests.rs | 8 +-- 7 files changed, 207 insertions(+), 70 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index db22f6f04..3bfe91b6c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2981,6 +2981,7 @@ dependencies = [ "figcraft-pathops", "figcraft-render", "figcraft-text", + "flate2", "image", "log", "serde", diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index f86da1023..f185c466c 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -30,6 +30,8 @@ egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts" serde = { workspace = true } serde_json = { workspace = true } log = { workspace = true } +# Unpacks the zlib-compressed string catalogs (`src/i18n.rs`). +flate2 = { workspace = true } chrono = { workspace = true } base64 = { workspace = true } image = { workspace = true } @@ -38,6 +40,7 @@ web-time = "1.1.0" [build-dependencies] serde_json = { workspace = true } +flate2 = { workspace = true } toml = "1" [dev-dependencies] diff --git a/crates/ui-egui/build.rs b/crates/ui-egui/build.rs index 10e70608a..f5ee2a933 100644 --- a/crates/ui-egui/build.rs +++ b/crates/ui-egui/build.rs @@ -32,10 +32,14 @@ fn main() { } } -/// `pub static LANGS: &[Lang]`: every `locales/*.toml`, English first, each table sorted by key. +/// `pub static LANGS: &[Lang]`: every `locales/*.toml`, English first. Each language's tables +/// (sorted by key) are serialized and zlib-compressed into OUT_DIR, and `i18n` unpacks a language +/// only when the UI first looks a string up in it: the ~65,000 rows of 27 languages would +/// otherwise be several megabytes of the browser build, nearly all of it never read. fn locales() -> String { let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("locales"); println!("cargo::rerun-if-changed={}", dir.display()); + let out_dir = std::path::PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()); let mut files: Vec<_> = std::fs::read_dir(&dir).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "toml")).collect(); // By code, so "es" comes before "es-419". @@ -47,50 +51,82 @@ fn locales() -> String { Some((path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(), path, t)) }) .collect(); - let mut o = String::from( - "pub static LANGS: &[Lang] = &[ -", - ); + let mut o = format!("static LANG_TABLE: [Lang; {}] = [\n", langs.len()); for (code, path, t) in &langs { let meta = |k: &str| t.get("meta").and_then(|m| m.get(k)).and_then(toml::Value::as_str).unwrap_or("").to_string(); // A regional catalog ("es-419") overlays its language's ("es"), if there is one. let parent = code.split_once('-').and_then(|(base, _)| langs.iter().position(|(c, ..)| c == base)).unwrap_or(0); - let _ = writeln!(o, " Lang {{ code: {code:?}, name: {:?}, draft: {}, parent: {parent}, ui: &[", meta("name"), !meta("status").is_empty()); - table(&mut o, path, t.get("ui")); - let _ = writeln!(o, " ], commands: &["); - table(&mut o, path, t.get("commands")); - let _ = writeln!(o, " ], menu: &["); - table(&mut o, path, t.get("menu")); - let _ = writeln!(o, " ] }},"); + let mut raw = Vec::new(); + for name in ["ui", "commands", "menu"] { + table(&mut raw, path, t.get(name)); + } + let packed_path = out_dir.join(format!("locale-{code}.zlib")); + let packed = { + use std::io::Write as _; + let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::best()); + e.write_all(&raw).and_then(|()| e.finish()) + }; + let written = packed.map_err(|e| e.to_string()).and_then(|p| std::fs::write(&packed_path, p).map_err(|e| e.to_string())); + if let Err(e) = written { + println!("cargo::warning=packing {}: {e}; the language shows English", path.display()); + let _ = std::fs::write(&packed_path, []); + } + let _ = writeln!( + o, + " Lang {{ code: {code:?}, name: {:?}, draft: {}, parent: {parent}, packed: include_bytes!({:?}), unpacked_len: {}, tables: std::sync::OnceLock::new() }},", + meta("name"), + !meta("status").is_empty(), + packed_path.display().to_string(), + raw.len(), + ); } - o.push_str( - "]; -", - ); + o.push_str("];\npub static LANGS: &[Lang] = &LANG_TABLE;\n"); o } -/// The rows of one catalog table: strings or plural forms (`other` required). -fn table(o: &mut String, path: &std::path::Path, t: Option<&toml::Value>) { - let Some(t) = t.and_then(toml::Value::as_table) else { return }; - // Sorted by key (byte order), as the lookup's binary search needs. - let mut rows: Vec<_> = t.iter().collect(); +/// Append one catalog table: its row count, then per row the key and either a string (tag 0) or +/// plural forms (tag 1: one, few, many, other; `other` required). Strings are a little-endian u32 +/// byte length and their UTF-8, `u32::MAX` for an absent form. Rows are sorted by key (byte +/// order), as the lookup's binary search needs. `i18n::unpack` reads this back. +fn table(o: &mut Vec, path: &std::path::Path, t: Option<&toml::Value>) { + let mut rows: Vec<_> = t.and_then(toml::Value::as_table).map(|t| t.iter().collect()).unwrap_or_default(); rows.sort_by(|a, b| a.0.cmp(b.0)); + let mut body = Vec::new(); + let mut count = 0u32; for (k, v) in rows { let s = |k: &str| v.get(k).and_then(toml::Value::as_str); - match (v.as_str(), s("one"), s("other")) { - (Some(text), ..) => _ = writeln!(o, " ({k:?}, Text::Plain({text:?})),"), - (None, one, Some(other)) => { - _ = writeln!( - o, - " ({k:?}, Text::Plural(&Forms {{ one: {}, few: {}, many: {}, other: {other:?} }})),", - name(one), - name(s("few")), - name(s("many")), - ); + match (v.as_str(), s("other")) { + (Some(text), _) => { + put(&mut body, Some(k)); + body.push(0); + put(&mut body, Some(text)); + } + (None, Some(other)) => { + put(&mut body, Some(k)); + body.push(1); + for form in [s("one"), s("few"), s("many")] { + put(&mut body, form.map(str::trim).filter(|f| !f.is_empty())); + } + put(&mut body, Some(other)); + } + _ => { + println!("cargo::warning={}: `{k}` is neither a string nor plural forms with `other`; left out", path.display()); + continue; } - _ => println!("cargo::warning={}: `{k}` is neither a string nor plural forms with `other`; left out", path.display()), } + count += 1; + } + o.extend_from_slice(&count.to_le_bytes()); + o.extend_from_slice(&body); +} + +fn put(o: &mut Vec, s: Option<&str>) { + match s { + Some(s) => { + o.extend_from_slice(&u32::try_from(s.len()).unwrap_or(u32::MAX - 1).to_le_bytes()); + o.extend_from_slice(s.as_bytes()); + } + None => o.extend_from_slice(&u32::MAX.to_le_bytes()), } } diff --git a/crates/ui-egui/src/field_tests.rs b/crates/ui-egui/src/field_tests.rs index ea462399e..1556cb24b 100644 --- a/crates/ui-egui/src/field_tests.rs +++ b/crates/ui-egui/src/field_tests.rs @@ -1051,7 +1051,7 @@ fn the_intensity_label_fits_whole_beside_its_value() { let width = |s: &str| ui.painter().layout_no_wrap(s.to_string(), crate::theme::regular(11.0), egui::Color32::WHITE).size().x; let mut english = 0.0; for lang in i18n::languages() { - let label = lang.ui.iter().find(|(k, _)| *k == "Intensity").map_or("Intensity", |(_, t)| match t { + let label = lang.ui().iter().find(|(k, _)| *k == "Intensity").map_or("Intensity", |(_, t)| match t { Text::Plain(s) | Text::Plural(Forms { other: s, .. }) => s, }); // The test's context has only egui's own font: a label it can't draw (Vietnamese diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 25b08dd03..2488a33e2 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -8,9 +8,10 @@ use std::borrow::Cow; use std::fmt::Display; +use std::sync::OnceLock; use std::sync::atomic::{AtomicUsize, Ordering}; -/// One catalog entry. Two words: the plural forms sit behind a reference, so the ~52,000 baked-in +/// One catalog entry. Two words: the plural forms sit behind a reference, so the ~65,000 unpacked /// rows don't each carry four strings' worth of space (about 450 KB of the browser build). pub enum Text { Plain(&'static str), @@ -25,7 +26,9 @@ pub struct Forms { pub other: &'static str, } -/// A language's catalog (generated from `locales/.toml`). +/// A language's catalog (generated from `locales/.toml`). Its tables are baked in +/// compressed and unpacked the first time they are read ([`Lang::ui`]), so only the languages the +/// UI shows take memory, and the browser build carries a fraction of their size. pub struct Lang { pub code: &'static str, /// The language's own name for itself (the language picker shows it untranslated). @@ -36,13 +39,96 @@ pub struct Lang { /// Index into [`LANGS`] of the catalog a regional one overlays ("es" under "es-419": it lists /// only what differs), else 0 (English). pub parent: usize, + /// The zlib-compressed tables (build.rs `table` writes the layout [`unpack`] reads). + packed: &'static [u8], + unpacked_len: usize, + tables: OnceLock, +} + +/// One language's unpacked tables. +#[derive(Default)] +struct Tables { + ui: Vec<(&'static str, Text)>, + commands: Vec<(&'static str, Text)>, + menu: Vec<(&'static str, Text)>, +} + +impl Lang { /// UI strings by English text, sorted. - pub ui: &'static [(&'static str, Text)], + pub fn ui(&'static self) -> &'static [(&'static str, Text)] { + &self.tables().ui + } + /// Command labels by command id, sorted. - pub commands: &'static [(&'static str, Text)], + pub fn commands(&'static self) -> &'static [(&'static str, Text)] { + &self.tables().commands + } + /// Main-menu labels by command id where the menu words it differently ("Fill" in Select /// matching for "Select same fill"), sorted. - pub menu: &'static [(&'static str, Text)], + pub fn menu(&'static self) -> &'static [(&'static str, Text)] { + &self.tables().menu + } + + fn tables(&'static self) -> &'static Tables { + self.tables.get_or_init(|| { + unpack(self.packed, self.unpacked_len).unwrap_or_else(|| { + log::warn!("the {} string catalog could not be read; it shows English", self.code); + Tables::default() + }) + }) + } +} + +/// Decode a packed catalog: exactly `len` bytes of zlib output, then three tables of rows (see +/// build.rs `table`). The text lives as long as the program, like the baked-in strings it replaces. +fn unpack(packed: &[u8], len: usize) -> Option { + let mut raw = vec![0; len]; + let mut z = flate2::Decompress::new(true); + let status = z.decompress(packed, &mut raw, flate2::FlushDecompress::Finish).ok()?; + if status != flate2::Status::StreamEnd || z.total_out() != len as u64 { + return None; + } + let raw: &'static [u8] = Vec::leak(raw); + let mut at = 0; + let mut tables = [Vec::new(), Vec::new(), Vec::new()]; + for rows in &mut tables { + let count = u32_at(raw, &mut at)?; + for _ in 0..count { + let key = text_at(raw, &mut at)??; + let tag = *raw.get(at)?; + at += 1; + let text = match tag { + 0 => Text::Plain(text_at(raw, &mut at)??), + 1 => { + let (one, few, many) = (text_at(raw, &mut at)?, text_at(raw, &mut at)?, text_at(raw, &mut at)?); + let other = text_at(raw, &mut at)??; + Text::Plural(Box::leak(Box::new(Forms { one, few, many, other }))) + } + _ => return None, + }; + rows.push((key, text)); + } + } + let [ui, commands, menu] = tables; + (at == raw.len()).then_some(Tables { ui, commands, menu }) +} + +fn u32_at(raw: &[u8], at: &mut usize) -> Option { + let bytes = raw.get(*at..*at + 4)?; + *at += 4; + Some(u32::from_le_bytes(bytes.try_into().ok()?)) +} + +/// A string (`Some(None)` for an absent plural form), or `None` when the data is malformed. +fn text_at(raw: &'static [u8], at: &mut usize) -> Option> { + let len = u32_at(raw, at)?; + if len == u32::MAX { + return Some(None); + } + let bytes = raw.get(*at..*at + usize::try_from(len).ok()?)?; + *at += bytes.len(); + std::str::from_utf8(bytes).ok().map(Some) } include!(concat!(env!("OUT_DIR"), "/locales.rs")); @@ -125,7 +211,7 @@ fn chain(lang: usize) -> impl Iterator { /// `key`'s entry in language `lang`, else in the catalog it overlays, else in English. fn lookup(lang: usize, key: &str) -> Option<&'static Text> { - chain(lang).find_map(|l| find(l.ui, key)) + chain(lang).find_map(|l| find(l.ui(), key)) } /// The UI string for `key` (its English text) in the current language. One English text that needs @@ -167,7 +253,7 @@ pub fn trn(key: &str, n: usize, args: &[(&str, &dyn Display)]) -> String { fn counted(lang: usize, key: &str, n: usize) -> &str { chain(lang) .find_map(|l| { - find(l.ui, key).map(|text| match text { + find(l.ui(), key).map(|text| match text { Text::Plain(s) => *s, Text::Plural(Forms { one, few, many, other }) => match plural(l.code, n) { Plural::One => one.unwrap_or(other), @@ -260,7 +346,7 @@ pub fn menu_item<'a>(id: &str, english: &'a str) -> Cow<'a, str> { /// A command's or menu item's label: the catalog wording from `chain`, keeping a dialog's trailing /// ellipsis when the English label has one. fn label<'a>(menu: bool, id: &str, english: &'a str) -> Cow<'a, str> { - let text = chain(CURRENT.load(Ordering::Relaxed)).find_map(|l| menu.then(|| find(l.menu, id)).flatten().or_else(|| find(l.commands, id))); + let text = chain(CURRENT.load(Ordering::Relaxed)).find_map(|l| menu.then(|| find(l.menu(), id)).flatten().or_else(|| find(l.commands(), id))); match text { Some(Text::Plain(s) | Text::Plural(Forms { other: s, .. })) if english.ends_with('…') && !s.ends_with('…') => Cow::Owned(format!("{s}…")), Some(Text::Plain(s) | Text::Plural(Forms { other: s, .. })) => Cow::Borrowed(s), diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 31047b321..4e222c104 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -307,7 +307,7 @@ fn english() -> &'static Lang { #[test] fn every_key_in_the_code_is_in_the_english_catalog_and_no_other() { let used: BTreeSet = used_keys().into_iter().chain(dynamic_keys()).chain(importer_notes()).collect(); - let en: BTreeSet = english().ui.iter().map(|(k, _)| k.to_string()).collect(); + let en: BTreeSet = english().ui().iter().map(|(k, _)| k.to_string()).collect(); let missing: Vec<_> = used.difference(&en).collect(); let unused: Vec<_> = en.difference(&used).collect(); assert!( @@ -320,13 +320,13 @@ fn every_key_in_the_code_is_in_the_english_catalog_and_no_other() { #[test] fn english_text_is_its_key_except_plurals() { - for (k, t) in english().ui { + for (k, t) in english().ui() { if let Text::Plain(s) = t { // "Fill|sizing": the same English as "Fill", translated apart (a context after `|`). assert_eq!(k.split('|').next(), Some(*s), "an English entry differs from its key (the key is the English text)"); } } - assert!(english().commands.is_empty() && english().menu.is_empty(), "English command labels come from the engine"); + assert!(english().commands().is_empty() && english().menu().is_empty(), "English command labels come from the engine"); } /// The ids `[commands]` entries translate: every command and every main-menu item. @@ -344,8 +344,8 @@ fn catalogs_have_known_keys_and_matching_placeholders() { let ids = command_ids(); for lang in LANGS { assert!(!lang.name.is_empty(), "{}: [meta] name is missing", lang.code); - for (k, t) in lang.ui { - let src = find(en.ui, k).unwrap_or_else(|| panic!("{}: unknown key {k:?}", lang.code)); + for (k, t) in lang.ui() { + let src = find(en.ui(), k).unwrap_or_else(|| panic!("{}: unknown key {k:?}", lang.code)); let want = placeholders(forms(src).last().unwrap()); for (i, form) in forms(t).iter().enumerate() { let got = placeholders(form); @@ -355,11 +355,11 @@ fn catalogs_have_known_keys_and_matching_placeholders() { } assert_eq!(matches!(t, Text::Plural(_)), matches!(src, Text::Plural(_)), "{}: {k:?} plural or not as in English", lang.code); } - for (id, t) in lang.commands.iter().chain(lang.menu) { + for (id, t) in lang.commands().iter().chain(lang.menu()) { assert!(ids.contains(id), "{}: unknown command id {id:?}", lang.code); assert!(matches!(t, Text::Plain(s) if !s.trim().is_empty()), "{}: {id:?} is empty or plural", lang.code); } - for (id, _) in lang.menu { + for (id, _) in lang.menu() { assert!(menu_worded_differently().contains(id), "{}: [menu] {id:?} reads like the command; [commands] covers it", lang.code); } } @@ -373,9 +373,9 @@ fn missing_translations_report() { let worded = menu_worded_differently(); for (i, lang) in LANGS.iter().enumerate().filter(|(_, l)| l.code != "en") { let own = || chain(i).filter(|l| l.code != "en"); - let ui: Vec<_> = english().ui.iter().map(|(k, _)| *k).filter(|k| own().all(|l| find(l.ui, k).is_none())).collect(); - let commands: Vec<_> = ids.iter().filter(|id| own().all(|l| find(l.commands, id).is_none())).collect(); - let menu: Vec<_> = worded.iter().filter(|id| own().all(|l| find(l.menu, id).is_none())).collect(); + let ui: Vec<_> = english().ui().iter().map(|(k, _)| *k).filter(|k| own().all(|l| find(l.ui(), k).is_none())).collect(); + let commands: Vec<_> = ids.iter().filter(|id| own().all(|l| find(l.commands(), id).is_none())).collect(); + let menu: Vec<_> = worded.iter().filter(|id| own().all(|l| find(l.menu(), id).is_none())).collect(); println!("{}: {} UI strings, {} command labels, {} menu wordings missing", lang.code, ui.len(), commands.len(), menu.len()); for k in ui { println!(" {k:?}"); @@ -400,7 +400,7 @@ fn lookups_fall_back_to_english_and_fill_placeholders() { let es = resolve("es-419", None); assert_ne!(es, 0, "Spanish is baked in"); // A key Spanish lacks reads English; Spanish entries read Spanish. - let (k, t) = LANGS[es].ui.first().unwrap(); + let (k, t) = LANGS[es].ui().first().unwrap(); assert!(matches!(lookup(es, k), Some(x) if std::ptr::eq(x, t))); } @@ -477,7 +477,7 @@ fn bosnian_tags_and_integer_plurals() { assert_eq!(plural("bs", n), Plural::Other, "{n}"); } // "one" covers 21 and 31 too, so every form keeps the count. - for (key, text) in LANGS[bs].ui { + for (key, text) in LANGS[bs].ui() { if let Text::Plural(Forms { one, few, other, .. }) = text { for form in [*one, *few, Some(*other)].into_iter().flatten() { assert!(form.contains("{n}"), "{key}: {form}"); @@ -502,15 +502,15 @@ fn latin_american_spanish_overlays_spanish() { assert_eq!(LANGS[la].parent, es); assert!(es < la, "the picker lists Español first"); // Its own wording, else Spanish's, else English's. - for (k, _) in LANGS[es].ui.iter().filter(|(k, _)| find(LANGS[la].ui, k).is_none()) { - assert!(lookup(la, k).is_some_and(|t| std::ptr::eq(t, find(LANGS[es].ui, k).unwrap())), "{k:?}"); + for (k, _) in LANGS[es].ui().iter().filter(|(k, _)| find(LANGS[la].ui(), k).is_none()) { + assert!(lookup(la, k).is_some_and(|t| std::ptr::eq(t, find(LANGS[es].ui(), k).unwrap())), "{k:?}"); } - let undo = |i: usize| chain(i).find_map(|l| find(l.commands, "edit.undo")).map(forms); + let undo = |i: usize| chain(i).find_map(|l| find(l.commands(), "edit.undo")).map(forms); assert_eq!(undo(la), undo(es), "command labels fall back too"); // An overlay lists only what differs from the catalog under it. for lang in LANGS.iter().filter(|l| l.parent != 0) { let under = &LANGS[lang.parent]; - for (table, base) in [(lang.ui, under.ui), (lang.commands, under.commands), (lang.menu, under.menu)] { + for (table, base) in [(lang.ui(), under.ui()), (lang.commands(), under.commands()), (lang.menu(), under.menu())] { for (k, t) in table { let same = find(base, k).is_some_and(|b| forms(b) == forms(t)); assert!(!same, "{}: {k:?} reads as in {}", lang.code, under.code); @@ -544,7 +544,7 @@ fn japanese_korean_chinese_and_vietnamese_have_no_plural_forms() { for code in ["ja", "ko", "th", "zh-Hans", "zh-Hant", "vi"] { let lang = LANGS.iter().position(|l| l.code == code).unwrap(); assert!(!plural_one(lang, 0) && !plural_one(lang, 1) && !plural_one(lang, 2), "{code}"); - let ones: Vec<_> = LANGS[lang].ui.iter().filter(|(_, t)| matches!(t, Text::Plural(Forms { one: Some(_), .. }))).map(|(k, _)| k).collect(); + let ones: Vec<_> = LANGS[lang].ui().iter().filter(|(_, t)| matches!(t, Text::Plural(Forms { one: Some(_), .. }))).map(|(k, _)| k).collect(); assert!(ones.is_empty(), "{code}: plural entries give only `other`: {ones:?}"); } } @@ -566,7 +566,7 @@ fn arabic_tags_and_count_neutral_forms() { assert_eq!(resolve(tag, None), ar, "{tag}"); } let counts = [0, 1, 2, 3, 10, 11, 99, 100, 102, 103, 111, 200, 1000]; - for (key, text) in LANGS[ar].ui { + for (key, text) in LANGS[ar].ui() { if let Text::Plural(Forms { one, few, many, other }) = text { assert!(one.is_none() && few.is_none() && many.is_none(), "{key}: count-neutral wording uses only other"); for n in counts { @@ -617,10 +617,10 @@ fn the_built_in_hebrew_face_draws_the_hebrew_catalog() { }; let he = &LANGS[LANGS.iter().position(|l| l.code == "he").unwrap()]; let letters: BTreeSet = he - .ui + .ui() .iter() - .chain(he.commands) - .chain(he.menu) + .chain(he.commands()) + .chain(he.menu()) .flat_map(|(_, t)| forms(t)) .flat_map(str::chars) .filter(|c| matches!(u32::from(*c), 0x05D0..=0x05EA)) @@ -641,10 +641,10 @@ fn the_built_in_arabic_face_draws_the_arabic_catalog() { }; let ar = &LANGS[LANGS.iter().position(|l| l.code == "ar").unwrap()]; let letters: BTreeSet = ar - .ui + .ui() .iter() - .chain(ar.commands) - .chain(ar.menu) + .chain(ar.commands()) + .chain(ar.menu()) .flat_map(|(_, t)| forms(t)) .flat_map(str::chars) .filter(|c| matches!(u32::from(*c), 0x0600..=0x06FF)) @@ -665,7 +665,7 @@ fn the_built_in_georgian_face_draws_the_georgian_catalog() { let ka = &LANGS[LANGS.iter().position(|l| l.code == "ka").unwrap()]; let georgian = |c: &char| matches!(u32::from(*c), 0x10A0..=0x10FF | 0x1C90..=0x1CBF | 0x2D00..=0x2D2F); let mut letters: BTreeSet = BTreeSet::new(); - for (_, t) in ka.ui.iter().chain(ka.commands).chain(ka.menu) { + for (_, t) in ka.ui().iter().chain(ka.commands()).chain(ka.menu()) { letters.extend(forms(t).into_iter().flat_map(str::chars).filter(georgian)); } assert!(letters.len() > 30, "{letters:?}"); @@ -805,3 +805,14 @@ fn the_language_preference_takes_language_codes() { assert!(s.execute("pref.language", &serde_json::json!({"language": bad})).is_err(), "{bad:?}"); } } + +/// A damaged packed catalog reads as no catalog (the UI shows English), never as partial or +/// misparsed rows. +#[test] +fn damaged_packed_catalogs_are_refused() { + let lang = &LANGS[LANGS.iter().position(|l| l.code == "sv").unwrap()]; + assert!(super::unpack(lang.packed, lang.unpacked_len).is_some_and(|t| t.ui.len() == lang.ui().len())); + assert!(super::unpack(&lang.packed[..lang.packed.len() / 2], lang.unpacked_len).is_none(), "truncated stream"); + assert!(super::unpack(lang.packed, lang.unpacked_len + 1).is_none(), "declared size too large"); + assert!(super::unpack(lang.packed, lang.unpacked_len - 1).is_none(), "declared size too small"); +} diff --git a/crates/ui-egui/src/naming_tests.rs b/crates/ui-egui/src/naming_tests.rs index 757a542c8..b51d817de 100644 --- a/crates/ui-egui/src/naming_tests.rs +++ b/crates/ui-egui/src/naming_tests.rs @@ -55,7 +55,7 @@ fn command_labels_and_parameter_docs_read_developer_mode() { fn the_catalogs_name_developer_mode() { let mut bad = Vec::new(); for lang in LANGS { - for (key, text) in lang.ui { + for (key, text) in lang.ui() { if retired(key) { bad.push(format!("{}: key {key:?}", lang.code)); } @@ -63,12 +63,12 @@ fn the_catalogs_name_developer_mode() { bad.push(format!("{}: {key:?} = {value:?}", lang.code)); } } - for (id, text) in lang.commands { + for (id, text) in lang.commands() { for value in entry_texts(text).into_iter().filter(|value| retired(value)) { bad.push(format!("{}: {id} = {value:?}", lang.code)); } } - for (id, text) in lang.menu { + for (id, text) in lang.menu() { for value in entry_texts(text).into_iter().filter(|value| retired(value)) { bad.push(format!("{}: {id} = {value:?}", lang.code)); } @@ -85,7 +85,7 @@ fn the_inspect_tab_and_its_refusal_read_developer_mode() { assert!(!retired(board), "{board:?}"); assert_eq!(crate::i18n::LANGS.first().map(|l| l.code), Some("en"), "English is baked in first"); assert!( - LANGS.first().is_some_and(|l| l.ui.iter().any(|(k, _)| *k == "Developer Mode only inspects: switch to Design (Shift+D) to edit")), + LANGS.first().is_some_and(|l| l.ui().iter().any(|(k, _)| *k == "Developer Mode only inspects: switch to Design (Shift+D) to edit")), "the refusal toast is in the catalog" ); } From 8fe016b2aa34b81f2eeeea6018a61f258eff6c78 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 28 Nov 2026 23:28:04 +0100 Subject: [PATCH 2/3] Web size: pack the string catalogs with Brotli instead of zlib (#2720) Brotli's best setting packs the 27 catalogs about 0.2 MB smaller; the decoder (brotli-decompressor 6) is the one craft-metadata already builds. --- Cargo.lock | 14 +++++++++++++- Cargo.toml | 2 ++ crates/ui-egui/Cargo.toml | 6 +++--- crates/ui-egui/build.rs | 11 ++++++----- crates/ui-egui/src/i18n.rs | 16 +++++++++------- 5 files changed, 33 insertions(+), 16 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3bfe91b6c..0ec5c624d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -673,6 +673,17 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "brotli" +version = "9.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9071f285ed78f04f37d675abaaef5de7689e2f30a216c8dc6795465d81910a13" +dependencies = [ + "alloc-no-stdlib 3.0.0", + "alloc-stdlib 0.3.0", + "brotli-decompressor 6.3.2", +] + [[package]] name = "brotli-decompressor" version = "5.0.3" @@ -2962,6 +2973,8 @@ name = "figcraft-ui-egui" version = "0.18.1" dependencies = [ "base64 0.22.1", + "brotli", + "brotli-decompressor 6.3.2", "chrono", "craft-host", "craft-i18n", @@ -2981,7 +2994,6 @@ dependencies = [ "figcraft-pathops", "figcraft-render", "figcraft-text", - "flate2", "image", "log", "serde", diff --git a/Cargo.toml b/Cargo.toml index f05ad8b41..7182b0768 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -124,6 +124,8 @@ linesweeper = "0.5" zip = { version = "=9.8.2", default-features = false, features = ["deflate-flate2"] } # `.fig` import: raw deflate chunks (already built for zip) and zstd chunks (pure Rust, MIT, wasm-safe). flate2 = { version = "1", default-features = false, features = ["rust_backend"] } +brotli = { version = "9", default-features = false, features = ["std"] } +brotli-decompressor = { version = "6", default-features = false, features = ["std"] } ruzstd = { version = "0.9.1", default-features = false, features = ["std"] } sha1 = "0.11" sha2 = "0.10" diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index f185c466c..7e901185c 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -30,8 +30,8 @@ egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts" serde = { workspace = true } serde_json = { workspace = true } log = { workspace = true } -# Unpacks the zlib-compressed string catalogs (`src/i18n.rs`). -flate2 = { workspace = true } +# Unpacks the Brotli-compressed string catalogs (`src/i18n.rs`). +brotli-decompressor = { workspace = true } chrono = { workspace = true } base64 = { workspace = true } image = { workspace = true } @@ -40,7 +40,7 @@ web-time = "1.1.0" [build-dependencies] serde_json = { workspace = true } -flate2 = { workspace = true } +brotli = { workspace = true } toml = "1" [dev-dependencies] diff --git a/crates/ui-egui/build.rs b/crates/ui-egui/build.rs index f5ee2a933..b2f2d4d6d 100644 --- a/crates/ui-egui/build.rs +++ b/crates/ui-egui/build.rs @@ -33,7 +33,7 @@ fn main() { } /// `pub static LANGS: &[Lang]`: every `locales/*.toml`, English first. Each language's tables -/// (sorted by key) are serialized and zlib-compressed into OUT_DIR, and `i18n` unpacks a language +/// (sorted by key) are serialized and Brotli-compressed into OUT_DIR, and `i18n` unpacks a language /// only when the UI first looks a string up in it: the ~65,000 rows of 27 languages would /// otherwise be several megabytes of the browser build, nearly all of it never read. fn locales() -> String { @@ -60,11 +60,12 @@ fn locales() -> String { for name in ["ui", "commands", "menu"] { table(&mut raw, path, t.get(name)); } - let packed_path = out_dir.join(format!("locale-{code}.zlib")); + let packed_path = out_dir.join(format!("locale-{code}.br")); let packed = { - use std::io::Write as _; - let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::best()); - e.write_all(&raw).and_then(|()| e.finish()) + // Brotli's best setting packs the catalogs about a sixth smaller than zlib's (#2720). + let params = brotli::enc::BrotliEncoderParams { quality: 11, lgwin: 24, ..Default::default() }; + let mut out = Vec::new(); + brotli::BrotliCompress(&mut raw.as_slice(), &mut out, ¶ms).map(|_| out) }; let written = packed.map_err(|e| e.to_string()).and_then(|p| std::fs::write(&packed_path, p).map_err(|e| e.to_string())); if let Err(e) = written { diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 2488a33e2..50dbde74c 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -39,7 +39,7 @@ pub struct Lang { /// Index into [`LANGS`] of the catalog a regional one overlays ("es" under "es-419": it lists /// only what differs), else 0 (English). pub parent: usize, - /// The zlib-compressed tables (build.rs `table` writes the layout [`unpack`] reads). + /// The Brotli-compressed tables (build.rs `table` writes the layout [`unpack`] reads). packed: &'static [u8], unpacked_len: usize, tables: OnceLock, @@ -80,13 +80,15 @@ impl Lang { } } -/// Decode a packed catalog: exactly `len` bytes of zlib output, then three tables of rows (see -/// build.rs `table`). The text lives as long as the program, like the baked-in strings it replaces. +/// Decode a packed catalog: a whole Brotli stream of exactly `len` bytes, then three tables of +/// rows (see build.rs `table`). The text lives as long as the program, like the baked-in strings +/// it replaces. fn unpack(packed: &[u8], len: usize) -> Option { - let mut raw = vec![0; len]; - let mut z = flate2::Decompress::new(true); - let status = z.decompress(packed, &mut raw, flate2::FlushDecompress::Finish).ok()?; - if status != flate2::Status::StreamEnd || z.total_out() != len as u64 { + use std::io::Read as _; + let mut raw = Vec::with_capacity(len); + // One byte past `len` tells a declared size that is too small from an exact one. + brotli_decompressor::Decompressor::new(packed, 4096).take(len as u64 + 1).read_to_end(&mut raw).ok()?; + if raw.len() != len { return None; } let raw: &'static [u8] = Vec::leak(raw); From 1300470756630ebf82d79e7f5b2765fa037b8613 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:01:46 +0100 Subject: [PATCH 3/3] Web size: unpack the catalogs through one checked Brotli helper that refuses bytes after the stream (#2720) Answers the review point on the unpack length check: the whole input must be consumed. --- crates/ui-egui/Cargo.toml | 1 + crates/ui-egui/src/i18n.rs | 8 +------ crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/packed.rs | 46 ++++++++++++++++++++++++++++++++++++ 4 files changed, 49 insertions(+), 7 deletions(-) create mode 100644 crates/ui-egui/src/packed.rs diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 7e901185c..2123edaec 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -44,6 +44,7 @@ brotli = { workspace = true } toml = "1" [dev-dependencies] +brotli = { workspace = true } wat = { workspace = true } # Keep the test font features explicit; production uses the same bundled fallback faces. # Dependency dev-features do not propagate into app release builds. diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 50dbde74c..d4a995002 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -84,13 +84,7 @@ impl Lang { /// rows (see build.rs `table`). The text lives as long as the program, like the baked-in strings /// it replaces. fn unpack(packed: &[u8], len: usize) -> Option { - use std::io::Read as _; - let mut raw = Vec::with_capacity(len); - // One byte past `len` tells a declared size that is too small from an exact one. - brotli_decompressor::Decompressor::new(packed, 4096).take(len as u64 + 1).read_to_end(&mut raw).ok()?; - if raw.len() != len { - return None; - } + let raw = crate::packed::unpack(packed, len)?; let raw: &'static [u8] = Vec::leak(raw); let mut at = 0; let mut tables = [Vec::new(), Vec::new(), Vec::new()]; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index b25cc1edd..d319e8b52 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -28,6 +28,7 @@ pub mod i18n; pub mod icons; pub mod live; pub mod menus; +mod packed; pub mod pending_open; pub mod popover; pub mod present; diff --git a/crates/ui-egui/src/packed.rs b/crates/ui-egui/src/packed.rs new file mode 100644 index 000000000..cff913607 --- /dev/null +++ b/crates/ui-egui/src/packed.rs @@ -0,0 +1,46 @@ +//! Data the build packs with Brotli to keep the browser version's page small (#2720): the string +//! catalogs (`i18n`) and the default fonts (`theme`). Whatever is packed is unpacked the first +//! time it is used. + +use brotli_decompressor::{BrotliDecompressStream, BrotliResult, BrotliState, StandardAlloc}; + +/// Unpack one whole Brotli stream into exactly `len` bytes. A stream that is damaged or cut off, +/// that unpacks to more or fewer bytes than `len`, or that has bytes after its end gives `None`. +pub(crate) fn unpack(packed: &[u8], len: usize) -> Option> { + let mut out = Vec::new(); + out.try_reserve_exact(len).ok()?; + out.resize(len, 0); + let mut state = BrotliState::new(StandardAlloc::default(), StandardAlloc::default(), StandardAlloc::default()); + let (mut available_in, mut read, mut available_out, mut written, mut total) = (packed.len(), 0, len, 0, 0); + let result = BrotliDecompressStream(&mut available_in, &mut read, packed, &mut available_out, &mut written, &mut out, &mut total, &mut state); + (matches!(result, BrotliResult::ResultSuccess) && written == len && read == packed.len()).then_some(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// "hello hello hello" as one Brotli stream, made with the reference encoder. + fn packed() -> Vec { + let mut out = Vec::new(); + let params = brotli::enc::BrotliEncoderParams { quality: 11, ..Default::default() }; + brotli::BrotliCompress(&mut b"hello hello hello".as_slice(), &mut out, ¶ms).unwrap(); + out + } + + /// Only the whole stream with its exact length unpacks: no cut-off, no extra bytes, no wrong size. + #[test] + fn damaged_streams_are_refused() { + let packed = packed(); + assert_eq!(unpack(&packed, 17).as_deref(), Some(&b"hello hello hello"[..])); + for end in 0..packed.len() { + assert!(unpack(&packed[..end], 17).is_none(), "cut off at byte {end}"); + } + let mut trailing = packed.clone(); + trailing.push(0); + assert!(unpack(&trailing, 17).is_none(), "bytes after the end"); + assert!(unpack(&packed, 16).is_none(), "declared size too small"); + assert!(unpack(&packed, 18).is_none(), "declared size too large"); + assert!(unpack(b"not a brotli stream", 4).is_none()); + } +}