Merge pull request #10875 from dotCooCoo/fix/compress-i18n-catalogs

i18n: embed the interface language catalogs Brotli-compressed, 16 MB smaller binary
This commit is contained in:
.CooCoo authored and GitHub committed 2026-12-04 16:52:39 -08:00
commit 2a17b3d23d
5 files changed
+208 -45

No files matched your search

Generated
+2
View File
@@ -9271,6 +9271,8 @@ dependencies = [
name = "vectorcraft-ui-egui"
version = "0.25.1"
dependencies = [
"brotli 9.1.3",
"brotli-decompressor 6.3.2",
"bytemuck",
"chrono",
"craft",
+7
View File
@@ -74,6 +74,9 @@ craft-image-codecs = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
# Unpacks the interface language catalogs, which build.rs stores Brotli-compressed (src/i18n.rs).
# Pure Rust, builds for wasm32, and already in Cargo.lock through craft-i18n.
brotli-decompressor = { version = "6", default-features = false, features = ["std"] }
# Floating panels open in OS windows of their own on the desktop; on the web they stay in the page.
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
@@ -110,10 +113,14 @@ vectorcraft-tools = { workspace = true, features = ["testing"] }
vectorcraft-text = { workspace = true, features = ["test-fonts"] }
vectorcraft-plugins = { workspace = true, features = ["test-steady"] }
wat = { workspace = true }
# Compresses bad catalogs for the i18n unpacking tests.
brotli = { version = "9", default-features = false, features = ["std"] }
[build-dependencies]
serde_json = { workspace = true }
toml = "1"
# Compresses the interface language catalogs (src/i18n/*.tsv); already in Cargo.lock through craft-i18n.
brotli = { version = "9", default-features = false, features = ["std"] }
# The files of other crates that this crate's tests read, for CI's test selection.
[package.metadata.craft]
+60
View File
@@ -6,12 +6,72 @@
//! JSON says the entry was verified (`people_entry`).
//!
//! A missing or malformed file gives empty tables (or no names) and a warning.
//!
//! Also compress the interface language catalogs, `src/i18n/*.tsv`, with Brotli into `OUT_DIR/i18n/`,
//! and write `i18n_catalogs.rs`, the table `src/i18n.rs` unpacks them from. A catalog that can't be
//! read or is larger than [`MAX_CATALOG_BYTES`] stops the build.
use std::fmt::Write as _;
use std::io::Write as _;
use std::path::Path;
use serde_json::Value;
/// The largest catalog embedded, in bytes; `src/i18n.rs` unpacks no more than this.
const MAX_CATALOG_BYTES: usize = 8 << 20;
fn main() {
if let Err(e) = pack_catalogs() {
println!("cargo::error=packing the interface language catalogs: {e}");
}
credits();
}
/// Compress each `src/i18n/<code>.tsv` to `OUT_DIR/i18n/<code>.tsv.br` and list them, by code, in
/// `OUT_DIR/i18n_catalogs.rs` as `CATALOGS: &[(code, compressed text, text length in bytes)]`.
fn pack_catalogs() -> Result<(), String> {
let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src/i18n");
println!("cargo::rerun-if-changed={}", src.display());
let out = std::path::PathBuf::from(std::env::var_os("OUT_DIR").ok_or("OUT_DIR is not set")?);
let packed = out.join("i18n");
std::fs::create_dir_all(&packed).map_err(|e| format!("{}: {e}", packed.display()))?;
let mut codes = Vec::new();
for entry in std::fs::read_dir(&src).map_err(|e| format!("{}: {e}", src.display()))? {
let path = entry.map_err(|e| format!("{}: {e}", src.display()))?.path();
if let (Some(code), Some("tsv")) = (path.file_stem().and_then(|s| s.to_str()), path.extension().and_then(|s| s.to_str())) {
codes.push(code.to_string());
}
}
codes.sort();
let mut table = String::from("const CATALOGS: &[(&str, &[u8], usize)] = &[\n");
for code in codes {
let path = src.join(format!("{code}.tsv"));
println!("cargo::rerun-if-changed={}", path.display());
let text = std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?;
if text.len() > MAX_CATALOG_BYTES {
return Err(format!("{} is {} bytes, over the {MAX_CATALOG_BYTES}-byte limit", path.display(), text.len()));
}
let mut compressed = Vec::new();
{
// Quality 9, a 4 MiB window.
let mut encoder = brotli::CompressorWriter::new(&mut compressed, 4096, 9, 22);
encoder.write_all(&text).map_err(|e| format!("{}: {e}", path.display()))?;
}
let file = packed.join(format!("{code}.tsv.br"));
if std::fs::read(&file).ok().as_deref() != Some(compressed.as_slice()) {
std::fs::write(&file, &compressed).map_err(|e| format!("{}: {e}", file.display()))?;
}
let _ = writeln!(table, " ({code:?}, include_bytes!(concat!(env!(\"OUT_DIR\"), \"/i18n/{code}.tsv.br\")), {}),", text.len());
}
table.push_str("];\n");
let file = out.join("i18n_catalogs.rs");
if std::fs::read_to_string(&file).is_ok_and(|old| old == table) {
return Ok(());
}
std::fs::write(&file, table).map_err(|e| format!("{}: {e}", file.display()))
}
fn credits() {
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../contributors");
let json = read(&dir.join("contributors.json"), "the About window shows no contributors", |t| {
serde_json::from_str::<Value>(t).map_err(|e| e.to_string())
+77 -41
View File
@@ -8,10 +8,10 @@
//! 1. Add `xx.tsv` next to `zh-hant.tsv` (copy its header; translate from the *meaning* of the
//! English text, clean-room, see `zh-hant.tsv`), with an `@id` row `language.name` holding the
//! language's name in itself.
//! 2. Add one entry to [`EMBEDDED`].
//!
//! That is all: the Preferences dropdown, the system-locale match, the catalog tests (parse,
//! placeholders, plural forms) and the untranslated report pick it up from the embedded list.
//! That is all: `build.rs` embeds every `*.tsv` in that folder, Brotli-compressed, and the
//! Preferences dropdown, the system-locale match, the catalog tests (parse, placeholders, plural
//! forms) and the untranslated report pick it up from the embedded list.
//!
//! # Looking strings up
//! - [`t`] / the `tl!` macro: a plain string in the language the UI is drawn in. [`tr`] takes the
@@ -31,53 +31,87 @@
// PLAN: crates/ui-egui/Cargo.toml needs `craft-i18n = { workspace = true }`; the manifest is not in
// this set's Files table.
use std::borrow::Cow;
use std::io::Read as _;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, OnceLock, PoisonError};
use craft::i18n::{Embedded, I18n, fmt_plain};
use craft::i18n::{I18n, fmt_plain};
pub use craft::i18n::Lang;
/// The catalogs of every language but English (the source language), by code. English is reserved
/// by `craft-i18n` and has no catalog.
static EMBEDDED: &Embedded = &[
("hi", "", include_str!("i18n/hi.tsv")),
("gu", "", include_str!("i18n/gu.tsv")),
("el", "", include_str!("i18n/el.tsv")),
("ja", "", include_str!("i18n/ja.tsv")),
("ko", "", include_str!("i18n/ko.tsv")),
("vi", "", include_str!("i18n/vi.tsv")),
("cs", "", include_str!("i18n/cs.tsv")),
("bs", "", include_str!("i18n/bs.tsv")),
("de", "", include_str!("i18n/de.tsv")),
("es", "", include_str!("i18n/es.tsv")),
("fr", "", include_str!("i18n/fr.tsv")),
("it", "", include_str!("i18n/it.tsv")),
("ka", "", include_str!("i18n/ka.tsv")),
("ru", "", include_str!("i18n/ru.tsv")),
("uk", "", include_str!("i18n/uk.tsv")),
("bg", "", include_str!("i18n/bg.tsv")),
("hu", "", include_str!("i18n/hu.tsv")),
("pl", "", include_str!("i18n/pl.tsv")),
("sv", "", include_str!("i18n/sv.tsv")),
("pt-br", "", include_str!("i18n/pt-br.tsv")),
("zh-hant", "", include_str!("i18n/zh-hant.tsv")),
("zh-hans", "", include_str!("i18n/zh-hans.tsv")),
("nl", "", include_str!("i18n/nl.tsv")),
("da", "", include_str!("i18n/da.tsv")),
("id", "", include_str!("i18n/id.tsv")),
("fi", "", include_str!("i18n/fi.tsv")),
("tr", "", include_str!("i18n/tr.tsv")),
("ca", "", include_str!("i18n/ca.tsv")),
("ar", "", include_str!("i18n/ar.tsv")),
];
// The catalogs of every language but English (the source language), by code: `CATALOGS`, each
// `(code, Brotli-compressed text, text length in bytes)`, which `build.rs` writes from `i18n/*.tsv`.
// English is reserved by `craft-i18n` and has no catalog.
include!(concat!(env!("OUT_DIR"), "/i18n_catalogs.rs"));
/// The codes of [`EMBEDDED`] the interface offers. Browsers cannot use the native installed-font
/// The largest catalog [`unpack`] returns, in bytes (`build.rs` embeds none larger).
const MAX_CATALOG_BYTES: usize = 8 << 20;
/// A catalog's text from its compressed bytes, which must unpack to exactly `len` bytes of UTF-8.
fn unpack(packed: &[u8], len: usize) -> Result<String, String> {
if len > MAX_CATALOG_BYTES {
return Err(format!("{len} bytes is over the {MAX_CATALOG_BYTES}-byte limit"));
}
let mut text = Vec::new();
text.try_reserve_exact(len).map_err(|e| e.to_string())?;
brotli_decompressor::Decompressor::new(packed, 4096).take(len as u64 + 1).read_to_end(&mut text).map_err(|e| e.to_string())?;
if text.len() != len {
return Err(format!("unpacked {} bytes instead of {len}", text.len()));
}
String::from_utf8(text).map_err(|e| e.to_string())
}
/// The embedded catalogs unpacked, as `I18n::from_owned` takes them: (code, shared catalog (none),
/// the app's catalog). A catalog that can't be unpacked is left out and comes back as a problem.
fn catalogs() -> (Vec<(String, String, String)>, Vec<String>) {
unpack_catalogs(CATALOGS)
}
/// [`catalogs`] for the given `(code, compressed text, text length)` list; on the desktop the
/// catalogs are unpacked on several threads.
fn unpack_catalogs(list: &[(&str, &[u8], usize)]) -> (Vec<(String, String, String)>, Vec<String>) {
let unpack_all =
|piece: &[(&str, &[u8], usize)]| piece.iter().map(|&(code, packed, len)| (code.to_string(), unpack(packed, len))).collect::<Vec<_>>();
#[cfg(not(target_arch = "wasm32"))]
let unpacked = {
let threads = std::thread::available_parallelism().map_or(1, usize::from).min(16);
let per = list.len().div_ceil(threads).max(1);
std::thread::scope(|scope| {
// A piece whose thread can't be started is unpacked on this one.
let pieces: Vec<_> = list
.chunks(per)
.map(|piece| (piece, std::thread::Builder::new().name("i18n-unpack".into()).spawn_scoped(scope, move || unpack_all(piece)).ok()))
.collect();
let stopped =
|piece: &[(&str, &[u8], usize)]| piece.iter().map(|&(code, ..)| (code.to_string(), Err("unpacking stopped".to_string()))).collect();
pieces
.into_iter()
.flat_map(|(piece, handle)| match handle {
Some(handle) => handle.join().unwrap_or_else(|_| stopped(piece)),
None => unpack_all(piece),
})
.collect::<Vec<_>>()
})
};
#[cfg(target_arch = "wasm32")]
let unpacked = unpack_all(list);
let mut texts = Vec::with_capacity(unpacked.len());
let mut problems = Vec::new();
for (code, text) in unpacked {
match text {
Ok(text) => texts.push((code, String::new(), text)),
Err(e) => problems.push(format!("{code}: the embedded catalog can't be unpacked ({e}); skipped")),
}
}
(texts, problems)
}
/// The codes of [`CATALOGS`] the interface offers. Browsers cannot use the native installed-font
/// fallback, so on the web a language whose text would be missing-glyph boxes (Gujarati without a
/// Gujarati face, see [`has_gujarati_face`]) is not offered, including when restoring a preference.
/// Arabic is kept unavailable to users until the shared catalog in `storytold/craft-i18n` is consumed.
fn offered_codes(web: bool, gujarati_font: bool) -> Vec<&'static str> {
EMBEDDED.iter().map(|(code, ..)| *code).filter(|code| *code != "ar" && (*code != "gu" || !web || gujarati_font)).collect()
CATALOGS.iter().map(|(code, ..)| *code).filter(|code| *code != "ar" && (*code != "gu" || !web || gujarati_font)).collect()
}
/// Whether the interface has a Gujarati face: an embedded craft-fonts face, or on the web a face
@@ -96,12 +130,14 @@ fn has_gujarati_face_in<'a>(embedded: &[vectorcraft_text::EmbeddedFace], mut ser
embedded.iter().any(|f| f.has_script("Gujr")) || served.any(|scripts| scripts.contains(&"Gujr"))
}
/// The one catalog set of the process, built on first use.
/// The one catalog set of the process, built on first use, which is when the catalogs are unpacked.
fn shared_cell() -> &'static Arc<I18n> {
static SHARED: OnceLock<Arc<I18n>> = OnceLock::new();
SHARED.get_or_init(|| {
let offered = offered_codes(cfg!(target_arch = "wasm32"), has_gujarati_face());
let (i18n, problems) = I18n::new(EMBEDDED, &offered);
let (texts, mut problems) = catalogs();
let (i18n, built) = I18n::from_owned(texts, &offered);
problems.extend(built);
for problem in problems {
log::warn!("vectorcraft: interface language catalog: {problem}");
}
+62 -4
View File
@@ -12,6 +12,64 @@ fn translated() -> Vec<Lang> {
Lang::all().filter(|l| l.complete_menus()).collect()
}
/// The embedded catalogs unpacked, as `I18n::from_owned` takes them; every one must unpack.
fn unpacked() -> Vec<(String, String, String)> {
let (texts, problems) = catalogs();
assert!(problems.is_empty(), "{problems:?}");
texts
}
/// The embedded entry of `code`: (code, compressed text, text length).
fn packed(code: &str) -> (&'static str, &'static [u8], usize) {
CATALOGS.iter().copied().find(|c| c.0 == code).unwrap_or_else(|| panic!("{code} embedded"))
}
/// A catalog is embedded compressed and unpacks to its source file byte for byte.
#[test]
fn embedded_catalogs_are_compressed_and_unpack_to_their_source() {
for code in ["de", "ja"] {
let (_, bytes, len) = packed(code);
let source = std::fs::read_to_string(format!("{}/src/i18n/{code}.tsv", env!("CARGO_MANIFEST_DIR"))).unwrap();
assert_eq!(len, source.len(), "{code}");
assert!(bytes.len() * 2 < len, "{code}: {} bytes embedded for {len}", bytes.len());
assert_eq!(unpack(bytes, len).as_deref(), Ok(source.as_str()), "{code}");
}
}
/// Bytes that do not unpack to exactly the recorded length of UTF-8 text, or a length over the
/// limit, give an error instead of a catalog.
#[test]
fn unpacking_rejects_a_catalog_that_does_not_match_its_record() {
use std::io::Write as _;
let (_, bytes, len) = packed("de");
assert!(unpack(bytes, len - 1).is_err(), "more text than recorded");
assert!(unpack(bytes, len + 1).is_err(), "less text than recorded");
assert!(unpack(&bytes[..bytes.len() / 2], len).is_err(), "cut short");
assert!(unpack(b"not a catalog", 13).is_err(), "not Brotli");
let over = unpack(bytes, MAX_CATALOG_BYTES + 1).unwrap_err();
assert!(over.contains("limit"), "{over}");
let mut not_utf8 = Vec::new();
{
let mut encoder = brotli::CompressorWriter::new(&mut not_utf8, 4096, 9, 22);
encoder.write_all(&[b'a', 0xff, b'b']).unwrap();
}
assert!(unpack(&not_utf8, 3).is_err(), "not UTF-8");
}
/// A catalog that does not unpack is left out and reported, so its language is not offered; the
/// others keep their order and load.
#[test]
fn a_catalog_that_does_not_unpack_is_left_out_and_reported() {
let (texts, problems) = unpack_catalogs(&[packed("de"), ("fr", b"not a catalog", 13), packed("ja")]);
assert_eq!(texts.iter().map(|t| t.0.as_str()).collect::<Vec<_>>(), ["de", "ja"]);
assert_eq!(problems.len(), 1, "{problems:?}");
assert!(problems[0].starts_with("fr: "), "{problems:?}");
let (i18n, _) = I18n::from_owned(texts, &["de", "fr", "ja"]);
assert_eq!(i18n.from_code("fr"), None);
let de = i18n.from_code("de").unwrap();
assert_ne!(i18n.t(de, "Layers"), "Layers");
}
/// (language, context, English source, the term the language's glossary gives it). One row per
/// rule: a term for a concept, a punctuation mark's typography.
const TERMS: &[(&str, &str, &str, &str)] = &[
@@ -148,7 +206,7 @@ fn messages_translate_in_every_complete_language() {
#[test]
fn gujarati_web_selection_requires_a_bundled_interface_font() {
let codes = |web, font| {
let (i18n, problems) = I18n::new(EMBEDDED, &offered_codes(web, font));
let (i18n, problems) = I18n::from_owned(unpacked(), &offered_codes(web, font));
assert!(problems.is_empty(), "{problems:?}");
i18n.languages().into_iter().map(|l| i18n.code(l).to_string()).collect::<Vec<_>>()
};
@@ -199,7 +257,7 @@ fn arabic_is_preparatory_and_unavailable_to_users() {
#[test]
fn arabic_plural_rule_and_catalog_infrastructure() {
let (i18n, problems) = I18n::new(EMBEDDED, &["ar"]);
let (i18n, problems) = I18n::from_owned(unpacked(), &["ar"]);
assert!(problems.is_empty(), "{problems:?}");
let ar = i18n.from_code("ar").expect("ar offered in custom instance");
assert_eq!(i18n.name(ar), "العربية");
@@ -236,7 +294,7 @@ fn a_language_set_by_another_test_leaves_this_one_in_english() {
fn bundled_catalogs_are_consistent() {
let problems = shared().check_all();
assert!(problems.is_empty(), "{problems:#?}");
for (code, _, app) in EMBEDDED {
for (code, _, app) in unpacked() {
for line in app.lines() {
let mut columns = line.split('\t');
let (Some("@id"), Some(id)) = (columns.next(), columns.next()) else { continue };
@@ -275,7 +333,7 @@ fn unescaped(column: &str) -> String {
#[test]
fn message_translations_keep_their_english_edges() {
let mut wrong = Vec::new();
for (code, _, catalog) in EMBEDDED {
for (code, _, catalog) in unpacked() {
for line in catalog.lines() {
let mut columns = line.splitn(3, '\t');
let (Some(ctx @ ("@msg" | "@msgplural")), Some(src), Some(tr)) = (columns.next(), columns.next(), columns.next()) else { continue };