Language: follow the system language by default (#10138) (#10183)

* claim: #10138

* Follow the system language on a first start (#10138)

The language preference defaults to a new 'system' value: the OS locale
(sys-locale) is matched against the catalog list - exact tag, base
language, then English - and a System choice sits at the top of the
Preferences language list. A saved language still wins.

* Drop the explicit deref clippy flagged; regenerate THIRD-PARTY-LICENSES.txt for sys-locale

---------

Co-authored-by: Dahak Builds <dahakbuilds@users.noreply.github.com>
This commit is contained in:
Dahak Builds
2026-10-31 19:50:08 +00:00
committed by GitHub
parent 8be56316f6
commit 538d7fcb43
19 changed files with 215 additions and 35 deletions
Generated
+14 -1
View File
@@ -4443,6 +4443,7 @@ dependencies = [
"solidcraft-gpu",
"solidcraft-space-mouse",
"syn 2.0.119",
"sys-locale",
"tiny-skia",
"toml",
"ttf-parser",
@@ -4558,6 +4559,18 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "sys-locale"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4"
dependencies = [
"js-sys",
"libc",
"wasm-bindgen",
"web-sys",
]
[[package]]
name = "tempfile"
version = "3.27.0"
@@ -4565,7 +4578,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom 0.3.4",
"getrandom 0.4.3",
"once_cell",
"rustix 1.1.5",
"windows-sys 0.61.2",
+30 -3
View File
@@ -1,6 +1,6 @@
Third-party software in SolidCraft
SolidCraft (the desktop app, solidcraft-cli and the web app) is built from the 560 crates below.
SolidCraft (the desktop app, solidcraft-cli and the web app) is built from the 561 crates below.
Generated by `cargo xtask licences` from Cargo.lock and the crates' own licence files.
SolidCraft's own licence is in LICENSE-MIT and LICENSE-APACHE, and NOTICE.
@@ -403,6 +403,7 @@ syn 1.0.109 (MIT OR Apache-2.0)
syn 2.0.119 (MIT OR Apache-2.0)
syn 3.0.6 (MIT OR Apache-2.0)
synstructure 0.13.2 (MIT)
sys-locale 0.3.2 (MIT OR Apache-2.0)
tempfile 3.27.0 (MIT OR Apache-2.0)
termcolor 1.4.1 (Unlicense OR MIT)
thiserror 1.0.69 (MIT OR Apache-2.0)
@@ -1836,8 +1837,8 @@ approx 0.4.0, as-raw-xcb-connection 1.0.1, atspi 0.29.0, atspi-common 0.13.0, at
cgmath 0.18.0, chardetng 0.1.17, codespan-reporting 0.13.1, encoding_rs 0.8.42, kurbo 0.13.1,
multiversion_no_op 1.0.0, nohash-hasher 0.2.0, peniko 0.6.1, polycool 0.4.0, raw-window-metal 1.1.0,
rustls-platform-verifier 0.7.1, self_cell 1.3.0, siphasher 1.0.4, spade 2.15.1, static_assertions
1.1.0, ureq 3.4.2, ureq-proto 0.6.4, utf8_iter 1.0.4, x11rb 0.13.2, x11rb-protocol 0.13.2, zeroize
1.9.1, zeroize_derive 1.5.0, zune-core 0.5.3, zune-jpeg 0.5.15
1.1.0, sys-locale 0.3.2, ureq 3.4.2, ureq-proto 0.6.4, utf8_iter 1.0.4, x11rb 0.13.2, x11rb-protocol
0.13.2, zeroize 1.9.1, zeroize_derive 1.5.0, zune-core 0.5.3, zune-jpeg 0.5.15
================================================================================
Apache License
@@ -13570,6 +13571,32 @@ The above copyright notice and this permission notice shall be included in all c
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
================================================================================
sys-locale 0.3.2
================================================================================
MIT License
Copyright (c) 2021 1Password
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================================================
tempfile 3.27.0
================================================================================
+9 -11
View File
@@ -684,7 +684,7 @@ mod web {
/// Whether the shell already has the on-demand face the live language needs.
fn script_font_ready(&self) -> bool {
match solidcraft_ui_egui::fonts::web_script_font_kind(&self.app.preferences.language) {
match solidcraft_ui_egui::fonts::web_script_font_kind(solidcraft_ui_egui::i18n::effective_language(&self.app.preferences.language)) {
Some("zh") => self.chinese_bytes.is_some() && self.chinese_kind == Some("zh"),
Some("zh-TW") => self.chinese_bytes.is_some() && self.chinese_kind == Some("zh-TW"),
Some("ja") => self.cjk_bytes.is_some(),
@@ -726,7 +726,8 @@ mod web {
false
}
};
if !installed && solidcraft_ui_egui::fonts::needs_cjk_font(&self.app.preferences.language) {
let effective = solidcraft_ui_egui::i18n::effective_language(&self.app.preferences.language);
if !installed && solidcraft_ui_egui::fonts::needs_cjk_font(effective) {
log::warn!("script font unavailable; showing English for this session");
}
self.font.finished(installed, &mut self.app.preferences.language);
@@ -734,12 +735,13 @@ mod web {
ctx.request_repaint();
}
let ready = self.script_font_ready();
let effective = solidcraft_ui_egui::i18n::effective_language(&self.app.preferences.language);
if self.font.tick(&mut self.app.preferences.language, ready) {
self.fetch_font(ctx, solidcraft_ui_egui::fonts::web_script_font_kind(&self.app.preferences.language).unwrap_or("ja"));
self.fetch_font(ctx, solidcraft_ui_egui::fonts::web_script_font_kind(effective).unwrap_or("ja"));
}
// The CJK face leads only a CJK UI: its Cyrillic glyphs are full-width, so switching
// to Ukrainian (or English) must put the Latin face back in front.
if self.app.preferences.language != self.font_language {
if solidcraft_ui_egui::i18n::effective_language(&self.app.preferences.language) != self.font_language {
self.apply_fonts(ctx);
}
}
@@ -747,17 +749,13 @@ mod web {
/// Set up the UI fonts for the live language, keeping fetched script fonts as fallbacks
/// (Chinese leads a Chinese UI; see [`solidcraft_ui_egui::fonts::install_web_script_fonts`]).
fn apply_fonts(&mut self, ctx: &egui::Context) {
let effective = solidcraft_ui_egui::i18n::effective_language(&self.app.preferences.language);
if self.cjk_bytes.is_none() && self.chinese_bytes.is_none() {
solidcraft_ui_egui::fonts::setup_fonts(ctx);
} else {
solidcraft_ui_egui::fonts::install_web_script_fonts(
ctx,
self.cjk_bytes.clone(),
self.chinese_bytes.clone(),
&self.app.preferences.language,
);
solidcraft_ui_egui::fonts::install_web_script_fonts(ctx, self.cjk_bytes.clone(), self.chinese_bytes.clone(), effective);
}
self.font_language.clone_from(&self.app.preferences.language);
self.font_language = effective.to_owned();
}
/// CJK text on screen with no Japanese font yet (an English UI showing a Japanese name):
+1
View File
@@ -2194,6 +2194,7 @@
"prefs.keep_work_on_tab_switch": "إبقاء مربعات الحوار والأدوات مفتوحة عند التبديل بين التصاميم",
"prefs.keep_work_on_tab_switch_note": "تحتفظ كل علامة تبويب تصميم بمربع الحوار أو الأداة المفتوحة، بما حددته وكتبته فيها، وبعلامة تبويب شريط الأدوات. وتجدها كما هي عند العودة إلى التصميم. عند الإيقاف: يؤدي التبديل بين التصاميم إلى إلغائها وعرض علامة التبويب «النموذج».",
"prefs.labels": "التسميات",
"prefs.language_system": "النظام",
"prefs.layout": "التخطيط",
"prefs.layout_note": "المضغوط يثبّت اللوحات على حواف النافذة. شفافية المستعرض متاحة في الوضع العائم. غيّر جهة المساعد من صفحة المساعد.",
"prefs.left": "يسار",
+1
View File
@@ -2193,6 +2193,7 @@
"prefs.keep_work_on_tab_switch": "Dialoge und Werkzeuge beim Wechsel zwischen Konstruktionen offen lassen",
"prefs.keep_work_on_tab_switch_note": "Jeder Konstruktions-Tab behält seinen offenen Dialog oder sein Werkzeug mit allem, was darin ausgewählt und eingegeben wurde, sowie seinen Werkzeugleisten-Tab. Beim Zurückkehren zur Konstruktion ist alles wieder da. Aus: Ein Wechsel bricht sie ab und zeigt den Tab Modell.",
"prefs.labels": "Beschriftungen",
"prefs.language_system": "System",
"prefs.layout": "Layout",
"prefs.layout_note": "Im Layout „Kompakt“ werden Bereiche an den Fensterrändern angedockt. Transparenz für den Browser ist nur im Layout „Schwebend“ verfügbar. Die Position des Assistenten ändern Sie auf der Seite „Assistent“.",
"prefs.left": "Links",
+1
View File
@@ -2194,6 +2194,7 @@
"prefs.keep_work_on_tab_switch": "Keep dialogs and tools open when switching designs",
"prefs.keep_work_on_tab_switch_note": "Each design tab keeps its open dialog or tool, with what you picked and typed in it, and its toolbar tab. They are there again when you come back to the design. Off: switching designs cancels them and shows the Model tab.",
"prefs.labels": "Labels",
"prefs.language_system": "System",
"prefs.layout": "Layout",
"prefs.layout_note": "Compact docks panels to the window edges. Browser translucency is available in Floating. Change the Assistant side on the Assistant page.",
"prefs.left": "Left",
+1
View File
@@ -2194,6 +2194,7 @@
"prefs.keep_work_on_tab_switch": "השארת תיבות דו־שיח וכלים פתוחים במעבר בין עיצובים",
"prefs.keep_work_on_tab_switch_note": "כל לשונית עיצוב שומרת את תיבת הדו־שיח או הכלי הפתוחים בה, עם מה שבחרת והקלדת בהם, ואת לשונית סרגל הכלים שלה. הם מחכים לך כשתחזור לעיצוב. כבוי: מעבר בין עיצובים מבטל אותם ומציג את הלשונית מודל.",
"prefs.labels": "תוויות",
"prefs.language_system": "מערכת",
"prefs.layout": "פריסה",
"prefs.layout_note": "הפריסה הדחוסה מצמידה חלוניות לשולי החלון. שקיפות עץ התכן זמינה בפריסה הצפה. את צד העוזר אפשר לשנות בעמוד העוזר.",
"prefs.left": "שמאל",
+1
View File
@@ -2194,6 +2194,7 @@
"prefs.keep_work_on_tab_switch": "デザインを切り替えてもダイアログとツールを開いたままにする",
"prefs.keep_work_on_tab_switch_note": "各デザインのタブが、開いているダイアログまたはツール(選択や入力した内容を含む)とツールバーのタブを保持します。デザインに戻ると元のまま表示されます。オフ: デザインを切り替えるとそれらはキャンセルされ、モデル タブが表示されます。",
"prefs.labels": "ラベル",
"prefs.language_system": "システム",
"prefs.layout": "レイアウト",
"prefs.layout_note": "コンパクトではパネルをウィンドウの端に固定します。ブラウザーの半透明表示はフローティングで使用できます。アシスタントの配置はアシスタントページで変更します。",
"prefs.left": "左",
+1
View File
@@ -1594,6 +1594,7 @@
"prefs.interface_note": "SolidCraft의 모양과 각 부분의 위치입니다.",
"prefs.interval_minutes": "{n}분",
"prefs.labels": "레이블",
"prefs.language_system": "시스템",
"prefs.layout": "레이아웃",
"prefs.layout_note": "컴팩트는 패널을 창 가장자리에 고정합니다. 브라우저 반투명은 플로팅에서 사용할 수 있습니다. 어시스턴트 위치는 어시스턴트 페이지에서 바꿀 수 있습니다.",
"prefs.left": "왼쪽",
+1
View File
@@ -2194,6 +2194,7 @@
"prefs.keep_work_on_tab_switch": "Giữ hộp thoại và công cụ mở khi chuyển giữa các thiết kế",
"prefs.keep_work_on_tab_switch_note": "Mỗi thẻ thiết kế giữ hộp thoại hoặc công cụ đang mở, cùng những gì bạn đã chọn và nhập trong đó, và thẻ thanh công cụ của nó. Chúng vẫn còn đó khi bạn quay lại thiết kế. Tắt: chuyển thiết kế sẽ hủy chúng và hiển thị thẻ Mô hình.",
"prefs.labels": "Nhãn chữ",
"prefs.language_system": "Hệ thống",
"prefs.layout": "Bố cục",
"prefs.layout_note": "Chế độ Gọn (Compact) gắn các bảng vào mép cửa sổ. Độ trong suốt của Cây thư mục chỉ khả dụng ở chế độ Nổi (Floating). Thay đổi vị trí của Trợ lý trong trang Trợ lý.",
"prefs.left": "Bên trái",
+1
View File
@@ -2194,6 +2194,7 @@
"prefs.keep_work_on_tab_switch": "切换设计时保持对话框和工具打开",
"prefs.keep_work_on_tab_switch_note": "每个设计标签页保留其打开的对话框或工具(包括其中已选择和输入的内容)以及工具栏选项卡。回到该设计时它们仍在原处。关闭时:切换设计会取消它们并显示“模型”选项卡。",
"prefs.labels": "标签",
"prefs.language_system": "系统",
"prefs.layout": "布局",
"prefs.layout_note": "紧凑模式将面板停靠在窗口边缘。浏览器半透明仅适用于浮动模式。助手面板的位置在助手页面中设置。",
"prefs.left": "左侧",
+3
View File
@@ -25,6 +25,9 @@ ttf-parser = { workspace = true }
# Right-to-left interface text (Hebrew): the Unicode Bidirectional Algorithm puts translated
# strings in display order, which egui does not do itself (MIT OR Apache-2.0).
unicode-bidi = "0.3"
# The system's preferred languages on a first start (MIT OR Apache-2.0, maintained by
# 1Password): the OS locale on desktop and, with `js`, `navigator.languages` in the browser (#10138).
sys-locale = { version = "0.3.2", features = ["js"] }
semver = { workspace = true }
# Updates: the downloaded package's SHA-256 (against the release's SHA256SUMS.txt), its optional
# minisign signature (MIT), and the portable .zip's executables.
+10 -6
View File
@@ -387,7 +387,8 @@ impl CjkFontLoader {
self.status
}
/// Called every frame with the live language. `ready` is true when the shell already has the
/// Called every frame with the live language (a `system` preference resolves to its catalog
/// via [`crate::i18n::effective_language`]). `ready` is true when the shell already has the
/// on-demand face that language needs. Returns true when a fetch should start now. After a
/// failed load a CJK language falls back to English for this session; the saved preference is
/// kept (see [`Self::persisted_language`]). Switching to another CJK language that still needs
@@ -400,7 +401,7 @@ impl CjkFontLoader {
self.status = CjkFontStatus::Unloaded;
}
}
if !needs_cjk_font(language) {
if !needs_cjk_font(crate::i18n::effective_language(language)) {
return false;
}
if ready {
@@ -436,13 +437,14 @@ impl CjkFontLoader {
self.status == CjkFontStatus::Unloaded
}
/// Record the outcome of the fetch and install.
/// Record the outcome of the fetch and install. A `system` preference resolves to its
/// catalog first ([`Self::tick`]).
pub fn finished(&mut self, installed: bool, language: &mut String) {
if installed {
self.status = CjkFontStatus::Installed;
} else {
self.status = CjkFontStatus::Failed;
if needs_cjk_font(language) {
if needs_cjk_font(crate::i18n::effective_language(language)) {
self.fall_back(language);
}
}
@@ -1241,8 +1243,10 @@ mod tests {
}
#[test]
fn default_ui_language_is_english() {
assert_eq!(crate::prefs::Prefs::default().language, "en");
fn default_ui_language_follows_the_system() {
// A first start follows the system (#10138); English, the fallback it lands on when
// nothing matches, needs no CJK face.
assert_eq!(crate::prefs::Prefs::default().language, crate::i18n::SYSTEM);
assert!(!needs_cjk_font("en"));
}
+73
View File
@@ -130,12 +130,50 @@ pub fn is_supported(id: &str) -> bool {
LOCALES.iter().any(|catalog| catalog.id == id)
}
/// The `language` preference value that follows the system (#10138). Not a catalog id: it
/// resolves through [`system_language`] wherever a catalog is needed.
pub const SYSTEM: &str = "system";
/// Match the system's preferred locale tags against the catalogs: the exact tag first
/// (`zh-TW`, `pt-BR`, `en-GB`), then the tag's base language (`zh-CN` → `zh`, `de-AT` → `de`),
/// then English. Tags come in the system's order of preference; the first one that matches wins.
pub fn match_system_tags(tags: &[String]) -> &'static str {
for tag in tags {
let tag = tag.replace('_', "-");
if let Some(catalog) = LOCALES.iter().find(|catalog| catalog.id.eq_ignore_ascii_case(&tag)) {
return catalog.id;
}
let base = tag.split('-').next().unwrap_or(&tag);
if let Some(catalog) = LOCALES.iter().find(|catalog| catalog.id.eq_ignore_ascii_case(base)) {
return catalog.id;
}
}
ENGLISH.id
}
/// The catalog id the system asks for, read once per process: the OS locale on desktop
/// (Windows, macOS, Linux/BSD) and `navigator.languages` in the browser.
pub fn system_language() -> &'static str {
static CACHED: OnceLock<&'static str> = OnceLock::new();
CACHED.get_or_init(|| match_system_tags(&sys_locale::get_locales().collect::<Vec<_>>()))
}
/// The catalog id a `language` preference resolves to: the saved choice, or the system's for
/// [`SYSTEM`]. For callers that need the id as text (font fallbacks), not a [`Locale`].
pub fn effective_language(preference: &str) -> &'static str {
Locale::for_language(preference).0.id
}
/// Immutable locale reference. Catalogs parse once; lookups are logarithmic.
#[derive(Clone, Copy)]
pub struct Locale(&'static Catalog);
impl Locale {
pub fn for_language(id: &str) -> Self {
if id == SYSTEM {
let system = system_language();
return Self(LOCALES.iter().copied().find(|catalog| catalog.id == system).unwrap_or(&ENGLISH));
}
Self(LOCALES.iter().copied().find(|catalog| catalog.id == id).unwrap_or(&ENGLISH))
}
@@ -351,6 +389,41 @@ pub fn tr_diagnostic(text: &str) -> String {
#[cfg(test)]
mod tests {
/// The system's locale tags pick a catalog: exact tag, then base language, then English (#10138).
#[test]
fn system_tags_match_the_catalog_exact_then_base_then_english() {
let tags = |list: &[&str]| list.iter().map(|s| s.to_string()).collect::<Vec<_>>();
assert_eq!(super::match_system_tags(&tags(&["zh-TW"])), "zh-TW", "exact tag");
assert_eq!(super::match_system_tags(&tags(&["pt-BR"])), "pt-BR");
assert_eq!(super::match_system_tags(&tags(&["en-GB"])), "en-GB");
assert_eq!(super::match_system_tags(&tags(&["zh-CN"])), "zh", "base language of zh-CN");
assert_eq!(super::match_system_tags(&tags(&["de-AT"])), "de");
assert_eq!(super::match_system_tags(&tags(&["zh_CN"])), "zh", "underscores normalize");
assert_eq!(super::match_system_tags(&tags(&["FR"])), "fr", "case-insensitive");
assert_eq!(super::match_system_tags(&tags(&["nl"])), "nl", "bare base tag");
assert_eq!(super::match_system_tags(&tags(&["pt-PT"])), "en", "pt has no catalog: English");
assert_eq!(super::match_system_tags(&tags(&["xx-YY"])), "en", "unknown: English");
assert_eq!(super::match_system_tags(&tags(&[])), "en", "nothing: English");
assert_eq!(super::match_system_tags(&tags(&["xx-YY", "de-DE"])), "de", "the first tag that matches wins");
}
/// A saved language is never overridden: only `system` resolves through the OS (#10138).
#[test]
fn a_saved_language_choice_is_never_overridden() {
assert_eq!(super::Locale::for_language("de").name(), "Deutsch");
assert_eq!(super::Locale::for_language("zh-TW").name(), "繁體中文");
assert_eq!(super::effective_language("de"), "de");
assert_eq!(super::effective_language("ja"), "ja");
// A first start has no saved language: the default follows the system.
assert_eq!(crate::prefs::Prefs::default().language, super::SYSTEM);
// A saved choice in the settings file wins over the default.
let saved: crate::prefs::Prefs = serde_json::from_str(r#"{"language":"ja"}"#).unwrap();
assert_eq!(saved.language, "ja");
// `system` is a preference value, not a catalog: it never enters the language list.
assert!(!super::is_supported(super::SYSTEM));
assert!(super::is_supported(super::effective_language(super::SYSTEM)), "system resolves to a catalog");
}
#[test]
fn theme_options_resolved_labels_are_verbatim_and_restore_catalog_adapters() {
let _language = super::scope("de");
+12
View File
@@ -62,6 +62,7 @@ fn sketch_palette_profile_and_points_rows_show_their_own_translation() {
#[test]
fn language_preference_cancel_restores_previous_locale() {
let mut h = Harness::new();
h.app.preferences.language = "en".into();
h.app.home.open = false;
h.call("ui.prefs", json!({"open":"General"}));
h.call("ui.prefs", json!({"language":"ja"}));
@@ -72,6 +73,17 @@ fn language_preference_cancel_restores_previous_locale() {
assert_eq!(h.app.tr("ui.preferences"), "Preferences");
}
/// A first start (no saved language) shows `System` as the interface language choice (#10138).
#[test]
fn language_dropdown_defaults_to_system() {
let mut h = Harness::new();
h.app.home.open = false;
assert_eq!(h.app.preferences.language, "system");
h.call("ui.prefs", json!({"open":"General"}));
let system = h.app.tr("prefs.language_system").to_owned();
assert!(h.widget(&system).is_some(), "the language dropdown reads {system}");
}
/// The chrome a user sees before touching anything: the browser heading and the SELECT panel.
/// Both were English literals in the drawing code, and a broken message id falls back to
/// English silently, so check the word actually rendered in each language.
+5 -1
View File
@@ -2856,7 +2856,11 @@ impl SolveApp {
self.applied_fonts_language.clone_from(&self.preferences.language);
self.applied_ui_font.clone_from(&self.preferences.ui_font);
self.applied_system_fonts = system_fonts;
crate::fonts::setup_fonts_without_waiting(ui.ctx(), &self.preferences.language, &self.preferences.ui_font);
crate::fonts::setup_fonts_without_waiting(
ui.ctx(),
crate::i18n::effective_language(&self.preferences.language),
&self.preferences.ui_font,
);
}
let _language = crate::i18n::scope(&self.preferences.language);
let mut report_input = None;
+19 -7
View File
@@ -1088,8 +1088,9 @@ preference_settings! {
theme_follow: String = String::new(), PAGE_INTERFACE;
/// Per-theme overrides. Raw JSON retains entries from newer or hand-edited settings.
theme_options: BTreeMap<String, BTreeMap<String, serde_json::Value>> = BTreeMap::new(), PAGE_INTERFACE;
/// Interface language (a registered locale ID).
language: String = "en".into(), 0;
/// Interface language: a registered locale ID, or `system` to follow the system's language
/// on every start (#10138). A saved language keeps winning, so existing users don't change.
language: String = "system".into(), 0;
/// Shared workspace composition; system windows and popups retain their purpose.
layout: crate::shell::LayoutMode = Default::default(), PAGE_INTERFACE;
/// Ordered view controls and their appearance.
@@ -3581,7 +3582,7 @@ fn theme_option_rows<'a>(
fn theme_options_row(app: &mut SolveApp, ui: &mut egui::Ui) {
let Some(file) = active_theme_file(app) else { return };
let rows = theme_option_rows(file, &app.preferences.language, crate::theme_options::PROVIDERS);
let rows = theme_option_rows(file, crate::i18n::effective_language(&app.preferences.language), crate::theme_options::PROVIDERS);
if rows.is_empty() {
return;
}
@@ -3654,7 +3655,12 @@ fn theme_options_reply(app: &SolveApp) -> solidcraft_engine::schema::ui_prefs::T
use solidcraft_engine::schema::ui_prefs::{ThemeChoice, ThemeOptionDef, ThemeOptionKind, ThemeOptionValue, ThemeOptionsReply};
let Some(file) = active_theme_file(app) else { return ThemeOptionsReply::default() };
let text = |texts: &crate::theme_files::OptionText, fallback: &str| {
texts.get(&app.preferences.language).or_else(|| texts.get("en")).map(String::as_str).unwrap_or(fallback).to_string()
texts
.get(crate::i18n::effective_language(&app.preferences.language))
.or_else(|| texts.get("en"))
.map(String::as_str)
.unwrap_or(fallback)
.to_string()
};
let (values, notices) = effective_theme_options(&app.preferences, file);
ThemeOptionsReply {
@@ -3914,8 +3920,12 @@ fn prepare_preferences(
}
crate::theme_files::follow_path(&new.theme_follow)?;
}
if !crate::i18n::is_supported(&new.language) {
return Err(format!("`language` must be one of: {}", crate::i18n::LOCALES.iter().map(|locale| locale.id).collect::<Vec<_>>().join(", ")));
if new.language != crate::i18n::SYSTEM && !crate::i18n::is_supported(&new.language) {
return Err(format!(
"`language` must be `{}` or one of: {}",
crate::i18n::SYSTEM,
crate::i18n::LOCALES.iter().map(|locale| locale.id).collect::<Vec<_>>().join(", ")
));
}
if new.ui_font != app.preferences.ui_font && !new.ui_font.trim().is_empty() && crate::fonts::ui_font(&new.ui_font).is_none() {
return Err(format!("`ui_font`: `{}` is not an installed font family or a readable font file", new.ui_font.trim()));
@@ -8398,7 +8408,9 @@ mod tests {
#[test]
fn language_preference_switches_and_persists() {
let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default());
assert_eq!(app.preferences.language, "en");
// A first start follows the system (#10138); pin English so the words below are fixed.
assert_eq!(app.preferences.language, crate::i18n::SYSTEM);
app.preferences.language = "en".into();
assert_eq!(app.tr("ui.preferences"), "Preferences");
assert_eq!(app.tr("ui.extrude"), "Extrude");
+25 -6
View File
@@ -9,13 +9,32 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
ui_kit::settings_form(ui, labels, |ui| {
ui_kit::row(ui, app.tr("prefs.interface_language"), |ui| {
ui_kit::settings_control_width(ui, t.form_card_width - t.space_4, |ui| {
ui_kit::dropdown_menu(ui, "pref_language", &crate::i18n::Locale::for_language(&app.preferences.language).display_name(), |ui| {
for locale in crate::i18n::LOCALES {
if ui_kit::list_picker(ui, locale.id, &locale.display_name(), app.preferences.language == locale.id).clicked() {
app.preferences.language = locale.id.into();
ui_kit::dropdown_menu(
ui,
"pref_language",
&if app.preferences.language == crate::i18n::SYSTEM {
app.tr("prefs.language_system").to_owned()
} else {
crate::i18n::Locale::for_language(&app.preferences.language).display_name().into_owned()
},
|ui| {
if ui_kit::list_picker(
ui,
crate::i18n::SYSTEM,
app.tr("prefs.language_system"),
app.preferences.language == crate::i18n::SYSTEM,
)
.clicked()
{
app.preferences.language = crate::i18n::SYSTEM.into();
}
}
});
for locale in crate::i18n::LOCALES {
if ui_kit::list_picker(ui, locale.id, &locale.display_name(), app.preferences.language == locale.id).clicked() {
app.preferences.language = locale.id.into();
}
}
},
);
});
});
});
+7
View File
@@ -5,6 +5,13 @@ Japanese, Korean, Malay, Norwegian Bokmål, Dutch, Polish, Brazilian Portuguese,
embedded catalog and one registration there; the preferences selector and validation use the same
registry.
The `language` preference is a registered locale ID, or `system` (the default on a first start):
the app then matches the system's preferred locales — the OS locale on desktop,
`navigator.languages` in the browser, read with the `sys-locale` crate — against the registry:
exact tag, then base language, then English (`match_system_tags` in
`crates/ui-egui/src/i18n.rs`). A saved specific language always wins, so existing users keep
their choice.
## Messages
`assets/locales/en.json` defines stable message IDs and English fallback text.