diff --git a/crates/ui-egui/build.rs b/crates/ui-egui/build.rs new file mode 100644 index 000000000..06d041a09 --- /dev/null +++ b/crates/ui-egui/build.rs @@ -0,0 +1,37 @@ +//! Optional `CRAFT_FONTS_DIR` discovery for Hebrew fallback font without committing binary assets. + +use std::path::{Path, PathBuf}; + +const FONT_NAME: &str = "NotoSansHebrew-Regular.ttf"; + +fn absolutize(path: &Path) -> PathBuf { + if path.is_absolute() { + path.to_path_buf() + } else { + std::env::current_dir() + .map(|cwd| cwd.join(path)) + .unwrap_or_else(|_| path.to_path_buf()) + } +} + +fn main() { + println!("cargo::rustc-check-cfg=cfg(has_hebrew_craft_font)"); + println!("cargo::rerun-if-env-changed=CRAFT_FONTS_DIR"); + + let Ok(dir) = std::env::var("CRAFT_FONTS_DIR") else { + return; + }; + let dir = dir.trim(); + if dir.is_empty() { + return; + } + let abs_dir = absolutize(Path::new(dir)); + println!("cargo::rerun-if-changed={}", abs_dir.display()); + let font_path = abs_dir.join(FONT_NAME); + if font_path.is_file() { + let abs = std::fs::canonicalize(&font_path).unwrap_or(font_path); + println!("cargo::rerun-if-changed={}", abs.display()); + println!("cargo::rustc-env=HEBREW_CRAFT_FONT_PATH={}", abs.display()); + println!("cargo::rustc-cfg=has_hebrew_craft_font"); + } +} diff --git a/crates/ui-egui/src/authoring.rs b/crates/ui-egui/src/authoring.rs index a7288e425..78d37ea7b 100644 --- a/crates/ui-egui/src/authoring.rs +++ b/crates/ui-egui/src/authoring.rs @@ -128,26 +128,26 @@ fn new_footprint() -> FootprintDefinition { unsupported: vec![], } } -fn point(ui: &mut egui::Ui, label: &str, p: &mut Point) { +fn point(ui: &mut egui::Ui, lang: i18n::Lang, label: &'static str, p: &mut Point) { ui.horizontal(|ui| { - ui.label(label); + ui.label(i18n::t(lang, label)); ui.add(egui::DragValue::new(&mut p.x).speed(0.1).prefix("X ")); ui.add(egui::DragValue::new(&mut p.y).speed(0.1).prefix("Y ")); }); } -fn text(ui: &mut egui::Ui, label: &str, value: &mut String) { +fn text(ui: &mut egui::Ui, lang: i18n::Lang, label: &'static str, value: &mut String) { ui.horizontal(|ui| { - ui.label(label); + ui.label(i18n::t(lang, label)); ui.text_edit_singleline(value); }); } -fn number(ui: &mut egui::Ui, label: &str, value: &mut f64) { +fn number(ui: &mut egui::Ui, lang: i18n::Lang, label: &'static str, value: &mut f64) { ui.horizontal(|ui| { - ui.label(label); + ui.label(i18n::t(lang, label)); ui.add(egui::DragValue::new(value).speed(0.1)); }); } -fn graphic(ui: &mut egui::Ui, g: &mut Graphic) { +fn graphic(ui: &mut egui::Ui, lang: i18n::Lang, g: &mut Graphic) { match g { Graphic::Line { start, @@ -155,10 +155,10 @@ fn graphic(ui: &mut egui::Ui, g: &mut Graphic) { width, layer, } => { - point(ui, "Start", start); - point(ui, "End", end); - number(ui, "Stroke", width); - text(ui, "Layer", layer); + point(ui, lang, "Start", start); + point(ui, lang, "End", end); + number(ui, lang, "Stroke", width); + text(ui, lang, "Layer", layer); } Graphic::Rectangle { start, @@ -167,11 +167,11 @@ fn graphic(ui: &mut egui::Ui, g: &mut Graphic) { fill, layer, } => { - point(ui, "Start", start); - point(ui, "End", end); - number(ui, "Stroke", width); - text(ui, "Fill", fill); - text(ui, "Layer", layer); + point(ui, lang, "Start", start); + point(ui, lang, "End", end); + number(ui, lang, "Stroke", width); + text(ui, lang, "Fill", fill); + text(ui, lang, "Layer", layer); } Graphic::Circle { center, @@ -180,11 +180,11 @@ fn graphic(ui: &mut egui::Ui, g: &mut Graphic) { fill, layer, } => { - point(ui, "Center", center); - number(ui, "Radius", radius); - number(ui, "Stroke", width); - text(ui, "Fill", fill); - text(ui, "Layer", layer); + point(ui, lang, "Center", center); + number(ui, lang, "Radius", radius); + number(ui, lang, "Stroke", width); + text(ui, lang, "Fill", fill); + text(ui, lang, "Layer", layer); } Graphic::Arc { start, @@ -193,11 +193,11 @@ fn graphic(ui: &mut egui::Ui, g: &mut Graphic) { width, layer, } => { - point(ui, "Start", start); - point(ui, "Through", mid); - point(ui, "End", end); - number(ui, "Stroke", width); - text(ui, "Layer", layer); + point(ui, lang, "Start", start); + point(ui, lang, "Through", mid); + point(ui, lang, "End", end); + number(ui, lang, "Stroke", width); + text(ui, lang, "Layer", layer); } Graphic::Polyline { points, @@ -206,20 +206,25 @@ fn graphic(ui: &mut egui::Ui, g: &mut Graphic) { layer, } => { for (i, p) in points.iter_mut().enumerate().take(128) { - point(ui, &format!("Vertex {}", i + 1), p); + let idx_s = (i + 1).to_string(); + ui.horizontal(|ui| { + ui.label(i18n::tf(lang, "Vertex {}", &[&idx_s])); + ui.add(egui::DragValue::new(&mut p.x).speed(0.1).prefix("X ")); + ui.add(egui::DragValue::new(&mut p.y).speed(0.1).prefix("Y ")); + }); } if points.len() > 128 { - ui.label("Remaining vertices are preserved."); + ui.label(i18n::t(lang, "Remaining vertices are preserved.")); } - if ui.button("Add vertex").clicked() && points.len() < 128 { + if ui.button(i18n::t(lang, "Add vertex")).clicked() && points.len() < 128 { points.push(Point::default()); } - if ui.button("Remove last vertex").clicked() && points.len() > 2 { + if ui.button(i18n::t(lang, "Remove last vertex")).clicked() && points.len() > 2 { points.pop(); } - number(ui, "Stroke", width); - text(ui, "Fill", fill); - text(ui, "Layer", layer); + number(ui, lang, "Stroke", width); + text(ui, lang, "Fill", fill); + text(ui, lang, "Layer", layer); } Graphic::Text { position, @@ -228,19 +233,19 @@ fn graphic(ui: &mut egui::Ui, g: &mut Graphic) { size, layer, } => { - point(ui, "Position", position); - text(ui, "Text", content); - point(ui, "Text size", size); - number(ui, "Angle", angle); - text(ui, "Layer", layer); + point(ui, lang, "Position", position); + text(ui, lang, "Text", content); + point(ui, lang, "Text size", size); + number(ui, lang, "Angle", angle); + text(ui, lang, "Layer", layer); } } } -fn add_graphic(ui: &mut egui::Ui, layer: &str) -> Option { +fn add_graphic(ui: &mut egui::Ui, lang: i18n::Lang, layer: &str) -> Option { let mut result = None; ui.horizontal_wrapped(|ui| { - ui.label("Add drawing:"); - if ui.button("Line").clicked() { + ui.label(i18n::t(lang, "Add drawing:")); + if ui.button(i18n::t(lang, "Line")).clicked() { result = Some(Graphic::Line { start: Point::new(-3.0, 0.0), end: Point::new(3.0, 0.0), @@ -248,10 +253,10 @@ fn add_graphic(ui: &mut egui::Ui, layer: &str) -> Option { layer: layer.into(), }); } - if ui.button("Rectangle").clicked() { + if ui.button(i18n::t(lang, "Rectangle")).clicked() { result = Some(rectangle(layer)); } - if ui.button("Circle").clicked() { + if ui.button(i18n::t(lang, "Circle")).clicked() { result = Some(Graphic::Circle { center: Point::default(), radius: 2.0, @@ -260,7 +265,7 @@ fn add_graphic(ui: &mut egui::Ui, layer: &str) -> Option { layer: layer.into(), }); } - if ui.button("Arc").clicked() { + if ui.button(i18n::t(lang, "Arc")).clicked() { result = Some(Graphic::Arc { start: Point::new(-3.0, 0.0), mid: Point::new(0.0, -3.0), @@ -269,7 +274,7 @@ fn add_graphic(ui: &mut egui::Ui, layer: &str) -> Option { layer: layer.into(), }); } - if ui.button("Polyline").clicked() { + if ui.button(i18n::t(lang, "Polyline")).clicked() { result = Some(Graphic::Polyline { points: vec![ Point::new(-2.0, 2.0), @@ -281,7 +286,7 @@ fn add_graphic(ui: &mut egui::Ui, layer: &str) -> Option { layer: layer.into(), }); } - if ui.button("Text").clicked() { + if ui.button(i18n::t(lang, "Text")).clicked() { result = Some(Graphic::Text { position: Point::default(), angle: 0.0, @@ -295,16 +300,25 @@ fn add_graphic(ui: &mut egui::Ui, layer: &str) -> Option { } impl App { pub(super) fn library_workspaces(&mut self, ui: &mut egui::Ui) { + let lang = self.preferences.language; ui.horizontal(|ui| { - ui.selectable_value(&mut self.library.editor.mode, 0, "Installed libraries"); - ui.selectable_value(&mut self.library.editor.mode, 1, "Project library"); - ui.selectable_value(&mut self.library.editor.mode, 2, "Editor"); - if ui.button("New symbol").clicked() { + ui.selectable_value( + &mut self.library.editor.mode, + 0, + i18n::t(lang, "Installed libraries"), + ); + ui.selectable_value( + &mut self.library.editor.mode, + 1, + i18n::t(lang, "Project library"), + ); + ui.selectable_value(&mut self.library.editor.mode, 2, i18n::t(lang, "Editor")); + if ui.button(i18n::t(lang, "New symbol")).clicked() { self.library.editor.draft = Some(Draft::Symbol(new_symbol())); self.library.editor.mode = 2; self.library.editor.notice = None; } - if ui.button("New footprint").clicked() { + if ui.button(i18n::t(lang, "New footprint")).clicked() { self.library.editor.draft = Some(Draft::Footprint(new_footprint())); self.library.editor.mode = 2; self.library.editor.notice = None; @@ -318,25 +332,30 @@ impl App { } } fn project_library(&mut self, ui: &mut egui::Ui) { - ui.heading("Editable project library"); - ui.label("Saved definitions live in this project. Placed components retain their embedded copies."); + ui.heading(self.tr("Editable project library")); + i18n::wrapped_label( + ui, + self.preferences.language, + "Saved definitions live in this project. Placed components retain their embedded copies.", + ); ui.horizontal(|ui| { - ui.label("Collection file"); + ui.label(self.tr("Collection file")); ui.text_edit_singleline(&mut self.library.editor.path); - if ui.button("Save library").clicked() { + if ui.button(self.tr("Save library")).clicked() { self.tool_call("library.save", json!({"path":self.library.editor.path})); } - if ui.button("Load library").clicked() { + if ui.button(self.tr("Load library")).clicked() { self.run("library.load", json!({"path":self.library.editor.path})); } }); ui.separator(); - ui.heading("Symbols"); + ui.heading(self.tr("Symbols")); for def in self.project.library.symbols.clone() { ui.horizontal_wrapped(|ui| { ui.strong(&def.name); - ui.label(format!("{} physical pins", def.pins.len())); - if ui.button("Edit").clicked() { + let pins_s = def.pins.len().to_string(); + ui.label(self.trf("{} physical pins", &[&pins_s])); + if ui.button(self.tr("Edit")).clicked() { self.library.editor.draft = Some(Draft::Symbol(def.clone())); self.library.editor.mode = 2; self.library.editor.notice = None; @@ -351,24 +370,25 @@ impl App { ) .is_ok(); if ui - .add_enabled(supported, egui::Button::new("Place")) + .add_enabled(supported, egui::Button::new(self.tr("Place"))) .clicked() { self.change_tab(Tab::Schematic); self.tool = Tool::CustomPlace(def.name.clone(), Box::new(def.clone())); } - if ui.button("Remove").clicked() { + if ui.button(self.tr("Remove")).clicked() { self.run("library.symbol.remove", json!({"name":def.name})); } }); } ui.separator(); - ui.heading("Footprints"); + ui.heading(self.tr("Footprints")); for def in self.project.library.footprints.clone() { ui.horizontal_wrapped(|ui| { ui.strong(&def.name); - ui.label(format!("{} pads", def.pads.len())); - if ui.button("Edit").clicked() { + let pads_s = def.pads.len().to_string(); + ui.label(self.trf("{} pads", &[&pads_s])); + if ui.button(self.tr("Edit")).clicked() { self.library.editor.draft = Some(Draft::Footprint(def.clone())); self.library.editor.mode = 2; self.library.editor.notice = None; @@ -388,53 +408,65 @@ impl App { if ui .add_enabled( matching && pcbcraft_doc::validate_footprint_support(&def).is_ok(), - egui::Button::new("Assign to selection"), + egui::Button::new(self.tr("Assign to selection")), ) .clicked() && let Some(id) = selected.map(|c| c.id) { self.run("footprint.assign_custom", json!({"id":id,"name":def.name})); } - if ui.button("Remove").clicked() { + if ui.button(self.tr("Remove")).clicked() { self.run("library.footprint.remove", json!({"name":def.name})); } }); } } fn library_editor(&mut self, ui: &mut egui::Ui) { + let lang = self.preferences.language; let Some(mut draft) = self.library.editor.draft.take() else { - ui.heading("Library editor"); - ui.label( + ui.heading(self.tr("Library editor")); + i18n::wrapped_label( + ui, + lang, "Create a symbol or footprint, or edit a copy from the installed/project library.", ); return; }; let mut save = None; - ui.label("Dimensions are millimetres; angles are counterclockwise degrees. Save commits one undoable edit."); + i18n::wrapped_label( + ui, + lang, + "Dimensions are millimetres; angles are counterclockwise degrees. Save commits one undoable edit.", + ); match &mut draft { Draft::Symbol(def) => { - ui.heading("Symbol editor"); - text(ui, "Name", &mut def.name); - text(ui, "Reference prefix", &mut def.reference); - text(ui, "Default value", &mut def.value); - text(ui, "Description", &mut def.description); - text(ui, "Suggested footprint", &mut def.footprint); + ui.heading(self.tr("Symbol editor")); + text(ui, lang, "Name", &mut def.name); + text(ui, lang, "Reference prefix", &mut def.reference); + text(ui, lang, "Default value", &mut def.value); + text(ui, lang, "Description", &mut def.description); + text(ui, lang, "Suggested footprint", &mut def.footprint); self.library_preview(ui, Some(def), None); if let Err(e) = def.validate() { ui.colored_label(Color32::LIGHT_RED, e.to_string()); } if !def.unsupported.is_empty() { - ui.label(format!( + let features = def.unsupported.join(", "); + ui.label(i18n::tf( + lang, "Preserved unsupported features: {}", - def.unsupported.join(", ") + &[&features], )); } - if ui.button("Save symbol to project library").clicked() { + if ui + .button(i18n::t(lang, "Save symbol to project library")) + .clicked() + { save = Some(("library.symbol.upsert", json!({"definition":def}))); } ui.separator(); - ui.heading("Pins"); - if ui.button("Duplicate preview unit").clicked() { + ui.heading(i18n::t(lang, "Pins")); + if ui.button(i18n::t(lang, "Duplicate preview unit")).clicked() { let unit = def .pins .iter() @@ -477,7 +509,7 @@ impl App { self.library.preview_unit = unit; } } - if ui.button("Add pin").clicked() && def.pins.len() < 64 { + if ui.button(i18n::t(lang, "Add pin")).clicked() && def.pins.len() < 64 { let mut n = 1; while def.pins.iter().any(|p| p.number == n.to_string()) { n += 1; @@ -492,47 +524,55 @@ impl App { let mut remove = None; for (i, pin) in def.pins.iter_mut().enumerate().take(64) { ui.push_id(i, |ui| { - ui.collapsing(format!("Pin {} · unit {}", pin.number, pin.unit), |ui| { - text(ui, "Number", &mut pin.number); - text(ui, "Name", &mut pin.name); - point(ui, "Connection", &mut pin.position); - number(ui, "Angle", &mut pin.angle); - number(ui, "Length", &mut pin.length); - ui.add( - egui::DragValue::new(&mut pin.unit) - .range(1..=32) - .prefix("Unit "), - ); - egui::ComboBox::from_id_salt("pin-type") - .selected_text(&pin.electrical_type) - .show_ui(ui, |ui| { - for t in [ - "passive", - "input", - "output", - "bidirectional", - "tri_state", - "power_in", - "power_out", - "open_collector", - "open_emitter", - "no_connect", - ] { - ui.selectable_value(&mut pin.electrical_type, t.into(), t); - } - }); - if ui.button("Delete pin").clicked() { - remove = Some(i); - } - }); + let u_s = pin.unit.to_string(); + ui.collapsing( + i18n::tf(lang, "Pin {} · unit {}", &[&pin.number, &u_s]), + |ui| { + text(ui, lang, "Number", &mut pin.number); + text(ui, lang, "Name", &mut pin.name); + point(ui, lang, "Connection", &mut pin.position); + number(ui, lang, "Angle", &mut pin.angle); + number(ui, lang, "Length", &mut pin.length); + ui.add( + egui::DragValue::new(&mut pin.unit) + .range(1..=32) + .prefix(i18n::t(lang, "Unit ")), + ); + egui::ComboBox::from_id_salt("pin-type") + .selected_text(&pin.electrical_type) + .show_ui(ui, |ui| { + for t in [ + "passive", + "input", + "output", + "bidirectional", + "tri_state", + "power_in", + "power_out", + "open_collector", + "open_emitter", + "no_connect", + ] { + ui.selectable_value( + &mut pin.electrical_type, + t.into(), + t, + ); + } + }); + if ui.button(i18n::t(lang, "Delete pin")).clicked() { + remove = Some(i); + } + }, + ); }); } if let Some(i) = remove { def.pins.remove(i); } ui.separator(); - ui.heading("Drawing"); - if let Some(primitive) = add_graphic(ui, "") { + ui.heading(i18n::t(lang, "Drawing")); + if let Some(primitive) = add_graphic(ui, lang, "") { def.graphics.push(UnitGraphic { unit: self.library.preview_unit.max(1), body_style: 1, @@ -542,17 +582,22 @@ impl App { let mut remove = None; for (i, g) in def.graphics.iter_mut().enumerate().take(256) { ui.push_id(("symbol-graphic", i), |ui| { - ui.collapsing(format!("Graphic {} · unit {}", i + 1, g.unit), |ui| { - ui.add( - egui::DragValue::new(&mut g.unit) - .range(0..=32) - .prefix("Unit (0 shared) "), - ); - graphic(ui, &mut g.primitive); - if ui.button("Delete graphic").clicked() { - remove = Some(i); - } - }); + let i_s = (i + 1).to_string(); + let u_s = g.unit.to_string(); + ui.collapsing( + i18n::tf(lang, "Graphic {} · unit {}", &[&i_s, &u_s]), + |ui| { + ui.add( + egui::DragValue::new(&mut g.unit) + .range(0..=32) + .prefix(i18n::t(lang, "Unit (0 shared) ")), + ); + graphic(ui, lang, &mut g.primitive); + if ui.button(i18n::t(lang, "Delete graphic")).clicked() { + remove = Some(i); + } + }, + ); }); } if let Some(i) = remove { @@ -560,9 +605,9 @@ impl App { } } Draft::Footprint(def) => { - ui.heading("Footprint editor"); - text(ui, "Name", &mut def.name); - text(ui, "Description", &mut def.description); + ui.heading(i18n::t(lang, "Footprint editor")); + text(ui, lang, "Name", &mut def.name); + text(ui, lang, "Description", &mut def.description); self.library_preview(ui, None, Some(def)); if let Err(e) = def.validate() { ui.colored_label(Color32::LIGHT_RED, e.to_string()); @@ -570,12 +615,15 @@ impl App { if let Err(e) = pcbcraft_doc::validate_footprint_support(def) { ui.label(e); } - if ui.button("Save footprint to project library").clicked() { + if ui + .button(i18n::t(lang, "Save footprint to project library")) + .clicked() + { save = Some(("library.footprint.upsert", json!({"definition":def}))); } ui.separator(); - ui.heading("Pads"); - if ui.button("Add pad").clicked() && def.pads.len() < 64 { + ui.heading(i18n::t(lang, "Pads")); + if ui.button(i18n::t(lang, "Add pad")).clicked() && def.pads.len() < 64 { let mut n = 1; while def.pads.iter().any(|p| p.number == n.to_string()) { n += 1; @@ -585,81 +633,97 @@ impl App { let mut remove = None; for (i, pad) in def.pads.iter_mut().enumerate().take(64) { ui.push_id(("pad", i), |ui| { - ui.collapsing(format!("Pad {} · {}", pad.number, pad.pad_type), |ui| { - text(ui, "Number", &mut pad.number); - point(ui, "Position", &mut pad.position); - point(ui, "Copper size", &mut pad.size); - number(ui, "Angle", &mut pad.rotation); - let before = pad.pad_type.clone(); - egui::ComboBox::from_id_salt("pad-type") - .selected_text(&pad.pad_type) - .show_ui(ui, |ui| { - ui.selectable_value( - &mut pad.pad_type, - "smd".into(), - "Front SMD", - ); - ui.selectable_value( - &mut pad.pad_type, - "thru_hole".into(), - "Plated through-hole", - ); - }); - if before != pad.pad_type { - if pad.pad_type == "thru_hole" { - pad.layers = vec!["*.Cu".into(), "*.Mask".into()]; - pad.drill = Some(Drill { - size: Point::new(0.8, 0.8), - offset: Point::default(), + ui.collapsing( + i18n::tf(lang, "Pad {} · {}", &[&pad.number, &pad.pad_type]), + |ui| { + text(ui, lang, "Number", &mut pad.number); + point(ui, lang, "Position", &mut pad.position); + point(ui, lang, "Copper size", &mut pad.size); + number(ui, lang, "Angle", &mut pad.rotation); + let before = pad.pad_type.clone(); + egui::ComboBox::from_id_salt("pad-type") + .selected_text(&pad.pad_type) + .show_ui(ui, |ui| { + ui.selectable_value( + &mut pad.pad_type, + "smd".into(), + i18n::t(lang, "Front SMD"), + ); + ui.selectable_value( + &mut pad.pad_type, + "thru_hole".into(), + i18n::t(lang, "Plated through-hole"), + ); }); - } else { - pad.layers = - vec!["F.Cu".into(), "F.Paste".into(), "F.Mask".into()]; - pad.drill = None; - } - } - egui::ComboBox::from_id_salt("pad-shape") - .selected_text(&pad.shape) - .show_ui(ui, |ui| { - for shape in ["circle", "rect", "oval", "roundrect"] { - ui.selectable_value(&mut pad.shape, shape.into(), shape); + if before != pad.pad_type { + if pad.pad_type == "thru_hole" { + pad.layers = vec!["*.Cu".into(), "*.Mask".into()]; + pad.drill = Some(Drill { + size: Point::new(0.8, 0.8), + offset: Point::default(), + }); + } else { + pad.layers = + vec!["F.Cu".into(), "F.Paste".into(), "F.Mask".into()]; + pad.drill = None; } - }); - if pad.shape == "roundrect" { - ui.add( - egui::DragValue::new(pad.roundrect_ratio.get_or_insert(0.25)) + } + egui::ComboBox::from_id_salt("pad-shape") + .selected_text(&pad.shape) + .show_ui(ui, |ui| { + for shape in ["circle", "rect", "oval", "roundrect"] { + ui.selectable_value( + &mut pad.shape, + shape.into(), + shape, + ); + } + }); + if pad.shape == "roundrect" { + ui.add( + egui::DragValue::new( + pad.roundrect_ratio.get_or_insert(0.25), + ) .range(0.0..=0.5) .speed(0.01) - .prefix("Corner ratio "), - ); - } else { - pad.roundrect_ratio = None; - } - if let Some(drill) = &mut pad.drill { - point(ui, "Drill size (oval if unequal)", &mut drill.size); - point(ui, "Drill offset", &mut drill.offset); - } - ui.label(format!("Layers: {}", pad.layers.join(", "))); - if ui.button("Delete pad").clicked() { - remove = Some(i); - } - }); + .prefix(i18n::t(lang, "Corner ratio ")), + ); + } else { + pad.roundrect_ratio = None; + } + if let Some(drill) = &mut pad.drill { + point( + ui, + lang, + "Drill size (oval if unequal)", + &mut drill.size, + ); + point(ui, lang, "Drill offset", &mut drill.offset); + } + let layers = pad.layers.join(", "); + ui.label(i18n::tf(lang, "Layers: {}", &[&layers])); + if ui.button(i18n::t(lang, "Delete pad")).clicked() { + remove = Some(i); + } + }, + ); }); } if let Some(i) = remove { def.pads.remove(i); } ui.separator(); - ui.heading("Drawing"); - if let Some(g) = add_graphic(ui, "F.SilkS") { + ui.heading(i18n::t(lang, "Drawing")); + if let Some(g) = add_graphic(ui, lang, "F.SilkS") { def.graphics.push(g); } let mut remove = None; for (i, g) in def.graphics.iter_mut().enumerate().take(256) { ui.push_id(("footprint-graphic", i), |ui| { - ui.collapsing(format!("Graphic {}", i + 1), |ui| { - graphic(ui, g); - if ui.button("Delete graphic").clicked() { + let i_s = (i + 1).to_string(); + ui.collapsing(i18n::tf(lang, "Graphic {}", &[&i_s]), |ui| { + graphic(ui, lang, g); + if ui.button(i18n::t(lang, "Delete graphic")).clicked() { remove = Some(i); } }); diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index fceb20683..d1d007aac 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -265,7 +265,7 @@ impl App { } else { self.paint_board(&painter, rect, camera, &visible); } - let text = match &self.tool { + let text = self.tr(match &self.tool { Tool::Select => "SELECT", Tool::Place(_) => "PLACE SYMBOL · CLICK TO COMMIT", Tool::LibraryPlace(..) | Tool::CustomPlace(..) => { @@ -277,7 +277,7 @@ impl App { Tool::Route(Some(_)) => "ROUTE · PICK SECOND PAD", Tool::Move => "MOVE · CLICK TO PLACE SELECTION", Tool::Cutout => "CUTOUT · CLICK TO PLACE", - }; + }); painter.text( rect.left_top() + Vec2::new(20.0, 20.0), Align2::LEFT_TOP, @@ -983,9 +983,13 @@ impl App { painter.text( board.left_bottom() + Vec2::new(0.0, 18.0), Align2::LEFT_TOP, - format!( + self.trf( "{} × {} mm F.Cu / B.Cu clearance {} mm", - p.board.width, p.board.height, p.board.clearance + &[ + &p.board.width.to_string(), + &p.board.height.to_string(), + &p.board.clearance.to_string(), + ], ), FontId::monospace(11.0), self.muted(), diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs new file mode 100644 index 000000000..b384feead --- /dev/null +++ b/crates/ui-egui/src/i18n.rs @@ -0,0 +1,862 @@ +//! Localization (`en` / `he`), BCP 47 tag normalization, and visual RTL helpers for egui 0.36. + +use serde::{Deserialize, Deserializer, Serialize, Serializer}; + +/// Supported UI languages. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Lang { + #[default] + English, + Hebrew, +} + +impl Serialize for Lang { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(self.code()) + } +} + +impl<'de> Deserialize<'de> for Lang { + fn deserialize>(deserializer: D) -> Result { + let raw = String::deserialize(deserializer)?; + let normalized = match raw.trim().to_ascii_lowercase().as_str() { + "english" => Some(Lang::English), + "hebrew" => Some(Lang::Hebrew), + _ => Lang::from_tag(&raw), + }; + Ok(normalized.unwrap_or_default()) + } +} + +impl Lang { + pub const ALL: [Lang; 2] = [Lang::English, Lang::Hebrew]; + + pub const fn code(self) -> &'static str { + match self { + Lang::English => "en", + Lang::Hebrew => "he", + } + } + + pub const fn display_name(self) -> &'static str { + match self { + Lang::English => "English", + Lang::Hebrew => "עברית", + } + } + + pub fn is_rtl(self) -> bool { + is_rtl_code(self.code()) + } + + /// Parses a BCP 47 / POSIX locale tag (normalizing legacy `iw` to Hebrew and rejecting + /// private-use `x-*` subtags). + pub fn from_tag(tag: &str) -> Option { + let clean = strip_posix_suffix(tag) + .replace('_', "-") + .to_ascii_lowercase(); + let mut parts = clean.split('-').filter(|s| !s.is_empty()); + let primary = parts.next()?; + if primary == "x" { + return None; + } + if let Some(script) = script_subtag(&mut parts) { + if script == "hebr" { + return Some(Lang::Hebrew); + } + if script == "latn" && (primary == "he" || primary == "iw") { + return None; + } + } + match primary { + "he" | "iw" => Some(Lang::Hebrew), + "en" => Some(Lang::English), + _ => None, + } + } +} + +fn strip_posix_suffix(tag: &str) -> &str { + tag.trim().split(['.', '@']).next().unwrap_or_default() +} + +fn script_subtag<'a>(parts: &mut impl Iterator) -> Option<&'a str> { + let mut extlangs = 0usize; + for sub in parts { + if sub.len() == 1 { + return None; + } + if sub.len() == 4 && sub.bytes().all(|b| b.is_ascii_alphabetic()) { + return Some(sub); + } + if extlangs < 3 && sub.len() == 3 && sub.bytes().all(|b| b.is_ascii_alphabetic()) { + extlangs += 1; + continue; + } + return None; + } + None +} + +/// Whether `code` names a right-to-left script or language (accepting legacy `iw`, honoring RFC +/// 5646 script position, and rejecting private-use `x-*` subtags). +pub fn is_rtl_code(code: &str) -> bool { + let clean = strip_posix_suffix(code) + .replace('_', "-") + .to_ascii_lowercase(); + let mut parts = clean.split('-').filter(|s| !s.is_empty()); + let Some(primary) = parts.next() else { + return false; + }; + if primary == "x" { + return false; + } + if let Some(script) = script_subtag(&mut parts) { + return matches!( + script, + "arab" + | "hebr" + | "syrc" + | "thaa" + | "nkoo" + | "adlm" + | "mend" + | "rohg" + | "samr" + | "mand" + | "yezi" + ); + } + matches!( + primary, + "ar" | "arc" + | "ckb" + | "dv" + | "fa" + | "he" + | "iw" + | "ji" + | "ps" + | "sd" + | "syr" + | "ug" + | "ur" + | "yi" + ) +} + +fn is_rtl_script(c: char) -> bool { + matches!( + c as u32, + 0x0590..=0x05FF | 0x0600..=0x06FF | 0x0750..=0x077F | 0x08A0..=0x08FF | 0xFB50..=0xFDFF + | 0xFE70..=0xFEFF + ) +} + +fn is_ltr_token_char(c: char) -> bool { + c.is_ascii_alphanumeric() + || matches!( + c, + '_' | '+' + | '-' + | '.' + | '/' + | ':' + | '~' + | '\\' + | '⌘' + | '⌃' + | '⇧' + | '⌥' + | '&' + | '=' + | '|' + ) +} + +fn mirror_bracket(c: char) -> char { + match c { + '(' => ')', + ')' => '(', + '[' => ']', + ']' => '[', + '{' => '}', + '}' => '{', + '<' => '>', + '>' => '<', + other => other, + } +} + +fn mask_atoms(line: &str) -> Vec { + let mut out = Vec::new(); + let chars: Vec<(usize, char)> = line.char_indices().collect(); + let mut i = 0usize; + while i < chars.len() { + let Some(&(start, ch)) = chars.get(i) else { + break; + }; + if ch == '\u{2066}' || ch == '\u{2067}' || ch == '\u{2068}' { + let mut j = i + 1; + let mut depth = 1usize; + while j < chars.len() && depth > 0 { + if let Some(&(_, c)) = chars.get(j) { + if c == '\u{2066}' || c == '\u{2067}' || c == '\u{2068}' { + depth += 1; + } else if c == '\u{2069}' { + depth -= 1; + } + } + j += 1; + } + let inner_start = chars.get(i + 1).map_or(line.len(), |(b, _)| *b); + let inner_end = chars + .get(j - 1) + .filter(|(_, c)| *c == '\u{2069}') + .map_or_else(|| chars.get(j).map_or(line.len(), |(b, _)| *b), |(b, _)| *b); + if let Some(span) = line.get(inner_start..inner_end) { + out.push(span.to_string()); + } + i = j; + continue; + } + if ch.is_whitespace() { + let mut j = i + 1; + while j < chars.len() && chars.get(j).is_some_and(|(_, c)| c.is_whitespace()) { + j += 1; + } + let end = chars.get(j).map_or(line.len(), |(b, _)| *b); + if let Some(seg) = line.get(start..end) { + out.push(seg.to_string()); + } + i = j; + continue; + } + if ch.is_ascii_alphanumeric() + || (matches!(ch, '.' | '/' | '~' | '\\') + && chars + .get(i + 1) + .is_some_and(|(_, next)| next.is_ascii_alphanumeric() || *next == '/')) + || (matches!(ch, '-' | '+') + && chars + .get(i + 1) + .is_some_and(|(_, next)| next.is_ascii_digit())) + { + let mut j = i + 1; + while j < chars.len() { + let Some(&(_, c)) = chars.get(j) else { + break; + }; + if is_ltr_token_char(c) + || (c == ' ' + && chars + .get(j + 1) + .is_some_and(|(_, next)| next.is_ascii_alphanumeric())) + { + j += 1; + } else { + break; + } + } + while j > i + 1 + && chars + .get(j - 1) + .is_some_and(|(_, c)| matches!(c, '.' | ':' | '-' | '/')) + { + j -= 1; + } + let end = chars.get(j).map_or(line.len(), |(b, _)| *b); + if let Some(seg) = line.get(start..end) { + out.push(seg.to_string()); + } + i = j; + continue; + } + if is_rtl_script(ch) { + let mut j = i + 1; + while j < chars.len() + && chars + .get(j) + .is_some_and(|(_, c)| is_rtl_script(*c) || matches!(c, '\'' | '"' | '״' | '׳')) + { + j += 1; + } + if chars.get(j).is_some_and(|(_, c)| *c == '-') + && chars + .get(j + 1) + .is_some_and(|(_, next)| next.is_ascii_alphanumeric()) + { + let mut k = j + 1; + while k < chars.len() && chars.get(k).is_some_and(|(_, c)| is_ltr_token_char(*c)) { + k += 1; + } + while k > j + 1 + && chars + .get(k - 1) + .is_some_and(|(_, c)| matches!(c, '.' | ':' | '-')) + { + k -= 1; + } + let word_end = chars.get(j).map_or(line.len(), |(b, _)| *b); + let suffix_end = chars.get(k).map_or(line.len(), |(b, _)| *b); + if let (Some(w), Some(s)) = + (line.get(start..word_end), line.get(word_end..suffix_end)) + { + out.push(w.to_string()); + out.push(s.to_string()); + } + i = k; + continue; + } + let end = chars.get(j).map_or(line.len(), |(b, _)| *b); + if let Some(seg) = line.get(start..end) { + out.push(seg.to_string()); + } + i = j; + continue; + } + out.push(mirror_bracket(ch).to_string()); + i += 1; + } + out +} + +fn push_visual_rtl_line(line: &str, out: &mut String) { + for tok in mask_atoms(line).into_iter().rev() { + out.push_str(&tok); + } +} + +/// Converts a logical RTL string to visual left-to-right display order for egui 0.36. Lines with +/// no RTL script characters are left untouched. +pub fn visual_rtl(logical: &str) -> String { + if !logical.chars().any(is_rtl_script) { + return logical.to_string(); + } + let mut out = String::with_capacity(logical.len()); + for (idx, raw_line) in logical.split('\n').enumerate() { + if idx > 0 { + out.push('\n'); + } + let (line, cr) = raw_line + .strip_suffix('\r') + .map_or((raw_line, false), |l| (l, true)); + if line.chars().any(is_rtl_script) { + push_visual_rtl_line(line, &mut out); + } else { + out.push_str(line); + } + if cr { + out.push('\r'); + } + } + out +} + +/// Breaks `logical` text at `max_width` first, then applies visual RTL reordering per row. +pub fn wrapped_visual_lines( + ctx: &egui::Context, + rtl: bool, + logical: &str, + font_id: egui::FontId, + max_width: f32, +) -> String { + if !rtl || !logical.chars().any(is_rtl_script) { + return logical.to_owned(); + } + let galley = ctx.fonts_mut(|f| { + f.layout( + logical.to_owned(), + font_id, + Default::default(), + max_width.max(1.0), + ) + }); + let mut out = String::with_capacity(logical.len()); + for (idx, placed) in galley.rows.iter().enumerate() { + if idx > 0 { + out.push('\n'); + } + let row_text = placed.text(); + let trimmed = row_text.trim_end_matches(' '); + if trimmed.chars().any(is_rtl_script) { + push_visual_rtl_line(trimmed, &mut out); + } else { + out.push_str(trimmed); + } + } + out +} + +/// Returns the logical translation of `key` in `lang`. +pub fn t_logical(lang: Lang, key: &'static str) -> &'static str { + if lang == Lang::English { + return key; + } + hebrew(key).unwrap_or(key) +} + +/// Returns the display string for `key` in `lang` (visually reordered when RTL for egui 0.36). +pub fn t(lang: Lang, key: &'static str) -> String { + let logical = t_logical(lang, key); + if lang.is_rtl() { + visual_rtl(logical) + } else { + logical.to_string() + } +} + +/// Substitutes `{}` placeholders sequentially in the logical translation, then applies visual RTL +/// reordering once when `lang.is_rtl()`. +pub fn tf(lang: Lang, key: &'static str, args: &[&str]) -> String { + let mut out = String::new(); + let mut iter = args.iter(); + let mut parts = t_logical(lang, key).split("{}").peekable(); + while let Some(part) = parts.next() { + out.push_str(part); + if parts.peek().is_some() { + out.push_str(iter.next().copied().unwrap_or_default()); + } + } + if lang.is_rtl() { visual_rtl(&out) } else { out } +} + +/// Renders a wrapping label that breaks logical text before visually reordering each display row. +pub fn wrapped_label(ui: &mut egui::Ui, lang: Lang, key: &'static str) { + let logical = t_logical(lang, key); + if !lang.is_rtl() { + ui.label(logical); + return; + } + let font_id = egui::TextStyle::Body.resolve(ui.style()); + let shown = wrapped_visual_lines(ui.ctx(), true, logical, font_id, ui.available_width()); + ui.add(egui::Label::new(shown).extend()); +} + +fn hebrew(key: &str) -> Option<&'static str> { + Some(match key { + "Language" => "שפה", + "Schematic" => "סכמה", + "PCB Layout" => "פריסת PCB", + "Libraries" => "ספריות", + "Checks" => "בדיקות", + "3D Board" => "לוח 3D", + "A real Rust 3D viewer is planned." => "מציג תלת-ממד אמיתי ב-Rust מתוכנן בהמשך.", + "Appearance" => "מראה", + "Save Ctrl+S" => "שמירה Ctrl+S", + "Redo" => "ביצוע חוזר", + "Undo" => "ביטול", + "Select Esc" => "בחירה Esc", + "Add symbol A" => "הוסף סמל A", + "Wire W" => "חיווט W", + "Sync to PCB >" => "סנכרון ל-PCB >", + "Route X" => "ניתוב X", + "Sync schematic" => "סנכרן סכמה", + "Circular cutout" => "חיתוך עגול", + "Move M" => "הזזה M", + "Rotate R" => "סיבוב R", + "Fit" => "התאמה", + "Commands Ctrl+K" => "פקודות Ctrl+K", + "PROJECT" => "פרויקט", + "Add symbol" => "הוסף סמל", + "Browse KiCad libraries →" => "עיון בספריות KiCad →", + "Resistor" => "נגד", + "LED" => "LED", + "Capacitor" => "קבל", + "2-pin connector" => "מחבר 2 פינים", + "COMPONENTS" => "רכיבים", + "Press A to place your first symbol" => "לחץ A להצבת הסמל הראשון שלך", + "NETS" => "רשתות", + "BOARD" => "לוח", + "{} × {} mm" => "{} × {} מ\"מ", + "2 copper layers · 1.6 mm" => "2 שכבות נחושת · 1.6 מ\"מ", + "{} footprints · {} segments" => "{} עקבות · {} מקטעים", + "One project. One window." => "פרויקט אחד. חלון אחד.", + "Scroll to zoom · middle-drag to pan" => "גלול לזום · גרירה אמצעית להזזה", + "Dark" => "כהה", + "Light" => "בהיר", + "Show grid" => "הצג רשת", + "Accent color" => "צבע הדגשה", + "Appearance is saved automatically." => "המראה נשמר אוטומטית.", + "PROPERTIES" => "מאפיינים", + "Unit {}" => "יחידה {}", + "Stable ID {}" => "מזהה יציב {}", + "Value" => "ערך", + "Apply value" => "החל ערך", + "Position · mm" => "מיקום · מ\"מ", + "X" => "X", + "Y" => "Y", + "Apply position" => "החל מיקום", + "Rotate 90° R" => "סובב 90° R", + "Footprint: {}" => "עקבה: {}", + "Footprint: unassigned" => "עקבה: לא משויכת", + "Footprint: starter package" => "עקבה: חבילת התחלה", + "Assign footprint in Libraries →" => "שייך עקבה בספריות →", + "Pin / net" => "פין / רשת", + "unassigned" => "לא משויך", + "Selected object" => "אובייקט נבחר", + "Delete Del" => "מחיקה Del", + "Project settings" => "הגדרות פרויקט", + "Select an item to inspect and edit it." => "בחר פריט כדי לבדוק ולערוך אותו.", + "BOARD GEOMETRY" => "גיאומטריית לוח", + "W" => "רוחב", + "H" => "גובה", + " mm" => " מ\"מ", + "Apply board dimensions" => "החל ממדי לוח", + "Cutout radius" => "רדיוס חיתוך", + "CHECKS" => "בדיקות", + "{} electrical · {} board >" => "{} חשמל · {} לוח >", + "Initial checks; full ERC/DRC is in development." => { + "בדיקות ראשוניות; בדיקות ERC/DRC מלאות בפיתוח." + } + "Ready · A add · W wire · X route · M move · R rotate · E properties" => { + "מוכן · A הוסף · W חוט · X נתיב · M הזז · R סובב · E מאפיינים" + } + "{} · committed" => "{} · אושר", + "{} · complete" => "{} · הושלם", + "operation failed" => "הפעולה נכשלה", + "Session unavailable" => "הסשן אינו זמין", + "{} library symbols need a footprint assignment in Libraries" => { + "{} סמלי ספרייה דורשים שיוך עקבה בספריות" + } + "rev {}" => "מהדורה {}", + "{}, {} mm" => "{}, {} מ\"מ", + "Project file" => "קובץ פרויקט", + "Open" => "פתיחה", + "Save" => "שמירה", + "Export KiCad board" => "ייצוא לוח KiCad", + "LED example" => "דוגמת LED", + "New project" => "פרויקט חדש", + "ENGINE COMMAND" => "פקודת מנוע", + "Execute" => "ביצוע", + "Original starter symbols" => "סמלי פתיחה מקוריים", + "{} · {} · 2 pins" => "{} · {} · 2 פינים", + "Place in schematic >" => "הצב בסכמה >", + "Design checks" => "בדיקות תכנון", + "Select a finding to inspect its affected object in the editor." => { + "בחר ממצא כדי לבדוק את האובייקט המושפע בעורך." + } + "Electrical" => "חשמל", + "Board" => "לוח", + "No findings in the implemented checks" => "לא נמצאו ממצאים בבדיקות המיושמות", + "finding" => "ממצא", + "SELECT" => "בחירה", + "PLACE SYMBOL · CLICK TO COMMIT" => "הצבת סמל · לחץ לאישור", + "PLACE SYMBOL PACKAGE · CLICK TO COMMIT" => "הצבת חבילת סמל · לחץ לאישור", + "WIRE · PICK FIRST PIN" => "חיווט · בחר פין ראשון", + "WIRE · PICK SECOND PIN" => "חיווט · בחר פין שני", + "ROUTE · PICK FIRST PAD" => "ניתוב · בחר פד ראשון", + "ROUTE · PICK SECOND PAD" => "ניתוב · בחר פד שני", + "MOVE · CLICK TO PLACE SELECTION" => "הזזה · לחץ להצבת הבחירה", + "CUTOUT · CLICK TO PLACE" => "חיתוך · לחץ להצבה", + "{} × {} mm F.Cu / B.Cu clearance {} mm" => { + "{} × {} מ\"מ F.Cu / B.Cu מרווח {} מ\"מ" + } + "Start" => "התחלה", + "End" => "סיום", + "Stroke" => "עובי קו", + "Layer" => "שכבה", + "Fill" => "מילוי", + "Center" => "מרכז", + "Radius" => "רדיוס", + "Through" => "דרך", + "Vertex {}" => "קודקוד {}", + "Remaining vertices are preserved." => "הקודקודים הנותרים נשמרים.", + "Add vertex" => "הוסף קודקוד", + "Remove last vertex" => "הסר קודקוד אחרון", + "Position" => "מיקום", + "Text" => "טקסט", + "Text size" => "גודל טקסט", + "Angle" => "זווית", + "Add drawing:" => "הוסף ציור:", + "Line" => "קו", + "Rectangle" => "מלבן", + "Circle" => "עיגול", + "Arc" => "קשת", + "Polyline" => "קו שבור", + "Installed libraries" => "ספריות מותקנות", + "Project library" => "ספריית פרויקט", + "Editor" => "עורך", + "New symbol" => "סמל חדש", + "New footprint" => "עקבה חדשה", + "Editable project library" => "ספריית פרויקט ניתנת לעריכה", + "Saved definitions live in this project. Placed components retain their embedded copies." => { + "הגדרות שמורות נשמרות בפרויקט זה. רכיבים שהוצבו שומרים על העותקים המוטמעים שלהם." + } + "Collection file" => "קובץ אוסף", + "Save library" => "שמור ספרייה", + "Load library" => "טען ספרייה", + "Symbols" => "סמלים", + "{} physical pins" => "{} פינים פיזיים", + "Edit" => "עריכה", + "Place" => "הצבה", + "Remove" => "הסרה", + "Footprints" => "עקבות", + "{} pads" => "{} פדים", + "Assign to selection" => "שייך לבחירה", + "Library editor" => "עורך ספריות", + "Create a symbol or footprint, or edit a copy from the installed/project library." => { + "צור סמל או עקבה, או ערוך עותק מהספרייה המותקנת או מספריית הפרויקט." + } + "Dimensions are millimetres; angles are counterclockwise degrees. Save commits one undoable edit." => { + "הממדים הם במילימטרים; הזוויות במעלות נגד כיוון השעון. שמירה יוצרת עריכה אחת הניתנת לביטול." + } + "Symbol editor" => "עורך סמלים", + "Name" => "שם", + "Reference prefix" => "קידומת ייחוס", + "Default value" => "ערך ברירת מחדל", + "Description" => "תיאור", + "Suggested footprint" => "עקבה מומלצת", + "Preserved unsupported features: {}" => "תכונות לא נתמכות שנשמרו: {}", + "Save symbol to project library" => "שמור סמל בספריית הפרויקט", + "Pins" => "פינים", + "Duplicate preview unit" => "שכפל יחידת תצוגה מקדימה", + "Add pin" => "הוסף פין", + "Pin {} · unit {}" => "פין {} · יחידה {}", + "Number" => "מספר", + "Connection" => "חיבור", + "Length" => "אורך", + "Unit " => "יחידה ", + "Unit (0 shared) " => "יחידה (0 משותף) ", + "Corner ratio " => "יחס פינה ", + "Delete pin" => "מחק פין", + "Drawing" => "ציור", + "Graphic {} · unit {}" => "גרפיקה {} · יחידה {}", + "Delete graphic" => "מחק גרפיקה", + "Footprint editor" => "עורך עקבות", + "Save footprint to project library" => "שמור עקבה בספריית הפרויקט", + "Pads" => "פדים", + "Add pad" => "הוסף פד", + "Pad {} · {}" => "פד {} · {}", + "Copper size" => "גודל נחושת", + "Front SMD" => "SMD קדמי", + "Plated through-hole" => "קדח מצופה", + "Drill size (oval if unequal)" => "גודל קדח (אובלי אם לא שווה)", + "Drill offset" => "היסט קדח", + "Layers: {}" => "שכבות: {}", + "Delete pad" => "מחק פד", + "Graphic {}" => "גרפיקה {}", + "KiCad libraries" => "ספריות KiCad", + "Browse installed libraries · definitions used by a project are embedded on placement." => { + "עיין בספריות מותקנות · הגדרות שבשימוש הפרויקט מוטמעות בעת ההצבה." + } + "Refresh folders" => "רענן תיקיות", + "Choose library" => "בחר ספרייה", + "Library path" => "נתיב ספרייה", + "Search names, descriptions, keywords" => "חפש שמות, תיאורים, מילות מפתח", + "Search" => "חיפוש", + "Reading library…" => "קורא ספרייה…", + "Installed library browsing is available in the desktop build." => { + "עיון בספריות מותקנות זמין בגרסת שולחן העבודה." + } + "Some library folders exceeded the scan limit; use a specific library path." => { + "תיקיות ספרייה מסוימות חרגו ממגבלת הסריקה; השתמש בנתיב ספרייה ספציפי." + } + "{} matches in scanned entries · showing up to 100" => { + "{} התאמות בערכים שנסרקו · מציג עד 100" + } + "Directory scan reached its limit; more entries may exist." => { + "סריקת התיקיות הגיעה למגבלה; ייתכן שקיימים ערכים נוספים." + } + "Original nodes exceed inline editing limits; the source file is preserved." => { + "הצמתים המקוריים חורגים ממגבלות העריכה המוטבעת; קובץ המקור נשמר." + } + "Edit a copy →" => "ערוך עותק →", + "{} pads · {} graphics" => "{} פדים · {} רכיבים גרפיים", + "Pad numbers must match every pin of the selected symbol." => { + "מספרי הפדים חייבים להתאים לכל פין בסמל הנבחר." + } + "Assign to {}" => "שייך אל {}", + "Select a schematic component before assigning its footprint." => { + "בחר רכיב סכמה לפני שיוך העקבה שלו." + } + "{} pins · {} units" => "{} פינים · {} יחידות", + "Suggested footprint: {}" => "עקבה מומלצת: {}", + "Place in schematic →" => "הצב בסכמה →", + "Inspection available; unsupported pin/graphic styles or repeated common pin numbers cannot be placed yet." => { + "הבדיקה זמינה; סגנונות פין/גרפיקה לא נתמכים או מספרי פין חוזרים עדיין לא ניתנים להצבה." + } + "Choose an entry to preview its real geometry." => { + "בחר ערך כדי לראות תצוגה מקדימה של הגיאומטריה." + } + "KiCad libraries: CC-BY-SA 4.0 + design exception" => { + "ספריות KiCad: CC-BY-SA 4.0 + חריג עיצוב" + } + "Placement: single/multi-unit symbols, matching front SMD or plated through-hole packages. Use Edit a copy to customize a definition." => { + "הצבה: סמלים של יחידה אחת או מספר יחידות, התאמת חבילות SMD קדמיות או קדח מצופה. השתמש בערוך עותק להתאמה אישית." + } + "Preview unit" => "יחידת תצוגה מקדימה", + _ => return None, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn bcp47_and_legacy_iw_normalization_and_rtl_detection() { + for tag in ["he", "he-IL", "he_IL.UTF-8", "iw", "iw-IL", "en-Hebr"] { + assert_eq!(Lang::from_tag(tag), Some(Lang::Hebrew), "{tag}"); + assert!(is_rtl_code(tag), "{tag}"); + } + for tag in [ + "x-he", + "en-x-he", + "en-x-arab", + "ar-Latn", + "he-Latn", + "en-US", + ] { + assert!(!is_rtl_code(tag), "{tag}"); + } + assert!(is_rtl_code("zh-Arab-CN")); + assert!(!is_rtl_code("en-u-ca-hebrew")); + assert_eq!(Lang::from_tag("x-he"), None); + assert_eq!(Lang::from_tag("en-x-he"), Some(Lang::English)); + } + + #[test] + fn every_ui_key_translates_and_visual_rtl_keeps_ltr_tokens() { + let keys = [ + "Language", + "Schematic", + "PCB Layout", + "Libraries", + "Checks", + "3D Board", + "A real Rust 3D viewer is planned.", + "Appearance", + "Save Ctrl+S", + "Redo", + "Undo", + "Select Esc", + "Add symbol A", + "Wire W", + "Sync to PCB >", + "Route X", + "Sync schematic", + "Circular cutout", + "Move M", + "Rotate R", + "Fit", + "Commands Ctrl+K", + "PROJECT", + "Add symbol", + "Browse KiCad libraries →", + "Resistor", + "Capacitor", + "2-pin connector", + "COMPONENTS", + "Press A to place your first symbol", + "NETS", + "BOARD", + "{} × {} mm", + "2 copper layers · 1.6 mm", + "{} footprints · {} segments", + "One project. One window.", + "Scroll to zoom · middle-drag to pan", + "Dark", + "Light", + "Show grid", + "Accent color", + "Appearance is saved automatically.", + "PROPERTIES", + "Value", + "Apply value", + "Position · mm", + "Apply position", + "Rotate 90° R", + "Footprint: {}", + "Footprint: unassigned", + "Footprint: starter package", + "Assign footprint in Libraries →", + "Pin / net", + "unassigned", + "Selected object", + "Delete Del", + "Project settings", + "Select an item to inspect and edit it.", + "BOARD GEOMETRY", + "Apply board dimensions", + "Cutout radius", + "CHECKS", + "{} electrical · {} board >", + "Initial checks; full ERC/DRC is in development.", + "Ready · A add · W wire · X route · M move · R rotate · E properties", + "Project file", + "Open", + "Save", + "Export KiCad board", + "LED example", + "New project", + "ENGINE COMMAND", + "Execute", + "Original starter symbols", + "Place in schematic >", + "Design checks", + "Select a finding to inspect its affected object in the editor.", + "Electrical", + "Board", + "No findings in the implemented checks", + "PLACE SYMBOL · CLICK TO COMMIT", + "WIRE · PICK FIRST PIN", + "ROUTE · PICK FIRST PAD", + "Installed libraries", + "Project library", + "Editor", + "New symbol", + "New footprint", + "Save symbol to project library", + "Save footprint to project library", + "KiCad libraries", + "Symbols", + "Footprints", + "Search", + ]; + for key in keys { + let tr = t_logical(Lang::Hebrew, key); + assert_ne!(tr, key, "key {key:?} missing Hebrew translation"); + } + assert_eq!(t(Lang::Hebrew, "Schematic"), "סכמה"); + assert_eq!(t(Lang::Hebrew, "PCB Layout"), "PCB פריסת"); + assert_eq!( + tf(Lang::Hebrew, "Footprint: {}", &["/tmp/R_0603.kicad_mod"]), + "/tmp/R_0603.kicad_mod :עקבה" + ); + assert_eq!( + visual_rtl("מיקום: -12.50, +4.00 מ\"מ"), + "מ\"מ +4.00 ,-12.50 :מיקום" + ); + assert_eq!(visual_rtl("שינוי - בדיקה"), "בדיקה - שינוי"); + assert_eq!( + tf( + Lang::Hebrew, + "Footprint: {}", + &["\u{2066}foo - אב - bar\u{2069}"] + ), + "foo - אב - bar :עקבה" + ); + assert_eq!( + visual_rtl("בדיקה (CSV)\n cargo test\nשורה שנייה"), + "(CSV) בדיקה\n cargo test\nשנייה שורה" + ); + + let ctx = egui::Context::default(); + ctx.run_ui(egui::RawInput::default(), |_| {}) + .textures_delta + .clear(); + let wrapped = wrapped_visual_lines( + &ctx, + true, + t_logical( + Lang::Hebrew, + "Saved definitions live in this project. Placed components retain their embedded copies.", + ), + egui::FontId::proportional(13.0), + 160.0, + ); + let first_row = wrapped.lines().next().unwrap_or_default(); + assert!(first_row.contains("הגדרות"), "got {wrapped:?}"); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 124c89114..04fecd793 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1,6 +1,7 @@ //! One window, shared project, tabbed workspaces. Edits use the engine exclusively. mod authoring; mod canvas; +mod i18n; mod library; use egui::{Align2, Color32, FontId, Rect, Stroke, Vec2}; use pcbcraft_doc::{Id, PinRef, Project, TEMPLATES}; @@ -21,6 +22,8 @@ struct Preferences { dark: bool, grid: bool, accent: [u8; 3], + #[serde(default)] + language: i18n::Lang, } impl Default for Preferences { fn default() -> Self { @@ -28,6 +31,7 @@ impl Default for Preferences { dark: true, grid: true, accent: [91, 224, 188], + language: i18n::Lang::default(), } } } @@ -94,6 +98,7 @@ pub struct App { command_open: bool, capture: Option, frames: u32, + fonts_ready: bool, library: library::Browser, } impl App { @@ -147,6 +152,7 @@ impl App { capture: Option, tab: Option<&str>, ) -> Self { + let lang = preferences.language; let project = session .lock() .map(|s| s.project.clone()) @@ -188,7 +194,10 @@ impl App { drag: None, drag_offset: Point::default(), cursor: None, - message: "Ready · A add · W wire · X route · M move · R rotate · E properties".into(), + message: i18n::t( + lang, + "Ready · A add · W wire · X route · M move · R rotate · E properties", + ), value: String::new(), x: 0.0, y: 0.0, @@ -202,9 +211,79 @@ impl App { command_open: false, capture, frames: 0, + fonts_ready: false, library, } } + fn tr(&self, key: &'static str) -> String { + i18n::t(self.preferences.language, key) + } + fn trf(&self, key: &'static str, args: &[&str]) -> String { + i18n::tf(self.preferences.language, key, args) + } + fn ensure_fonts(&mut self, ctx: &egui::Context) { + if self.fonts_ready { + return; + } + self.fonts_ready = true; + let mut fonts = egui::FontDefinitions::default(); + let mut added = false; + + #[cfg(has_hebrew_craft_font)] + { + const HEBREW_NAME: &str = "Noto Sans Hebrew"; + let bytes = include_bytes!(env!("HEBREW_CRAFT_FONT_PATH")); + fonts.font_data.insert( + HEBREW_NAME.into(), + std::sync::Arc::new(egui::FontData::from_static(bytes)), + ); + append_hebrew_fallback(&mut fonts, HEBREW_NAME); + added = true; + } + + #[cfg(not(target_arch = "wasm32"))] + { + const CANDIDATES: [(&str, &str); 8] = [ + ( + "Arial Hebrew", + "/System/Library/Fonts/Supplemental/Arial Hebrew.ttf", + ), + ("SF Hebrew", "/System/Library/Fonts/SFHebrew.ttf"), + ("Arial Hebrew Local", "/Library/Fonts/Arial Hebrew.ttf"), + ( + "Noto Sans Hebrew", + "/usr/share/fonts/truetype/noto/NotoSansHebrew-Regular.ttf", + ), + ( + "Noto Sans Hebrew Arch", + "/usr/share/fonts/noto/NotoSansHebrew-Regular.ttf", + ), + ( + "DejaVu Sans", + "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", + ), + ("Arial", "C:\\Windows\\Fonts\\arial.ttf"), + ("Segoe UI", "C:\\Windows\\Fonts\\segoeui.ttf"), + ]; + for (name, path) in CANDIDATES { + if fonts.font_data.contains_key(name) { + continue; + } + if let Ok(bytes) = std::fs::read(path) { + fonts.font_data.insert( + name.into(), + std::sync::Arc::new(egui::FontData::from_owned(bytes)), + ); + append_hebrew_fallback(&mut fonts, name); + added = true; + } + } + } + + if added { + ctx.set_fonts(fonts); + } + } fn refresh(&mut self) { let snapshot = self.session.lock().ok().and_then(|s| { if s.revision != self.revision { @@ -229,25 +308,27 @@ impl App { } } fn run(&mut self, command: &str, params: Value) { + let lang = self.preferences.language; let result = self .session .lock() - .map_err(|_| "Session unavailable".to_string()) + .map_err(|_| i18n::t(lang, "Session unavailable")) .and_then(|mut s| { s.execute(command, params, Some(self.revision)) .map_err(|e| e.to_string()) }); match result { Ok(v) => { - self.message = format!("{command} · committed"); + self.message = self.trf("{} · committed", &[command]); if let Some(skipped) = v .pointer("/result/unassigned_components") .and_then(Value::as_array) && !skipped.is_empty() { - self.message = format!( + let count = skipped.len().to_string(); + self.message = self.trf( "{} library symbols need a footprint assignment in Libraries", - skipped.len() + &[&count], ); } if let Some(id) = v.pointer("/result/id").and_then(Value::as_u64) { @@ -265,13 +346,13 @@ impl App { let result = pcbcraft_mcp::call_tool(&self.session, name, &args); let success = result.get("isError").and_then(Value::as_bool) != Some(true); self.message = if success { - format!("{name} · complete") + self.trf("{} · complete", &[name]) } else { result .pointer("/content/0/text") .and_then(Value::as_str) - .unwrap_or("operation failed") - .into() + .map(|s| s.to_string()) + .unwrap_or_else(|| self.tr("operation failed")) }; self.refresh(); if success && (name == "save" || name == "open") { @@ -485,16 +566,16 @@ impl App { ui.label(egui::RichText::new("*").color(self.accent())); } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.button("Appearance").clicked() { + if ui.button(self.tr("Appearance")).clicked() { self.appearance = !self.appearance; } - if ui.button("Save Ctrl+S").clicked() { + if ui.button(self.tr("Save Ctrl+S")).clicked() { self.tool_call("save", json!({"path":self.path})); } - if ui.button("Redo").clicked() { + if ui.button(self.tr("Redo")).clicked() { self.tool_call("redo", json!({})); } - if ui.button("Undo").clicked() { + if ui.button(self.tr("Undo")).clicked() { self.tool_call("undo", json!({})); } ui.label( @@ -507,67 +588,73 @@ impl App { ui.add_space(5.0); ui.horizontal(|ui| { ui.add_space(12.0); - for (tab, label) in [ + for (tab, label_key) in [ (Tab::Schematic, "Schematic"), (Tab::Pcb, "PCB Layout"), (Tab::Libraries, "Libraries"), (Tab::Checks, "Checks"), ] { + let label = self.tr(label_key); + let logical_label = i18n::t_logical(self.preferences.language, label_key); let (_, rect) = ui.allocate_space(Vec2::new(132.0, 30.0)); let selected = self.tab == tab; let accent = self.accent(); let ink = self.ink(); let muted = self.muted(); - let response = craft_ui::tabs::Tab::new(ui.id().with(label), label, selected) - .show_at(ui, rect, |ui, response| { - if selected || response.hovered() { - ui.painter().rect_filled( - rect, - 6.0, - accent.gamma_multiply(if selected { 0.16 } else { 0.08 }), - ); - } - ui.painter().text( - rect.center(), - Align2::CENTER_CENTER, - label, - FontId::proportional(13.0), - if selected { ink } else { muted }, - ); - if selected { - ui.painter().line_segment( - [rect.left_bottom(), rect.right_bottom()], - Stroke::new(2.0, accent), + let response = + craft_ui::tabs::Tab::new(ui.id().with(label_key), logical_label, selected) + .show_at(ui, rect, |ui, response| { + if selected || response.hovered() { + ui.painter().rect_filled( + rect, + 6.0, + accent.gamma_multiply(if selected { 0.16 } else { 0.08 }), + ); + } + ui.painter().text( + rect.center(), + Align2::CENTER_CENTER, + label, + FontId::proportional(13.0), + if selected { ink } else { muted }, ); - } - }); + if selected { + ui.painter().line_segment( + [rect.left_bottom(), rect.right_bottom()], + Stroke::new(2.0, accent), + ); + } + }); if response.clicked() { self.change_tab(tab); } } - ui.add_enabled(false, egui::Button::new("3D Board")) - .on_hover_text("A real Rust 3D viewer is planned."); + ui.add_enabled(false, egui::Button::new(self.tr("3D Board"))) + .on_hover_text(self.tr("A real Rust 3D viewer is planned.")); }); ui.horizontal(|ui| { ui.add_space(12.0); if ui - .selectable_label(matches!(self.tool, Tool::Select), "Select Esc") + .selectable_label(matches!(self.tool, Tool::Select), self.tr("Select Esc")) .clicked() { self.tool = Tool::Select; } match self.tab { Tab::Schematic => { - if ui.button("Add symbol A").clicked() { + if ui.button(self.tr("Add symbol A")).clicked() { self.palette = !self.palette; } if ui - .selectable_label(matches!(self.tool, Tool::Wire(_)), "Wire W") + .selectable_label( + matches!(self.tool, Tool::Wire(_)), + self.tr("Wire W"), + ) .clicked() { self.tool = Tool::Wire(None); } - if ui.button("Sync to PCB >").clicked() { + if ui.button(self.tr("Sync to PCB >")).clicked() { self.run("board.sync", json!({})); self.change_tab(Tab::Pcb); } @@ -589,16 +676,22 @@ impl App { ); }); if ui - .selectable_label(matches!(self.tool, Tool::Route(_)), "Route X") + .selectable_label( + matches!(self.tool, Tool::Route(_)), + self.tr("Route X"), + ) .clicked() { self.tool = Tool::Route(None); } - if ui.button("Sync schematic").clicked() { + if ui.button(self.tr("Sync schematic")).clicked() { self.run("board.sync", json!({})); } if ui - .selectable_label(matches!(self.tool, Tool::Cutout), "Circular cutout") + .selectable_label( + matches!(self.tool, Tool::Cutout), + self.tr("Circular cutout"), + ) .clicked() { self.tool = Tool::Cutout; @@ -606,16 +699,16 @@ impl App { } _ => {} } - if ui.button("Move M").clicked() { + if ui.button(self.tr("Move M")).clicked() { self.tool = Tool::Move; } - if ui.button("Rotate R").clicked() { + if ui.button(self.tr("Rotate R")).clicked() { self.rotate(); } - if ui.button("Fit").clicked() { + if ui.button(self.tr("Fit")).clicked() { self.fit(); } - if ui.button("Commands Ctrl+K").clicked() { + if ui.button(self.tr("Commands Ctrl+K")).clicked() { self.command_open = !self.command_open; } }); @@ -664,20 +757,20 @@ impl App { .show(ui, |ui| { ui.add_space(12.0); ui.label( - egui::RichText::new("PROJECT") + egui::RichText::new(self.tr("PROJECT")) .size(10.0) .color(self.muted()), ); ui.label(egui::RichText::new(&self.project.name).strong()); ui.add_space(12.0); if self.palette { - ui.label(egui::RichText::new("Add symbol").strong()); - if ui.button("Browse KiCad libraries →").clicked() { + ui.label(egui::RichText::new(self.tr("Add symbol")).strong()); + if ui.button(self.tr("Browse KiCad libraries →")).clicked() { self.change_tab(Tab::Libraries); self.palette = false; } for t in TEMPLATES { - if ui.button(t.label).clicked() { + if ui.button(self.tr(t.label)).clicked() { self.change_tab(Tab::Schematic); self.tool = Tool::Place(t.kind.into()); self.palette = false; @@ -686,7 +779,7 @@ impl App { ui.separator(); } ui.label( - egui::RichText::new("COMPONENTS") + egui::RichText::new(self.tr("COMPONENTS")) .size(10.0) .color(self.muted()), ); @@ -714,13 +807,17 @@ impl App { } if self.project.components.is_empty() { ui.label( - egui::RichText::new("Press A to place your first symbol") + egui::RichText::new(self.tr("Press A to place your first symbol")) .small() .color(self.muted()), ); } ui.add_space(20.0); - ui.label(egui::RichText::new("NETS").size(10.0).color(self.muted())); + ui.label( + egui::RichText::new(self.tr("NETS")) + .size(10.0) + .color(self.muted()), + ); for net in &self.project.nets { ui.horizontal(|ui| { ui.label(egui::RichText::new("*").color(self.accent())); @@ -728,26 +825,27 @@ impl App { }); } ui.add_space(20.0); - ui.label(egui::RichText::new("BOARD").size(10.0).color(self.muted())); - ui.label(format!( - "{} × {} mm", - self.project.board.width, self.project.board.height - )); - ui.label("2 copper layers · 1.6 mm"); - ui.label(format!( - "{} footprints · {} segments", - self.project.board.footprints.len(), - self.project.board.tracks.len() - )); + ui.label( + egui::RichText::new(self.tr("BOARD")) + .size(10.0) + .color(self.muted()), + ); + let bw = self.project.board.width.to_string(); + let bh = self.project.board.height.to_string(); + ui.label(self.trf("{} × {} mm", &[&bw, &bh])); + ui.label(self.tr("2 copper layers · 1.6 mm")); + let fp_count = self.project.board.footprints.len().to_string(); + let tr_count = self.project.board.tracks.len().to_string(); + ui.label(self.trf("{} footprints · {} segments", &[&fp_count, &tr_count])); ui.add_space(20.0); ui.separator(); ui.label( - egui::RichText::new("One project. One window.") + egui::RichText::new(self.tr("One project. One window.")) .small() .color(self.muted()), ); ui.label( - egui::RichText::new("Scroll to zoom · middle-drag to pan") + egui::RichText::new(self.tr("Scroll to zoom · middle-drag to pan")) .small() .color(self.muted()), ); @@ -758,23 +856,44 @@ impl App { .default_size(250.0) .min_size(220.0) .show(ui, |ui| { + let lang = self.preferences.language; ui.add_space(12.0); if self.appearance { - ui.heading("Appearance"); + ui.heading(i18n::t(lang, "Appearance")); ui.add_space(12.0); + let dark_label = i18n::t(lang, "Dark"); + let light_label = i18n::t(lang, "Light"); ui.horizontal(|ui| { - ui.selectable_value(&mut self.preferences.dark, true, "Dark"); - ui.selectable_value(&mut self.preferences.dark, false, "Light"); + ui.selectable_value(&mut self.preferences.dark, true, dark_label); + ui.selectable_value(&mut self.preferences.dark, false, light_label); }); - ui.checkbox(&mut self.preferences.grid, "Show grid"); - ui.label("Accent color"); + ui.checkbox(&mut self.preferences.grid, i18n::t(lang, "Show grid")); + ui.label(i18n::t(lang, "Accent color")); ui.color_edit_button_srgb(&mut self.preferences.accent); + ui.add_space(10.0); + ui.label(i18n::t(lang, "Language")); + ui.horizontal(|ui| { + let before = self.preferences.language; + for choice in i18n::Lang::ALL { + ui.selectable_value( + &mut self.preferences.language, + choice, + choice.display_name(), + ); + } + if self.preferences.language != before { + self.message = i18n::t( + self.preferences.language, + "Ready · A add · W wire · X route · M move · R rotate · E properties", + ); + } + }); ui.add_space(16.0); - ui.label("Appearance is saved automatically."); + i18n::wrapped_label(ui, self.preferences.language, "Appearance is saved automatically."); return; } ui.label( - egui::RichText::new("PROPERTIES") + egui::RichText::new(i18n::t(lang, "PROPERTIES")) .size(10.0) .color(self.muted()), ); @@ -789,16 +908,18 @@ impl App { ui.heading(&c.reference); if !c.units.is_empty() && self.project.component(id).is_some() { let before = self.selected_unit; + let unit_s = self.selected_unit.to_string(); egui::ComboBox::from_id_salt("selected-symbol-unit") - .selected_text(format!("Unit {}", self.selected_unit)) + .selected_text(i18n::tf(lang, "Unit {}", &[&unit_s])) .show_ui(ui, |ui| { for unit in std::iter::once(1).chain(c.units.iter().map(|u| u.unit)) { + let u_s = unit.to_string(); ui.selectable_value( &mut self.selected_unit, unit, - format!("Unit {unit}"), + i18n::tf(lang, "Unit {}", &[&u_s]), ); } }); @@ -807,26 +928,27 @@ impl App { } } ui.label(&c.kind); + let id_s = id.to_string(); ui.label( - egui::RichText::new(format!("Stable ID {id}")) + egui::RichText::new(self.trf("Stable ID {}", &[&id_s])) .small() .color(self.muted()), ); ui.add_space(10.0); - ui.label("Value"); + ui.label(self.tr("Value")); ui.text_edit_singleline(&mut self.value); - if ui.button("Apply value").clicked() { + if ui.button(self.tr("Apply value")).clicked() { self.run("component.value", json!({"id":c.id,"value":self.value})); } ui.add_space(12.0); - ui.label("Position · mm"); + ui.label(self.tr("Position · mm")); ui.horizontal(|ui| { ui.label("X"); ui.add(egui::DragValue::new(&mut self.x).speed(0.1)); ui.label("Y"); ui.add(egui::DragValue::new(&mut self.y).speed(0.1)); }); - if ui.button("Apply position").clicked() { + if ui.button(self.tr("Apply position")).clicked() { let mut params = json!({"id":id,"position":{"x":self.x,"y":self.y}}); if self.project.component(id).is_some() { params["unit"] = json!(self.selected_unit); @@ -840,22 +962,22 @@ impl App { params, ); } - if ui.button("Rotate 90° R").clicked() { + if ui.button(self.tr("Rotate 90° R")).clicked() { self.rotate(); } ui.label( c.library_footprint .as_ref() - .map(|f| format!("Footprint: {}", f.definition.name)) + .map(|f| self.trf("Footprint: {}", &[&f.definition.name])) .unwrap_or_else(|| { if c.library_symbol.is_some() { - "Footprint: unassigned".into() + self.tr("Footprint: unassigned") } else { - "Footprint: starter package".into() + self.tr("Footprint: starter package") } }), ); - if ui.button("Assign footprint in Libraries →").clicked() { + if ui.button(self.tr("Assign footprint in Libraries →")).clicked() { self.change_tab(Tab::Libraries); self.library.kind = true; self.library.pending = None; @@ -865,68 +987,75 @@ impl App { self.library.query.clear(); } ui.add_space(12.0); - ui.label("Pin / net"); + ui.label(self.tr("Pin / net")); + let unassigned = self.tr("unassigned"); for pin in &c.pins { ui.label(format!( "{} · {}", pin.number, pin.net .map(|n| self.project.net_name(n)) - .unwrap_or("unassigned") + .unwrap_or(&unassigned) )); } } else { - ui.heading("Selected object"); - ui.label(format!("Stable ID {id}")); + ui.heading(self.tr("Selected object")); + let id_s = id.to_string(); + ui.label(self.trf("Stable ID {}", &[&id_s])); } ui.add_space(10.0); - if ui.button("Delete Del").clicked() { + if ui.button(self.tr("Delete Del")).clicked() { self.run("object.delete", json!({"id":id})); self.select(None); } ui.separator(); } else { - ui.heading("Project settings"); - ui.label("Select an item to inspect and edit it."); + ui.heading(self.tr("Project settings")); + i18n::wrapped_label(ui, self.preferences.language, "Select an item to inspect and edit it."); ui.add_space(12.0); } ui.label( - egui::RichText::new("BOARD GEOMETRY") + egui::RichText::new(self.tr("BOARD GEOMETRY")) .size(10.0) .color(self.muted()), ); + let mm_suffix = self.tr(" mm"); ui.horizontal(|ui| { - ui.label("W"); + ui.label(self.tr("W")); ui.add( egui::DragValue::new(&mut self.width) .speed(0.5) - .suffix(" mm"), + .suffix(mm_suffix.clone()), ); }); ui.horizontal(|ui| { - ui.label("H"); + ui.label(self.tr("H")); ui.add( egui::DragValue::new(&mut self.height) .speed(0.5) - .suffix(" mm"), + .suffix(mm_suffix.clone()), ); }); - if ui.button("Apply board dimensions").clicked() { + if ui.button(self.tr("Apply board dimensions")).clicked() { self.run( "board.resize", json!({"width":self.width,"height":self.height}), ); } ui.horizontal(|ui| { - ui.label("Cutout radius"); + ui.label(self.tr("Cutout radius")); ui.add( egui::DragValue::new(&mut self.cutout_radius) .speed(0.1) - .suffix(" mm"), + .suffix(mm_suffix), ); }); ui.add_space(12.0); - ui.label(egui::RichText::new("CHECKS").size(10.0).color(self.muted())); + ui.label( + egui::RichText::new(self.tr("CHECKS")) + .size(10.0) + .color(self.muted()), + ); let erc = self .checks .get("erc") @@ -939,14 +1068,16 @@ impl App { .and_then(Value::as_array) .map(Vec::len) .unwrap_or(0); + let erc_s = erc.to_string(); + let drc_s = drc.to_string(); if ui - .button(format!("{erc} electrical · {drc} board >")) + .button(self.trf("{} electrical · {} board >", &[&erc_s, &drc_s])) .clicked() { self.change_tab(Tab::Checks); } ui.label( - egui::RichText::new("Initial checks; full ERC/DRC is in development.") + egui::RichText::new(self.tr("Initial checks; full ERC/DRC is in development.")) .small() .color(self.muted()), ); @@ -961,14 +1092,17 @@ impl App { .color(self.muted()), ); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let rev_s = self.revision.to_string(); ui.label( - egui::RichText::new(format!("rev {}", self.revision)) + egui::RichText::new(self.trf("rev {}", &[&rev_s])) .small() .color(self.muted()), ); if let Some(p) = self.cursor { + let px = format!("{:.2}", p.x); + let py = format!("{:.2}", p.y); ui.label( - egui::RichText::new(format!("{:.2}, {:.2} mm", p.x, p.y)) + egui::RichText::new(self.trf("{}, {} mm", &[&px, &py])) .small() .color(self.muted()), ); @@ -978,26 +1112,26 @@ impl App { }); egui::Panel::bottom("files").show(ui, |ui| { ui.horizontal(|ui| { - ui.label("Project file"); + ui.label(self.tr("Project file")); ui.add(egui::TextEdit::singleline(&mut self.path).desired_width(260.0)); - if ui.button("Open").clicked() { + if ui.button(self.tr("Open")).clicked() { self.tool_call("open", json!({"path":self.path})); } - if ui.button("Save").clicked() { + if ui.button(self.tr("Save")).clicked() { self.tool_call("save", json!({"path":self.path})); } - if ui.button("Export KiCad board").clicked() { + if ui.button(self.tr("Export KiCad board")).clicked() { let path = std::path::Path::new(&self.path) .with_extension("kicad_pcb") .to_string_lossy() .into_owned(); self.tool_call("export", json!({"path":path,"format":"kicad_pcb"})); } - if ui.button("LED example").clicked() { + if ui.button(self.tr("LED example")).clicked() { self.tool_call("sample_design", json!({})); self.fit(); } - if ui.button("New project").clicked() { + if ui.button(self.tr("New project")).clicked() { self.tool_call("new_design", json!({})); self.select(None); } @@ -1010,13 +1144,13 @@ impl App { .show(ui, |ui| { ui.horizontal(|ui| { ui.label( - egui::RichText::new("ENGINE COMMAND") + egui::RichText::new(self.tr("ENGINE COMMAND")) .small() .color(self.accent()), ); ui.text_edit_singleline(&mut self.command); ui.add(egui::TextEdit::singleline(&mut self.params).desired_width(500.0)); - if ui.button("Execute").clicked() { + if ui.button(self.tr("Execute")).clicked() { match serde_json::from_str(&self.params) { Ok(v) => self.run(&self.command.clone(), v), Err(e) => self.message = e.to_string(), @@ -1044,20 +1178,20 @@ impl App { } fn library(&mut self, ui: &mut egui::Ui) { self.library_workspaces(ui); - ui.collapsing("Original starter symbols", |ui| { + ui.collapsing(self.tr("Original starter symbols"), |ui| { for t in TEMPLATES { egui::Frame::group(ui.style()) .inner_margin(18.0) .show(ui, |ui| { ui.horizontal(|ui| { ui.vertical(|ui| { - ui.label(egui::RichText::new(t.label).size(18.0).strong()); - ui.label(format!("{} · {} · 2 pins", t.prefix, t.value)); + ui.label(egui::RichText::new(self.tr(t.label)).size(18.0).strong()); + ui.label(self.trf("{} · {} · 2 pins", &[t.prefix, t.value])); }); ui.with_layout( egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.button("Place in schematic >").clicked() { + if ui.button(self.tr("Place in schematic >")).clicked() { self.change_tab(Tab::Schematic); self.tool = Tool::Place(t.kind.into()); } @@ -1071,23 +1205,30 @@ impl App { } fn checks_view(&mut self, ui: &mut egui::Ui) { ui.add_space(24.0); - ui.heading("Design checks"); - ui.label("Select a finding to inspect its affected object in the editor."); + ui.heading(self.tr("Design checks")); + i18n::wrapped_label( + ui, + self.preferences.language, + "Select a finding to inspect its affected object in the editor.", + ); ui.add_space(16.0); let checks = self.checks.clone(); - for (key, label) in [("erc", "Electrical"), ("drc", "Board")] { - ui.label(egui::RichText::new(label).size(18.0).strong()); + for (key, label_key) in [("erc", "Electrical"), ("drc", "Board")] { + ui.label(egui::RichText::new(self.tr(label_key)).size(18.0).strong()); if let Some(findings) = checks.get(key).and_then(Value::as_array) { if findings.is_empty() { ui.label( - egui::RichText::new("No findings in the implemented checks") + egui::RichText::new(self.tr("No findings in the implemented checks")) .color(self.accent()), ); } + let default_finding = self.tr("finding"); for f in findings { let text = format!( "{} {}", - f.get("code").and_then(Value::as_str).unwrap_or("finding"), + f.get("code") + .and_then(Value::as_str) + .unwrap_or(&default_finding), f.get("message").and_then(Value::as_str).unwrap_or("") ); if ui.button(text).clicked() @@ -1157,6 +1298,7 @@ impl App { fn show(&mut self, ui: &mut egui::Ui) { let ctx = ui.ctx().clone(); self.refresh(); + self.ensure_fonts(&ctx); self.style(&ctx); self.shortcuts(&ctx); self.header(ui); @@ -1196,6 +1338,15 @@ impl eframe::App for App { } } } +fn append_hebrew_fallback(fonts: &mut egui::FontDefinitions, name: &str) { + for family in [egui::FontFamily::Proportional, egui::FontFamily::Monospace] { + if let Some(list) = fonts.families.get_mut(&family) + && !list.iter().any(|existing| existing == name) + { + list.push(name.to_owned()); + } + } +} fn pcbcraft_io_limit() -> usize { 8 * 1024 * 1024 } @@ -1385,4 +1536,68 @@ mod tests { ); Ok(()) } + #[test] + fn preferences_preserve_legacy_defaults_and_hebrew_round_trip() -> Result<(), String> { + let legacy: Preferences = + serde_json::from_str(r#"{"dark":false,"grid":true,"accent":[1,2,3]}"#) + .map_err(|e| e.to_string())?; + assert_eq!(legacy.language, i18n::Lang::English); + let iw: Preferences = + serde_json::from_str(r#"{"dark":true,"grid":true,"accent":[1,2,3],"language":"iw"}"#) + .map_err(|e| e.to_string())?; + assert_eq!(iw.language, i18n::Lang::Hebrew); + let priv_use: Preferences = + serde_json::from_str(r#"{"dark":true,"grid":true,"accent":[1,2,3],"language":"x-he"}"#) + .map_err(|e| e.to_string())?; + assert_eq!(priv_use.language, i18n::Lang::English); + let he = Preferences { + language: i18n::Lang::Hebrew, + ..Preferences::default() + }; + let decoded: Preferences = + serde_json::from_str(&serde_json::to_string(&he).map_err(|e| e.to_string())?) + .map_err(|e| e.to_string())?; + assert_eq!(decoded.language, i18n::Lang::Hebrew); + Ok(()) + } + #[test] + fn hebrew_ui_renders_rtl_labels_across_tabs() -> Result<(), String> { + let shared = + pcbcraft_mcp::shared(pcbcraft_engine::Session::sample().map_err(|e| e.to_string())?); + let prefs = Preferences { + language: i18n::Lang::Hebrew, + ..Preferences::default() + }; + let mut app = App::create(shared, prefs, None, None); + app.refresh(); + app.appearance = true; + let ctx = egui::Context::default(); + let output = frame(&ctx, &mut app, vec![], egui::Modifiers::NONE); + let painted: String = output + .shapes + .iter() + .filter_map(|s| match &s.shape { + egui::Shape::Text(t) => Some(t.galley.text()), + _ => None, + }) + .collect::>() + .join("\n"); + assert!( + painted.contains("סכמה"), + "missing Hebrew Schematic tab: {painted}" + ); + assert!( + painted.contains("PCB פריסת"), + "missing visual RTL PCB Layout tab: {painted}" + ); + assert!( + painted.contains("שפה"), + "missing Language label in Appearance panel: {painted}" + ); + assert!( + painted.contains("עברית"), + "missing עברית button in Appearance panel: {painted}" + ); + Ok(()) + } } diff --git a/crates/ui-egui/src/library.rs b/crates/ui-egui/src/library.rs index a14091350..c59b084e0 100644 --- a/crates/ui-egui/src/library.rs +++ b/crates/ui-egui/src/library.rs @@ -73,17 +73,20 @@ impl App { if self.library.catalog.is_none() && self.library.pending.is_none() { self.library.request(ui.ctx(), "library.catalog", json!({})); } - ui.heading("KiCad libraries"); - ui.label( + ui.heading(self.tr("KiCad libraries")); + i18n::wrapped_label( + ui, + self.preferences.language, "Browse installed libraries · definitions used by a project are embedded on placement.", ); let busy = self.library.pending.is_some(); let before = self.library.kind; + let lang = self.preferences.language; ui.add_enabled_ui(!busy, |ui| { ui.horizontal(|ui| { - ui.selectable_value(&mut self.library.kind, false, "Symbols"); - ui.selectable_value(&mut self.library.kind, true, "Footprints"); - if ui.button("Refresh folders").clicked() { + ui.selectable_value(&mut self.library.kind, false, i18n::t(lang, "Symbols")); + ui.selectable_value(&mut self.library.kind, true, i18n::t(lang, "Footprints")); + if ui.button(i18n::t(lang, "Refresh folders")).clicked() { self.library.catalog = None; self.library.path.clear(); self.library.results = None; @@ -128,10 +131,11 @@ impl App { } } ui.add_enabled_ui(!busy, |ui| { + let choose = self.tr("Choose library"); let label = std::path::Path::new(&self.library.path) .file_stem() .and_then(|s| s.to_str()) - .unwrap_or("Choose library"); + .unwrap_or(&choose); egui::ComboBox::from_id_salt("kicad-library") .selected_text(label) .width(300.0) @@ -148,16 +152,16 @@ impl App { } }); ui.horizontal(|ui| { - ui.label("Library path"); + ui.label(self.tr("Library path")); ui.add(egui::TextEdit::singleline(&mut self.library.path).desired_width(480.0)); }); ui.horizontal(|ui| { let response = ui.add( egui::TextEdit::singleline(&mut self.library.query) - .hint_text("Search names, descriptions, keywords") + .hint_text(i18n::t(lang, "Search names, descriptions, keywords")) .desired_width(360.0), ); - if ui.button("Search").clicked() + if ui.button(i18n::t(lang, "Search")).clicked() || (response.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter))) { changed = true; @@ -170,11 +174,22 @@ impl App { if busy { ui.horizontal(|ui| { ui.spinner(); - ui.label("Reading library…"); + ui.label(self.tr("Reading library…")); }); } if !self.library.error.is_empty() { - ui.colored_label(Color32::from_rgb(237, 135, 113), &self.library.error); + let shown = self.tr(match self.library.error.as_str() { + "Installed library browsing is available in the desktop build." => { + "Installed library browsing is available in the desktop build." + } + _ => "", + }); + let err_text = if shown.is_empty() { + self.library.error.as_str() + } else { + shown.as_str() + }; + ui.colored_label(Color32::from_rgb(237, 135, 113), err_text); } let results = self.library.results.clone().unwrap_or(json!({})); if self @@ -185,62 +200,236 @@ impl App { .and_then(Value::as_bool) == Some(true) { - ui.label("Some library folders exceeded the scan limit; use a specific library path."); + i18n::wrapped_label( + ui, + self.preferences.language, + "Some library folders exceeded the scan limit; use a specific library path.", + ); } - ui.columns(2,|cols| { - let left=&mut cols[0]; - if let Some(total)=results.get("total").and_then(Value::as_u64) {left.label(format!("{total} matches in scanned entries · showing up to 100"));} - if results.get("scan_truncated").and_then(Value::as_bool)==Some(true) {left.label("Directory scan reached its limit; more entries may exist.");} - egui::ScrollArea::vertical().id_salt("library-results").max_height(360.0).show(left,|ui| { - for item in results.get("entries").and_then(Value::as_array).into_iter().flatten() { - let name=item.get("name").and_then(Value::as_str).unwrap_or(""); - if ui.add_enabled(!busy,egui::Button::new(name).selected(self.library.preview.as_ref().and_then(|v|v.pointer("/definition/name")).and_then(Value::as_str)==Some(name))).clicked() { - self.library.preview=None; - let path=item.get("path").and_then(Value::as_str).unwrap_or(&self.library.path); - let (tool,args)=if self.library.kind {("library.inspect_footprint",json!({"path":path,"include_source":true}))} else {("library.inspect_symbol",json!({"path":path,"name":name,"include_source":true}))}; - self.library.request(ui.ctx(),tool,args); + let lang = self.preferences.language; + ui.columns(2, |cols| { + let left = &mut cols[0]; + if let Some(total) = results.get("total").and_then(Value::as_u64) { + let total_s = total.to_string(); + left.label(i18n::tf( + lang, + "{} matches in scanned entries · showing up to 100", + &[&total_s], + )); + } + if results.get("scan_truncated").and_then(Value::as_bool) == Some(true) { + left.label(i18n::t( + lang, + "Directory scan reached its limit; more entries may exist.", + )); + } + egui::ScrollArea::vertical() + .id_salt("library-results") + .max_height(360.0) + .show(left, |ui| { + for item in results + .get("entries") + .and_then(Value::as_array) + .into_iter() + .flatten() + { + let name = item.get("name").and_then(Value::as_str).unwrap_or(""); + if ui + .add_enabled( + !busy, + egui::Button::new(name).selected( + self.library + .preview + .as_ref() + .and_then(|v| v.pointer("/definition/name")) + .and_then(Value::as_str) + == Some(name), + ), + ) + .clicked() + { + self.library.preview = None; + let path = item + .get("path") + .and_then(Value::as_str) + .unwrap_or(&self.library.path); + let (tool, args) = if self.library.kind { + ( + "library.inspect_footprint", + json!({"path":path,"include_source":true}), + ) + } else { + ( + "library.inspect_symbol", + json!({"path":path,"name":name,"include_source":true}), + ) + }; + self.library.request(ui.ctx(), tool, args); + } } + }); + let right = &mut cols[1]; + if let Some(preview) = self.library.preview.clone() { + let path = preview + .get("path") + .and_then(Value::as_str) + .unwrap_or("") + .to_owned(); + if preview.get("source_truncated").and_then(Value::as_bool) == Some(true) { + i18n::wrapped_label( + right, + lang, + "Original nodes exceed inline editing limits; the source file is preserved.", + ); } - }); - let right=&mut cols[1]; - if let Some(preview)=self.library.preview.clone() { - let path=preview.get("path").and_then(Value::as_str).unwrap_or("").to_owned(); - if preview.get("source_truncated").and_then(Value::as_bool)==Some(true) {right.label("Original nodes exceed inline editing limits; the source file is preserved.");} if self.library.kind { - if let Some(def)=preview.get("definition").and_then(|v|serde_json::from_value::(v.clone()).ok()) { - right.heading(&def.name);right.label(&def.description); - if right.add_enabled(preview.get("source_truncated").and_then(Value::as_bool)!=Some(true),egui::Button::new("Edit a copy →")).clicked() {let mut copy=def.clone();copy.name.push_str("_custom");self.library.editor.notice=Some(format!("Edited copy of {} from {}. KiCad-derived data credits the KiCad community contributors; custom sources retain their original license. Official collections: https://gitlab.com/kicad/libraries/kicad-symbols and https://gitlab.com/kicad/libraries/kicad-footprints.\n{}",def.name,path,include_str!("../../library/tests/fixtures/LICENSE-kicad-libraries.md")));self.library.editor.draft=Some(super::authoring::Draft::Footprint(copy));self.library.editor.mode=2;} - self.library_preview(right,None,Some(&def)); - right.label(format!("{} pads · {} graphics",def.pads.len(),def.graphics.len())); - let supported=pcbcraft_doc::validate_footprint_support(&def); - if let Err(e)=&supported {right.label(e);} - let component=self.selected.and_then(|id|self.project.component(id)).map(|c|(c.id,c.reference.clone())); - if let Some((id,reference))=component { - let matches=self.project.component(id).is_some_and(|c|c.pins.iter().map(|p|p.number.as_str()).collect::>()==def.pads.iter().map(|p|p.number.as_str()).collect::>()); - if !matches {right.label("Pad numbers must match every pin of the selected symbol.");} - if right.add_enabled(supported.is_ok() && matches,egui::Button::new(format!("Assign to {reference}"))).clicked() {self.run("footprint.assign",json!({"id":id,"path":path}));} - } else {right.label("Select a schematic component before assigning its footprint.");} + if let Some(def) = preview + .get("definition") + .and_then(|v| serde_json::from_value::(v.clone()).ok()) + { + right.heading(&def.name); + right.label(&def.description); + if right + .add_enabled( + preview.get("source_truncated").and_then(Value::as_bool) + != Some(true), + egui::Button::new(i18n::t(lang, "Edit a copy →")), + ) + .clicked() + { + let mut copy = def.clone(); + copy.name.push_str("_custom"); + self.library.editor.notice = Some(format!( + "Edited copy of {} from {}. KiCad-derived data credits the KiCad community contributors; custom sources retain their original license. Official collections: https://gitlab.com/kicad/libraries/kicad-symbols and https://gitlab.com/kicad/libraries/kicad-footprints.\n{}", + def.name, + path, + include_str!("../../library/tests/fixtures/LICENSE-kicad-libraries.md") + )); + self.library.editor.draft = Some(super::authoring::Draft::Footprint(copy)); + self.library.editor.mode = 2; + } + self.library_preview(right, None, Some(&def)); + let pads_s = def.pads.len().to_string(); + let gfx_s = def.graphics.len().to_string(); + right.label(i18n::tf(lang, "{} pads · {} graphics", &[&pads_s, &gfx_s])); + let supported = pcbcraft_doc::validate_footprint_support(&def); + if let Err(e) = &supported { + right.label(e); + } + let component = self + .selected + .and_then(|id| self.project.component(id)) + .map(|c| (c.id, c.reference.clone())); + if let Some((id, reference)) = component { + let matches = self.project.component(id).is_some_and(|c| { + c.pins + .iter() + .map(|p| p.number.as_str()) + .collect::>() + == def + .pads + .iter() + .map(|p| p.number.as_str()) + .collect::>() + }); + if !matches { + i18n::wrapped_label( + right, + lang, + "Pad numbers must match every pin of the selected symbol.", + ); + } + if right + .add_enabled( + supported.is_ok() && matches, + egui::Button::new(i18n::tf(lang, "Assign to {}", &[&reference])), + ) + .clicked() + { + self.run("footprint.assign", json!({"id":id,"path":path})); + } + } else { + i18n::wrapped_label( + right, + lang, + "Select a schematic component before assigning its footprint.", + ); + } + } + } else if let Some(def) = preview + .get("definition") + .and_then(|v| serde_json::from_value::(v.clone()).ok()) + { + right.heading(&def.name); + right.label(&def.description); + if right + .add_enabled( + preview.get("source_truncated").and_then(Value::as_bool) != Some(true), + egui::Button::new(i18n::t(lang, "Edit a copy →")), + ) + .clicked() + { + let mut copy = def.clone(); + copy.name.push_str("_custom"); + self.library.editor.notice = Some(format!( + "Edited copy of {} from {}. KiCad-derived data credits the KiCad community contributors; custom sources retain their original license. Official collections: https://gitlab.com/kicad/libraries/kicad-symbols and https://gitlab.com/kicad/libraries/kicad-footprints.\n{}", + def.name, + path, + include_str!("../../library/tests/fixtures/LICENSE-kicad-libraries.md") + )); + self.library.editor.draft = Some(super::authoring::Draft::Symbol(copy)); + self.library.editor.mode = 2; } - } else if let Some(def)=preview.get("definition").and_then(|v|serde_json::from_value::(v.clone()).ok()) { - right.heading(&def.name);right.label(&def.description); - if right.add_enabled(preview.get("source_truncated").and_then(Value::as_bool)!=Some(true),egui::Button::new("Edit a copy →")).clicked() {let mut copy=def.clone();copy.name.push_str("_custom");self.library.editor.notice=Some(format!("Edited copy of {} from {}. KiCad-derived data credits the KiCad community contributors; custom sources retain their original license. Official collections: https://gitlab.com/kicad/libraries/kicad-symbols and https://gitlab.com/kicad/libraries/kicad-footprints.\n{}",def.name,path,include_str!("../../library/tests/fixtures/LICENSE-kicad-libraries.md")));self.library.editor.draft=Some(super::authoring::Draft::Symbol(copy));self.library.editor.mode=2;} - self.library_preview(right,Some(&def),None); - let supported=pcbcraft_doc::library_component(def.clone(),"preview".into(),0,"preview".into(),Point::default(),None).is_ok(); - right.label(format!("{} pins · {} units",def.pins.len(),def.pins.iter().map(|p|p.unit).max().unwrap_or(1))); - right.label(format!("Suggested footprint: {}",def.footprint)); - if right.add_enabled(supported,egui::Button::new("Place in schematic →")).clicked() { - self.change_tab(Tab::Schematic);self.tool=Tool::LibraryPlace(path,def.name.clone(),Box::new(def)); + self.library_preview(right, Some(&def), None); + let supported = pcbcraft_doc::library_component( + def.clone(), + "preview".into(), + 0, + "preview".into(), + Point::default(), + None, + ) + .is_ok(); + let pins_s = def.pins.len().to_string(); + let units_s = def.pins.iter().map(|p| p.unit).max().unwrap_or(1).to_string(); + right.label(i18n::tf(lang, "{} pins · {} units", &[&pins_s, &units_s])); + right.label(i18n::tf(lang, "Suggested footprint: {}", &[&def.footprint])); + if right + .add_enabled( + supported, + egui::Button::new(i18n::t(lang, "Place in schematic →")), + ) + .clicked() + { + self.change_tab(Tab::Schematic); + self.tool = Tool::LibraryPlace(path, def.name.clone(), Box::new(def)); + } + if !supported { + i18n::wrapped_label( + right, + lang, + "Inspection available; unsupported pin/graphic styles or repeated common pin numbers cannot be placed yet.", + ); } - if !supported {right.label("Inspection available; unsupported pin/graphic styles or repeated common pin numbers cannot be placed yet.");} } - } else {right.label("Choose an entry to preview its real geometry.");} + } else { + i18n::wrapped_label( + right, + lang, + "Choose an entry to preview its real geometry.", + ); + } }); ui.separator(); ui.hyperlink_to( - "KiCad libraries: CC-BY-SA 4.0 + design exception", + self.tr("KiCad libraries: CC-BY-SA 4.0 + design exception"), "https://www.kicad.org/libraries/license/", ); - ui.label("Placement: single/multi-unit symbols, matching front SMD or plated through-hole packages. Use Edit a copy to customize a definition."); + i18n::wrapped_label( + ui, + self.preferences.language, + "Placement: single/multi-unit symbols, matching front SMD or plated through-hole packages. Use Edit a copy to customize a definition.", + ); } pub(super) fn library_preview( &mut self, @@ -259,7 +448,7 @@ impl App { } if units.len() > 1 { ui.horizontal_wrapped(|ui| { - ui.label("Preview unit"); + ui.label(self.tr("Preview unit")); for unit in units { ui.selectable_value(&mut self.library.preview_unit, unit, unit.to_string()); }