diff --git a/assets/icons/ui/source/glyphs.rs b/assets/icons/ui/source/glyphs.rs index c2b5eba7f..75edc8fe1 100644 --- a/assets/icons/ui/source/glyphs.rs +++ b/assets/icons/ui/source/glyphs.rs @@ -89,6 +89,15 @@ pub(crate) fn pin_icon(p: &egui::Painter, r: Rect, on: bool, col: Color32) { p.line_segment([at(0.0, -2.0), at(0.0, 7.0)], stroke); } +/// A breadcrumb separator ("Sketch › Create"): a thin chevron about 3 by 6 px, centred on `c`. +/// Drawn rather than typed, because a font's "›" sits on the baseline in some languages +/// (Japanese), where it reads as a comma. +pub(crate) fn breadcrumb(p: &egui::Painter, c: egui::Pos2, col: Color32) { + let s = Stroke::new(1.0, col); + p.line_segment([pos2(c.x - 1.5, c.y - 3.0), pos2(c.x + 1.5, c.y)], s); + p.line_segment([pos2(c.x + 1.5, c.y), pos2(c.x - 1.5, c.y + 3.0)], s); +} + pub(crate) fn caret(p: &egui::Painter, c: egui::Pos2, col: Color32) { p.add(egui::Shape::convex_polygon(vec![pos2(c.x - 3.5, c.y - 2.0), pos2(c.x + 3.5, c.y - 2.0), pos2(c.x, c.y + 2.5)], col, Stroke::NONE)); } diff --git a/assets/locales/cs.json b/assets/locales/cs.json index a27ed4e6e..a6119472b 100644 --- a/assets/locales/cs.json +++ b/assets/locales/cs.json @@ -1337,6 +1337,8 @@ "ui.save_mesh_pick_bodies": "Vyberte tělesa k uložení", "ui.save_mesh_temp_failed": "Nelze vytvořit {folder}: {error}", "ui.saved_to": "Uloženo {path}", + "ui.sbox_pin": "Připnout nahoru ve vyhledávání S", + "ui.sbox_unpin": "Odepnout", "ui.scale": "Měřítko", "ui.section_analysis": "Analýza řezu", "ui.select": "Vybrat", diff --git a/assets/locales/de.json b/assets/locales/de.json index 77a6bbcb1..914914962 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -1118,6 +1118,8 @@ "ui.save_mesh_pick_bodies": "Wähle die Körper zum Speichern aus", "ui.save_mesh_temp_failed": "{folder} konnte nicht angelegt werden: {error}", "ui.saved_to": "Gespeichert: {path}", + "ui.sbox_pin": "Oben im S-Feld anheften", + "ui.sbox_unpin": "Lösen", "ui.scale": "Skalieren", "ui.second_rail": "Zweite Leitkurve", "ui.section_analysis": "Querschnittsanalyse", diff --git a/assets/locales/en.json b/assets/locales/en.json index 4394f3d63..063cb9a4a 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -1423,6 +1423,8 @@ "ui.save_mesh_pick_bodies": "Select the bodies to save", "ui.save_mesh_temp_failed": "Couldn't make {folder}: {error}", "ui.saved_to": "Saved {path}", + "ui.sbox_pin": "Pin to the top of the S box", + "ui.sbox_unpin": "Unpin", "ui.scale": "Scale", "ui.second_rail": "Second Rail", "ui.section_analysis": "Section Analysis", diff --git a/assets/locales/es.json b/assets/locales/es.json index 0b18f3c7a..1750c8966 100644 --- a/assets/locales/es.json +++ b/assets/locales/es.json @@ -1372,6 +1372,8 @@ "ui.save_mesh_pick_bodies": "Selecciona los cuerpos que se van a guardar", "ui.save_mesh_temp_failed": "No se ha podido crear {folder}: {error}", "ui.saved_to": "Guardado en {path}", + "ui.sbox_pin": "Fijar arriba en la búsqueda S", + "ui.sbox_unpin": "Desfijar", "ui.scale": "Escala", "ui.second_rail": "Segunda línea guía", "ui.section_analysis": "Análisis de sección", diff --git a/assets/locales/fr.json b/assets/locales/fr.json index 2bbbed45e..444117d2b 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -1379,6 +1379,8 @@ "ui.save_mesh_pick_bodies": "Sélectionner les corps à enregistrer", "ui.save_mesh_temp_failed": "Impossible de créer {folder} : {error}", "ui.saved_to": "Enregistré : {path}", + "ui.sbox_pin": "Épingler en haut de la boîte S", + "ui.sbox_unpin": "Désépingler", "ui.scale": "Échelle", "ui.second_rail": "Second rail", "ui.section_analysis": "Analyse de coupe", diff --git a/assets/locales/gl.json b/assets/locales/gl.json index b34e88612..d7a219660 100644 --- a/assets/locales/gl.json +++ b/assets/locales/gl.json @@ -1337,6 +1337,8 @@ "ui.save_mesh_pick_bodies": "Selecciona os corpos que queres gardar", "ui.save_mesh_temp_failed": "Non se puido crear {folder}: {error}", "ui.saved_to": "Gardado {path}", + "ui.sbox_pin": "Fixar arriba na caixa S", + "ui.sbox_unpin": "Desfixar", "ui.scale": "Escala", "ui.section_analysis": "Análise de sección", "ui.select": "Seleccionar", diff --git a/assets/locales/it.json b/assets/locales/it.json index 243c6290f..e28daca5e 100644 --- a/assets/locales/it.json +++ b/assets/locales/it.json @@ -1363,6 +1363,8 @@ "ui.save_mesh_pick_bodies": "Seleziona i corpi da salvare", "ui.save_mesh_temp_failed": "Impossibile creare {folder}: {error}", "ui.saved_to": "Salvato {path}", + "ui.sbox_pin": "Fissa in cima al riquadro S", + "ui.sbox_unpin": "Sblocca", "ui.scale": "Scala", "ui.second_rail": "Seconda guida", "ui.section_analysis": "Analisi in sezione", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 0cfb388f9..58e7a1136 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -1423,6 +1423,8 @@ "ui.save_mesh_pick_bodies": "保存するボディを選択してください", "ui.save_mesh_temp_failed": "{folder} を作成できません: {error}", "ui.saved_to": "保存しました: {path}", + "ui.sbox_pin": "Sボックスの上部に固定", + "ui.sbox_unpin": "固定を解除", "ui.scale": "尺度", "ui.second_rail": "第2レール", "ui.section_analysis": "断面解析", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index 63df7e568..367b9b628 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -1116,6 +1116,8 @@ "ui.save_mesh_pick_bodies": "저장할 바디를 선택하세요", "ui.save_mesh_temp_failed": "{folder}을(를) 만들 수 없습니다: {error}", "ui.saved_to": "저장됨: {path}", + "ui.sbox_pin": "S 상자 맨 위에 고정", + "ui.sbox_unpin": "고정 해제", "ui.scale": "축척", "ui.section_analysis": "단면 분석", "ui.select": "선택", diff --git a/assets/locales/pl.json b/assets/locales/pl.json index 501e0f7a9..8507e9f07 100644 --- a/assets/locales/pl.json +++ b/assets/locales/pl.json @@ -1384,6 +1384,8 @@ "ui.save_mesh_pick_bodies": "Zaznacz bryły do zapisania", "ui.save_mesh_temp_failed": "Nie udało się utworzyć {folder}: {error}", "ui.saved_to": "Zapisano {path}", + "ui.sbox_pin": "Przypnij na górze okna S", + "ui.sbox_unpin": "Odepnij", "ui.scale": "Skala", "ui.second_rail": "Druga prowadnica", "ui.section_analysis": "Analiza przekroju", diff --git a/assets/locales/pt-BR.json b/assets/locales/pt-BR.json index 3653a46a5..da4c5c4e5 100644 --- a/assets/locales/pt-BR.json +++ b/assets/locales/pt-BR.json @@ -1317,6 +1317,8 @@ "ui.save_mesh_pick_bodies": "Selecione os corpos a salvar", "ui.save_mesh_temp_failed": "Não foi possível criar {folder}: {error}", "ui.saved_to": "Salvo {path}", + "ui.sbox_pin": "Fixar no topo da caixa S", + "ui.sbox_unpin": "Desafixar", "ui.scale": "Escala", "ui.section_analysis": "Análise de seção", "ui.select": "Selecionar", diff --git a/assets/locales/ru.json b/assets/locales/ru.json index 9550ec467..79b92c584 100644 --- a/assets/locales/ru.json +++ b/assets/locales/ru.json @@ -1116,6 +1116,8 @@ "ui.save_mesh_pick_bodies": "Выберите тела для сохранения", "ui.save_mesh_temp_failed": "Не удалось создать {folder}: {error}", "ui.saved_to": "Сохранено: {path}", + "ui.sbox_pin": "Закрепить вверху панели S", + "ui.sbox_unpin": "Открепить", "ui.scale": "Масштаб", "ui.section_analysis": "Анализ сечения", "ui.select": "Выбрать", diff --git a/assets/locales/tr.json b/assets/locales/tr.json index 3769e61ac..513250cd1 100644 --- a/assets/locales/tr.json +++ b/assets/locales/tr.json @@ -1264,6 +1264,8 @@ "ui.save_mesh_pick_bodies": "Kaydedilecek gövdeleri seçin", "ui.save_mesh_temp_failed": "{folder} oluşturulamadı: {error}", "ui.saved_to": "{path} konumuna kaydedildi", + "ui.sbox_pin": "S kutusunun en üstüne sabitle", + "ui.sbox_unpin": "Sabitlemeyi kaldır", "ui.scale": "Ölçekle", "ui.section_analysis": "Kesit analizi", "ui.select": "Seç", diff --git a/assets/locales/uk.json b/assets/locales/uk.json index 724954ef4..898789df4 100644 --- a/assets/locales/uk.json +++ b/assets/locales/uk.json @@ -1340,6 +1340,8 @@ "ui.save_mesh_pick_bodies": "Виберіть тіла для збереження", "ui.save_mesh_temp_failed": "Не вдалося створити {folder}: {error}", "ui.saved_to": "Збережено {path}", + "ui.sbox_pin": "Закріпити вгорі поля S", + "ui.sbox_unpin": "Відкріпити", "ui.scale": "Масштаб", "ui.section_analysis": "Аналіз перерізу", "ui.select": "Вибрати", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index d342f7a19..f366f0df2 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -1423,6 +1423,8 @@ "ui.save_mesh_pick_bodies": "请选择要保存的实体", "ui.save_mesh_temp_failed": "无法创建 {folder}:{error}", "ui.saved_to": "已保存:{path}", + "ui.sbox_pin": "固定到 S 框顶部", + "ui.sbox_unpin": "取消固定", "ui.scale": "缩放", "ui.second_rail": "第二导轨", "ui.section_analysis": "截面分析", diff --git a/crates/ui-egui/src/documents.rs b/crates/ui-egui/src/documents.rs index be579a94f..7e7656aff 100644 --- a/crates/ui-egui/src/documents.rs +++ b/crates/ui-egui/src/documents.rs @@ -402,8 +402,7 @@ pub fn tabs(app: &mut SolveApp, ui: &mut egui::Ui, r: Rect, x0: f32, x1: f32) { } tab_shape(ui.painter(), &t, tr, active, resp.hovered()); let ink = if active { t.text } else { t.app_bar_text }; - let name_display = if name == "Untitled" { app.tr("ui.untitled") } else { name }; - let label = format!("{name_display}{}", if *dirty { " •" } else { "" }); + let label = format!("{}{}", crate::i18n::Locale::for_language(&app.preferences.language).given_name(name), if *dirty { " •" } else { "" }); let g = ui.painter().layout_no_wrap(label, FontId::proportional(13.0), ink); let text_w = (tr.width() - 30.0).max(10.0); let clip = Rect::from_min_size(tr.min, vec2(text_w + 10.0, tr.height())); @@ -528,7 +527,7 @@ pub fn prompt(app: &mut SolveApp, ctx: &egui::Context) { quit_step(app); let Some(i) = app.docs.closing else { return }; let name = tabs_info(app).get(i).map(|x| x.0.clone()).unwrap_or_default(); - let name_display = if name == "Untitled" { crate::i18n::tr("ui.untitled") } else { &name }; + let name_display = crate::i18n::tr_name(&name); let mut answer: Option = None; // Left and Right move between the buttons (Save is picked first); Enter gives the picked one. let order = [Answer::Save, Answer::DontSave, Answer::Cancel]; @@ -552,14 +551,14 @@ pub fn prompt(app: &mut SolveApp, ctx: &egui::Context) { if enter { answer = Some(choice); } - let title = crate::i18n::format("document.save_changes", &[("name", name_display)]); + let title = crate::i18n::format("document.save_changes", &[("name", &name_display)]); crate::frame::window(ctx, title, crate::frame::Width::Normal) .id(egui::Id::new("sc_close_prompt")) .collapsible(false) .resizable(false) .anchor(Align2::CENTER_CENTER, vec2(0.0, 0.0)) .show(ctx, |ui| { - ui.label(crate::i18n::format("document.unsaved_changes", &[("name", name_display)])); + ui.label(crate::i18n::format("document.unsaved_changes", &[("name", &name_display)])); ui.add_space(8.0); ui.horizontal(|ui| { if ui.add(egui::Button::new(crate::i18n::tr("ui.save")).selected(choice == Answer::Save)).clicked() { diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index dda84b6bb..1863d2de0 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -104,8 +104,12 @@ impl Locale { interpolate(self.text(id), args) } - /// The default names SolidCraft gives (`Sketch1`, `Body2`, `Component3`), translated. + /// The default names SolidCraft gives (`Untitled` for a new design, `Sketch1`, `Body2`, + /// `Component3`), translated. fn default_name(self, text: &str) -> Option { + if text == "Untitled" { + return Some(self.text("ui.untitled").to_string()); + } for (prefix, id) in [("Sketch", "browser.sketch_name"), ("Body", "browser.body_name"), ("Component", "browser.component_name")] { if let Some(number) = text.strip_prefix(prefix) && !number.is_empty() @@ -228,6 +232,19 @@ mod tests { assert_eq!(ids.first(), Some(&"en")); assert!(ids[1..].is_sorted(), "{ids:?}"); } + + /// A new design's name, `Untitled`, is a default name like `Sketch1`: it shows translated + /// wherever the design's name is shown (the tab, the browser's top row, the save prompt). + #[test] + fn a_new_designs_name_is_translated_like_the_other_default_names() { + let ja = Locale::for_language("ja"); + assert_eq!(ja.given_name("Untitled"), ja.text("ui.untitled")); + assert_ne!(ja.given_name("Untitled"), "Untitled"); + assert_eq!(Locale::for_language("en").given_name("Untitled"), "Untitled"); + // Only the whole default name: names people type stay as typed. + assert_eq!(ja.given_name("Untitled bracket"), "Untitled bracket"); + assert_eq!(ja.given_name("Boss"), "Boss"); + } use std::collections::BTreeSet; fn placeholders(text: &str) -> BTreeSet<&str> { diff --git a/crates/ui-egui/src/i18n_painted_tests.rs b/crates/ui-egui/src/i18n_painted_tests.rs new file mode 100644 index 000000000..3e97db262 --- /dev/null +++ b/crates/ui-egui/src/i18n_painted_tests.rs @@ -0,0 +1,168 @@ +//! No English where a translation exists (#2544): the text a frame actually paints, in every +//! language. A painter call that skips the label lookup (`ui.painter().text(.., c.label, ..)`) +//! paints the English text even though the language has a translation; this sweep catches it +//! wherever it happens on the surfaces it opens. + +use std::collections::{BTreeMap, BTreeSet}; + +use solidcraft_engine::Session; + +use crate::context_menu::Target; +use crate::scenario::Harness; +use crate::{Services, SolveApp}; + +/// English text → the catalog ids that carry it. +fn english_ids() -> BTreeMap> { + const EN: &str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/locales/en.json")); + let messages: BTreeMap = serde_json::from_str(EN).unwrap(); + let mut ids: BTreeMap> = BTreeMap::new(); + for (id, text) in messages { + ids.entry(text).or_default().push(id); + } + ids +} + +/// Every piece of text one more frame paints: whole texts, and the parts of a composed one +/// ("SKETCH › CREATE", "R SKETCH › CREATE", a tab's "Untitled •"). +fn painted(h: &mut Harness) -> BTreeSet { + fn walk(shape: &egui::Shape, out: &mut BTreeSet) { + match shape { + egui::Shape::Text(t) => { + let text = t.galley.job.text.trim(); + out.insert(text.to_string()); + for part in text.split(['›', '·', '•']).flat_map(|p| p.split(" ")) { + out.insert(part.trim().to_string()); + } + } + egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| walk(s, out)), + _ => {} + } + } + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0)); + let mut out = h.ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| { + h.app.logic(ui.ctx()); + h.app.ui(ui); + }); + out.textures_delta.clear(); + let mut texts = BTreeSet::new(); + out.shapes.iter().for_each(|s| walk(&s.shape, &mut texts)); + texts +} + +/// Names the design holds (its own name, features, bodies, components, occurrences), and the +/// keyboard shortcuts' key names. They are shown as typed or as printed on the key in every +/// language, even when one matches a label ("Boss", "Holes", the Delete key). +fn design_names(app: &SolveApp) -> BTreeSet { + let doc = &app.session.doc; + let mut names: BTreeSet = [doc.name.clone()].into(); + names.extend(doc.features.iter().map(|f| f.name.clone())); + names.extend(doc.components.iter().map(|c| c.name.clone())); + names.extend(doc.occurrences.iter().map(|o| o.name.clone())); + names.extend(app.session.model.state().bodies.iter().map(|b| b.name.clone())); + names.extend(solidcraft_engine::command_specs().iter().filter_map(|c| crate::keymap::effective(app, c.id))); + names +} + +/// Texts painted in English although every catalog entry with that English text is translated +/// in `language`. (When one entry with the text is still English there, English is right.) +/// `names` are the design's own names, which are not UI text, except the default names the +/// language translates (a new design's `Untitled`, `Sketch1`): those must show translated. +fn english_leaks(language: &str, texts: &BTreeSet, english: &BTreeMap>, names: &BTreeSet) -> Vec { + let locale = crate::i18n::Locale::for_language(language); + texts + .iter() + .filter(|text| !names.contains(*text) || locale.given_name(text) != text.as_str()) + .filter(|text| english.get(*text).is_some_and(|ids| ids.iter().all(|id| locale.text(id) != text.as_str()))) + .cloned() + .collect() +} + +fn sample() -> Harness { + let mut h = Harness::new(); + let mut session = Session::default(); + session.run_script(&solidcraft_engine::sample::script()).unwrap(); + h.app = SolveApp::new(session, Services::default()); + h.app.home.open = false; + h.frames(3); + h +} + +/// The surfaces the sweep opens, each in every language: the window with the sample design; the +/// S command search with nothing typed (the first rows of every command, by name) and with two +/// queries; every Preferences page; and the right-click menus of the viewport, a body, the +/// toolbar and the workspace. +fn sweep(h: &mut Harness, language: &str) -> BTreeMap<&'static str, BTreeSet> { + h.app.preferences.language = language.into(); + let mut seen = BTreeMap::new(); + h.app.ui.palette_open = false; + h.frames(2); + seen.insert("window", painted(h)); + for (name, query) in [("S box", ""), ("S box: rect", "rect"), ("S box: sketch", "sketch")] { + crate::shortcut_box::open(&mut h.app, None); + h.app.sbox.text = query.into(); + h.frames(2); + seen.insert(name, painted(h)); + } + h.app.ui.palette_open = false; + let title = crate::i18n::Locale::for_language(language).text("ui.preferences").to_string(); + for page in crate::prefs::PAGES { + h.call("ui.prefs", serde_json::json!({"open": page})); + h.frames(2); + let texts = painted(h); + assert!(texts.contains(&title), "{language}: the {page} page isn't showing"); + seen.insert(page, texts); + } + h.call("ui.prefs", serde_json::json!({"button": "cancel"})); + h.frames(1); + let body = h.app.session.model.state().bodies.first().map(|b| b.name.clone()).unwrap_or_default(); + let menus = [ + ("viewport menu", Target::Viewport), + ("body menu", Target::Body { name: body }), + ("toolbar menu", Target::Toolbar), + ("workspace menu", Target::Workspace), + ]; + for (name, target) in menus { + crate::context_menu::open_for(&mut h.app, egui::pos2(700.0, 400.0), target); + h.frames(2); + let texts = painted(h); + let new = texts.difference(&seen["window"]).count(); + assert!(new >= 2, "{language}: the {name} isn't showing ({new} new texts)"); + seen.insert(name, texts); + crate::context_menu::close(&mut h.app); + h.frames(1); + } + seen +} + +#[test] +fn no_english_is_painted_where_the_language_has_a_translation() { + let english = english_ids(); + let mut h = sample(); + let names = design_names(&h.app); + assert!(names.contains("Boss") && names.len() > 5, "{names:?}"); + let mut leaks = Vec::new(); + for catalog in crate::i18n::LOCALES.iter().filter(|c| c.id != "en") { + for (surface, texts) in sweep(&mut h, catalog.id) { + assert!(texts.len() > 20, "{} {surface}: only {} texts painted", catalog.id, texts.len()); + for text in english_leaks(catalog.id, &texts, &english, &names) { + leaks.push(format!("{} {surface}: {text:?}", catalog.id)); + } + } + } + assert!(leaks.is_empty(), "{} English text(s) painted where the language has a translation:\n{}", leaks.len(), leaks.join("\n")); +} + +/// The sweep can see a leak: English painted by a plain painter call is reported, the same text +/// in the language is not, and English that the language leaves untranslated is not either. +#[test] +fn the_sweep_reports_english_only_where_a_translation_exists() { + let english = english_ids(); + let locale = crate::i18n::Locale::for_language("ja"); + let translated = locale.text("cmd.sketch_rectangle_center").to_string(); + assert_ne!(translated, "Center Rectangle"); + let texts: BTreeSet = + ["Center Rectangle".to_string(), translated, "mm".to_string(), "Untranslated Text 2544".to_string(), "Fillet".to_string()].into(); + // "Fillet" here is a feature someone named so: a design name, not a label. + let names: BTreeSet = ["Fillet".to_string()].into(); + assert_eq!(english_leaks("ja", &texts, &english, &names), vec!["Center Rectangle".to_string()]); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f24a2e7e4..edd7374ee 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -59,6 +59,8 @@ pub mod i18n; #[cfg(test)] mod i18n_menu_tests; #[cfg(test)] +mod i18n_painted_tests; +#[cfg(test)] mod i18n_ui_tests; pub mod icon_svg; pub mod icons; diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 47cea3258..e26e33947 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -15,16 +15,22 @@ pub struct Palette { focus: bool, } -/// Commands whose id or label matches the query. +/// Commands whose id or label matches the query: (id, label in the current language, icon). +/// The label matches in the current language and in English, so a name typed in either finds +/// the command. pub fn matches(q: &str) -> Vec<(&'static str, &'static str, &'static str)> { - let q = q.trim().to_ascii_lowercase(); - let mut v: Vec<(&'static str, &'static str, &'static str)> = command_specs() + let q = q.trim().to_lowercase(); + let mut v: Vec<(bool, bool, &'static str, &'static str, &'static str)> = command_specs() .into_iter() - .filter(|c| q.is_empty() || c.label.to_ascii_lowercase().contains(&q) || c.id.to_ascii_lowercase().contains(&q)) - .map(|c| (c.id, c.label, c.icon)) + .filter_map(|c| { + let label = crate::i18n::tr_label(c.label); + let (shown, english, id) = (label.to_lowercase(), c.label.to_lowercase(), c.id.to_lowercase()); + let found = q.is_empty() || shown.contains(&q) || english.contains(&q) || id.contains(&q); + found.then(|| (!(shown.starts_with(&q) || english.starts_with(&q)), !id.starts_with(&q), label, c.id, c.icon)) + }) .collect(); - v.sort_by_key(|(id, label, _)| (!label.to_ascii_lowercase().starts_with(&q), !id.to_ascii_lowercase().starts_with(&q), *label)); - v + v.sort(); + v.into_iter().map(|(_, _, label, id, icon)| (id, label, icon)).collect() } /// Execute a line of palette input. @@ -136,3 +142,19 @@ pub fn popup(app: &mut SolveApp, ctx: &egui::Context) { app.palette.text.clear(); } } + +#[cfg(test)] +mod tests { + use super::*; + + /// The command line finds a name typed in the current language or in English (#2544). + #[test] + fn matches_finds_a_name_in_the_current_language_and_in_english() { + let _ja = crate::i18n::scope("ja"); + let name = crate::i18n::Locale::for_language("ja").text("cmd.sketch_rectangle_center"); + for query in [name, "Center Rectangle", "sketch.rectangle.center"] { + let found = matches(query); + assert_eq!(found.first().map(|m| (m.0, m.1)), Some(("sketch.rectangle.center", name)), "{query:?}"); + } + } +} diff --git a/crates/ui-egui/src/shortcut_box.rs b/crates/ui-egui/src/shortcut_box.rs index ca3da74de..a2b341bcd 100644 --- a/crates/ui-egui/src/shortcut_box.rs +++ b/crates/ui-egui/src/shortcut_box.rs @@ -98,23 +98,63 @@ pub fn score(q: &str, s: &str) -> u32 { 300u32.saturating_sub(gaps * 20).max(10) } -/// Commands matching `q`, best first: (id, label, icon, where it lives on the toolbar). With an -/// empty query, recent commands come first, then everything by name. -pub fn search(app: &SolveApp, q: &str) -> Vec<(&'static str, &'static str, &'static str, String)> { +/// A row of the box: the command id, its label, its icon, and where it lives on the toolbar +/// (tab, panel; `None` off the toolbar), in the current language. +pub type Row = (&'static str, &'static str, &'static str, Option<(&'static str, &'static str)>); + +/// Commands matching `q`, best first. With an empty query, recent commands come first, then +/// everything by name. +/// +/// The query matches the label, tab and panel in the current language and in English, and the +/// id, so a name typed in either language, or an id, finds the command in every language. +pub fn search(app: &SolveApp, q: &str) -> Vec { let q = q.trim().to_lowercase(); - let mut v: Vec<(u32, &'static str, &'static str, &'static str, String)> = command_specs() + let mut v: Vec<(u32, Row)> = command_specs() .into_iter() .filter_map(|c| { - let place = if c.tab.is_empty() { String::new() } else { format!("{} › {}", c.tab, c.panel) }; - let s = score(&q, c.label).max(score(&q, c.id) * 9 / 10).max(score(&q, c.tab) / 3).max(score(&q, c.panel) / 3); + let (label, tab, panel) = (crate::i18n::tr_label(c.label), crate::i18n::tr_label(c.tab), crate::i18n::tr_label(c.panel)); + let place = (!c.tab.is_empty()).then_some((tab, panel)); + let s = score(&q, label) + .max(score(&q, c.label)) + .max(score(&q, c.id) * 9 / 10) + .max(score(&q, tab).max(score(&q, c.tab)) / 3) + .max(score(&q, panel).max(score(&q, c.panel)) / 3); let recent = app.sbox.recent.iter().position(|r| r == c.id).map_or(0, |i| 2000 - i as u32); // Commands that can run now come before those that can't. let usable = if c.info(&app.session).enabled { 150 } else { 0 }; - (s > 0).then_some((s + usable + if q.is_empty() { recent } else { recent / 20 }, c.id, c.label, c.icon, place)) + (s > 0).then_some((s + usable + if q.is_empty() { recent } else { recent / 20 }, (c.id, label, c.icon, place))) }) .collect(); - v.sort_by(|a, b| b.0.cmp(&a.0).then(a.2.cmp(b.2))); - v.into_iter().map(|(_, id, label, icon, place)| (id, label, icon, place)).collect() + v.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.1.cmp(b.1.1))); + v.into_iter().map(|(_, row)| row).collect() +} + +/// A row's right-hand side, ending at `at`: the shortcut, then where the command lives +/// ("Sketch › Create"). The separator is drawn, centred on the ink of the panel's name: a +/// font's "›", or one centred on the row, sits low beside Japanese or Chinese words. +fn paint_key_and_place(painter: &egui::Painter, at: Pos2, key: &str, place: Option<(&str, &str)>, color: egui::Color32) { + let font = FontId::proportional(10.5); + // One piece of text ending at `x`, centred on the row: its left edge and the middle of its ink. + let piece = |x: f32, text: &str| -> (f32, f32) { + let galley = painter.layout_no_wrap(text.to_string(), font.clone(), color); + let pos = pos2(x - galley.size().x, at.y - galley.size().y / 2.0); + let ink = galley + .rows + .first() + .filter(|r| r.row.visuals.mesh_bounds.is_positive()) + .map_or(galley.size().y / 2.0, |r| r.pos.y + r.row.visuals.mesh_bounds.center().y); + painter.galley(pos, galley, color); + (pos.x, pos.y + ink) + }; + let mut x = at.x; + if let Some((tab, panel)) = place { + let (left, ink) = piece(x, panel); + icons::glyphs::breadcrumb(painter, pos2(left - 5.0, ink), color); + x = piece(left - 10.0, tab).0 - 14.0; + } + if !key.is_empty() { + piece(x, key); + } } /// Open the box at a point (the cursor), or at the middle of the window. @@ -178,7 +218,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { ui.painter().rect_filled(r, 4.0, t.hover); } icons::paint(ui.painter(), r.shrink(5.0), c.icon, t.icon, t.icon_fill, t.accent); - if resp.on_hover_text(c.label).clicked() { + if resp.on_hover_text(crate::i18n::tr_label(c.label)).clicked() { picked = Some(c.id); } } @@ -223,10 +263,9 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { t.accent, ); let col = if enabled { t.text } else { t.text_dim }; - ui.painter().text(pos2(r.left() + 30.0, r.center().y), Align2::LEFT_CENTER, *label, FontId::proportional(13.0), col); + ui.painter().text(pos2(r.left() + 30.0, r.center().y), Align2::LEFT_CENTER, label, FontId::proportional(13.0), col); let key = crate::keymap::effective(app, id).unwrap_or_default(); - let right = if key.is_empty() { place.clone() } else { format!("{key} {place}") }; - ui.painter().text(pos2(r.right() - 26.0, r.center().y), Align2::RIGHT_CENTER, right, FontId::proportional(10.5), t.text_dim); + paint_key_and_place(ui.painter(), pos2(r.right() - 26.0, r.center().y), &key, *place, t.text_dim); // The pin. let pinned = app.sbox.pinned.iter().any(|p| p == id); let pr = Rect::from_center_size(pos2(r.right() - 11.0, r.center().y), vec2(16.0, 16.0)); @@ -245,7 +284,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { } ui.painter().add(egui::Shape::closed_line(pts, Stroke::new(1.0, if pinned { t.warning } else { t.text_dim }))); } - if presp.on_hover_text(if pinned { "Unpin" } else { "Pin to the top of the S box" }).clicked() { + if presp.on_hover_text(crate::i18n::tr(if pinned { "ui.sbox_unpin" } else { "ui.sbox_pin" })).clicked() { pin = Some(id); } else if resp.clicked() && enabled { picked = Some(id); @@ -337,4 +376,26 @@ mod tests { other.sbox.load(&app.sbox.prefs()); assert_eq!((other.sbox.pinned.clone(), other.sbox.recent.len()), (vec!["solid.extrude".to_string()], 2)); } + + /// The box shows each command's label and place in the current language, and finds a name + /// typed in that language, in English, or an id (#2544). + #[test] + fn search_shows_and_matches_the_current_language() { + let app = SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + let _ja = crate::i18n::scope("ja"); + let ja = crate::i18n::Locale::for_language("ja"); + let name = ja.text("cmd.sketch_rectangle_center"); + assert_ne!(name, "Center Rectangle"); + let place = Some((ja.label("SKETCH"), ja.label("CREATE"))); + for query in [name, "長方形", "center rect", "sketch.rectangle.center"] { + let rows = search(&app, query); + let row = rows.iter().find(|r| r.0 == "sketch.rectangle.center").unwrap_or_else(|| panic!("{query:?} doesn't find it")); + assert_eq!((row.1, row.3), (name, place), "{query:?}"); + } + assert_eq!(search(&app, name).first().map(|r| r.0), Some("sketch.rectangle.center"), "the exact name comes first"); + // English is unchanged. + drop(_ja); + let row = search(&app, "center rect").into_iter().find(|r| r.0 == "sketch.rectangle.center").unwrap(); + assert_eq!((row.1, row.3), ("Center Rectangle", Some(("SKETCH", "CREATE")))); + } }