mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-21 20:08:15 +00:00
Migrate TextureCraft UI translations to shared craft-i18n
This commit is contained in:
Generated
+1
@@ -4443,6 +4443,7 @@ version = "0.3.1"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"craft-dialogs",
|
||||
"craft-i18n",
|
||||
"craft-keymap",
|
||||
"craft-quit",
|
||||
"craft-ui",
|
||||
|
||||
@@ -65,6 +65,8 @@ getrandom = "0.3"
|
||||
rustix = { version = "1", default-features = false, features = ["std", "fs", "process"] }
|
||||
# Shared Craft egui components (widget palette, icon buttons, panel docking): storytold/craft-libs,
|
||||
# MIT OR Apache-2.0, pinned to one rev.
|
||||
# Shared catalog lookup, pinned with the other Craft libraries.
|
||||
craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" }
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["serde"] }
|
||||
# Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs).
|
||||
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] }
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
cdf4401147d573dbc200042a771690e3b1d80623
|
||||
@@ -14,6 +14,7 @@ texturecraft-render = { workspace = true }
|
||||
eframe = { workspace = true, features = ["default_fonts", "wgpu", "persistence"] }
|
||||
egui = { workspace = true }
|
||||
craft-ui = { workspace = true }
|
||||
craft-i18n = { workspace = true }
|
||||
craft-window = { workspace = true }
|
||||
craft-keymap = { workspace = true }
|
||||
craft-quit = { workspace = true }
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
//! recipe follows craft-fonts' `docs/integration.md`; no font file is committed here. The Latin
|
||||
//! faces are embedded without their Private Use Area ([`without_private_use`]).
|
||||
|
||||
mod i18n_build;
|
||||
|
||||
use std::fmt::Write as _;
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -23,6 +25,7 @@ const LATIN: Faces = &[("Inter", "Regular"), ("Inter", "SemiBold")];
|
||||
type Faces = &'static [(&'static str, &'static str)];
|
||||
|
||||
fn main() {
|
||||
i18n_build::embed();
|
||||
println!("cargo::rerun-if-env-changed=CRAFT_FONTS_DIR");
|
||||
println!("cargo::rerun-if-env-changed=CRAFT_FONTS_REQUIRED");
|
||||
let mut src = String::from("pub static CRAFT_FONTS: &[CraftFont] = &[\n");
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
//! Optional shared translation catalogs, embedded at build time.
|
||||
use std::fmt::Write as _;
|
||||
use std::path::Path;
|
||||
|
||||
pub fn generate(dir: Option<&Path>, required: bool) -> Result<String, String> {
|
||||
let mut source = String::from("pub static CRAFT_I18N: &craft_i18n::Embedded = &[\n");
|
||||
let Some(dir) = dir else {
|
||||
if required {
|
||||
return Err("CRAFT_I18N_REQUIRED=1 requires CRAFT_I18N_DIR".into());
|
||||
}
|
||||
source.push_str("];\n");
|
||||
return Ok(source);
|
||||
};
|
||||
if !dir.is_absolute() {
|
||||
return Err("CRAFT_I18N_DIR must be an absolute path".into());
|
||||
}
|
||||
let locales = dir.join("locales");
|
||||
let entries = std::fs::read_dir(&locales).map_err(|e| format!("{}: {e}", locales.display()))?;
|
||||
println!("cargo::rerun-if-changed={}", locales.display());
|
||||
let mut paths = Vec::new();
|
||||
for entry in entries {
|
||||
let entry = entry.map_err(|e| e.to_string())?;
|
||||
if entry.file_type().map_err(|e| e.to_string())?.is_dir() {
|
||||
paths.push(entry.path());
|
||||
}
|
||||
}
|
||||
paths.sort();
|
||||
let mut count = 0;
|
||||
for path in paths {
|
||||
// Watch directories too: adding/removing an app catalog must rebuild the embedding.
|
||||
println!("cargo::rerun-if-changed={}", path.display());
|
||||
let app = path.join("texturecraft.tsv");
|
||||
if !app.is_file() {
|
||||
continue;
|
||||
}
|
||||
let locale = path.file_name().and_then(|n| n.to_str()).ok_or("non-UTF-8 locale")?;
|
||||
let common = path.join("common.tsv");
|
||||
let embed = |file: &Path| -> Result<String, String> {
|
||||
std::fs::read_to_string(file).map_err(|e| format!("{}: {e}", file.display()))?;
|
||||
let name = file.to_str().ok_or("non-UTF-8 catalog path")?;
|
||||
println!("cargo::rerun-if-changed={name}");
|
||||
Ok(format!("include_str!({name:?})"))
|
||||
};
|
||||
let shared = if common.is_file() { embed(&common)? } else { "\"\"".into() };
|
||||
let app = embed(&app)?;
|
||||
let _ = writeln!(source, " ({locale:?}, {shared}, {app}),");
|
||||
count += 1;
|
||||
}
|
||||
if required && count == 0 {
|
||||
return Err("no TextureCraft translation catalogs found".into());
|
||||
}
|
||||
source.push_str("];\n");
|
||||
Ok(source)
|
||||
}
|
||||
|
||||
pub fn embed() {
|
||||
println!("cargo::rerun-if-env-changed=CRAFT_I18N_DIR");
|
||||
println!("cargo::rerun-if-env-changed=CRAFT_I18N_REQUIRED");
|
||||
let dir = std::env::var_os("CRAFT_I18N_DIR").map(std::path::PathBuf::from);
|
||||
let required = std::env::var("CRAFT_I18N_REQUIRED").is_ok_and(|v| v == "1");
|
||||
let source = match generate(dir.as_deref(), required) {
|
||||
Ok(source) => source,
|
||||
Err(error) => {
|
||||
if required {
|
||||
println!("cargo::error={error}");
|
||||
} else {
|
||||
println!("cargo::warning=building without craft-i18n: {error}");
|
||||
}
|
||||
"pub static CRAFT_I18N: &craft_i18n::Embedded = &[];\n".into()
|
||||
}
|
||||
};
|
||||
let out = std::path::PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join("craft_i18n.rs");
|
||||
if let Err(error) = std::fs::write(&out, source) {
|
||||
println!("cargo::error=writing {}: {error}", out.display());
|
||||
}
|
||||
}
|
||||
+100
-80
@@ -1,22 +1,31 @@
|
||||
//! UI text lookup. Keys are the English strings, so English needs no table and a missing
|
||||
//! translation falls back to English. Every user-visible literal goes through [`tr`] (or [`trf`]
|
||||
//! for text with `{name}` placeholders); each language is a static `(English, translation)`
|
||||
//! table, indexed into a hash map the first time the language is used. `Prefs::language` picks it.
|
||||
//! UI text lookup over the optional shared craft-i18n catalogs.
|
||||
//! Missing translations and builds without catalogs use the English source text.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::Display;
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::{LazyLock, OnceLock};
|
||||
|
||||
mod ar;
|
||||
mod de;
|
||||
mod es;
|
||||
mod fr;
|
||||
mod it;
|
||||
mod ja;
|
||||
mod ko;
|
||||
mod pt_br;
|
||||
mod zh_hans;
|
||||
include!(concat!(env!("OUT_DIR"), "/craft_i18n.rs"));
|
||||
|
||||
static I18N: LazyLock<craft_i18n::I18n> = LazyLock::new(|| {
|
||||
let offered: Vec<_> = LANGUAGES.iter().map(|l| l.code).collect();
|
||||
let (i18n, problems) = craft_i18n::I18n::new(CRAFT_I18N, &offered);
|
||||
for problem in problems {
|
||||
log::warn!("translation catalog: {problem}");
|
||||
}
|
||||
i18n
|
||||
});
|
||||
|
||||
static SHARED_LANGUAGES: OnceLock<[craft_i18n::Lang; COUNT]> = OnceLock::new();
|
||||
|
||||
fn shared_languages() -> &'static [craft_i18n::Lang; COUNT] {
|
||||
SHARED_LANGUAGES.get_or_init(|| LANGUAGES.each_ref().map(|l| I18N.from_code(l.code).unwrap_or(craft_i18n::Lang::EN)))
|
||||
}
|
||||
|
||||
/// Whether this build embeds a catalog for a supported language.
|
||||
pub fn available(code: &str) -> bool {
|
||||
I18N.from_code(code).is_some()
|
||||
}
|
||||
|
||||
pub struct Language {
|
||||
/// BCP 47 code ("en", "pt-BR", "zh-Hans").
|
||||
@@ -25,26 +34,23 @@ pub struct Language {
|
||||
pub name: &'static str,
|
||||
/// Its English name (the picker's fallback when no font can draw `name`).
|
||||
pub english: &'static str,
|
||||
/// `(English, translation)` pairs, in any order.
|
||||
pub table: &'static [(&'static str, &'static str)],
|
||||
}
|
||||
|
||||
const COUNT: usize = 10;
|
||||
|
||||
pub static LANGUAGES: [Language; COUNT] = [
|
||||
Language { code: "en", name: "English", english: "English", table: &[] },
|
||||
Language { code: "fr", name: "Français", english: "French", table: fr::TABLE },
|
||||
Language { code: "de", name: "Deutsch", english: "German", table: de::TABLE },
|
||||
Language { code: "es", name: "Español", english: "Spanish", table: es::TABLE },
|
||||
Language { code: "pt-BR", name: "Português (Brasil)", english: "Portuguese (Brazil)", table: pt_br::TABLE },
|
||||
Language { code: "it", name: "Italiano", english: "Italian", table: it::TABLE },
|
||||
Language { code: "ja", name: "日本語", english: "Japanese", table: ja::TABLE },
|
||||
Language { code: "zh-Hans", name: "简体中文", english: "Chinese (Simplified)", table: zh_hans::TABLE },
|
||||
Language { code: "ko", name: "한국어", english: "Korean", table: ko::TABLE },
|
||||
Language { code: "ar", name: "العربية", english: "Arabic", table: ar::TABLE },
|
||||
Language { code: "en", name: "English", english: "English" },
|
||||
Language { code: "fr", name: "Français", english: "French" },
|
||||
Language { code: "de", name: "Deutsch", english: "German" },
|
||||
Language { code: "es", name: "Español", english: "Spanish" },
|
||||
Language { code: "pt-BR", name: "Português (Brasil)", english: "Portuguese (Brazil)" },
|
||||
Language { code: "it", name: "Italiano", english: "Italian" },
|
||||
Language { code: "ja", name: "日本語", english: "Japanese" },
|
||||
Language { code: "zh-Hans", name: "简体中文", english: "Chinese (Simplified)" },
|
||||
Language { code: "ko", name: "한국어", english: "Korean" },
|
||||
Language { code: "ar", name: "العربية", english: "Arabic" },
|
||||
];
|
||||
|
||||
static MAPS: [OnceLock<HashMap<&'static str, &'static str>>; COUNT] = [const { OnceLock::new() }; COUNT];
|
||||
static CURRENT: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
/// Display labels belong to the UI; the model exposes only map identities
|
||||
@@ -67,7 +73,7 @@ pub(crate) fn baked_map_label(map: texturecraft_engine::core::BakedMap) -> &'sta
|
||||
|
||||
/// Switch the UI language (unknown codes fall back to English).
|
||||
pub fn set_language(code: &str) {
|
||||
CURRENT.store(LANGUAGES.iter().position(|l| l.code == code).unwrap_or(0), Ordering::Relaxed);
|
||||
CURRENT.store(LANGUAGES.iter().position(|l| l.code.eq_ignore_ascii_case(code) && available(l.code)).unwrap_or(0), Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// The current UI language.
|
||||
@@ -77,12 +83,8 @@ pub fn current() -> &'static Language {
|
||||
|
||||
/// `text` in the current language (unchanged when it has no translation).
|
||||
pub fn tr(text: &str) -> &str {
|
||||
let i = CURRENT.load(Ordering::Relaxed);
|
||||
let (Some(lang), Some(map)) = (LANGUAGES.get(i), MAPS.get(i)) else { return text };
|
||||
if lang.table.is_empty() {
|
||||
return text;
|
||||
}
|
||||
map.get_or_init(|| lang.table.iter().copied().collect()).get(text).copied().unwrap_or(text)
|
||||
let lang = shared_languages().get(CURRENT.load(Ordering::Relaxed)).copied().unwrap_or(craft_i18n::Lang::EN);
|
||||
I18N.t(lang, text)
|
||||
}
|
||||
|
||||
/// Marks a static string for translation where it is defined (gettext's `N_`); it is translated
|
||||
@@ -93,25 +95,9 @@ pub const fn n_(text: &'static str) -> &'static str {
|
||||
|
||||
/// `template` translated, with each `{name}` replaced by its value in `args`.
|
||||
pub fn trf(template: &str, args: &[(&str, &dyn Display)]) -> String {
|
||||
let mut out = String::with_capacity(template.len() + 16);
|
||||
let mut rest = tr(template);
|
||||
while let Some(open) = rest.find('{') {
|
||||
out.push_str(&rest[..open]);
|
||||
let after = &rest[open + 1..];
|
||||
match after.find('}').and_then(|close| args.iter().find(|(k, _)| *k == &after[..close]).map(|(_, v)| (close, v))) {
|
||||
Some((close, v)) => {
|
||||
use std::fmt::Write as _;
|
||||
let _ = write!(out, "{v}");
|
||||
rest = &after[close + 1..];
|
||||
}
|
||||
None => {
|
||||
out.push('{');
|
||||
rest = after;
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push_str(rest);
|
||||
out
|
||||
let values: Vec<_> = args.iter().map(|(name, value)| (*name, value.to_string())).collect();
|
||||
let args: Vec<_> = values.iter().map(|(name, value)| (*name, value.as_str())).collect();
|
||||
craft_i18n::fmt(tr(template), &args)
|
||||
}
|
||||
|
||||
/// The supported language for a locale such as "de-AT", "pt_BR.UTF-8" or "zh-Hant-TW" ("en" when
|
||||
@@ -142,6 +128,7 @@ pub(crate) static TEST_LANGUAGE: std::sync::Mutex<()> = std::sync::Mutex::new(()
|
||||
mod tests {
|
||||
use super::TEST_LANGUAGE as LANGUAGE;
|
||||
use super::*;
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
|
||||
/// Every key the UI looks up: `tr("…")` / `trf("…"` literals in the sources, plus the
|
||||
/// static catalogs whose labels are translated where they are shown.
|
||||
@@ -252,43 +239,51 @@ mod tests",
|
||||
}
|
||||
}
|
||||
|
||||
fn placeholders(s: &str) -> Vec<&str> {
|
||||
let mut v: Vec<&str> = s.split('{').skip(1).filter_map(|p| p.split_once('}').map(|(name, _)| name)).collect();
|
||||
v.sort_unstable();
|
||||
v
|
||||
#[test]
|
||||
fn embedded_catalogs_are_valid() {
|
||||
assert!(I18N.check_all().is_empty(), "{:?}", I18N.check_all());
|
||||
}
|
||||
|
||||
/// Translation work never blocks a feature: report missing/stale keys without failing.
|
||||
#[test]
|
||||
fn every_key_is_translated_in_every_language() {
|
||||
fn translation_coverage_report() {
|
||||
let keys = keys();
|
||||
assert!(keys.len() > 300, "found only {} keys", keys.len());
|
||||
let mut missing = Vec::new();
|
||||
for l in LANGUAGES.iter().skip(1) {
|
||||
let map: HashMap<&str, &str> = l.table.iter().copied().collect();
|
||||
assert_eq!(map.len(), l.table.len(), "{}: duplicate keys", l.code);
|
||||
for k in &keys {
|
||||
if !map.contains_key(k.as_str()) {
|
||||
missing.push(format!("{}: {k:?}", l.code));
|
||||
let used: BTreeSet<_> = keys.iter().map(String::as_str).collect();
|
||||
for &(locale, common, app) in CRAFT_I18N {
|
||||
let Some(lang) = I18N.from_code(locale) else { continue };
|
||||
let missing: Vec<_> = keys.iter().filter(|key| I18N.get(lang, "", key).is_none()).collect();
|
||||
// Decode TSV escapes for comparison with the literal source strings.
|
||||
let mut rows = HashMap::new();
|
||||
for text in [common, app] {
|
||||
for line in text.lines().filter(|l| !l.starts_with('#')) {
|
||||
let columns: Vec<_> = line.split('\t').collect();
|
||||
if let ["", source, _] = columns.as_slice() {
|
||||
let mut decoded = String::new();
|
||||
let mut chars = source.chars();
|
||||
while let Some(c) = chars.next() {
|
||||
decoded.push(if c == '\\' {
|
||||
match chars.next() {
|
||||
Some('n') => '\n',
|
||||
Some('t') => '\t',
|
||||
Some(c) => c,
|
||||
None => '\\',
|
||||
}
|
||||
} else {
|
||||
c
|
||||
});
|
||||
}
|
||||
rows.insert(decoded, ());
|
||||
}
|
||||
}
|
||||
}
|
||||
let stale: Vec<_> = rows.keys().filter(|key| !used.contains(key.as_str())).collect();
|
||||
eprintln!("{locale}: missing {} {missing:?}; unused/shared {} {stale:?}", missing.len(), stale.len());
|
||||
}
|
||||
assert!(missing.is_empty(), "{} missing translations:\n{}", missing.len(), missing.join("\n"));
|
||||
}
|
||||
|
||||
/// Catalog labels that read the same in every language (names and formats).
|
||||
const UNTRANSLATED: &[&str] = &["RGB", "RGBA"];
|
||||
|
||||
#[test]
|
||||
fn translations_keep_placeholders_and_are_not_empty() {
|
||||
for l in &LANGUAGES {
|
||||
for (en, t) in l.table {
|
||||
assert!(!t.trim().is_empty(), "{}: empty translation of {en:?}", l.code);
|
||||
assert_eq!(placeholders(en), placeholders(t), "{}: placeholders of {en:?} in {t:?}", l.code);
|
||||
assert_eq!(en.ends_with("..."), t.ends_with("...") || t.ends_with('…'), "{}: ellipsis of {en:?} in {t:?}", l.code);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lookup_formatting_and_fallbacks() {
|
||||
let _lock = LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
@@ -304,11 +299,36 @@ mod tests",
|
||||
assert_eq!(language_for_locale(locale), code, "{locale}");
|
||||
}
|
||||
set_language("de");
|
||||
assert_eq!(current().code, "de");
|
||||
assert_eq!(current().code, if available("de") { "de" } else { "en" });
|
||||
assert_eq!(tr("not a key"), "not a key");
|
||||
set_language("en");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_lookup_overrides_and_missing_translations() {
|
||||
static CATALOGS: &craft_i18n::Embedded = &[("es", "\tSave\tGuardar\n\tOpen\tAbrir\n", "\tSave\tGuardar proyecto\n")];
|
||||
let (runtime, problems) = craft_i18n::I18n::new(CATALOGS, &["es"]);
|
||||
assert!(problems.is_empty());
|
||||
assert!(runtime.check_all().is_empty());
|
||||
let lang = runtime.from_code("es").unwrap();
|
||||
assert_eq!(runtime.t(lang, "Save"), "Guardar proyecto");
|
||||
assert_eq!(runtime.t(lang, "Open"), "Abrir");
|
||||
assert_eq!(runtime.t(lang, "New feature"), "New feature");
|
||||
assert_eq!(runtime.t(craft_i18n::Lang::EN, "Save"), "Save");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_language_codes_and_spanish_lookup() {
|
||||
let _lock = LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
for language in &LANGUAGES {
|
||||
set_language(language.code);
|
||||
assert_eq!(current().code, if available(language.code) { language.code } else { "en" });
|
||||
}
|
||||
set_language("es");
|
||||
assert_eq!(tr("Layers"), if available("es") { "Capas" } else { "Layers" });
|
||||
set_language("en");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lookup_is_fast() {
|
||||
let _lock = LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -611,7 +611,7 @@ fn settings(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
ui.label(tr("Language"));
|
||||
let current = crate::i18n::current();
|
||||
egui::ComboBox::from_id_salt("language").width(180.0).height(320.0).selected_text(current.name).show_ui(ui, |ui| {
|
||||
for (l, ok) in LANGUAGES.iter().zip(drawable) {
|
||||
for (l, ok) in LANGUAGES.iter().zip(drawable).filter(|(l, _)| crate::i18n::available(l.code)) {
|
||||
let item = egui::Button::selectable(l.code == current.code, if ok { l.name } else { l.english });
|
||||
if ui.add_enabled(ok, item).on_disabled_hover_text(tr("No font on this system can show this language")).clicked() {
|
||||
p.language = l.code.to_owned();
|
||||
@@ -1303,6 +1303,8 @@ mod tests {
|
||||
fn harness() -> Harness<'static, TextureCraftApp> {
|
||||
let session = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
let mut h = Harness::builder().with_size(vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
|
||||
// These dialog tests query English labels, independently of the system locale.
|
||||
h.state_mut().ui.prefs.language = "en".into();
|
||||
h.run_steps(2);
|
||||
h
|
||||
}
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
//! Optional catalog embedding must work without network or application dependencies.
|
||||
#[path = "../i18n_build.rs"]
|
||||
#[allow(dead_code)] // The production build entry point is not invoked by these pure-input tests.
|
||||
mod i18n_build;
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
struct Fixture(PathBuf);
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
static NEXT: AtomicUsize = AtomicUsize::new(0);
|
||||
let path = std::env::temp_dir().join(format!("texturecraft-i18n-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
std::fs::create_dir_all(path.join("locales/es")).unwrap();
|
||||
Self(path)
|
||||
}
|
||||
}
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_input_is_english_but_required_input_errors() {
|
||||
assert!(!i18n_build::generate(None, false).unwrap().contains("include_str!"));
|
||||
assert!(i18n_build::generate(None, true).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_and_relative_checkouts_are_rejected() {
|
||||
let fixture = Fixture::new();
|
||||
assert!(i18n_build::generate(Some(&fixture.0.join("missing")), false).is_err());
|
||||
assert!(i18n_build::generate(Some(std::path::Path::new("relative")), false).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_only_locale_is_not_offered_and_required_needs_app_catalog() {
|
||||
let fixture = Fixture::new();
|
||||
std::fs::write(fixture.0.join("locales/es/common.tsv"), "\tSave\tGuardar\n").unwrap();
|
||||
assert!(!i18n_build::generate(Some(&fixture.0), false).unwrap().contains("include_str!"));
|
||||
assert!(i18n_build::generate(Some(&fixture.0), true).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn app_catalog_is_embedded_with_optional_shared_catalog() {
|
||||
let fixture = Fixture::new();
|
||||
let app = fixture.0.join("locales/es/texturecraft.tsv");
|
||||
std::fs::write(&app, "\tLayers\tCapas\n").unwrap();
|
||||
let source = i18n_build::generate(Some(&fixture.0), true).unwrap();
|
||||
assert!(source.contains("texturecraft.tsv"));
|
||||
assert!(source.contains("(\"es\", \"\","));
|
||||
let common = fixture.0.join("locales/es/common.tsv");
|
||||
std::fs::write(&common, "\tSave\tGuardar\n").unwrap();
|
||||
assert!(i18n_build::generate(Some(&fixture.0), true).unwrap().contains("common.tsv"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unreadable_catalog_fails_before_generating_rust_source() {
|
||||
let fixture = Fixture::new();
|
||||
std::fs::write(fixture.0.join("locales/es/texturecraft.tsv"), [0xff, 0xfe]).unwrap();
|
||||
assert!(i18n_build::generate(Some(&fixture.0), true).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_paths_compile_and_embed_the_catalog_contents() {
|
||||
let fixture = Fixture::new();
|
||||
std::fs::write(fixture.0.join("locales/es/texturecraft.tsv"), "\tLayers\tCapas\n").unwrap();
|
||||
let generated = i18n_build::generate(Some(&fixture.0), true).unwrap();
|
||||
let program = format!(
|
||||
"extern crate self as craft_i18n;\npub type Embedded = [(&'static str, &'static str, &'static str)];\n{generated}\nfn main() {{ assert_eq!(CRAFT_I18N[0].2, \"\\tLayers\\tCapas\\n\"); }}"
|
||||
);
|
||||
let source = fixture.0.join("check.rs");
|
||||
let binary = fixture.0.join(format!("check{}", std::env::consts::EXE_SUFFIX));
|
||||
std::fs::write(&source, program).unwrap();
|
||||
assert!(std::process::Command::new("rustc").arg(&source).arg("-o").arg(&binary).status().unwrap().success());
|
||||
assert!(std::process::Command::new(binary).status().unwrap().success());
|
||||
}
|
||||
@@ -497,3 +497,21 @@ fn rail_window_snapshots() {
|
||||
texturecraft_ui_egui::menus::invoke(harness.state_mut(), &context, "ui.view.history");
|
||||
save(&mut harness, &output_dir, "rail-history-short");
|
||||
}
|
||||
|
||||
/// Visual check of the migrated catalogs and the live language selector.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn i18n_snapshots() {
|
||||
let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return };
|
||||
std::fs::create_dir_all(&output_dir).unwrap();
|
||||
for code in ["en", "es", "ar"] {
|
||||
assert!(texturecraft_ui_egui::i18n::available(code), "build with migrated catalogs for {code}");
|
||||
let session = texturecraft_engine::sample_session(128, 32).unwrap();
|
||||
let mut harness =
|
||||
Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session));
|
||||
harness.state_mut().ui.prefs.language = code.into();
|
||||
harness.state_mut().ui.windows.settings = true;
|
||||
save(&mut harness, &output_dir, &format!("i18n-{code}"));
|
||||
}
|
||||
texturecraft_ui_egui::i18n::set_language("en");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
# Interface translations
|
||||
|
||||
TextureCraft uses the `craft-i18n` runtime from craft-libs and optional catalogs from
|
||||
[craft-i18n](https://github.com/storytold/craft-i18n).
|
||||
|
||||
Set `CRAFT_I18N_DIR` to the absolute path of a craft-i18n checkout before building.
|
||||
The build embeds `locales/<locale>/common.tsv` and `texturecraft.tsv`. Without catalog input,
|
||||
the application uses English. `CRAFT_I18N_REQUIRED=1` makes missing/invalid input a build error.
|
||||
The same catalogs are embedded for native and WebAssembly builds; no runtime files are needed.
|
||||
|
||||
Feature changes add English strings through `tr`, `n_` or `trf`. Translations belong in
|
||||
craft-i18n PRs. A missing translation displays English and does not block a feature or release.
|
||||
Run `cargo test -p texturecraft-ui-egui translation_coverage_report -- --nocapture` with
|
||||
catalog input to inspect untranslated and unused/shared keys. Shared catalogs contain other
|
||||
apps' strings, so unused shared keys are informational, not candidates for automatic deletion.
|
||||
|
||||
The initial migration is tracked in storytold/texturecraft#419. Catalog changes must merge
|
||||
before the application cutover, and translations landing meanwhile need a final sync.
|
||||
Saved `pt-BR` and `zh-Hans` preferences retain their original spelling and meaning.
|
||||
|
||||
## CI and release catalog revision
|
||||
|
||||
`craft-i18n.rev` pins the catalog commit. The shared craft-common-actions gate and release
|
||||
workflows read this file, check out storytold/craft-i18n and set CRAFT_I18N_DIR together with
|
||||
CRAFT_I18N_REQUIRED=1. No application workflow changes are needed.
|
||||
|
||||
The catalog commit must be available in storytold/craft-i18n before merging the app cutover.
|
||||
After a squash or rebase merge of the companion catalog PR, update the pin to the resulting
|
||||
upstream commit and rerun validation before merging TextureCraft.
|
||||
@@ -2,20 +2,23 @@
|
||||
|
||||
TextureCraft's interface text goes through one lookup, `tr("English text")` in
|
||||
`crates/ui-egui/src/i18n.rs`: the English string is the key, so English needs no table and a
|
||||
missing translation falls back to English. Each language is a static `(English, translation)`
|
||||
table in `crates/ui-egui/src/i18n/<code>.rs`, indexed into a hash map the first time the
|
||||
language is used. Text with values uses `trf("Saved {path}", &[("path", &p)])`; static labels
|
||||
that are translated where they are shown are marked with `n_("…")`.
|
||||
missing translation falls back to English. Translations are embedded from the optional shared
|
||||
craft-i18n catalogs; see [integration and contribution instructions](internationalization.md).
|
||||
Text with values uses `trf("Saved {path}", &[("path", &p)])`; static labels translated where
|
||||
they are shown are marked with `n_("…")`.
|
||||
|
||||
Pick the language in **Edit ▸ Settings ▸ Language** (it switches live). The first run follows
|
||||
the operating system's language (the browser's in the web build).
|
||||
|
||||
## Status
|
||||
|
||||
The table records coverage before the initial catalog migration. Actual coverage depends on
|
||||
the craft-i18n catalogs embedded in a build. Without catalogs, only English is offered.
|
||||
|
||||
UI strings: every `tr`/`trf`/`n_` literal in `crates/ui-egui/src` plus the menu catalog, panel
|
||||
names, shortcut editor rows and the engine's channel, blend mode, mesh map, tool, procedural,
|
||||
generator, filter and brush alpha names (**KEYS** strings, counted by the
|
||||
`every_key_is_translated_in_every_language` test, which fails when one is missing).
|
||||
`translation_coverage_report` test, which reports missing and unused keys without failing).
|
||||
|
||||
| Language | Code | UI strings | Dialogs, tooltips, help | Script support | Native review | Status | To `full` |
|
||||
|---|---|---|---|---|---|---|---|
|
||||
|
||||
Reference in New Issue
Block a user