From ff9dcc4ef7b5f9fcf2465402364610fc10512ef8 Mon Sep 17 00:00:00 2001 From: Nils Schlemminger Date: Wed, 21 Oct 2026 16:44:20 +0200 Subject: [PATCH] Add multi-language support (English, German, French, Spanish) - New crate openecraft-i18n: language state, tr / tr_fmt! / tr_const! lookup and a tab separated translation catalog (~900 texts) - Translate the editor and the parts manager UI, generated reports, check messages, title block labels and built-in symbol names - View > Language menu (editor) and language menu (parts manager); choice is persisted, default is the OS / browser language - Tests: catalog completeness, placeholders, source coverage, glyphs of translations, and no untranslated widget literals - AGENTS.md: all features must be available in all four languages --- AGENTS.md | 35 +- Cargo.lock | 7 + Cargo.toml | 7 +- README.md | 3 + crates/openecraft-i18n/Cargo.toml | 8 + crates/openecraft-i18n/src/catalog.rs | 47 + crates/openecraft-i18n/src/catalog/extra.tsv | 15 + .../src/catalog/translations.tsv | 892 ++++++++++++++++++ crates/openecraft-i18n/src/lib.rs | 9 + crates/openecraft-i18n/src/translate.rs | 154 +++ crates/openecraft-i18n/src/translate/tests.rs | 155 +++ crates/openecraft-ui/Cargo.toml | 1 + crates/openecraft-ui/src/client.rs | 31 +- crates/openecraft-ui/src/language.rs | 21 + crates/openecraft-ui/src/lib.rs | 2 + crates/openecraft-ui/src/part_editor.rs | 154 +-- parts-manager/Cargo.toml | 5 +- parts-manager/src/app.rs | 95 +- parts-manager/src/main.rs | 3 + src/app.rs | 582 ++++++------ src/app/engineering.rs | 157 +-- src/app/forms_ui.rs | 99 +- src/app/harness_ui.rs | 35 +- src/app/symbol_editor.rs | 139 +-- src/conventions/tests.rs | 50 + src/editor.rs | 21 +- src/forms.rs | 61 +- src/glyphs/tests.rs | 23 + src/io.rs | 11 +- src/macros.rs | 3 +- src/main.rs | 3 + src/model.rs | 39 +- src/panel.rs | 15 +- src/panel_ui.rs | 167 ++-- src/parts_ui.rs | 93 +- src/render.rs | 19 +- src/reports.rs | 233 ++--- src/revision.rs | 11 +- src/symbols.rs | 55 +- src/symlib.rs | 11 +- 40 files changed, 2468 insertions(+), 1003 deletions(-) create mode 100644 crates/openecraft-i18n/Cargo.toml create mode 100644 crates/openecraft-i18n/src/catalog.rs create mode 100644 crates/openecraft-i18n/src/catalog/extra.tsv create mode 100644 crates/openecraft-i18n/src/catalog/translations.tsv create mode 100644 crates/openecraft-i18n/src/lib.rs create mode 100644 crates/openecraft-i18n/src/translate.rs create mode 100644 crates/openecraft-i18n/src/translate/tests.rs create mode 100644 crates/openecraft-ui/src/language.rs diff --git a/AGENTS.md b/AGENTS.md index 431cbd65..6104bec4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -26,7 +26,8 @@ cargo clippy -p openecraft -p openecraft-parts-manager --target wasm32-unknown-u | --- | --- | --- | | `openecraft` | `.` (`src/`) | Editor (desktop + web) – the root package, built by trunk | | `openecraft-parts` | `crates/openecraft-parts` | Shared library: part model, function templates, CSV/JSON, catalog, parts server API types | -| `openecraft-ui` | `crates/openecraft-ui` | Shared egui library: part tree / editor / previews, parts server client, file dialogs | +| `openecraft-i18n` | `crates/openecraft-i18n` | Languages and UI translations (English, German, French, Spanish); no dependencies | +| `openecraft-ui` | `crates/openecraft-ui` | Shared egui library: part tree / editor / previews, parts server client, file dialogs, language menu | | `openecraft-server` | `server/` | Standalone parts database server (axum, JSON file storage) | | `openecraft-parts-manager` | `parts-manager/` | Standalone parts server maintenance app (desktop + web, own `index.html` / `Trunk.toml`) | @@ -41,6 +42,38 @@ cargo clippy -p openecraft -p openecraft-parts-manager --target wasm32-unknown-u - New crates are added to `[workspace] members` in the root `Cargo.toml`; the convention test reads that list, so its rules apply to every member. +## Languages – mandatory for every feature + +The app is available in **English, German, French and Spanish**. All four are required: +a feature, menu entry, dialog, message, tooltip, report heading or placeholder text is +not done until it is available in all of them. Further languages are optional (add a +column to the catalog and a `Lang` variant). + +- Write texts in English in the code and pass them through `openecraft_i18n`: + `tr("Open")` for plain texts, `tr_fmt!("Saved {}", name)` for texts with `{}` + placeholders (the translation may reorder with `{0}`, `{1}`), `tr_const!("…")` in + `const` / `static` tables (translate with `tr(…)` where the text is shown). + Never build sentences from translated fragments (`"Macro " + tr("saved")`); translate + the whole sentence, one catalog entry per variant. +- Every English text needs a line in `crates/openecraft-i18n/src/catalog/extra.tsv` + (`EnglishDeutschFrançaisEspañol`; `\n` and `\"` as in Rust source; + `{}` placeholders must appear in every translation). `translations.tsv` holds the + initial set. The catalog is checked by `cargo test`: all four languages present, + placeholders equal, every literal passed to `tr` / `tr_fmt!` / `tr_const!` and every + built-in symbol name is in the catalog, and all translated characters exist in the + bundled fonts. +- `src/conventions/tests.rs` fails for plain string literals passed to widgets + (`ui.button("…")`, `.label("…")`, `.on_hover_text("…")`, `Window::new("…")`, …). +- Translate at the point where the text is shown, so that switching the language in + View › Language (or the parts manager's toolbar) takes effect immediately. Texts + that are stored in the project (user input, names of built-in forms) stay as they are; + generated content (reports, title blocks, check messages) is translated when it is + generated, `App` regenerates it when the language changes. +- Do not translate file formats, CSV headers of machine readable exports, JSON keys, + part data and log messages. +- Language choice: stored by the apps (`language` key), otherwise the OS / browser + language if supported, otherwise English (`openecraft_i18n::init`). + ## Unit tests – mandatory layout **Unit tests never live inline in a module file.** Each module keeps its tests in a diff --git a/Cargo.lock b/Cargo.lock index ead7263e..22c46d89 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2541,6 +2541,7 @@ dependencies = [ "egui", "env_logger", "log", + "openecraft-i18n", "openecraft-parts", "openecraft-ui", "serde", @@ -2550,6 +2551,10 @@ dependencies = [ "web-sys", ] +[[package]] +name = "openecraft-i18n" +version = "0.1.0" + [[package]] name = "openecraft-parts" version = "0.1.0" @@ -2566,6 +2571,7 @@ dependencies = [ "egui", "env_logger", "log", + "openecraft-i18n", "openecraft-parts", "openecraft-ui", "serde_json", @@ -2599,6 +2605,7 @@ dependencies = [ "ehttp", "js-sys", "log", + "openecraft-i18n", "openecraft-parts", "rfd", "serde", diff --git a/Cargo.toml b/Cargo.toml index 33ab7880..85d0cab4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,4 +1,4 @@ -[package] +[package] name = "openecraft" version = "0.1.0" edition = "2021" @@ -10,7 +10,7 @@ name = "openecraft" path = "src/main.rs" [workspace] -members = [".", "crates/openecraft-parts", "crates/openecraft-ui", "server", "parts-manager"] +members = [".", "crates/openecraft-i18n", "crates/openecraft-parts", "crates/openecraft-ui", "server", "parts-manager"] [dependencies] eframe = { version = "0.37", default-features = false, features = [ @@ -30,6 +30,7 @@ serde = { version = "1", features = ["derive", "rc"] } serde_json = "1" log = "0.4" openecraft-parts = { path = "crates/openecraft-parts" } +openecraft-i18n = { path = "crates/openecraft-i18n" } openecraft-ui = { path = "crates/openecraft-ui" } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] @@ -38,7 +39,7 @@ env_logger = "0.11" [target.'cfg(target_arch = "wasm32")'.dependencies] wasm-bindgen = "0.2" wasm-bindgen-futures = "0.4" -web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlCanvasElement"] } +web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlCanvasElement", "Navigator"] } [profile.release] opt-level = 2 diff --git a/README.md b/README.md index 66218f94..40841d21 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,8 @@ built with [egui / eframe](https://github.com/emilk/egui). ## Features +- **Languages**: English, German, French and Spanish (View › Language; the editor and the + parts manager remember the choice and start in the system / browser language if supported). - **Projects with pages**: multi-line schematic pages (A3, 10 columns / 6 rows, title block), cover sheet and generated report pages. Page navigator with reordering. - **IEC symbol library** (~40 symbols): coils and timers, NO/NC/changeover contacts, main @@ -236,6 +238,7 @@ cargo test --workspace | File | Purpose | | --- | --- | +| `crates/openecraft-i18n` | Languages and UI translations (English, German, French, Spanish); catalog in `src/catalog/*.tsv` | | `crates/openecraft-parts` | Shared library: part model, function templates, CSV/JSON, catalog, server API types, 3D math | | `crates/openecraft-ui` | Shared egui library: part editor and previews, parts server client, file dialogs | | `server/` | `openecraft-server`: parts database server (REST API, JSON storage) | diff --git a/crates/openecraft-i18n/Cargo.toml b/crates/openecraft-i18n/Cargo.toml new file mode 100644 index 00000000..3236c6f6 --- /dev/null +++ b/crates/openecraft-i18n/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "openecraft-i18n" +version = "0.1.0" +edition = "2021" +description = "Language selection and UI translations (English, German, French, Spanish) of OpenECraft" +license = "MIT OR Apache-2.0" + +[dependencies] diff --git a/crates/openecraft-i18n/src/catalog.rs b/crates/openecraft-i18n/src/catalog.rs new file mode 100644 index 00000000..8a371be6 --- /dev/null +++ b/crates/openecraft-i18n/src/catalog.rs @@ -0,0 +1,47 @@ +//! The translation catalog: tab separated `EnglishDeutschFrançaisEspañol` +//! lines in `catalog/*.tsv`. The English text is the lookup key and must be identical to +//! the literal passed to `tr` / `tr_fmt!` / `tr_const!` (`\n` and `\"` are written as in +//! Rust source). Lines starting with `#` are comments. + +pub type Entry = (&'static str, &'static str, &'static str, &'static str); + +const FILES: [&str; 2] = [include_str!("catalog/translations.tsv"), include_str!("catalog/extra.tsv")]; + +/// All catalog entries; a malformed line yields `None` (reported by the tests). +pub fn parse() -> impl Iterator> { + FILES + .iter() + .flat_map(|f| f.lines()) + .filter(|l| !l.trim().is_empty() && !l.starts_with('#')) + .map(|line| { + let mut cols = line.split('\t'); + let entry = (unescape(cols.next()?), unescape(cols.next()?), unescape(cols.next()?), unescape(cols.next()?)); + cols.next().is_none().then_some(entry) + }) +} + +pub fn all() -> impl Iterator { + parse().flatten() +} + +/// Resolves the Rust escapes used in the catalog (`\n`, `\t`, `\"`, `\\`). +fn unescape(s: &'static str) -> &'static str { + if !s.contains('\\') { + return s; + } + let mut out = String::with_capacity(s.len()); + let mut chars = s.chars(); + while let Some(c) = chars.next() { + if c != '\\' { + out.push(c); + continue; + } + match chars.next() { + Some('n') => out.push('\n'), + Some('t') => out.push('\t'), + Some(other) => out.push(other), + None => out.push('\\'), + } + } + Box::leak(out.into_boxed_str()) +} diff --git a/crates/openecraft-i18n/src/catalog/extra.tsv b/crates/openecraft-i18n/src/catalog/extra.tsv new file mode 100644 index 00000000..0d0e2769 --- /dev/null +++ b/crates/openecraft-i18n/src/catalog/extra.tsv @@ -0,0 +1,15 @@ +# Entries added by hand (not part of the generated translations.tsv). +{} connections removed from their harness {} Verbindungen aus ihrem Kabelbaum entfernt {} liaisons retirées de leur faisceau {} conexiones quitadas de su mazo +{} connections assigned to {} {} Verbindungen {} zugewiesen {} liaisons affectées à {} {} conexiones asignadas a {} +🗄 Show in panel layout ({}) 🗄 Im Schaltschrank-Layout anzeigen ({}) 🗄 Afficher dans l'implantation de l'armoire ({}) 🗄 Mostrar en la distribución del armario ({}) + | Potential {} | Potenzial {} | Potentiel {} | Potencial {} +📁 Project parts ({}) 📁 Projektartikel ({}) 📁 Articles du projet ({}) 📁 Artículos del proyecto ({}) +part {} not found Artikel {} nicht gefunden article {} introuvable artículo {} no encontrado +… {} more rows – see Reports window / CSV export … {} weitere Zeilen – siehe Berichtsfenster / CSV-Export … {} lignes de plus – voir la fenêtre Rapports / export CSV … {} filas más – ver la ventana de informes / exportación CSV +strip {} mm, ferrule {} mm² {} abisolieren {} mm, Aderendhülse {} mm² {} dénuder {} mm, embout {} mm² {} pelar {} mm, punta {} mm² {} +strip {} mm abisolieren {} mm dénuder {} mm pelar {} mm +unexpected answer: {} unerwartete Antwort: {} réponse inattendue : {} respuesta inesperada: {} +connection failed: {} Verbindung fehlgeschlagen: {} échec de la connexion : {} conexión fallida: {} +value set… Wertesatz … jeu de valeurs… conjunto de valores… +Shown in title blocks with {prop:Name} Wird in Schriftfeldern mit {prop:Name} angezeigt Affiché dans les cartouches avec {prop:Name} Se muestra en los cajetines con {prop:Name} +e.g. W z. B. W p. ex. W p. ej. W diff --git a/crates/openecraft-i18n/src/catalog/translations.tsv b/crates/openecraft-i18n/src/catalog/translations.tsv new file mode 100644 index 00000000..a5ca795b --- /dev/null +++ b/crates/openecraft-i18n/src/catalog/translations.tsv @@ -0,0 +1,892 @@ +# EnglishDeutschFrancaisEspanol (generated key order: sorted) +(custom size) (benutzerdefinierte Größe) (taille personnalisée) (tamaño personalizado) +(no entries) (keine Einträge) (aucune entrée) (sin entradas) +(project default) (Projektstandard) (valeur par défaut du projet) (valor predeterminado del proyecto) +(renamed from {}) (umbenannt von {}) (renommé depuis {}) (renombrado desde {}) ++ Page + Seite + Page + Página +0 = no jumper 0 = keine Brücke 0 = aucun pont 0 = sin puente +1. Pick a symbol in the library (right) and click into the page to place it. Device tags (-K1, -S2 …) are assigned automatically. 1. Wähle ein Symbol in der Bibliothek (rechts) und klicke in die Seite, um es zu platzieren. Betriebsmittelkennzeichen (-K1, -S2 …) werden automatisch vergeben. 1. Choisissez un symbole dans la bibliothèque (à droite) et cliquez dans la page pour le placer. Les repères d'appareil (-K1, -S2 …) sont attribués automatiquement. 1. Elige un símbolo de la biblioteca (a la derecha) y haz clic en la página para colocarlo. Las designaciones de dispositivo (-K1, -S2 …) se asignan automáticamente. +10. Project › Symbol editor: draw your own symbols (or copy built-in ones) with connection points and function; they are saved in the project and can be exchanged as library files. 10. Projekt › Symboleditor: Zeichne eigene Symbole (oder kopiere eingebaute) mit Anschlusspunkten und Funktion; sie werden im Projekt gespeichert und können als Bibliotheksdateien ausgetauscht werden. 10. Projet › Éditeur de symboles : dessinez vos propres symboles (ou copiez ceux fournis) avec points de connexion et fonction ; ils sont enregistrés dans le projet et peuvent être échangés sous forme de fichiers de bibliothèque. 10. Proyecto › Editor de símbolos: dibuja tus propios símbolos (o copia los incorporados) con puntos de conexión y función; se guardan en el proyecto y se pueden intercambiar como archivos de biblioteca. +100% ≈ real size on a 96 dpi screen 100 % ≈ reale Größe auf einem 96-dpi-Bildschirm 100 % ≈ taille réelle sur un écran de 96 dpi 100 % ≈ tamaño real en una pantalla de 96 ppp +11. Project › Title blocks and report forms: own title blocks with placeholders ({project}, {page}, {prop:Name} …) and the columns of report pages. 11. Projekt › Schriftfelder und Berichtsformulare: eigene Schriftfelder mit Platzhaltern ({project}, {page}, {prop:Name} …) und die Spalten der Berichtsseiten. 11. Projet › Cartouches et formulaires de rapport : cartouches personnalisés avec champs variables ({project}, {page}, {prop:Name} …) et colonnes des pages de rapport. 11. Proyecto › Cajetines y formularios de informe: cajetines propios con marcadores ({project}, {page}, {prop:Name} …) y las columnas de las páginas de informe. +12. Panel layout: busbars and cutouts; the enclosure properties export the drilling pattern (NC data as DXF / CSV). The production wire list contains stripping lengths and ferrules. 12. Schaltschrank-Layout: Sammelschienen und Ausschnitte; die Gehäuse-Eigenschaften exportieren das Bohrbild (NC-Daten als DXF / CSV). Die Fertigungs-Leitungsliste enthält Abisolierlängen und Aderendhülsen. 12. Implantation de l'armoire : barres de cuivre et découpes ; les propriétés de l'enveloppe exportent le plan de perçage (données CN en DXF / CSV). La liste de câblage de production contient les longueurs de dénudage et les embouts. 12. Distribución del armario: pletinas y recortes; las propiedades de la envolvente exportan el patrón de taladrado (datos NC como DXF / CSV). La lista de cableado de producción contiene longitudes de pelado y punteras. +13. Harnesses: Project › Harnesses…; select the wires between two devices › Assign to harness, or per connection in the wire properties. Harness data report with lengths, connectors and bundle diameter, KBL export. 13. Kabelbäume: Projekt › Kabelbäume…; wähle die Leitungen zwischen zwei Betriebsmitteln › Kabelbaum zuweisen, oder je Verbindung in den Leitungseigenschaften. Kabelbaum-Bericht mit Längen, Steckern und Bündeldurchmesser, KBL-Export. 13. Faisceaux : Projet › Faisceaux… ; sélectionnez les fils entre deux appareils › Affecter au faisceau, ou par liaison dans les propriétés du fil. Rapport de faisceau avec longueurs, connecteurs et diamètre de faisceau, export KBL. 13. Mazos de cables: Proyecto › Mazos de cables…; selecciona los hilos entre dos dispositivos › Asignar al mazo, o por conexión en las propiedades del hilo. Informe de mazos con longitudes, conectores y diámetro del haz, exportación KBL. +14. Door: switch the panel front view to Door and place command / signal devices there; their door cutouts are generated. Collisions are checked with the parts' 3D models. 14. Tür: Schalte die Schaltschrank-Frontansicht auf Tür und platziere dort Befehls- / Meldegeräte; ihre Türausschnitte werden erzeugt. Kollisionen werden mit den 3D-Modellen der Artikel geprüft. 14. Porte : passez la vue de face de l'armoire sur Porte et placez-y les appareils de commande / signalisation ; leurs découpes de porte sont générées. Les collisions sont vérifiées avec les modèles 3D des articles. 14. Puerta: cambia la vista frontal del armario a Puerta y coloca allí los dispositivos de mando / señalización; sus recortes de puerta se generan. Las colisiones se comprueban con los modelos 3D de los artículos. +2. Select a coil, then place contacts: they are assigned to that coil and numbered (13/14, 21/22 …). Cross references and the contact image update live. 2. Wähle eine Spule und platziere dann Kontakte: Sie werden dieser Spule zugeordnet und nummeriert (13/14, 21/22 …). Querverweise und das Kontaktbild werden live aktualisiert. 2. Sélectionnez une bobine, puis placez des contacts : ils sont affectés à cette bobine et numérotés (13/14, 21/22 …). Les renvois et l'image des contacts se mettent à jour en direct. 2. Selecciona una bobina y coloca contactos: se asignan a esa bobina y se numeran (13/14, 21/22 …). Las referencias cruzadas y la imagen de contactos se actualizan en vivo. +2D front view 2D-Frontansicht Vue de face 2D Vista frontal 2D +3. Draw wires with the wire tool (W). Wires end automatically on connection points. T-junctions get a connection dot. 3. Zeichne Leitungen mit dem Leitungswerkzeug (W). Leitungen enden automatisch an Anschlusspunkten. T-Abzweige erhalten einen Verbindungspunkt. 3. Tracez les fils avec l'outil fil (W). Les fils se terminent automatiquement sur les points de connexion. Les dérivations en T reçoivent un point de jonction. 3. Dibuja hilos con la herramienta de hilo (W). Los hilos terminan automáticamente en los puntos de conexión. Las derivaciones en T reciben un punto de unión. +3D model 3D-Modell Modèle 3D Modelo 3D +4. Potentials (L1, +24V …) and interruption points name the nets across pages. Select a wire to highlight its potential. 4. Potenziale (L1, +24V …) und Unterbrechungspunkte benennen die Netze über Seiten hinweg. Wähle eine Leitung, um ihr Potenzial hervorzuheben. 4. Les potentiels (L1, +24V …) et les points d'interruption nomment les réseaux d'une page à l'autre. Sélectionnez un fil pour mettre son potentiel en évidence. 4. Los potenciales (L1, +24V …) y los puntos de interrupción nombran las redes entre páginas. Selecciona un hilo para resaltar su potencial. +4/2 directional valve 4/2-Wegeventil Distributeur 4/2 Válvula direccional 4/2 +5. Assign parts in the property panel; generate reports (device list, BOM, terminal diagram, connection list, PLC list) and insert them as report pages. 5. Weise Artikel im Eigenschaftenbereich zu; erzeuge Berichte (Betriebsmittelliste, Stückliste, Klemmenplan, Verbindungsliste, SPS-Liste) und füge sie als Berichtsseiten ein. 5. Affectez des articles dans le panneau des propriétés ; générez des rapports (liste des appareils, nomenclature, plan de bornes, liste des liaisons, liste API) et insérez-les comme pages de rapport. 5. Asigna artículos en el panel de propiedades; genera informes (lista de dispositivos, lista de materiales, diagrama de bornes, lista de conexiones, lista PLC) e insértalos como páginas de informe. +6. Structure: give pages a function (=A1) and location (+CAB1) in the page properties. Devices placed there get it (=A1+CAB1-K1); on the page only the differing part is shown. 6. Struktur: Gib Seiten eine Funktion (=A1) und einen Ort (+CAB1) in den Seiteneigenschaften. Dort platzierte Betriebsmittel erhalten sie (=A1+CAB1-K1); auf der Seite wird nur der abweichende Teil angezeigt. 6. Structure : donnez aux pages une fonction (=A1) et un emplacement (+CAB1) dans leurs propriétés. Les appareils placés dessus les héritent (=A1+CAB1-K1) ; sur la page, seule la partie différente est affichée. 6. Estructura: asigna a las páginas una función (=A1) y una ubicación (+CAB1) en sus propiedades. Los dispositivos colocados en ellas las heredan (=A1+CAB1-K1); en la página solo se muestra la parte diferente. +7. Cables: define them in Project › Cables…, select wires and use Assign to cable. Wire numbers: Project › Wire numbering…, or type a number in the wire properties. 7. Kabel: Definiere sie unter Projekt › Kabel…, wähle Leitungen und nutze Kabel zuweisen. Leitungsnummern: Projekt › Leitungsnummerierung…, oder gib eine Nummer in den Leitungseigenschaften ein. 7. Câbles : définissez-les dans Projet › Câbles…, sélectionnez des fils et utilisez Affecter au câble. Numéros de fil : Projet › Numérotation des fils…, ou saisissez un numéro dans les propriétés du fil. 7. Cables: defínelos en Proyecto › Cables…, selecciona hilos y usa Asignar al cable. Números de hilo: Proyecto › Numeración de hilos…, o escribe un número en las propiedades del hilo. +8. Macros: select items › Edit › Save selection as macro; insert them from Insert › Macro…. Placeholders {NAME} are filled from value sets. 8. Makros: Wähle Elemente › Bearbeiten › Auswahl als Makro speichern; füge sie über Einfügen › Makro… ein. Platzhalter {NAME} werden aus Wertesätzen gefüllt. 8. Macros : sélectionnez des éléments › Édition › Enregistrer la sélection comme macro ; insérez-les via Insertion › Macro…. Les variables {NAME} sont remplies à partir des jeux de valeurs. 8. Macros: selecciona elementos › Edición › Guardar selección como macro; insértalos desde Insertar › Macro…. Los marcadores {NAME} se rellenan con conjuntos de valores. +9. Project › Terminal strips / PLC overview / Revisions: strip order, jumpers and spares; PLC addresses and symbol tables; revisions with change marks and released (locked) pages. 9. Projekt › Klemmenleisten / SPS-Übersicht / Revisionen: Leistenreihenfolge, Brücken und Reserven; SPS-Adressen und Symboltabellen; Revisionen mit Änderungsmarken und freigegebene (gesperrte) Seiten. 9. Projet › Borniers / Vue d'ensemble API / Révisions : ordre des borniers, ponts et réserves ; adresses API et tables de symboles ; révisions avec repères de modification et pages validées (verrouillées). 9. Proyecto › Regletas de bornes / Resumen PLC / Revisiones: orden de regletas, puentes y reservas; direcciones PLC y tablas de símbolos; revisiones con marcas de cambio y páginas liberadas (bloqueadas). +Access token Zugriffstoken Jeton d'accès Token de acceso +Accessories Zubehör Accessoires Accesorios +Add missing parts of the example catalog Fehlende Artikel des Beispielkatalogs hinzufügen Ajouter les articles manquants du catalogue d'exemple Añadir los artículos que faltan del catálogo de ejemplo +Add to selection Zur Auswahl hinzufügen Ajouter à la sélection Añadir a la selección +Address Adresse Adresse Dirección +Adds / replaces all parts of the local database on the server Fügt alle Artikel der lokalen Datenbank auf dem Server hinzu / ersetzt sie Ajoute / remplace tous les articles de la base locale sur le serveur Añade / reemplaza en el servidor todos los artículos de la base de datos local +Adds new parts and replaces existing ones on the server Fügt neue Artikel hinzu und ersetzt vorhandene auf dem Server Ajoute de nouveaux articles et remplace ceux qui existent sur le serveur Añade artículos nuevos y reemplaza los existentes en el servidor +Adds new parts and updates existing ones in the local parts database Fügt neue Artikel hinzu und aktualisiert vorhandene in der lokalen Artikeldatenbank Ajoute de nouveaux articles et met à jour ceux qui existent dans la base d'articles locale Añade artículos nuevos y actualiza los existentes en la base de datos de artículos local +Adds parts that only exist in the project to the database Fügt Artikel, die nur im Projekt vorhanden sind, zur Datenbank hinzu Ajoute à la base les articles qui n'existent que dans le projet Añade a la base de datos los artículos que solo existen en el proyecto +Alignment Ausrichtung Alignement Alineación +All devices with mounting data are placed. Alle Geräte mit Montagedaten sind platziert. Tous les appareils avec données de montage sont placés. Todos los dispositivos con datos de montaje están colocados. +All user symbols as library file Alle Benutzersymbole als Bibliotheksdatei Tous les symboles utilisateur en fichier de bibliothèque Todos los símbolos de usuario como archivo de biblioteca +All wires of this potential are highlighted. Alle Leitungen dieses Potenzials sind hervorgehoben. Tous les fils de ce potentiel sont mis en évidence. Todos los hilos de este potencial están resaltados. +Applies to all wires of this connection; automatic numbering keeps manual numbers Gilt für alle Leitungen dieser Verbindung; die automatische Nummerierung behält manuelle Nummern bei S'applique à tous les fils de cette liaison ; la numérotation automatique conserve les numéros manuels Se aplica a todos los hilos de esta conexión; la numeración automática conserva los números manuales +Applies to report pages, the PDF and the print export. Gilt für Berichtsseiten, das PDF und den Druckexport. S'applique aux pages de rapport, au PDF et à l'export d'impression. Se aplica a las páginas de informe, al PDF y a la exportación para impresión. +Apply Übernehmen Appliquer Aplicar +Apply designations Bezeichnungen übernehmen Appliquer les désignations Aplicar designaciones +Apply structure Struktur übernehmen Appliquer la structure Aplicar estructura +Arrows Pfeiltasten Flèches Flechas +Assign connections: select the wires between two devices in the schematic › Assign to harness. Verbindungen zuweisen: Wähle im Schaltplan die Leitungen zwischen zwei Betriebsmitteln › Kabelbaum zuweisen. Affecter des liaisons : sélectionnez dans le schéma les fils entre deux appareils › Affecter au faisceau. Asignar conexiones: selecciona en el esquema los hilos entre dos dispositivos › Asignar al mazo. +Assign to cable Kabel zuweisen Affecter au câble Asignar al cable +Assign to existing device Vorhandenem Betriebsmittel zuweisen Affecter à un appareil existant Asignar a un dispositivo existente +Assign to harness Kabelbaum zuweisen Affecter au faisceau Asignar al mazo +Assign wires: select them in the schematic › Assign to cable. Leitungen zuweisen: Wähle sie im Schaltplan › Kabel zuweisen. Affecter des fils : sélectionnez-les dans le schéma › Affecter au câble. Asignar hilos: selecciónalos en el esquema › Asignar al cable. +Author Autor Auteur Autor +Author of the last revision Autor der letzten Revision Auteur de la dernière révision Autor de la última revisión +Aux Hilfs Aux Aux +Aux. functions Hilfsfunktionen Fonctions auxiliaires Func. auxiliares +Auxiliary function: NC contact Hilfsfunktion: Öffner Fonction auxiliaire : contact NF Función auxiliar: contacto NC +Auxiliary function: NO contact Hilfsfunktion: Schließer Fonction auxiliaire : contact NO Función auxiliar: contacto NA +Auxiliary function: changeover Hilfsfunktion: Wechsler Fonction auxiliaire : inverseur Función auxiliar: conmutado +Auxiliary function: main contact Hilfsfunktion: Hauptkontakt Fonction auxiliaire : contact principal Función auxiliar: contacto principal +Bill of materials Stückliste Nomenclature Lista de materiales +Black box 2 + 2 connections Black Box 2 + 2 Anschlüsse Boîte noire 2 + 2 connexions Caja negra 2 + 2 conexiones +Black box 4 + 4 connections Black Box 4 + 4 Anschlüsse Boîte noire 4 + 4 connexions Caja negra 4 + 4 conexiones +Black boxes / PLC boxes Black Boxes / SPS-Boxen Boîtes noires / boîtiers API Cajas negras / cajas PLC +Built-in title blocks are read only – use “Copy as new” to make your own. Eingebaute Schriftfelder sind schreibgeschützt – nutze „Als neu kopieren“, um ein eigenes zu erstellen. Les cartouches intégrés sont en lecture seule – utilisez « Copier comme nouveau » pour créer le vôtre. Los cajetines incorporados son de solo lectura: usa «Copiar como nuevo» para crear el tuyo. +Bundle Ø Bündel-Ø Ø faisceau Ø del haz +Busbar Sammelschiene Barre de cuivre Pletina +Busbar system Sammelschienensystem Système de barres Sistema de pletinas +Cable Kabel Câble Cable +Cable diagram Kabelplan Schéma de câbles Diagrama de cables +Cable duct Kabelkanal Goulotte Canaleta +Cable overview Kabelübersicht Vue d'ensemble des câbles Resumen de cables +Cable without tag Kabel ohne Kennzeichen Câble sans repère Cable sin designación +Cable {} defined {} times Kabel {} {}-mal definiert Câble {} défini {} fois Cable {} definido {} veces +Cables Kabel Câbles Cables +Cables… Kabel… Câbles… Cables… +Cancel Abbrechen Annuler Cancelar +Cancel / select tool / clear selection Abbrechen / Werkzeug wählen / Auswahl aufheben Annuler / choisir l'outil / effacer la sélection Cancelar / seleccionar herramienta / borrar selección +Capacitor Kondensator Condensateur Condensador +Card Karte Carte Tarjeta +Category Kategorie Catégorie Categoría +Centre Mitte Centre Centro +Certificates Zertifikate Certificats Certificados +Change Änderung Modification Cambio +Changeover contact Wechslerkontakt Contact inverseur Contacto conmutado +Changes since revision {} Änderungen seit Revision {} Modifications depuis la révision {} Cambios desde la revisión {} +Changes the tag of all functions of this device Ändert das Kennzeichen aller Funktionen dieses Betriebsmittels Modifie le repère de toutes les fonctions de cet appareil Cambia la designación de todas las funciones de este dispositivo +Check Prüfung Contrôle Revisión +Check ({}) Prüfung ({}) Contrôle ({}) Revisión ({}) +Check project Projekt prüfen Vérifier le projet Comprobar proyecto +Circle Kreis Cercle Círculo +Circuit breaker (single-line) Leistungsschalter (einpolig dargestellt) Disjoncteur (unifilaire) Interruptor automático (unifilar) +Circuit breaker 1-pole Leitungsschutzschalter 1-polig Disjoncteur 1 pôle Interruptor automático 1 polo +Circuit breaker 3-pole Leistungsschalter 3-polig Disjoncteur 3 pôles Interruptor automático 3 polos +Click an element in the drawing to edit it. Klicke auf ein Element in der Zeichnung, um es zu bearbeiten. Cliquez sur un élément du dessin pour le modifier. Haz clic en un elemento del dibujo para editarlo. +Click centre, then a point on the circle Klicke auf den Mittelpunkt, dann auf einen Punkt des Kreises Cliquez sur le centre, puis sur un point du cercle Haz clic en el centro y luego en un punto del círculo +Click into the page to place {} Klicke in die Seite, um {} zu platzieren Cliquez dans la page pour placer {} Haz clic en la página para colocar {} +Click on the 4 mm grid Klicke auf das 4-mm-Raster Cliquez sur la grille de 4 mm Haz clic en la cuadrícula de 4 mm +Click start and corner points · Space toggles corner direction · ends automatically on a connection · Right click / Esc finish Klicke Start- und Eckpunkte · Leertaste wechselt die Eckrichtung · endet automatisch an einem Anschluss · Rechtsklick / Esc beendet Cliquez sur le départ et les coins · Espace change le sens du coin · se termine automatiquement sur une connexion · clic droit / Échap pour terminer Haz clic en el inicio y las esquinas · Espacio cambia la dirección de la esquina · termina automáticamente en una conexión · clic derecho / Esc para finalizar +Click start and end point Klicke auf Start- und Endpunkt Cliquez sur le point de départ et le point d'arrivée Haz clic en el punto inicial y el final +Click start point, click end point Klicke auf Startpunkt, dann auf Endpunkt Cliquez sur le point de départ, puis sur le point d'arrivée Haz clic en el punto inicial y luego en el final +Click to add to the selected text. Klicke, um zum gewählten Text hinzuzufügen. Cliquez pour ajouter au texte sélectionné. Haz clic para añadir al texto seleccionado. +Click to insert the macro · Esc cancel Klicke, um das Makro einzufügen · Esc bricht ab Cliquez pour insérer la macro · Échap pour annuler Haz clic para insertar la macro · Esc para cancelar +Click to place a text Klicke, um einen Text zu platzieren Cliquez pour placer un texte Haz clic para colocar un texto +Click to place the text from the field below Klicke, um den Text aus dem Feld unten zu platzieren Cliquez pour placer le texte du champ ci-dessous Haz clic para colocar el texto del campo inferior +Click to place · R rotate · M mirror · Esc finish Klicken zum Platzieren · R drehen · M spiegeln · Esc beenden Cliquez pour placer · R pivoter · M miroir · Échap pour terminer Clic para colocar · R girar · M reflejar · Esc para finalizar +Click to select, drag to move, drag on empty space for window selection. Right/middle drag pans, wheel zooms. Klicken zum Auswählen, Ziehen zum Verschieben, Ziehen auf leerer Fläche für Fensterauswahl. Rechts-/Mittelklick-Ziehen verschiebt die Ansicht, das Mausrad zoomt. Cliquez pour sélectionner, glissez pour déplacer, glissez dans le vide pour une sélection par fenêtre. Glisser avec le clic droit/milieu déplace la vue, la molette zoome. Clic para seleccionar, arrastra para mover, arrastra en un espacio vacío para seleccionar por ventana. Arrastrar con el botón derecho/central desplaza la vista, la rueda hace zoom. +Click to show Klicken zum Anzeigen Cliquez pour afficher Haz clic para mostrar +Click two corners Klicke auf zwei Ecken Cliquez sur deux coins Haz clic en dos esquinas +Closed / filled Geschlossen / gefüllt Fermé / rempli Cerrado / relleno +Coils / Relays Spulen / Relais Bobines / Relais Bobinas / Relés +Colour Farbe Couleur Color +Colour / cross-section Farbe / Querschnitt Couleur / section Color / sección +Columns Spalten Colonnes Columnas +Columns, order and rows of the report pages Spalten, Reihenfolge und Zeilen der Berichtsseiten Colonnes, ordre et lignes des pages de rapport Columnas, orden y filas de las páginas de informe +Company Firma Société Empresa +Complete tag: {}\nAspects missing here are taken from the page (=function +location). Vollständiges Kennzeichen: {}\nFehlende Aspekte werden von der Seite übernommen (=Funktion +Ort). Repère complet : {}\nLes aspects manquants sont repris de la page (=fonction +emplacement). Designación completa: {}\nLos aspectos que faltan se toman de la página (=función +ubicación). +Connect Verbinden Connecter Conectar +Connect to a parts server Mit einem Artikelserver verbinden Se connecter à un serveur d'articles Conectar con un servidor de artículos +Connected devices Angeschlossene Betriebsmittel Appareils raccordés Dispositivos conectados +Connected to Verbunden mit Relié à Conectado a +Connected to: Verbunden mit: Relié à : Conectado a: +Connecting… Verbinde … Connexion… Conectando… +Connection designations Verbindungsbezeichnungen Désignations des liaisons Designaciones de conexión +Connection list Verbindungsliste Liste des liaisons Lista de conexiones +Connection point {} Anschlusspunkt {} Point de connexion {} Punto de conexión {} +Connection point {} is not on the {} mm grid. Anschlusspunkt {} liegt nicht auf dem {}-mm-Raster. Le point de connexion {} n'est pas sur la grille de {} mm. El punto de conexión {} no está en la cuadrícula de {} mm. +Connection point {} lies on another one. Anschlusspunkt {} liegt auf einem anderen. Le point de connexion {} est superposé à un autre. El punto de conexión {} coincide con otro. +Connection points Anschlusspunkte Points de connexion Puntos de conexión +Connection points 1 and 2 are connected inside Anschlusspunkte 1 und 2 sind intern verbunden Les points de connexion 1 et 2 sont reliés en interne Los puntos de conexión 1 y 2 están conectados internamente +Connections Verbindungen Liaisons Conexiones +Connections ({}) Verbindungen ({}) Liaisons ({}) Conexiones ({}) +Connections / harness Verbindungen / Kabelbaum Liaisons / faisceau Conexiones / mazo +Connections whose two ends are both on selected wires Verbindungen, deren beide Enden an gewählten Leitungen liegen Liaisons dont les deux extrémités sont sur les fils sélectionnés Conexiones cuyos dos extremos están en los hilos seleccionados +Connectors Stecker Connecteurs Conectores +Consecutive addresses from the start byte, in schematic order Aufeinanderfolgende Adressen ab dem Startbyte, in Schaltplan-Reihenfolge Adresses consécutives à partir de l'octet de départ, dans l'ordre du schéma Direcciones consecutivas desde el byte inicial, en el orden del esquema +Contactor (single-line) Schütz (einpolig dargestellt) Contacteur (unifilaire) Contactor (unifilar) +Contacts Kontakte Contacts Contactos +Control transformer Steuertransformator Transformateur de commande Transformador de control +Copper busbar system: click start and end point Kupfer-Sammelschienensystem: Start- und Endpunkt anklicken Système de barres en cuivre : cliquez sur le point de départ et d'arrivée Sistema de pletinas de cobre: haz clic en el punto inicial y el final +Copy / cut / paste (devices get new tags) Kopieren / Ausschneiden / Einfügen (Betriebsmittel erhalten neue Kennzeichen) Copier / couper / coller (les appareils reçoivent de nouveaux repères) Copiar / cortar / pegar (los dispositivos reciben nuevas designaciones) +Copy / paste: Ctrl+C, Ctrl+X, Ctrl+V Kopieren / Einfügen: Strg+C, Strg+X, Strg+V Copier / coller : Ctrl+C, Ctrl+X, Ctrl+V Copiar / pegar: Ctrl+C, Ctrl+X, Ctrl+V +Copy as new Als neu kopieren Copier comme nouveau Copiar como nuevo +Copy built-in… Eingebautes kopieren… Copier un élément intégré… Copiar incorporado… +Core Ader Âme Núcleo +Core designations separated by blanks Aderbezeichnungen, durch Leerzeichen getrennt Désignations des âmes, séparées par des espaces Designaciones de núcleos separadas por espacios +Cores Adern Âmes Núcleos +Cores used Adern belegt Âmes utilisées Núcleos usados +Corner Ecke Coin Esquina +Cover Deckblatt Page de garde Portada +Cover sheet Deckblatt Page de garde Portada +Create / update the part on the server (Ctrl+S) Artikel auf dem Server anlegen / aktualisieren (Strg+S) Créer / mettre à jour l'article sur le serveur (Ctrl+S) Crear / actualizar el artículo en el servidor (Ctrl+S) +Create an enclosure (➕ in the navigator on the left) to start the panel layout. Lege ein Gehäuse an (➕ in der Navigation links), um das Schaltschrank-Layout zu beginnen. Créez une enveloppe (➕ dans le navigateur à gauche) pour commencer l'implantation de l'armoire. Crea una envolvente (➕ en el navegador de la izquierda) para empezar la distribución del armario. +Create an enclosure in the panel layout first. Lege zuerst im Schaltschrank-Layout ein Gehäuse an. Créez d'abord une enveloppe dans l'implantation de l'armoire. Crea primero una envolvente en la distribución del armario. +Create revision Revision anlegen Créer une révision Crear revisión +Created by Erstellt von Créé par Creado por +Cross references Querverweise Renvois Referencias cruzadas +Cross-section Querschnitt Section Sección +Ctrl+A Ctrl+A Ctrl+A Ctrl+A +Ctrl+C / X / V Ctrl+C / X / V Ctrl+C / X / V Ctrl+C / X / V +Ctrl+S / Ctrl+O Ctrl+S / Ctrl+O Ctrl+S / Ctrl+O Ctrl+S / Ctrl+O +Ctrl+Z / Ctrl+Y Ctrl+Z / Ctrl+Y Ctrl+Z / Ctrl+Y Ctrl+Z / Ctrl+Y +Current Strom Courant Corriente +Cutout Ausschnitt Découpe Recorte +Cutout {} × {} mm Ausschnitt {} × {} mm Découpe {} × {} mm Recorte {} × {} mm +Cylinder, double-acting Zylinder, doppeltwirkend Vérin double effet Cilindro de doble efecto +DXF drawing DXF-Zeichnung Dessin DXF Dibujo DXF +Dark Dunkel Sombre Oscuro +Dashed Gestrichelt Pointillé Discontinuo +Datasheet (URL) Datenblatt (URL) Fiche technique (URL) Hoja de datos (URL) +Date Datum Date Fecha +Date of the last revision Datum der letzten Revision Date de la dernière révision Fecha de la última revisión +Default label Standardbezeichnung Désignation par défaut Designación predeterminada +Del Entf Suppr Supr +Delete Del Löschen Entf Supprimer Suppr Eliminar Supr +Delete (Del) Löschen (Entf) Supprimer (Suppr) Eliminar (Supr) +Delete cable (its wires are removed from it) Kabel löschen (seine Leitungen werden entfernt) Supprimer le câble (ses fils en sont retirés) Eliminar cable (sus hilos se quitan de él) +Delete enclosure Gehäuse löschen Supprimer l'enveloppe Eliminar envolvente +Delete harness (its wires are removed from it) Kabelbaum löschen (seine Leitungen werden entfernt) Supprimer le faisceau (ses fils en sont retirés) Eliminar mazo (sus hilos se quitan de él) +Delete page Seite löschen Supprimer la page Eliminar página +Delete part {} from the server? This cannot be undone. Artikel {} vom Server löschen? Das kann nicht rückgängig gemacht werden. Supprimer l'article {} du serveur ? Cette action est irréversible. ¿Eliminar el artículo {} del servidor? Esta acción no se puede deshacer. +Delete selection Auswahl löschen Supprimer la sélection Eliminar selección +Deleted part {} Artikel {} gelöscht Article {} supprimé Artículo {} eliminado +Deleting {}… Lösche {} … Suppression de {}… Eliminando {}… +Depth Tiefe Profondeur Profundidad +Depth / mounted at Tiefe / Montage bei Profondeur / montage à Profundidad / montaje a +Description Beschreibung Description Descripción +Description (since last revision) Beschreibung (seit der letzten Revision) Description (depuis la dernière révision) Descripción (desde la última revisión) +Description of the last revision Beschreibung der letzten Revision Description de la dernière révision Descripción de la última revisión +Designation Bezeichnung Désignation Designación +Device Betriebsmittel Appareil Dispositivo +Device list Betriebsmittelliste Liste des appareils Lista de dispositivos +Device selection Gerätewahl Sélection d'appareil Selección de dispositivo +Device tag Betriebsmittelkennzeichen Repère d'appareil Designación de dispositivo +Device {} Betriebsmittel {} Appareil {} Dispositivo {} +Devices Betriebsmittel Appareils Dispositivos +Devices placed on the page get its structure; their tags are shown without it. Auf der Seite platzierte Betriebsmittel erhalten deren Struktur; ihre Kennzeichen werden ohne sie angezeigt. Les appareils placés sur la page reprennent sa structure ; leurs repères sont affichés sans elle. Los dispositivos colocados en la página adoptan su estructura; sus designaciones se muestran sin ella. +Devices to place Zu platzierende Betriebsmittel Appareils à placer Dispositivos por colocar +Diameter Durchmesser Diamètre Diámetro +Different wire numbers in one connection: {} Unterschiedliche Leitungsnummern in einer Verbindung: {} Numéros de fil différents dans une liaison : {} Números de hilo distintos en una conexión: {} +Dimensions Abmessungen Dimensions Dimensiones +Diode Diode Diode Diodo +Discard the changes Änderungen verwerfen Abandonner les modifications Descartar los cambios +Discard the unsaved changes of {}? Die nicht gespeicherten Änderungen von {} verwerfen? Abandonner les modifications non enregistrées de {} ? ¿Descartar los cambios sin guardar de {}? +Door Tür Porte Puerta +Door (front view) Tür (Frontansicht) Porte (vue de face) Puerta (vista frontal) +Door clearance Türfreiraum Dégagement de porte Espacio libre de la puerta +Door: {} devices, {} cutouts Tür: {} Betriebsmittel, {} Ausschnitte Porte : {} appareils, {} découpes Puerta: {} dispositivos, {} recortes +Download project Ctrl+S Projekt herunterladen Strg+S Télécharger le projet Ctrl+S Descargar proyecto Ctrl+S +Downloaded {} parts (revision {}): {} new, {} updated {} Artikel heruntergeladen (Revision {}): {} neu, {} aktualisiert {} articles téléchargés (révision {}) : {} nouveaux, {} mis à jour {} artículos descargados (revisión {}): {} nuevos, {} actualizados +Downloading parts… Lade Artikel herunter … Téléchargement des articles… Descargando artículos… +Drag: orbit · right/middle drag: pan · wheel: zoom · click: select device or wire Ziehen: Orbit · Rechts-/Mittelklick-Ziehen: verschieben · Mausrad: Zoom · Klick: Betriebsmittel oder Leitung wählen Glisser : orbite · glisser avec clic droit/milieu : déplacer · molette : zoom · clic : sélectionner un appareil ou un fil Arrastrar: órbita · arrastrar con botón derecho/central: desplazar · rueda: zoom · clic: seleccionar dispositivo o hilo +Draw connections (W) Verbindungen zeichnen (W) Tracer des liaisons (W) Dibujar conexiones (W) +Duplicate Duplizieren Dupliquer Duplicar +Each point-to-point connection can belong to a harness Jede Punkt-zu-Punkt-Verbindung kann zu einem Kabelbaum gehören Chaque liaison point à point peut appartenir à un faisceau Cada conexión punto a punto puede pertenecer a un mazo +Edit Bearbeiten Édition Edición +Editable copy of this title block Bearbeitbare Kopie dieses Schriftfelds Copie modifiable de ce cartouche Copia editable de este cajetín +Emergency stop NC Not-Halt Öffner Arrêt d'urgence NF Parada de emergencia NC +Enclosure Gehäuse Enveloppe Envolvente +Enclosure not found - choose another one in the page properties Gehäuse nicht gefunden - wähle in den Seiteneigenschaften ein anderes Enveloppe introuvable - choisissez-en une autre dans les propriétés de la page Envolvente no encontrada - elige otra en las propiedades de la página +Enclosures Gehäuse Enveloppes Envolventes +End Ende Fin Fin +End treatment Endenbehandlung Traitement des extrémités Tratamiento de extremos +Enter the address of an openecraft-server and click Connect. Gib die Adresse eines openecraft-server ein und klicke auf Verbinden. Saisissez l'adresse d'un openecraft-server et cliquez sur Connecter. Introduce la dirección de un openecraft-server y haz clic en Conectar. +Esc Esc Échap Esc +Every connection gets one number for all its wires; the two sides of a terminal are separate connections. Jede Verbindung erhält eine Nummer für alle ihre Leitungen; die beiden Seiten einer Klemme sind getrennte Verbindungen. Chaque liaison reçoit un numéro pour tous ses fils ; les deux côtés d'une borne sont des liaisons distinctes. Cada conexión recibe un número para todos sus hilos; los dos lados de un borne son conexiones distintas. +Exchange parts with a global parts database (openecraft-server) Artikel mit einer globalen Artikeldatenbank austauschen (openecraft-server) Échanger des articles avec une base d'articles globale (openecraft-server) Intercambiar artículos con una base de datos global de artículos (openecraft-server) +Export all pages as DXF… Alle Seiten als DXF exportieren… Exporter toutes les pages en DXF… Exportar todas las páginas como DXF… +Export all pages for printing (HTML/PDF)… Alle Seiten für den Druck exportieren (HTML/PDF)… Exporter toutes les pages pour l'impression (HTML/PDF)… Exportar todas las páginas para imprimir (HTML/PDF)… +Export as CSV… Als CSV exportieren… Exporter en CSV… Exportar como CSV… +Export as JSON… Als JSON exportieren… Exporter en JSON… Exportar como JSON… +Export as PDF (bookmarks, linked cross references)… Als PDF exportieren (Lesezeichen, verlinkte Querverweise)… Exporter en PDF (signets, renvois liés)… Exportar como PDF (marcadores, referencias cruzadas vinculadas)… +Export failed: {} Export fehlgeschlagen: {} Échec de l'export : {} Error al exportar: {} +Export macros (JSON)… Makros exportieren (JSON)… Exporter les macros (JSON)… Exportar macros (JSON)… +Export page as DXF… Seite als DXF exportieren… Exporter la page en DXF… Exportar página como DXF… +Export page as SVG… Seite als SVG exportieren… Exporter la page en SVG… Exportar página como SVG… +Export production wire list (CSV)… Fertigungs-Leitungsliste exportieren (CSV)… Exporter la liste de câblage de production (CSV)… Exportar lista de cableado de producción (CSV)… +Exported {} {} exportiert {} exporté {} exportado +Exported {} parts to {} {} Artikel nach {} exportiert {} articles exportés vers {} {} artículos exportados a {} +External (top) Extern (oben) Externe (haut) Externo (arriba) +Extras Extras Extras Extras +F / Home F / Pos1 F / Origine F / Inicio +Ferrule Aderendhülse Embout Punta +Ferrule part Artikel Aderendhülse Article embout Artículo de punta +Field Feld Champ Campo +Field length Feldlänge Longueur sur site Longitud en campo +File Datei Fichier Archivo +Filled Gefüllt Rempli Relleno +Filter Filter Filtre Filtro +Filter (number, type, manufacturer, text …) Filter (Nummer, Typ, Hersteller, Text …) Filtre (numéro, type, fabricant, texte …) Filtro (número, tipo, fabricante, texto …) +Filter devices… Betriebsmittel filtern … Filtrer les appareils… Filtrar dispositivos… +Filter… Filter … Filtre… Filtro… +Fit page Seite einpassen Ajuster la page Ajustar página +Fit page F Seite einpassen F Ajuster la page F Ajustar página F +Fit page (F) Seite einpassen (F) Ajuster la page (F) Ajustar página (F) +Fluid power (ISO 1219) Fluidtechnik (ISO 1219) Hydraulique et pneumatique (ISO 1219) Neumática e hidráulica (ISO 1219) +Forms – title blocks and reports Formulare – Schriftfelder und Berichte Formulaires – cartouches et rapports Formularios – cajetines e informes +Form… Formular… Formulaire… Formulario… +From Von De De +Front view (2D) Frontansicht (2D) Vue de face (2D) Vista frontal (2D) +Full page name (=A1+CAB1/3) Vollständiger Seitenname (=A1+CAB1/3) Nom complet de la page (=A1+CAB1/3) Nombre completo de la página (=A1+CAB1/3) +Function Funktion Fonction Función +Function = Funktion = Fonction = Función = +Function of the page Funktion der Seite Fonction de la page Función de la página +Function template Funktionsvorlage Modèle de fonction Plantilla de función +Function text Funktionstext Texte de fonction Texto de función +Functions Funktionen Fonctions Funciones +Functions the part provides. Used for device selection, the contact image (reserve contacts), the project check and to assign connection designations. Designations are listed in symbol connection order, separated by blanks. Funktionen, die der Artikel bietet. Verwendet für die Gerätewahl, das Kontaktbild (Reservekontakte), die Projektprüfung und die Vergabe von Anschlussbezeichnungen. Bezeichnungen werden in der Anschlussreihenfolge des Symbols aufgeführt, durch Leerzeichen getrennt. Fonctions fournies par l'article. Utilisées pour la sélection d'appareil, l'image des contacts (contacts de réserve), le contrôle du projet et l'attribution des désignations de connexion. Les désignations sont listées dans l'ordre des connexions du symbole, séparées par des espaces. Funciones que ofrece el artículo. Se usan para la selección de dispositivos, la imagen de contactos (contactos de reserva), la comprobación del proyecto y la asignación de designaciones de conexión. Las designaciones se enumeran en el orden de conexión del símbolo, separadas por espacios. +Fuse Sicherung Fusible Fusible +Fuse (single-line) Sicherung (einpolig dargestellt) Fusible (unifilaire) Fusible (unifilar) +General Allgemein Général General +Generated page – edit via page properties Erzeugte Seite – bearbeiten über die Seiteneigenschaften Page générée – à modifier via les propriétés de la page Página generada – editar mediante las propiedades de la página +Graphic line Grafische Linie Ligne graphique Línea gráfica +Graphic rectangle Grafisches Rechteck Rectangle graphique Rectángulo gráfico +Graphics Grafik Graphiques Gráficos +Grid Raster Grille Cuadrícula +Group in the symbol list, e.g. your company Gruppe in der Symbolliste, z. B. deine Firma Groupe dans la liste des symboles, p. ex. votre société Grupo en la lista de símbolos, p. ej. tu empresa +HTML document HTML-Dokument Document HTML Documento HTML +Harness Kabelbaum Faisceau Mazo +Harness data Kabelbaumdaten Données de faisceau Datos de mazos +Harness {} has no wires Kabelbaum {} hat keine Leitungen Le faisceau {} n'a aucun fil El mazo {} no tiene hilos +Harness {}: connection {} – {} does not exist in the schematic Kabelbaum {}: Verbindung {} – {} existiert im Schaltplan nicht Faisceau {} : la liaison {} – {} n'existe pas dans le schéma Mazo {}: la conexión {} – {} no existe en el esquema +Harnesses Kabelbäume Faisceaux Mazos +Harnesses… Kabelbäume… Faisceaux… Mazos… +Height Höhe Hauteur Altura +Height (mm) Höhe (mm) Hauteur (mm) Altura (mm) +Help Hilfe Aide Ayuda +Horn / buzzer Hupe / Summer Klaxon / avertisseur Bocina / zumbador +Hydraulic pump Hydraulikpumpe Pompe hydraulique Bomba hidráulica +Identifier Kennung Identifiant Identificador +Identifying letter Kennbuchstabe Lettre d'identification Letra identificativa +Identifying letter of devices using this part (K, Q, S …) Kennbuchstabe von Betriebsmitteln mit diesem Artikel (K, Q, S …) Lettre d'identification des appareils utilisant cet article (K, Q, S …) Letra identificativa de los dispositivos que usan este artículo (K, Q, S …) +Import / export Import / Export Import / export Importar / exportar +Import STL / OBJ… STL / OBJ importieren… Importer STL / OBJ… Importar STL / OBJ… +Import SVG… SVG importieren… Importer SVG… Importar SVG… +Import macros… Makros importieren… Importer des macros… Importar macros… +Import parts (CSV / JSON)… Artikel importieren (CSV / JSON)… Importer des articles (CSV / JSON)… Importar artículos (CSV / JSON)… +Imported {} macros {} Makros importiert {} macros importées {} macros importadas +Imported {} parts into the database {} Artikel in die Datenbank importiert {} articles importés dans la base de données {} artículos importados en la base de datos +Imported {} title blocks {} Schriftfelder importiert {} cartouches importés {} cajetines importados +In strip order; PE and other non-numeric terminals keep their designation In Leistenreihenfolge; PE und andere nicht numerische Klemmen behalten ihre Bezeichnung Dans l'ordre du bornier ; PE et les autres bornes non numériques conservent leur désignation En el orden de la regleta; PE y otros bornes no numéricos conservan su designación +In the structure of the current page In der Struktur der aktuellen Seite Dans la structure de la page actuelle En la estructura de la página actual +Include manually set numbers Manuell gesetzte Nummern einbeziehen Inclure les numéros définis manuellement Incluir los números definidos manualmente +Index Index Indice Índice +Indicator lamp Meldeleuchte Voyant lumineux Piloto luminoso +Insert Einfügen Insertion Insertar +Insert with Einfügen mit Insérer avec Insertar con +Internal (bottom) Intern (unten) Interne (bas) Interno (abajo) +Interruption point Unterbrechungspunkt Point d'interruption Punto de interrupción +Interruption point '{}' has no counterpart Unterbrechungspunkt '{}' hat keine Gegenstelle Le point d'interruption '{}' n'a pas de correspondant El punto de interrupción '{}' no tiene contraparte +Item Element Élément Elemento +Jumper Brücke Pont Puente +K, Q, MM … K, Q, MM … K, Q, MM … K, Q, MM … +KBL harness data (XML) KBL-Kabelbaumdaten (XML) Données de faisceau KBL (XML) Datos de mazos KBL (XML) +Key: {} Schlüssel: {} Clé : {} Clave: {} +Label Beschriftung Libellé Etiqueta +Label (grey) Beschriftung (grau) Libellé (gris) Etiqueta (gris) +Label field Beschriftungsfeld Champ de libellé Campo de etiqueta +Language Sprache Langue Idioma +Last revision Letzte Revision Dernière révision Última revisión +Left Links Gauche Izquierda +Length Länge Longueur Longitud +Length (m) Länge (m) Longueur (m) Longitud (m) +Length (mm) Länge (mm) Longueur (mm) Longitud (mm) +Length of wires that are not routed in the panel layout Länge der Leitungen, die im Schaltschrank-Layout nicht geroutet sind Longueur des fils non routés dans l'implantation de l'armoire Longitud de los hilos que no están tendidos en la distribución del armario +Length {} mm Länge {} mm Longueur {} mm Longitud {} mm +Library Bibliothek Bibliothèque Biblioteca +Light Hell Clair Claro +Line Linie Ligne Línea +Line width Linienstärke Épaisseur de ligne Grosor de línea +Literal braces Geschweifte Klammern (wörtlich) Accolades littérales Llaves literales +Load all parts from the server again Alle Artikel erneut vom Server laden Recharger tous les articles depuis le serveur Volver a cargar todos los artículos del servidor +Loaded {} parts (revision {}) {} Artikel geladen (Revision {}) {} articles chargés (révision {}) {} artículos cargados (revisión {}) +Location Ort Emplacement Ubicación +Location + Ort + Emplacement + Ubicación + +Location of the page Ort der Seite Emplacement de la page Ubicación de la página +Lock all Alle sperren Tout verrouiller Bloquear todo +Longer values are drawn smaller (0 = no limit) Längere Werte werden kleiner gezeichnet (0 = keine Begrenzung) Les valeurs plus longues sont dessinées plus petites (0 = sans limite) Los valores más largos se dibujan más pequeños (0 = sin límite) +Macro {} replaced Makro {} ersetzt Macro {} remplacée Macro {} reemplazada +Macro {} saved Makro {} gespeichert Macro {} enregistrée Macro {} guardada +Macros Makros Macros Macros +Macros… Makros… Macros… Macros… +Macro… Makro… Macro… Macro… +Main Haupt Principal Principal +Main contact 1-pole Hauptkontakt 1-polig Contact principal 1 pôle Contacto principal 1 polo +Main contacts 3-pole Hauptkontakte 3-polig Contacts principaux 3 pôles Contactos principales 3 polos +Main function Hauptfunktion Fonction principale Función principal +Main function with contact image Hauptfunktion mit Kontaktbild Fonction principale avec image des contacts Función principal con imagen de contactos +Manufacturer Hersteller Fabricant Fabricante +Max. width Max. Breite Largeur max. Ancho máx. +Merge a symbol library file Eine Symbolbibliotheksdatei zusammenführen Fusionner un fichier de bibliothèque de symboles Combinar un archivo de biblioteca de símbolos +Mirror Spiegeln Miroir Reflejar +Mirror M Spiegeln M Miroir M Reflejar M +Model import failed: {} Modellimport fehlgeschlagen: {} Échec de l'import du modèle : {} Error al importar el modelo: {} +Motor (single-line) Motor (einpolig dargestellt) Moteur (unifilaire) Motor (unifilar) +Motor 1-phase Motor 1-phasig Moteur monophasé Motor monofásico +Motor 3-phase Motor 3-phasig Moteur triphasé Motor trifásico +Motor protection switch Motorschutzschalter Disjoncteur-moteur Guardamotor +Motors / Loads Motoren / Lasten Moteurs / charges Motores / cargas +Mounted on Montiert auf Monté sur Montado en +Mounting Montage Montage Montaje +Mounting data Montagedaten Données de montage Datos de montaje +Mounting layout Montageplan Implantation Distribución de montaje +Mounting layout {} Montageplan {} Implantation {} Distribución de montaje {} +Mounting plate Montageplatte Plaque de montage Placa de montaje +Mounting plate: {} holes, {} cutouts Montageplatte: {} Bohrungen, {} Ausschnitte Plaque de montage : {} perçages, {} découpes Placa de montaje: {} taladros, {} recortes +Mounting rail Tragschiene Rail de montage Carril de montaje +Move page down Seite nach unten schieben Déplacer la page vers le bas Mover página hacia abajo +Move page up Seite nach oben schieben Déplacer la page vers le haut Mover página hacia arriba +Move selection by one grid step Auswahl um einen Rasterschritt verschieben Déplacer la sélection d'un pas de grille Mover la selección un paso de cuadrícula +Move the devices of this page into the new structure Die Betriebsmittel dieser Seite in die neue Struktur verschieben Déplacer les appareils de cette page dans la nouvelle structure Mover los dispositivos de esta página a la nueva estructura +NC contact Öffner Contact NF Contacto NC +NC contact (NFPA) Öffner (NFPA) Contact NF (NFPA) Contacto NC (NFPA) +NFPA / JIC NFPA / JIC NFPA / JIC NFPA / JIC +NO contact Schließer Contact NO Contacto NA +NO contact (NFPA) Schließer (NFPA) Contact NO (NFPA) Contacto NA (NFPA) +Name Name Nom Nombre +Name; Data Type; Logical Address; Comment – for PLC programming tools Name; Datentyp; Logische Adresse; Kommentar – für SPS-Programmierwerkzeuge Nom ; Type de données ; Adresse logique ; Commentaire – pour les outils de programmation API Nombre; Tipo de datos; Dirección lógica; Comentario – para herramientas de programación PLC +New cover sheet Neues Deckblatt Nouvelle page de garde Nueva portada +New empty Neu, leer Nouveau, vide Nuevo, vacío +New enclosure Neues Gehäuse Nouvelle enveloppe Nueva envolvente +New mounting layout page Neue Montageplan-Seite Nouvelle page d'implantation Nueva página de distribución de montaje +New part based on the open one Neuer Artikel auf Basis des geöffneten Nouvel article basé sur celui qui est ouvert Nuevo artículo basado en el abierto +New project Neues Projekt Nouveau projet Nuevo proyecto +New report page Neue Berichtsseite Nouvelle page de rapport Nueva página de informe +New revision Neue Revision Nouvelle révision Nueva revisión +New schematic page Neue Schaltplanseite Nouvelle page de schéma Nueva página de esquema +New schematic page after the current one Neue Schaltplanseite nach der aktuellen Nouvelle page de schéma après la page actuelle Nueva página de esquema después de la actual +Next free contact numbers on this device Nächste freie Kontaktnummern an diesem Betriebsmittel Prochains numéros de contact libres sur cet appareil Próximos números de contacto libres en este dispositivo +Next page (Page Down) Nächste Seite (Bild ab) Page suivante (Page suiv.) Página siguiente (Av Pág) +No PLC inputs / outputs placed. Keine SPS-Ein- / Ausgänge platziert. Aucune entrée / sortie API placée. No hay entradas / salidas PLC colocadas. +No cables defined. Keine Kabel definiert. Aucun câble défini. No hay cables definidos. +No cables yet – Project › Cables… Noch keine Kabel – Projekt › Kabel… Aucun câble pour l'instant – Projet › Câbles… Aún no hay cables – Proyecto › Cables… +No changes since the last revision. Keine Änderungen seit der letzten Revision. Aucune modification depuis la dernière révision. No hay cambios desde la última revisión. +No devices yet. Pick a symbol from the library on the right and click into the page. Noch keine Betriebsmittel. Wähle rechts in der Bibliothek ein Symbol und klicke in die Seite. Aucun appareil pour l'instant. Choisissez un symbole dans la bibliothèque à droite et cliquez dans la page. Aún no hay dispositivos. Elige un símbolo de la biblioteca de la derecha y haz clic en la página. +No enclosure yet – create one with ➕. Noch kein Gehäuse – lege eines mit ➕ an. Aucune enveloppe pour l'instant – créez-en une avec ➕. Aún no hay envolvente – crea una con ➕. +No harnesses defined. Keine Kabelbäume definiert. Aucun faisceau défini. No hay mazos definidos. +No harnesses yet – Project › Harnesses… Noch keine Kabelbäume – Projekt › Kabelbäume… Aucun faisceau pour l'instant – Projet › Faisceaux… Aún no hay mazos – Proyecto › Mazos… +No identifying letter for the device tag. Kein Kennbuchstabe für das Betriebsmittelkennzeichen. Pas de lettre d'identification pour le repère d'appareil. Falta la letra identificativa de la designación del dispositivo. +No macros yet. Select items in a schematic and save them as a macro. Noch keine Makros. Wähle Elemente in einem Schaltplan und speichere sie als Makro. Aucune macro pour l'instant. Sélectionnez des éléments dans un schéma et enregistrez-les comme macro. Aún no hay macros. Selecciona elementos en un esquema y guárdalos como macro. +No parts found. Keine Artikel gefunden. Aucun article trouvé. No se encontraron artículos. +No parts of the product group Cables in the parts database. Keine Artikel der Produktgruppe Kabel in der Artikeldatenbank. Aucun article du groupe de produits Câbles dans la base d'articles. No hay artículos del grupo de productos Cables en la base de datos de artículos. +No revision yet. Changes are tracked from the first revision on. Noch keine Revision. Änderungen werden ab der ersten Revision verfolgt. Aucune révision pour l'instant. Les modifications sont suivies à partir de la première révision. Aún no hay revisión. Los cambios se registran a partir de la primera revisión. +No terminal strips: place terminals in a schematic first. Keine Klemmenleisten: Platziere zuerst Klemmen in einem Schaltplan. Aucun bornier : placez d'abord des bornes dans un schéma. No hay regletas de bornes: coloca primero bornes en un esquema. +No user symbols yet. Create one or copy a built-in symbol. Noch keine Benutzersymbole. Erstelle eines oder kopiere ein eingebautes Symbol. Aucun symbole utilisateur pour l'instant. Créez-en un ou copiez un symbole intégré. Aún no hay símbolos de usuario. Crea uno o copia un símbolo incorporado. +Not a macro file: {} Keine Makrodatei: {} Ce n'est pas un fichier de macros : {} No es un archivo de macros: {} +Not a symbol library: {} Keine Symbolbibliothek: {} Ce n'est pas une bibliothèque de symboles : {} No es una biblioteca de símbolos: {} +Not a title block file: {} Keine Schriftfelddatei: {} Ce n'est pas un fichier de cartouches : {} No es un archivo de cajetines: {} +Not a valid project file: {} Keine gültige Projektdatei: {} Fichier de projet non valide : {} No es un archivo de proyecto válido: {} +Not in the project parts – synchronize in parts management Nicht in den Projektartikeln – in der Artikelverwaltung synchronisieren Absent des articles du projet – synchroniser dans la gestion des articles No está en los artículos del proyecto – sincroniza en la gestión de artículos +Note Hinweis Remarque Nota +Number contacts automatically (13/14, 21/22 …) Kontakte automatisch nummerieren (13/14, 21/22 …) Numéroter les contacts automatiquement (13/14, 21/22 …) Numerar los contactos automáticamente (13/14, 21/22 …) +Number of pages Seitenanzahl Nombre de pages Número de páginas +Number of sheets Anzahl der Blätter Nombre de feuilles Número de hojas +Number wires Leitungen nummerieren Numéroter les fils Numerar hilos +Numbers removed from {} wires Nummern von {} Leitungen entfernt Numéros retirés de {} fils Números eliminados de {} hilos +Only parts whose function template provides the device's main function Nur Artikel, deren Funktionsvorlage die Hauptfunktion des Betriebsmittels bietet Uniquement les articles dont le modèle de fonction fournit la fonction principale de l'appareil Solo artículos cuya plantilla de función ofrece la función principal del dispositivo +Open connection point {} ({}) Offener Anschlusspunkt {} ({}) Point de connexion ouvert {} ({}) Punto de conexión abierto {} ({}) +Open datasheet Datenblatt öffnen Ouvrir la fiche technique Abrir hoja de datos +Open demo project Demoprojekt öffnen Ouvrir le projet de démonstration Abrir proyecto de demostración +OpenECraft OpenECraft OpenECraft OpenECraft +OpenECraft macros (JSON) OpenECraft-Makros (JSON) Macros OpenECraft (JSON) Macros de OpenECraft (JSON) +OpenECraft parts manager OpenECraft-Artikelverwaltung Gestionnaire d'articles OpenECraft Gestor de artículos de OpenECraft +OpenECraft project OpenECraft-Projekt Projet OpenECraft Proyecto de OpenECraft +OpenECraft symbol library OpenECraft-Symbolbibliothek Bibliothèque de symboles OpenECraft Biblioteca de símbolos de OpenECraft +OpenECraft symbol library (JSON) OpenECraft-Symbolbibliothek (JSON) Bibliothèque de symboles OpenECraft (JSON) Biblioteca de símbolos de OpenECraft (JSON) +OpenECraft title blocks OpenECraft-Schriftfelder Cartouches OpenECraft Cajetines de OpenECraft +OpenECraft title blocks (JSON) OpenECraft-Schriftfelder (JSON) Cartouches OpenECraft (JSON) Cajetines de OpenECraft (JSON) +OpenECraft – usage OpenECraft – Bedienung OpenECraft – utilisation OpenECraft – uso +Opened {} {} geöffnet {} ouvert {} abierto +Opening in the mounting plate / door: click two corners (round: in the properties) Öffnung in Montageplatte / Tür: Zwei Ecken anklicken (rund: in den Eigenschaften) Ouverture dans la plaque de montage / la porte : cliquez sur deux coins (rond : dans les propriétés) Abertura en la placa de montaje / puerta: haz clic en dos esquinas (redonda: en las propiedades) +Open… Ctrl+O Öffnen… Strg+O Ouvrir… Ctrl+O Abrir… Ctrl+O +Order number Bestellnummer Référence de commande Número de pedido +Orientation Ausrichtung Orientation Orientación +Overload aux contact NC Überlast-Hilfskontakt Öffner Contact auxiliaire de relais thermique NF Contacto auxiliar de relé térmico NC +Overload heater (NFPA) Überlast-Heizelement (NFPA) Élément chauffant de relais thermique (NFPA) Elemento térmico de sobrecarga (NFPA) +Overview / single-line Übersicht / einpolig Vue d'ensemble / unifilaire Resumen / unifilar +PDF document PDF-Dokument Document PDF Documento PDF +PE PE PE PE +PE terminal PE-Klemme Borne PE Borne PE +PLC SPS API PLC +PLC address {} used on several cards: {} SPS-Adresse {} an mehreren Karten verwendet: {} Adresse API {} utilisée sur plusieurs cartes : {} Dirección PLC {} usada en varias tarjetas: {} +PLC assignment list SPS-Zuordnungsliste Liste d'affectation API Lista de asignación PLC +PLC card SPS-Karte Carte API Tarjeta PLC +PLC card 8 digital inputs SPS-Karte 8 digitale Eingänge Carte API 8 entrées numériques Tarjeta PLC 8 entradas digitales +PLC card 8 digital outputs SPS-Karte 8 digitale Ausgänge Carte API 8 sorties numériques Tarjeta PLC 8 salidas digitales +PLC connection point SPS-Anschlusspunkt Point de connexion API Punto de conexión PLC +PLC digital input SPS-Digitaleingang Entrée numérique API Entrada digital PLC +PLC digital output SPS-Digitalausgang Sortie numérique API Salida digital PLC +PLC overview SPS-Übersicht Vue d'ensemble API Resumen PLC +PLC overview… SPS-Übersicht… Vue d'ensemble API… Resumen PLC… +Packaging quantity Verpackungseinheit Quantité par conditionnement Cantidad por embalaje +Page Seite Page Página +Page / column (3.4.1) Seite / Spalte (3.4.1) Page / colonne (3.4.1) Página / columna (3.4.1) +Page Up / Down Bild auf / Bild ab Page préc. / suiv. Re Pág / Av Pág +Page description Seitenbeschreibung Description de la page Descripción de la página +Page heading Seitenüberschrift Titre de la page Encabezado de la página +Page macro {} inserted as page {} Seitenmakro {} als Seite {} eingefügt Macro de page {} insérée comme page {} Macro de página {} insertada como página {} +Page macro: {} Seitenmakro: {} Macro de page : {} Macro de página: {} +Page name / number Seitenname / -nummer Nom / numéro de page Nombre / número de página +Page number Seitennummer Numéro de page Número de página +Page properties Seiteneigenschaften Propriétés de la page Propiedades de la página +Page properties… Seiteneigenschaften… Propriétés de la page… Propiedades de la página… +Page structure (=A1+CAB1) Seitenstruktur (=A1+CAB1) Structure de la page (=A1+CAB1) Estructura de la página (=A1+CAB1) +Page type Seitentyp Type de page Tipo de página +Page {} {} Seite {} {} Page {} {} Página {} {} +Page {} (deleted) Seite {} (gelöscht) Page {} (supprimée) Página {} (eliminada) +Page {} ({}) Seite {} ({}) Page {} ({}) Página {} ({}) +Page {} locked Seite {} gesperrt Page {} verrouillée Página {} bloqueada +Page {} – {} Seite {} – {} Page {} – {} Página {} – {} +Pages Seiten Pages Páginas +Pages using it get the project default Seiten, die es verwenden, erhalten den Projektstandard Les pages qui l'utilisent prennent la valeur par défaut du projet Las páginas que lo usan reciben el valor predeterminado del proyecto +Part Artikel Article Artículo +Part number Artikelnummer Numéro d'article Número de artículo +Part number already exists Artikelnummer existiert bereits Le numéro d'article existe déjà El número de artículo ya existe +Part selection from the parts database Artikelauswahl aus der Artikeldatenbank Sélection d'article dans la base d'articles Selección de artículo de la base de datos de artículos +Part selection – {} Artikelauswahl – {} Sélection d'article – {} Selección de artículo – {} +Parts Artikel Articles Artículos +Parts (CSV, JSON) Artikel (CSV, JSON) Articles (CSV, JSON) Artículos (CSV, JSON) +Parts import failed: {} Artikelimport fehlgeschlagen: {} Échec de l'import des articles : {} Error al importar artículos: {} +Parts management Artikelverwaltung Gestion des articles Gestión de artículos +Parts management… Artikelverwaltung… Gestion des articles… Gestión de artículos… +Parts server: {} Artikelserver: {} Serveur d'articles : {} Servidor de artículos: {} +Passive components Passive Bauteile Composants passifs Componentes pasivos +Pilot light (NFPA) Meldeleuchte (NFPA) Voyant (NFPA) Piloto luminoso (NFPA) +Place text (T) Text platzieren (T) Placer un texte (T) Colocar texto (T) +Placed Platziert Placé Colocado +Placed {}× in the project {}× im Projekt platziert Placé {}× dans le projet Colocado {}× en el proyecto +Placeholders Platzhalter Variables Marcadores +Placeholders like {MOTOR} in tags, texts and function texts are filled in when inserting. Platzhalter wie {MOTOR} in Kennzeichen, Texten und Funktionstexten werden beim Einfügen gefüllt. Les variables comme {MOTOR} dans les repères, textes et textes de fonction sont remplies à l'insertion. Los marcadores como {MOTOR} en designaciones, textos y textos de función se rellenan al insertar. +Placing {} Platziere {} Placement de {} Colocando {} +Placing: {} Platziere: {} Placement : {} Colocando: {} +Plate outline, holes per diameter, cutouts Plattenumriss, Bohrungen je Durchmesser, Ausschnitte Contour de la plaque, perçages par diamètre, découpes Contorno de la placa, taladros por diámetro, recortes +Points Punkte Points Puntos +Polyline / rectangle Polylinie / Rechteck Polyligne / rectangle Polilínea / rectángulo +Pos Pos Pos Pos +Position Position Position Posición +Position of the device tag (instead of the tag block) Position des Betriebsmittelkennzeichens (anstelle des Kennzeichenblocks) Position du repère d'appareil (au lieu du bloc de repère) Posición de la designación del dispositivo (en lugar del bloque de designación) +Position of the label (terminal number, address …) Position der Beschriftung (Klemmennummer, Adresse …) Position du libellé (numéro de borne, adresse …) Posición de la etiqueta (número de borne, dirección …) +Position switch NO Positionsschalter Schließer Interrupteur de position NO Interruptor de posición NA +Potential Potenzial Potentiel Potencial +Potential (custom) Potenzial (benutzerdefiniert) Potentiel (personnalisé) Potencial (personalizado) +Potential +24V Potenzial +24V Potentiel +24V Potencial +24V +Potential 0V Potenzial 0V Potentiel 0V Potencial 0V +Potential L1 Potenzial L1 Potentiel L1 Potencial L1 +Potential L2 Potenzial L2 Potentiel L2 Potencial L2 +Potential L3 Potenzial L3 Potentiel L3 Potencial L3 +Potential N Potenzial N Potentiel N Potencial N +Potential PE Potenzial PE Potentiel PE Potencial PE +Potential name Potenzialname Nom du potentiel Nombre del potencial +Potential name (L1, +24V, otherwise counted) Potenzialname (L1, +24V, sonst gezählt) Nom du potentiel (L1, +24V, sinon compté) Nombre del potencial (L1, +24V, si no, contado) +Potential overview Potenzialübersicht Vue d'ensemble des potentiels Resumen de potenciales +Potential: {} Potenzial: {} Potentiel : {} Potencial: {} +Potentials / Connectors Potenziale / Stecker Potentiels / connecteurs Potenciales / conectores +Power Leistung Puissance Potencia +Power supply AC/DC Netzteil AC/DC Alimentation AC/DC Fuente de alimentación AC/DC +Prefix Präfix Préfixe Prefijo +Pressure gauge Manometer Manomètre Manómetro +Previous / next page Vorherige / nächste Seite Page précédente / suivante Página anterior / siguiente +Previous page (Page Up) Vorherige Seite (Bild auf) Page précédente (Page préc.) Página anterior (Re Pág) +Price Preis Prix Precio +Price unit Preiseinheit Unité de prix Unidad de precio +Prices / other Preise / Sonstiges Prix / divers Precios / otros +Product group Produktgruppe Groupe de produits Grupo de productos +Product subgroup Produktuntergruppe Sous-groupe de produits Subgrupo de productos +Product top group Produkthauptgruppe Groupe de produits principal Grupo principal de productos +Production wire list and bill of materials Fertigungs-Leitungsliste und Stückliste Liste de câblage de production et nomenclature Lista de cableado de producción y lista de materiales +Project Projekt Projet Proyecto +Project default; pages can choose their own in the page properties Projektstandard; Seiten können in den Seiteneigenschaften einen eigenen wählen Valeur par défaut du projet ; les pages peuvent choisir la leur dans leurs propriétés Valor predeterminado del proyecto; las páginas pueden elegir el suyo en sus propiedades +Project description Projektbeschreibung Description du projet Descripción del proyecto +Project name Projektname Nom du projet Nombre del proyecto +Project parts are the copies stored in this project; they are used for the bill of materials and the project check. Projektartikel sind die in diesem Projekt gespeicherten Kopien; sie werden für die Stückliste und die Projektprüfung verwendet. Les articles du projet sont les copies enregistrées dans ce projet ; ils servent à la nomenclature et au contrôle du projet. Los artículos del proyecto son las copias guardadas en este proyecto; se usan para la lista de materiales y la comprobación del proyecto. +Project properties Projekteigenschaften Propriétés du projet Propiedades del proyecto +Project properties… Projekteigenschaften… Propriétés du projet… Propiedades del proyecto… +Project revision Projektrevision Révision du projet Revisión del proyecto +Properties Eigenschaften Propriétés Propiedades +Protective devices Schutzgeräte Appareils de protection Dispositivos de protección +Protective earth Schutzerde Terre de protection Tierra de protección +Proximity sensor NO Näherungsschalter Schließer Capteur de proximité NO Sensor de proximidad NA +Push button NC Taster Öffner Bouton-poussoir NF Pulsador NC +Push button NC (NFPA) Taster Öffner (NFPA) Bouton-poussoir NF (NFPA) Pulsador NC (NFPA) +Push button NO Taster Schließer Bouton-poussoir NO Pulsador NA +Push button NO (NFPA) Taster Schließer (NFPA) Bouton-poussoir NO (NFPA) Pulsador NA (NFPA) +Qty Menge Qté Cant. +Quantity unit Mengeneinheit Unité de quantité Unidad de cantidad +Quit Beenden Quitter Salir +Rack Baugruppenträger Châssis Bastidor +Radius Radius Rayon Radio +Readdress card Karte neu adressieren Réadresser la carte Redireccionar tarjeta +Rectangle Rechteck Rectangle Rectángulo +Rectangular Rechteckig Rectangulaire Rectangular +Redo Ctrl+Y Wiederholen Strg+Y Rétablir Ctrl+Y Rehacer Ctrl+Y +Redo (Ctrl+Y) Wiederholen (Strg+Y) Rétablir (Ctrl+Y) Rehacer (Ctrl+Y) +Refresh example catalog parts (GEN.*) Beispielkatalog-Artikel (GEN.*) aktualisieren Actualiser les articles du catalogue d'exemple (GEN.*) Actualizar los artículos del catálogo de ejemplo (GEN.*) +Relay / contactor coil Relais- / Schützspule Bobine de relais / contacteur Bobina de relé / contactor +Relay coil (NFPA) Relaisspule (NFPA) Bobine de relais (NFPA) Bobina de relé (NFPA) +Release: lock all pages Freigeben: alle Seiten sperren Valider : verrouiller toutes les pages Liberar: bloquear todas las páginas +Released page – unlock it in Project › Revisions to change it Freigegebene Seite – zum Ändern unter Projekt › Revisionen entsperren Page validée – déverrouillez-la dans Projet › Révisions pour la modifier Página liberada – desbloquéala en Proyecto › Revisiones para modificarla +Remove from cable Aus Kabel entfernen Retirer du câble Quitar del cable +Remove from harness Aus Kabelbaum entfernen Retirer du faisceau Quitar del mazo +Remove from the harness Aus dem Kabelbaum entfernen Retirer du faisceau Quitar del mazo +Remove numbers Nummern entfernen Supprimer les numéros Quitar números +Remove part Artikel entfernen Retirer l'article Quitar artículo +Remove unused project parts Nicht verwendete Projektartikel entfernen Supprimer les articles du projet inutilisés Quitar artículos del proyecto no usados +Rename device Betriebsmittel umbenennen Renommer l'appareil Renombrar dispositivo +Renames the devices (all their functions, also on other pages) Benennt die Betriebsmittel um (alle ihre Funktionen, auch auf anderen Seiten) Renomme les appareils (toutes leurs fonctions, y compris sur d'autres pages) Renombra los dispositivos (todas sus funciones, también en otras páginas) +Renumber 1 … n Neu nummerieren 1 … n Renuméroter 1 … n Renumerar 1 … n +Renumber contact Kontakt neu nummerieren Renuméroter le contact Renumerar contacto +Replaces the GEN.* parts in the database with the current example catalog (including models) Ersetzt die GEN.*-Artikel in der Datenbank durch den aktuellen Beispielkatalog (inklusive Modelle) Remplace les articles GEN.* de la base par le catalogue d'exemple actuel (modèles inclus) Reemplaza los artículos GEN.* de la base de datos por el catálogo de ejemplo actual (incluidos los modelos) +Report Bericht Rapport Informe +Report forms Berichtsformulare Formulaires de rapport Formularios de informe +Report with all harness wires Bericht mit allen Kabelbaum-Leitungen Rapport avec tous les fils du faisceau Informe con todos los hilos del mazo +Report: {} Bericht: {} Rapport : {} Informe: {} +Reports Berichte Rapports Informes +Reset to standard Auf Standard zurücksetzen Rétablir la valeur standard Restablecer al estándar +Resistor Widerstand Résistance Resistencia +Revision Revision Révision Revisión +Revision marks Revisionsmarken Repères de révision Marcas de revisión +Revision overview (changes) Revisionsübersicht (Änderungen) Vue d'ensemble des révisions (modifications) Resumen de revisiones (cambios) +Revision {} created Revision {} angelegt Révision {} créée Revisión {} creada +Revisions Revisionen Révisions Revisiones +Revisions… Revisionen… Révisions… Revisiones… +Right Rechts Droite Derecha +Rotate R Drehen R Pivoter R Girar R +Rotate (R) Drehen (R) Pivoter (R) Girar (R) +Rotate / mirror (selection or symbol being placed) Drehen / Spiegeln (Auswahl oder zu platzierendes Symbol) Pivoter / miroir (sélection ou symbole en cours de placement) Girar / reflejar (selección o símbolo que se está colocando) +Rotate 90°: Um 90° drehen: Pivoter de 90° : Girar 90°: +Round Rund Rond Redondo +Routing Verlegung Cheminement Tendido +Rows per page Zeilen pro Seite Lignes par page Filas por página +SVG image SVG-Grafik Image SVG Imagen SVG +Save Ctrl+S Speichern Strg+S Enregistrer Ctrl+S Guardar Ctrl+S +Save / open Speichern / Öffnen Enregistrer / ouvrir Guardar / abrir +Save as macro Als Makro speichern Enregistrer comme macro Guardar como macro +Save as… Speichern unter… Enregistrer sous… Guardar como… +Save page as macro… Seite als Makro speichern… Enregistrer la page comme macro… Guardar página como macro… +Save selection as macro… Auswahl als Makro speichern… Enregistrer la sélection comme macro… Guardar selección como macro… +Saved part {} Artikel {} gespeichert Article {} enregistré Artículo {} guardado +Saved {} {} gespeichert {} enregistré {} guardado +Saving failed: {} Speichern fehlgeschlagen: {} Échec de l'enregistrement : {} Error al guardar: {} +Saving {}… Speichere {} … Enregistrement de {}… Guardando {}… +Scale × Maßstab × Échelle × Escala × +Schematic Schaltplan Schéma Esquema +Schematic (multi-line) Schaltplan (mehrpolig) Schéma (multifilaire) Esquema (multifilar) +Search… Suchen … Rechercher… Buscar… +Select / move (Esc) Auswählen / Verschieben (Esc) Sélectionner / déplacer (Échap) Seleccionar / mover (Esc) +Select a macro. Wähle ein Makro. Sélectionnez une macro. Selecciona una macro. +Select a part in the tree or create a new one. Wähle einen Artikel im Baum oder lege einen neuen an. Sélectionnez un article dans l'arborescence ou créez-en un nouveau. Selecciona un artículo en el árbol o crea uno nuevo. +Select a part. Double click adds it to the device. Wähle einen Artikel. Doppelklick fügt ihn dem Betriebsmittel hinzu. Sélectionnez un article. Un double-clic l'ajoute à l'appareil. Selecciona un artículo. Doble clic lo añade al dispositivo. +Select all Alles auswählen Tout sélectionner Seleccionar todo +Select all Ctrl+A Alles auswählen Strg+A Tout sélectionner Ctrl+A Seleccionar todo Ctrl+A +Select an element in the list or the drawing. Wähle ein Element in der Liste oder der Zeichnung. Sélectionnez un élément dans la liste ou le dessin. Selecciona un elemento de la lista o del dibujo. +Select and drag elements; Del deletes Elemente wählen und ziehen; Entf löscht Sélectionner et glisser des éléments ; Suppr supprime Selecciona y arrastra elementos; Supr elimina +Select device Betriebsmittel wählen Sélectionner l'appareil Seleccionar dispositivo +Selector switch NO Wahlschalter Schließer Sélecteur NO Selector NA +Sequential (1, 2, 3 …) Fortlaufend (1, 2, 3 …) Séquentiel (1, 2, 3 …) Secuencial (1, 2, 3 …) +Server Server Serveur Servidor +Server URL Server-URL URL du serveur URL del servidor +Shape Form Forme Forma +Sheet number Blattnummer Numéro de feuille Número de hoja +Shift + click / drag Umschalt + Klick / Ziehen Maj + clic / glisser Mayús + clic / arrastrar +Short circuit between potentials {} Kurzschluss zwischen den Potenzialen {} Court-circuit entre les potentiels {} Cortocircuito entre los potenciales {} +Shortcuts Tastenkürzel Raccourcis Atajos +Shortcuts & usage Tastenkürzel & Bedienung Raccourcis et utilisation Atajos y uso +Show connection point designations Anschlussbezeichnungen anzeigen Afficher les désignations de connexion Mostrar designaciones de conexión +Show connectors Stecker anzeigen Afficher les connecteurs Mostrar conectores +Show device tag and cross references Betriebsmittelkennzeichen und Querverweise anzeigen Afficher le repère d'appareil et les renvois Mostrar designación de dispositivo y referencias cruzadas +Show in schematic Im Schaltplan anzeigen Afficher dans le schéma Mostrar en el esquema +Show this wire Diese Leitung anzeigen Afficher ce fil Mostrar este hilo +Shows Zeigt Affiche Muestra +Simplified KBL (VDA 4964) for harness manufacturing Vereinfachtes KBL (VDA 4964) für die Kabelbaumfertigung KBL simplifié (VDA 4964) pour la fabrication de faisceaux KBL simplificado (VDA 4964) para la fabricación de mazos +Single-line / overview Einpolig / Übersicht Unifilaire / vue d'ensemble Unifilar / resumen +Size Größe Taille Tamaño +Slot Schlitz Fente Ranura +Solenoid valve coil Magnetventilspule Bobine d'électrovanne Bobina de electroválvula +Some wires have no length: place their devices in the panel layout or set the field length. Einige Leitungen haben keine Länge: Platziere ihre Betriebsmittel im Schaltschrank-Layout oder setze die Feldlänge. Certains fils n'ont pas de longueur : placez leurs appareils dans l'implantation de l'armoire ou définissez la longueur sur site. Algunos hilos no tienen longitud: coloca sus dispositivos en la distribución del armario o define la longitud en campo. +Sort by designation Nach Bezeichnung sortieren Trier par désignation Ordenar por designación +Space Leertaste Espace Espacio +Space behind the door that devices must keep free (door-mounted devices, handles) Raum hinter der Tür, den Betriebsmittel freihalten müssen (Türeinbaugeräte, Griffe) Espace derrière la porte à laisser libre (appareils en porte, poignées) Espacio detrás de la puerta que los dispositivos deben dejar libre (dispositivos en puerta, manetas) +Spare terminals Reserveklemmen Bornes de réserve Bornes de reserva +Start Start Départ Inicio +Start a server with: openecraft-server --token Starte einen Server mit: openecraft-server --token Démarrez un serveur avec : openecraft-server --token Inicia un servidor con: openecraft-server --token +Start at Beginnen bei Commencer à Empezar en +Start byte Startbyte Octet de départ Byte inicial +Start openecraft-server with --token to allow changes Starte openecraft-server mit --token, um Änderungen zu erlauben Démarrez openecraft-server avec --token pour autoriser les modifications Inicia openecraft-server con --token para permitir cambios +Strip Abisolierung Dénudage Pelado +Strip (mm) Abisolierung (mm) Dénudage (mm) Pelado (mm) +Structure (IEC 81346) Struktur (IEC 81346) Structure (CEI 81346) Estructura (IEC 81346) +Structure (function / location)… Struktur (Funktion / Ort)… Structure (fonction / emplacement)… Estructura (función / ubicación)… +Style Stil Style Estilo +Sum Summe Somme Suma +Supplier Lieferant Fournisseur Proveedor +Switches / Sensors Schalter / Sensoren Interrupteurs / capteurs Interruptores / sensores +Symbol Symbol Symbole Símbolo +Symbol editor Symboleditor Éditeur de symboles Editor de símbolos +Symbol editor… Symboleditor… Éditeur de symboles… Editor de símbolos… +Symbol table import failed: {} Import der Symboltabelle fehlgeschlagen: {} Échec de l'import de la table de symboles : {} Error al importar la tabla de símbolos: {} +Symbols Symbole Symboles Símbolos +Synchronize project parts from database Projektartikel aus der Datenbank synchronisieren Synchroniser les articles du projet depuis la base Sincronizar los artículos del proyecto desde la base de datos +System System Système Sistema +T Text T Text T Texte T Texto +Table of contents Inhaltsverzeichnis Table des matières Índice de contenido +Tag field Kennzeichenfeld Champ de repère Campo de designación +Takes the comments as function texts (matched by address) Übernimmt die Kommentare als Funktionstexte (zugeordnet über die Adresse) Reprend les commentaires comme textes de fonction (associés par l'adresse) Toma los comentarios como textos de función (asignados por la dirección) +Takes the connection point designations of all functions of this device from the function templates of its parts Übernimmt die Anschlussbezeichnungen aller Funktionen dieses Betriebsmittels aus den Funktionsvorlagen seiner Artikel Reprend les désignations de connexion de toutes les fonctions de cet appareil à partir des modèles de fonction de ses articles Toma las designaciones de conexión de todas las funciones de este dispositivo de las plantillas de función de sus artículos +Tank Tank Réservoir Depósito +Technical data Technische Daten Caractéristiques techniques Datos técnicos +Terminal Klemme Borne Borne +Terminal diagram Klemmenplan Plan de bornes Diagrama de bornes +Terminal number Klemmennummer Numéro de borne Número de borne +Terminal number, PLC address, potential name … Klemmennummer, SPS-Adresse, Potenzialname … Numéro de borne, adresse API, nom du potentiel … Número de borne, dirección PLC, nombre del potencial … +Terminal strip Klemmenleiste Bornier Regleta de bornes +Terminal strips Klemmenleisten Borniers Regletas de bornes +Terminal strips… Klemmenleisten… Borniers… Regletas de bornes… +Terminals Klemmen Bornes Bornes +Terminals with the same jumper number are bridged (same potential). Spare terminals are counted in the bill of materials. Klemmen mit gleicher Brückennummer sind verbunden (gleiches Potenzial). Reserveklemmen werden in der Stückliste mitgezählt. Les bornes de même numéro de pont sont reliées (même potentiel). Les bornes de réserve sont comptées dans la nomenclature. Los bornes con el mismo número de puente están unidos (mismo potencial). Los bornes de reserva se cuentan en la lista de materiales. +Test connection Verbindung testen Tester la connexion Probar conexión +Text Text Texte Texto +Text T Text T Texte T Texto T +The 2D front view is used in the panel front view and on mounting layout pages, the 3D model in the 3D panel view. Both are fitted to the mounting data (width × height × depth). Die 2D-Frontansicht wird in der Schaltschrank-Frontansicht und auf Montageplan-Seiten verwendet, das 3D-Modell in der 3D-Schaltschrankansicht. Beide werden an die Montagedaten (Breite × Höhe × Tiefe) angepasst. La vue de face 2D est utilisée dans la vue de face de l'armoire et sur les pages d'implantation, le modèle 3D dans la vue 3D de l'armoire. Les deux sont adaptés aux données de montage (largeur × hauteur × profondeur). La vista frontal 2D se usa en la vista frontal del armario y en las páginas de distribución de montaje, el modelo 3D en la vista 3D del armario. Ambos se ajustan a los datos de montaje (ancho × alto × profundidad). +The access token is only needed for changes; it is not stored. Das Zugriffstoken wird nur für Änderungen benötigt; es wird nicht gespeichert. Le jeton d'accès n'est nécessaire que pour les modifications ; il n'est pas enregistré. El token de acceso solo se necesita para los cambios; no se guarda. +The model ({} × {} × {}) differs from the mounting data ({} × {} × {}); it is stretched to the mounting data. Das Modell ({} × {} × {}) weicht von den Montagedaten ({} × {} × {}) ab; es wird auf die Montagedaten gestreckt. Le modèle ({} × {} × {}) diffère des données de montage ({} × {} × {}) ; il est étiré aux données de montage. El modelo ({} × {} × {}) difiere de los datos de montaje ({} × {} × {}); se estira a los datos de montaje. +The parts database is shared by all projects. Parts are copied into a project when they are assigned to a device. Die Artikeldatenbank wird von allen Projekten gemeinsam genutzt. Artikel werden in ein Projekt kopiert, wenn sie einem Betriebsmittel zugewiesen werden. La base d'articles est partagée par tous les projets. Les articles sont copiés dans un projet lorsqu'ils sont affectés à un appareil. La base de datos de artículos es común a todos los proyectos. Los artículos se copian en un proyecto cuando se asignan a un dispositivo. +The price refers to this many units Der Preis bezieht sich auf diese Anzahl Einheiten Le prix se rapporte à ce nombre d'unités El precio se refiere a esta cantidad de unidades +The project's own title blocks Die eigenen Schriftfelder des Projekts Les cartouches propres au projet Los cajetines propios del proyecto +The symbol has no connection points. Das Symbol hat keine Anschlusspunkte. Le symbole n'a aucun point de connexion. El símbolo no tiene puntos de conexión. +The symbol has no name. Das Symbol hat keinen Namen. Le symbole n'a pas de nom. El símbolo no tiene nombre. +The symbol is placed in the project Das Symbol wird im Projekt verwendet Le symbole est utilisé dans le projet El símbolo se usa en el proyecto +The wires get the free cores of the cable in order (left to right) Die Leitungen erhalten der Reihe nach (von links nach rechts) die freien Adern des Kabels Les fils reçoivent dans l'ordre (de gauche à droite) les âmes libres du câble Los hilos reciben en orden (de izquierda a derecha) los núcleos libres del cable +Thermal overload relay Thermisches Überlastrelais Relais thermique Relé térmico de sobrecarga +This page contains schematic content which is not evaluated on non-schematic pages. Diese Seite enthält Schaltplaninhalte, die auf Nicht-Schaltplanseiten nicht ausgewertet werden. Cette page contient des éléments de schéma qui ne sont pas évalués sur les pages autres que les schémas. Esta página contiene contenido de esquema que no se evalúa en páginas que no son de esquema. +Timer coil, off-delay Zeitrelaisspule, ausschaltverzögert Bobine temporisée, à la retombée Bobina temporizada, a la desconexión +Timer coil, on-delay Zeitrelaisspule, einschaltverzögert Bobine temporisée, à l'appel Bobina temporizada, a la conexión +Title block Schriftfeld Cartouche Cajetín +Title blocks Schriftfelder Cartouches Cajetines +Title blocks and report forms… Schriftfelder und Berichtsformulare… Cartouches et formulaires de rapport… Cajetines y formularios de informe… +To Nach Vers A +Toggle corner direction while drawing wires Eckrichtung beim Zeichnen von Leitungen umschalten Changer le sens du coin pendant le tracé des fils Cambiar la dirección de la esquina al dibujar hilos +Total Gesamt Total Total +Transfer project parts to database Projektartikel in die Datenbank übernehmen Transférer les articles du projet dans la base Transferir los artículos del proyecto a la base de datos +Transformer (single-line) Transformator (einpolig dargestellt) Transformateur (unifilaire) Transformador (unifilar) +Turn the model so that its front faces the viewer (+Z) and its top is +Y Drehe das Modell so, dass die Vorderseite zum Betrachter zeigt (+Z) und die Oberseite +Y ist Orientez le modèle pour que sa face avant regarde l'observateur (+Z) et que son dessus soit +Y Gira el modelo para que su frente mire al observador (+Z) y su parte superior sea +Y +Type Typ Type Tipo +Type number Typnummer Numéro de type Número de tipo +Undo Ctrl+Z Rückgängig Strg+Z Annuler Ctrl+Z Deshacer Ctrl+Z +Undo (Ctrl+Z) Rückgängig (Strg+Z) Annuler (Ctrl+Z) Deshacer (Ctrl+Z) +Undo / redo Rückgängig / Wiederholen Annuler / rétablir Deshacer / rehacer +Unit Einheit Unité Unidad +Unit price Einzelpreis Prix unitaire Precio unitario +Unknown symbol '{}' Unbekanntes Symbol '{}' Symbole inconnu '{}' Símbolo desconocido '{}' +Unknown symbol {} Unbekanntes Symbol {} Symbole inconnu {} Símbolo desconocido {} +Unlock all Alle entsperren Tout déverrouiller Desbloquear todo +Updates the project parts with the current database data Aktualisiert die Projektartikel mit den aktuellen Daten der Datenbank Met à jour les articles du projet avec les données actuelles de la base Actualiza los artículos del proyecto con los datos actuales de la base de datos +Uploaded {} parts, server revision {} {} Artikel hochgeladen, Server-Revision {} {} articles envoyés, révision du serveur {} {} artículos subidos, revisión del servidor {} +Uploading parts file… Lade Artikeldatei hoch … Envoi du fichier d'articles… Subiendo archivo de artículos… +Uploading {} parts… Lade {} Artikel hoch … Envoi de {} articles… Subiendo {} artículos… +Use for all pages Für alle Seiten verwenden Utiliser pour toutes les pages Usar para todas las páginas +Use model size as mounting data Modellgröße als Montagedaten übernehmen Utiliser la taille du modèle comme données de montage Usar el tamaño del modelo como datos de montaje +Used Verwendet Utilisé Usado +Used on {} of {} pages Auf {} von {} Seiten verwendet Utilisé sur {} pages sur {} Usado en {} de {} páginas +User symbols Benutzersymbole Symboles utilisateur Símbolos de usuario +Value Wert Valeur Valor +Value sets Wertesätze Jeux de valeurs Conjuntos de valores +View Ansicht Affichage Ver +Voltage Spannung Tension Tensión +Voltage / current Spannung / Strom Tension / courant Tensión / corriente +Weight Gewicht Poids Peso +Wheel / right or middle drag Mausrad / Rechts- oder Mittelklick-Ziehen Molette / glisser avec clic droit ou milieu Rueda / arrastrar con botón derecho o central +Wheel: zoom · right click: cancel · graphics snap to 0.5 mm, connection points to the 4 mm grid Mausrad: Zoom · Rechtsklick: abbrechen · Grafik rastet auf 0,5 mm ein, Anschlusspunkte auf das 4-mm-Raster Molette : zoom · clic droit : annuler · les graphiques s'alignent sur 0,5 mm, les points de connexion sur la grille de 4 mm Rueda: zoom · clic derecho: cancelar · los gráficos se ajustan a 0,5 mm, los puntos de conexión a la cuadrícula de 4 mm +Width Breite Largeur Ancho +Width × height Breite × Höhe Largeur × hauteur Ancho × alto +Width × height × depth Breite × Höhe × Tiefe Largeur × hauteur × profondeur Ancho × alto × profundidad +Window macro: {} Fenstermakro: {} Macro de fenêtre : {} Macro de ventana: {} +Wire Leitung Fil Hilo +Wire W Leitung W Fil W Hilo W +Wire assigned to unknown cable {} Leitung einem unbekannten Kabel zugewiesen {} Fil affecté à un câble inconnu {} Hilo asignado a un cable desconocido {} +Wire ends with ferrules Leitungsenden mit Aderendhülsen Extrémités de fil avec embouts Extremos de hilo con punteras +Wire list (panel routing) Leitungsliste (Schaltschrank-Verlegung) Liste des fils (cheminement en armoire) Lista de hilos (tendido en armario) +Wire no. Leitungsnr. N° de fil N.º de hilo +Wire number Leitungsnummer Numéro de fil Número de hilo +Wire number {} is used for {} different potentials Leitungsnummer {} wird für {} verschiedene Potenziale verwendet Le numéro de fil {} est utilisé pour {} potentiels différents El número de hilo {} se usa para {} potenciales distintos +Wire numbering Leitungsnummerierung Numérotation des fils Numeración de hilos +Wire numbering… Leitungsnummerierung… Numérotation des fils… Numeración de hilos… +Wire numbers, ends, colour, cross-section, routed length, cable cores Leitungsnummern, Enden, Farbe, Querschnitt, verlegte Länge, Kabeladern Numéros de fil, extrémités, couleur, section, longueur cheminée, âmes de câble Números de hilo, extremos, color, sección, longitud tendida, núcleos de cable +Wire reserve per connection Leitungsreserve je Verbindung Réserve de fil par liaison Reserva de hilo por conexión +Wire tool / text tool Leitungswerkzeug / Textwerkzeug Outil fil / outil texte Herramienta de hilo / de texto +Wire {} – {} ({} of {} here, click again for the next) Leitung {} – {} ({} von {} hier, erneut klicken für die nächste) Fil {} – {} ({} sur {} ici, cliquez à nouveau pour le suivant) Hilo {} – {} ({} de {} aquí, haz clic de nuevo para el siguiente) +Wire {} – {} {} mm Leitung {} – {} {} mm Fil {} – {} {} mm Hilo {} – {} {} mm +Wires Leitungen Fils Hilos +Workflow Ablauf Procédure Flujo de trabajo +X {} Y {} mm Column {} Row {} X {} Y {} mm Spalte {} Zeile {} X {} Y {} mm Colonne {} Ligne {} X {} Y {} mm Columna {} Fila {} +X {} Y {} mm on the {} X {} Y {} mm auf der Seite {} X {} Y {} mm sur {} X {} Y {} mm en {} +YYYY-MM-DD JJJJ-MM-TT AAAA-MM-JJ AAAA-MM-DD +Zoom / pan Zoom / Verschieben Zoom / déplacement Zoom / desplazar +added hinzugefügt ajouté añadido +all cards alle Karten toutes les cartes todas las tarjetas +changed geändert modifié cambiado +changed, not saved geändert, nicht gespeichert modifié, non enregistré modificado, sin guardar +changes with token Änderungen mit Token modifications avec jeton cambios con token +e.g. 1.5 mm² z. B. 1,5 mm² p. ex. 1,5 mm² p. ej. 1,5 mm² +e.g. 25.4 for models in inch, 1000 for models in metres z. B. 25,4 für Modelle in Zoll, 1000 für Modelle in Metern p. ex. 25,4 pour des modèles en pouces, 1000 pour des modèles en mètres p. ej. 25,4 para modelos en pulgadas, 1000 para modelos en metros +e.g. A1, PUMP.2 z. B. A1, PUMP.2 p. ex. A1, PUMP.2 p. ej. A1, PUMP.2 +e.g. BU, BK, GNYE z. B. BU, BK, GNYE p. ex. BU, BK, GNYE p. ej. BU, BK, GNYE +e.g. CAB1, FIELD z. B. CAB1, FIELD p. ex. CAB1, FIELD p. ej. CAB1, FIELD +e.g. Motors z. B. Motoren p. ex. Moteurs p. ej. Motores +manual manuell manuel manual +needed for changes für Änderungen erforderlich nécessaire pour les modifications necesario para los cambios +new part, not saved neuer Artikel, nicht gespeichert nouvel article, non enregistré artículo nuevo, sin guardar +none – a box of the mounting dimensions is drawn keines – ein Quader der Montageabmessungen wird gezeichnet aucun – un parallélépipède aux dimensions de montage est dessiné ninguno – se dibuja una caja con las dimensiones de montaje +none – a plain rectangle is drawn keines – ein einfaches Rechteck wird gezeichnet aucun – un simple rectangle est dessiné ninguno – se dibuja un rectángulo simple +not connected nicht angeschlossen non raccordé no conectado +not in the schematic nicht im Schaltplan absent du schéma no está en el esquema +not numbered nicht nummeriert non numéroté sin numerar +only needed for uploads nur für Uploads erforderlich nécessaire uniquement pour les envois necesario solo para las subidas +open offen ouvert abierto +page properties Seiteneigenschaften propriétés de la page propiedades de la página +part number Artikelnummer numéro d'article número de artículo +placed / provided by the parts platziert / von den Artikeln bereitgestellt placé / fourni par les articles colocado / proporcionado por los artículos +read-only schreibgeschützt lecture seule solo lectura +read-only server schreibgeschützter Server serveur en lecture seule servidor de solo lectura +removed entfernt supprimé eliminado +saved gespeichert enregistré guardado +spare Reserve réserve reserva +writable with token mit Token beschreibbar modifiable avec jeton escribible con token +{} (door) {} (Tür) {} (porte) {} (puerta) +{} (used) {} (verwendet) {} (utilisé) {} (usado) +{} / {} mm (column {}) {} / {} mm (Spalte {}) {} / {} mm (colonne {}) {} / {} mm (columna {}) +{} PLC function texts updated {} SPS-Funktionstexte aktualisiert {} textes de fonction API mis à jour {} textos de función PLC actualizados +{} catalog parts added {} Katalogartikel hinzugefügt {} articles du catalogue ajoutés {} artículos del catálogo añadidos +{} connections numbered {} Verbindungen nummeriert {} liaisons numérotées {} conexiones numeradas +{} connections {} {} Verbindungen {} {} liaisons {} {} conexiones {} +{} devices placed, {} wires routed ({} m) {} Betriebsmittel platziert, {} Leitungen verlegt ({} m) {} appareils placés, {} fils cheminés ({} m) {} dispositivos colocados, {} hilos tendidos ({} m) +{} example catalog parts refreshed {} Beispielkatalog-Artikel aktualisiert {} articles du catalogue d'exemple actualisés {} artículos del catálogo de ejemplo actualizados +{} items selected {} Elemente ausgewählt {} éléments sélectionnés {} elementos seleccionados +{} objects selected {} Objekte ausgewählt {} objets sélectionnés {} objetos seleccionados +{} of {} connections numbered {} von {} Verbindungen nummeriert {} liaisons sur {} numérotées {} de {} conexiones numeradas +{} of {} pages locked {} von {} Seiten gesperrt {} pages sur {} verrouillées {} de {} páginas bloqueadas +{} of {} wires assigned to cores of {} {} von {} Leitungen den Adern von {} zugewiesen {} fils sur {} affectés aux âmes de {} {} de {} hilos asignados a los núcleos de {} +{} parts {} Artikel {} articles {} artículos +{} parts added to the database {} Artikel zur Datenbank hinzugefügt {} articles ajoutés à la base de données {} artículos añadidos a la base de datos +{} placement problems (red) – see Check {} Platzierungsprobleme (rot) – siehe Prüfung {} problèmes de placement (en rouge) – voir Contrôle {} problemas de colocación (en rojo) – ver Revisión +{} project parts updated {} Projektartikel aktualisiert {} articles du projet mis à jour {} artículos del proyecto actualizados +{} symbols added, {} replaced {} Symbole hinzugefügt, {} ersetzt {} symboles ajoutés, {} remplacés {} símbolos añadidos, {} reemplazados +{} symbols, {} wires, {} texts / graphics {} Symbole, {} Leitungen, {} Texte / Grafiken {} symboles, {} fils, {} textes / graphiques {} símbolos, {} hilos, {} textos / gráficos +{} unused project parts removed {} nicht verwendete Projektartikel entfernt {} articles du projet inutilisés supprimés {} artículos del proyecto no usados eliminados +{} wires {} Leitungen {} fils {} hilos +{} without device tag on page {} {} ohne Betriebsmittelkennzeichen auf Seite {} {} sans repère d'appareil sur la page {} {} sin designación de dispositivo en la página {} +{} × {} mm, {} elements {} × {} mm, {} Elemente {} × {} mm, {} éléments {} × {} mm, {} elementos +{} × {} × {} mm {} × {} × {} mm {} × {} × {} mm {} × {} × {} mm +{} × {} × {} mm, {} triangles {} × {} × {} mm, {} Dreiecke {} × {} × {} mm, {} triangles {} × {} × {} mm, {} triángulos +{} – save to upload it {} – zum Hochladen speichern {} – enregistrer pour l'envoyer {} – guardar para subirlo +{}: 2D front view with {} elements assigned to {} {}: 2D-Frontansicht mit {} Elementen {} zugewiesen {} : vue de face 2D avec {} éléments affectée à {} {}: vista frontal 2D con {} elementos asignada a {} +{}: 3D model with {} triangles ({} × {} × {} mm) assigned to {} {}: 3D-Modell mit {} Dreiecken ({} × {} × {} mm) {} zugewiesen {} : modèle 3D avec {} triangles ({} × {} × {} mm) affecté à {} {}: modelo 3D con {} triángulos ({} × {} × {} mm) asignado a {} +{}: auxiliary function(s) without main function {}: Hilfsfunktion(en) ohne Hauptfunktion {} : fonction(s) auxiliaire(s) sans fonction principale {}: función(es) auxiliar(es) sin función principal +{}: core {} is not a core of the cable ({}) {}: Ader {} ist keine Ader des Kabels ({}) {} : l'âme {} n'est pas une âme du câble ({}) {}: el núcleo {} no es un núcleo del cable ({}) +{}: core {} used for {} connections {}: Ader {} für {} Verbindungen verwendet {} : âme {} utilisée pour {} liaisons {}: núcleo {} usado para {} conexiones +{}: designation '{}' used more than once {}: Bezeichnung '{}' mehrfach verwendet {} : désignation '{}' utilisée plusieurs fois {}: designación '{}' usada más de una vez +{}: device tag without device name {}: Betriebsmittelkennzeichen ohne Betriebsmittelname {} : repère d'appareil sans nom d'appareil {}: designación de dispositivo sin nombre de dispositivo +{}: jumper {} on terminal {}, which is not placed {}: Brücke {} an Klemme {}, die nicht platziert ist {} : pont {} sur la borne {}, qui n'est pas placée {}: puente {} en el borne {}, que no está colocado +{}: main function placed {} times {}: Hauptfunktion {}-mal platziert {} : fonction principale placée {} fois {}: función principal colocada {} veces +{}: no part assigned {}: kein Artikel zugewiesen {} : aucun article affecté {}: ningún artículo asignado +{}: not placed in the panel layout {}: nicht im Schaltschrank-Layout platziert {} : non placé dans l'implantation de l'armoire {}: no colocado en la distribución del armario +{}: part {} is not in the project parts (Parts management › synchronize) {}: Artikel {} ist nicht in den Projektartikeln (Artikelverwaltung › synchronisieren) {} : l'article {} n'est pas dans les articles du projet (Gestion des articles › synchroniser) {}: el artículo {} no está en los artículos del proyecto (Gestión de artículos › sincronizar) +{}: the part is no longer open {}: der Artikel ist nicht mehr geöffnet {} : l'article n'est plus ouvert {}: el artículo ya no está abierto +{}: wire without core designation {}: Leitung ohne Aderbezeichnung {} : fil sans désignation d'âme {}: hilo sin designación de núcleo +{}: {} addresses changed {}: {} Adressen geändert {} : {} adresses modifiées {}: {} direcciones cambiadas +{}: {} collides with {} {}: {} kollidiert mit {} {} : {} entre en collision avec {} {}: {} colisiona con {} +{}: {} is inside the required clearance of {} {}: {} liegt im erforderlichen Freiraum von {} {} : {} se trouve dans le dégagement requis de {} {}: {} está dentro del espacio libre requerido de {} +{}: {} outside the mounting plate / enclosure {}: {} außerhalb der Montageplatte / des Gehäuses {} : {} en dehors de la plaque de montage / de l'enveloppe {}: {} fuera de la placa de montaje / de la envolvente +{}: {} terminals renumbered {}: {} Klemmen neu nummeriert {} : {} bornes renumérotées {}: {} bornes renumerados +{}: {} wires, {} m wire in total {}: {} Leitungen, insgesamt {} m Leitung {} : {} fils, {} m de fil au total {}: {} hilos, {} m de hilo en total +{}: {}× {} placed, assigned parts provide {} {}: {}× {} platziert, zugewiesene Artikel stellen {} bereit {} : {}× {} placé, les articles affectés en fournissent {} {}: {}× {} colocado, los artículos asignados proporcionan {} +— Line — Linie — Ligne — Línea +• Connection point • Anschlusspunkt • Point de connexion • Punto de conexión +⎘ Copy ⎘ Kopieren ⎘ Copier ⎘ Copiar +○ Circle ○ Kreis ○ Cercle ○ Círculo +☐ Rect ☐ Rechteck ☐ Rect. ☐ Rect. +⛶ Fit ⛶ Einpassen ⛶ Ajuster ⛶ Ajustar +✏ Place in schematic ✏ Im Schaltplan platzieren ✏ Placer dans le schéma ✏ Colocar en el esquema +✏ Wire ✏ Leitung ✏ Fil ✏ Hilo +✔ Add to device ✔ Zum Betriebsmittel hinzufügen ✔ Ajouter à l'appareil ✔ Añadir al dispositivo +✔ Create ✔ Anlegen ✔ Créer ✔ Crear +✔ No problems found. ✔ Keine Probleme gefunden. ✔ Aucun problème trouvé. ✔ No se encontraron problemas. +✔ Save ✔ Speichern ✔ Enregistrer ✔ Guardar +➕ Add accessory ➕ Zubehör hinzufügen ➕ Ajouter un accessoire ➕ Añadir accesorio +➕ Add function ➕ Funktion hinzufügen ➕ Ajouter une fonction ➕ Añadir función +➕ Add part… ➕ Artikel hinzufügen… ➕ Ajouter un article… ➕ Añadir artículo… +➕ Insert (click into the page) ➕ Einfügen (in die Seite klicken) ➕ Insérer (cliquer dans la page) ➕ Insertar (clic en la página) +➕ Insert as new page ➕ Als neue Seite einfügen ➕ Insérer comme nouvelle page ➕ Insertar como página nueva +➕ Insert as report page ➕ Als Berichtsseite einfügen ➕ Insérer comme page de rapport ➕ Insertar como página de informe +➕ Insert mounting layout page ➕ Montageplan-Seite einfügen ➕ Insérer une page d'implantation ➕ Insertar página de distribución de montaje +➕ Label ➕ Beschriftung ➕ Libellé ➕ Etiqueta +➕ Line ➕ Linie ➕ Ligne ➕ Línea +➕ New ➕ Neu ➕ Nouveau ➕ Nuevo +➕ New cable ➕ Neues Kabel ➕ Nouveau câble ➕ Nuevo cable +➕ New harness ➕ Neuer Kabelbaum ➕ Nouveau faisceau ➕ Nuevo mazo +➕ Property ➕ Eigenschaft ➕ Propriété ➕ Propiedad +➕ Rectangle ➕ Rechteck ➕ Rectangle ➕ Rectángulo +➕ Text ➕ Text ➕ Texte ➕ Texto +➕ Value set ➕ Wertesatz ➕ Jeu de valeurs ➕ Conjunto de valores +➕ {} (not saved) ➕ {} (nicht gespeichert) ➕ {} (non enregistré) ➕ {} (sin guardar) +⟲ Revert ⟲ Zurücksetzen ⟲ Rétablir ⟲ Revertir +⟳ Reload ⟳ Neu laden ⟳ Recharger ⟳ Recargar +⟳ Rotate ⟳ Drehen ⟳ Pivoter ⟳ Girar +⬆ Import symbol table… ⬆ Symboltabelle importieren… ⬆ Importer la table de symboles… ⬆ Importar tabla de símbolos… +⬆ Import… ⬆ Importieren… ⬆ Importer… ⬆ Importar… +⬆ Upload database ({}) ⬆ Datenbank hochladen ({}) ⬆ Envoyer la base ({}) ⬆ Subir base de datos ({}) +⬆ Upload parts file (CSV / JSON)… ⬆ Artikeldatei hochladen (CSV / JSON)… ⬆ Envoyer un fichier d'articles (CSV / JSON)… ⬆ Subir archivo de artículos (CSV / JSON)… +⬆ Upload selected part ⬆ Gewählten Artikel hochladen ⬆ Envoyer l'article sélectionné ⬆ Subir el artículo seleccionado +⬇ Door NC data (DXF) ⬇ Tür-NC-Daten (DXF) ⬇ Données CN de la porte (DXF) ⬇ Datos NC de la puerta (DXF) +⬇ Door cutouts (CSV) ⬇ Türausschnitte (CSV) ⬇ Découpes de porte (CSV) ⬇ Recortes de puerta (CSV) +⬇ Download into database ⬇ In Datenbank laden ⬇ Télécharger dans la base ⬇ Descargar a la base de datos +⬇ Drilling list (CSV) ⬇ Bohrliste (CSV) ⬇ Liste de perçage (CSV) ⬇ Lista de taladrado (CSV) +⬇ Export CSV ⬇ CSV exportieren ⬇ Exporter en CSV ⬇ Exportar CSV +⬇ Export KBL (XML)… ⬇ KBL exportieren (XML)… ⬇ Exporter KBL (XML)… ⬇ Exportar KBL (XML)… +⬇ Export symbol table (CSV)… ⬇ Symboltabelle exportieren (CSV)… ⬇ Exporter la table de symboles (CSV)… ⬇ Exportar tabla de símbolos (CSV)… +⬇ Export… ⬇ Exportieren… ⬇ Exporter… ⬇ Exportar… +⬇ NC data (DXF) ⬇ NC-Daten (DXF) ⬇ Données CN (DXF) ⬇ Datos NC (DXF) +⬉ Select ⬉ Auswählen ⬉ Sélectionner ⬉ Seleccionar +🌐 Parts server 🌐 Artikelserver 🌐 Serveur d'articles 🌐 Servidor de artículos +💾 Save 💾 Speichern 💾 Enregistrer 💾 Guardar +💾 Save selection as macro… 💾 Auswahl als Makro speichern… 💾 Enregistrer la sélection comme macro… 💾 Guardar selección como macro… +📊 Cable overview 📊 Kabelübersicht 📊 Vue d'ensemble des câbles 📊 Resumen de cables +📊 Harness data 📊 Kabelbaumdaten 📊 Données de faisceau 📊 Datos de mazos +📊 Reports 📊 Berichte 📊 Rapports 📊 Informes +📊 Revision overview 📊 Revisionsübersicht 📊 Vue d'ensemble des révisions 📊 Resumen de revisiones +🔒 Released page – read only 🔒 Freigegebene Seite – schreibgeschützt 🔒 Page validée – lecture seule 🔒 Página liberada – solo lectura +🗄 Panel layout 🗄 Schaltschrank-Layout 🗄 Implantation de l'armoire 🗄 Distribución del armario +🗄 Parts database 🗄 Artikeldatenbank 🗄 Base d'articles 🗄 Base de datos de artículos +🗋 Schematic 🗋 Schaltplan 🗋 Schéma 🗋 Esquema +🗑 Delete 🗑 Löschen 🗑 Supprimer 🗑 Eliminar +🗑 Delete connection point 🗑 Anschlusspunkt löschen 🗑 Supprimer le point de connexion 🗑 Eliminar punto de conexión +🗑 Delete element 🗑 Element löschen 🗑 Supprimer l'élément 🗑 Eliminar elemento +🗑 Delete macro 🗑 Makro löschen 🗑 Supprimer la macro 🗑 Eliminar macro +🗑 Remove 🗑 Entfernen 🗑 Retirer 🗑 Quitar diff --git a/crates/openecraft-i18n/src/lib.rs b/crates/openecraft-i18n/src/lib.rs new file mode 100644 index 00000000..ccf2d55b --- /dev/null +++ b/crates/openecraft-i18n/src/lib.rs @@ -0,0 +1,9 @@ +//! Multi-language support: the UI texts are written in English in the source and +//! translated at run time through [`tr`] / [`tr_args`]. English, German, French and +//! Spanish are mandatory (see `AGENTS.md`); every text passed to `tr` must have an +//! entry in the catalog (`catalog/*.tsv`), which `translate/tests.rs` verifies. + +mod catalog; +mod translate; + +pub use translate::*; diff --git a/crates/openecraft-i18n/src/translate.rs b/crates/openecraft-i18n/src/translate.rs new file mode 100644 index 00000000..3bf173b1 --- /dev/null +++ b/crates/openecraft-i18n/src/translate.rs @@ -0,0 +1,154 @@ +//! Language state and the lookup / substitution functions (see the crate docs). + +use crate::catalog; +use std::collections::HashMap; +use std::fmt::Display; +use std::sync::atomic::{AtomicU8, Ordering}; +use std::sync::OnceLock; + +/// A supported UI language. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Lang { + En, + De, + Fr, + Es, +} + +impl Lang { + pub const ALL: [Lang; 4] = [Lang::En, Lang::De, Lang::Fr, Lang::Es]; + + /// ISO 639-1 code, also used for persisting the choice. + pub fn code(self) -> &'static str { + match self { + Lang::En => "en", + Lang::De => "de", + Lang::Fr => "fr", + Lang::Es => "es", + } + } + + /// Name of the language in the language itself. + pub fn native_name(self) -> &'static str { + match self { + Lang::En => "English", + Lang::De => "Deutsch", + Lang::Fr => "Français", + Lang::Es => "Español", + } + } + + /// Language for an ISO code or a locale such as `de_DE.UTF-8` / `fr-CA`. + pub fn from_code(code: &str) -> Option { + let primary = code.trim().split(['_', '-', '.', '@']).next()?.to_ascii_lowercase(); + Lang::ALL.into_iter().find(|l| l.code() == primary) + } + + fn index(self) -> u8 { + self as u8 + } +} + +static CURRENT: AtomicU8 = AtomicU8::new(0); + +pub fn lang() -> Lang { + Lang::ALL[CURRENT.load(Ordering::Relaxed) as usize % Lang::ALL.len()] +} + +pub fn set_lang(lang: Lang) { + CURRENT.store(lang.index(), Ordering::Relaxed); +} + +/// Language of the operating system (`LC_ALL`, `LC_MESSAGES`, `LANG`), English if unknown. +pub fn system_lang() -> Lang { + ["LC_ALL", "LC_MESSAGES", "LANG"] + .iter() + .filter_map(|v| std::env::var(v).ok()) + .find_map(|v| Lang::from_code(&v)) + .unwrap_or(Lang::En) +} + +/// Start-up language: the stored choice (ISO code), otherwise the language of the +/// operating system if it is supported; a language already set by the platform entry +/// point (browser language) is kept. +pub fn init(stored: Option<&str>) { + if let Some(l) = stored.and_then(Lang::from_code) { + set_lang(l); + } else if system_lang() != Lang::En { + set_lang(system_lang()); + } +} + +/// All catalog entries as `[English, German, French, Spanish]` (for tests of the applications). +pub fn catalog_entries() -> Vec<[&'static str; 4]> { + catalog::all().map(|(en, de, fr, es)| [en, de, fr, es]).collect() +} + +fn table() -> &'static HashMap<&'static str, [&'static str; 3]> { + static TABLE: OnceLock> = OnceLock::new(); + TABLE.get_or_init(|| catalog::all().map(|(en, de, fr, es)| (en, [de, fr, es])).collect()) +} + +/// Translation of the English text `en` into the current language; unknown texts are +/// returned unchanged. +pub fn tr(en: &'static str) -> &'static str { + translate(en, lang()) +} + +pub fn translate(en: &'static str, lang: Lang) -> &'static str { + match lang { + Lang::En => en, + _ => table().get(en).map(|t| t[lang.index() as usize - 1]).unwrap_or(en), + } +} + +/// Like [`tr`] for texts with placeholders: `{}` is replaced by the arguments in order, +/// `{0}`, `{1}`, … by the argument with that index (translations may reorder them). +pub fn tr_args(en: &'static str, args: &[&dyn Display]) -> String { + fill(translate(en, lang()), args) +} + +/// `tr_fmt!("Saved {}", name)` – translated text with `{}` placeholders filled by the +/// arguments (anything that implements `Display`). +#[macro_export] +macro_rules! tr_fmt { + ($text:literal $(, $arg:expr)* $(,)?) => { + $crate::tr_args($text, &[$(&$arg as &dyn ::std::fmt::Display),*]) + }; +} + +/// Marks an English text in a `const` / `static` table as translatable (the text is +/// translated with [`tr`] where it is shown); keeps it visible to the catalog test. +#[macro_export] +macro_rules! tr_const { + ($text:literal) => { + $text + }; +} + +fn fill(text: &str, args: &[&dyn Display]) -> String { + let mut out = String::with_capacity(text.len() + 16); + let mut next = 0; + let mut rest = text; + while let Some(start) = rest.find('{') { + let Some(end) = rest[start..].find('}') else { break }; + let key = &rest[start + 1..start + end]; + let index = if key.is_empty() { + next += 1; + Some(next - 1) + } else { + key.parse::().ok() + }; + out.push_str(&rest[..start]); + match index.and_then(|i| args.get(i)) { + Some(arg) => out.push_str(&arg.to_string()), + None => out.push_str(&rest[start..start + end + 1]), + } + rest = &rest[start + end + 1..]; + } + out.push_str(rest); + out +} + +#[cfg(test)] +mod tests; diff --git a/crates/openecraft-i18n/src/translate/tests.rs b/crates/openecraft-i18n/src/translate/tests.rs new file mode 100644 index 00000000..83c66d00 --- /dev/null +++ b/crates/openecraft-i18n/src/translate/tests.rs @@ -0,0 +1,155 @@ +use super::*; + +#[test] +fn lang_codes_round_trip() { + for l in Lang::ALL { + assert_eq!(Lang::from_code(l.code()), Some(l)); + } + assert_eq!(Lang::from_code("de_DE.UTF-8"), Some(Lang::De)); + assert_eq!(Lang::from_code("fr-CA"), Some(Lang::Fr)); + assert_eq!(Lang::from_code("ja"), None); +} + +#[test] +fn translates_and_falls_back_to_english() { + assert_eq!(translate("Cancel", Lang::En), "Cancel"); + assert_eq!(translate("Cancel", Lang::De), "Abbrechen"); + assert_eq!(translate("Cancel", Lang::Fr), "Annuler"); + assert_eq!(translate("Cancel", Lang::Es), "Cancelar"); + assert_eq!(translate("no such text", Lang::De), "no such text"); +} + +#[test] +fn placeholders_are_filled_in_order_or_by_index() { + assert_eq!(fill("Saved {} as {}", &[&"a", &3]), "Saved a as 3"); + assert_eq!(fill("{1} von {0}", &[&"x", &"y"]), "y von x"); + assert_eq!(fill("keeps {unknown} and {}", &[&1]), "keeps {unknown} and 1"); +} + +#[test] +fn catalog_is_complete_and_consistent() { + let mut seen = std::collections::HashSet::new(); + for (en, de, fr, es) in catalog::all() { + assert!(seen.insert(en), "duplicate catalog entry: {en}"); + let count = |s: &str| s.matches("{}").count() + s.matches("{0}").count() + s.matches("{1}").count() + s.matches("{2}").count(); + for (name, t) in [("German", de), ("French", fr), ("Spanish", es)] { + assert!(!t.trim().is_empty(), "{name} translation missing: {en}"); + assert_eq!(count(en), count(t), "{name} placeholders differ: {en}"); + assert_eq!(en.starts_with(' '), t.starts_with(' '), "{name} leading space differs: {en}"); + assert_eq!(en.ends_with(' '), t.ends_with(' '), "{name} trailing space differs: {en}"); + } + } +} + +#[test] +fn catalog_lines_are_well_formed() { + let bad = catalog::parse().filter(|e| e.is_none()).count(); + assert_eq!(bad, 0, "{bad} malformed catalog lines (need exactly 4 tab separated columns)"); +} + +/// Resolves the escapes of a Rust string literal body. +fn unescape(s: &str) -> String { + let mut out = String::new(); + let mut chars = s.chars(); + while let Some(c) = chars.next() { + if c != '\\' { + out.push(c); + continue; + } + match chars.next() { + Some('n') => out.push('\n'), + Some('t') => out.push('\t'), + Some(other) => out.push(other), + None => {} + } + } + out +} + +/// The string literal that starts right after `marker` in `src` (raw body, no unescaping). +fn literal_after(src: &str, from: usize) -> Option<(&str, usize)> { + let rest = &src[from..]; + let start = rest.find('"')?; + let mut end = start + 1; + let bytes = rest.as_bytes(); + while end < bytes.len() && bytes[end] != b'"' { + end += if bytes[end] == b'\\' { 2 } else { 1 }; + } + Some((&rest[start + 1..end], from + end + 1)) +} + +/// All texts passed to `tr("…")`, `tr_fmt!("…"`, `tr_const!("…")` and the names of the +/// built-in symbols in `symbols.rs`. +fn texts_in_source(src: &str, is_symbols: bool) -> Vec { + let mut out = Vec::new(); + for marker in ["tr(", "tr_fmt!(", "tr_const!("] { + let mut at = 0; + while let Some(i) = src[at..].find(marker) { + let pos = at + i; + at = pos + marker.len(); + let prev = src[..pos].chars().last(); + if prev.is_some_and(|c| c.is_alphanumeric() || c == '_' || c == '!') { + continue; + } + // only a literal directly after the parenthesis (tr(some_variable) is skipped) + if !src[at..].trim_start().starts_with('"') { + continue; + } + if let Some((text, _)) = literal_after(src, at) { + out.push(unescape(text)); + } + } + } + if is_symbols { + // def("key", "Name", …) and the potential table ("pot_x", "Name", "label") + for marker in ["def(\"", "(\"pot"] { + let mut at = 0; + while let Some(i) = src[at..].find(marker) { + let pos = at + i + marker.find('"').unwrap(); + at = pos + 1; + if let Some((_, after_key)) = literal_after(src, pos) { + if let Some((name, _)) = literal_after(src, after_key) { + out.push(unescape(name)); + } + } + } + } + } + out +} + +fn source_files(dir: &std::path::Path, out: &mut Vec) { + for entry in std::fs::read_dir(dir).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + source_files(&path, out); + } else if path.extension().is_some_and(|e| e == "rs") && path.file_name().is_some_and(|n| n != "tests.rs") { + out.push(path); + } + } +} + +/// Every text the applications translate must be in the catalog in all languages. +#[test] +fn all_texts_used_in_the_sources_are_in_the_catalog() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let known: std::collections::HashSet<&str> = catalog::all().map(|e| e.0).collect(); + let mut files = Vec::new(); + for dir in ["src", "crates/openecraft-ui/src", "parts-manager/src"] { + source_files(&root.join(dir), &mut files); + } + let mut missing = Vec::new(); + let mut checked = 0; + for file in files { + let src = std::fs::read_to_string(&file).unwrap(); + let is_symbols = file.ends_with("symbols.rs"); + for text in texts_in_source(&src, is_symbols) { + checked += 1; + if !known.contains(text.as_str()) { + missing.push(format!("{} -> {text:?}", file.file_name().unwrap().to_string_lossy())); + } + } + } + assert!(checked > 500, "source scan found only {checked} texts – scanner broken?"); + assert!(missing.is_empty(), "texts without catalog entry (add them to catalog/extra.tsv):\n{}", missing.join("\n")); +} diff --git a/crates/openecraft-ui/Cargo.toml b/crates/openecraft-ui/Cargo.toml index 2f1347f4..afc2f84a 100644 --- a/crates/openecraft-ui/Cargo.toml +++ b/crates/openecraft-ui/Cargo.toml @@ -14,6 +14,7 @@ rfd = "0.17" serde = { version = "1", features = ["derive"] } serde_json = "1" openecraft-parts = { path = "../openecraft-parts" } +openecraft-i18n = { path = "../openecraft-i18n" } [target.'cfg(target_arch = "wasm32")'.dependencies] wasm-bindgen = "0.2" diff --git a/crates/openecraft-ui/src/client.rs b/crates/openecraft-ui/src/client.rs index c0ea7dc1..0aface4d 100644 --- a/crates/openecraft-ui/src/client.rs +++ b/crates/openecraft-ui/src/client.rs @@ -2,6 +2,7 @@ //! background (thread on desktop, fetch in the browser); results are collected with //! [`ServerClient::poll`]. +use openecraft_i18n::{tr, tr_fmt}; use openecraft_parts::api::{self, ApiError, ImportResult, PartList, ServerInfo, API_PREFIX, DEFAULT_PORT}; use openecraft_parts::Part; use serde::de::DeserializeOwned; @@ -31,7 +32,7 @@ impl Reply { /// Text for a status line. pub fn describe(&self) -> String { if let Some(e) = self.error() { - return format!("Parts server: {e}"); + return tr_fmt!("Parts server: {}", e); } match self { Reply::Info(Ok(info)) => format!( @@ -40,12 +41,12 @@ impl Reply { info.version, info.parts, info.revision, - if info.writable { "changes with token" } else { "read-only" } + if info.writable { tr("changes with token") } else { tr("read-only") } ), - Reply::Parts(Ok(list)) => format!("Loaded {} parts (revision {})", list.parts.len(), list.revision), - Reply::Imported(Ok(r)) => format!("Uploaded {} parts, server revision {}", r.imported, r.revision), - Reply::Saved(Ok(p)) => format!("Saved part {}", p.number), - Reply::Deleted(number, Ok(())) => format!("Deleted part {number}"), + Reply::Parts(Ok(list)) => tr_fmt!("Loaded {} parts (revision {})", list.parts.len(), list.revision), + Reply::Imported(Ok(r)) => tr_fmt!("Uploaded {} parts, server revision {}", r.imported, r.revision), + Reply::Saved(Ok(p)) => tr_fmt!("Saved part {}", p.number), + Reply::Deleted(number, Ok(())) => tr_fmt!("Deleted part {}", number), _ => String::new(), } } @@ -77,13 +78,13 @@ impl Default for ServerClient { /// Turns an HTTP result into the expected JSON type or a readable error. pub fn decode(result: ehttp::Result) -> Result { let resp = check(result)?; - serde_json::from_slice(&resp.bytes).map_err(|e| format!("unexpected answer: {e}")) + serde_json::from_slice(&resp.bytes).map_err(|e| tr_fmt!("unexpected answer: {}", e)) } /// Successful response or a readable error (server message, HTTP status, connection error). fn check(result: ehttp::Result) -> Result { match result { - Err(e) => Err(format!("connection failed: {e}")), + Err(e) => Err(tr_fmt!("connection failed: {}", e)), Ok(resp) if resp.ok => Ok(resp), Ok(resp) => Err(serde_json::from_slice::(&resp.bytes) .map(|e| e.error) @@ -134,24 +135,24 @@ impl ServerClient { /// GET /api/v1/info pub fn check(&mut self, ctx: &egui::Context) { let req = ehttp::Request::get(self.endpoint(&format!("{API_PREFIX}/info"))); - self.send(ctx, req, "Connecting…".into(), |r| Reply::Info(decode(r))); + self.send(ctx, req, tr("Connecting…").into(), |r| Reply::Info(decode(r))); } /// GET /api/v1/parts (all parts) pub fn download(&mut self, ctx: &egui::Context) { let req = ehttp::Request::get(self.endpoint(&format!("{API_PREFIX}/parts"))); - self.send(ctx, req, "Downloading parts…".into(), |r| Reply::Parts(decode(r))); + self.send(ctx, req, tr("Downloading parts…").into(), |r| Reply::Parts(decode(r))); } /// POST /api/v1/import with the parts as JSON (needs the access token). pub fn upload(&mut self, ctx: &egui::Context, parts: &[Part]) { let body = serde_json::to_vec(parts).unwrap_or_default(); - self.import(ctx, body, "application/json", format!("Uploading {} parts…", parts.len())); + self.import(ctx, body, "application/json", tr_fmt!("Uploading {} parts…", parts.len())); } /// POST /api/v1/import with the content of a CSV or JSON parts file. pub fn upload_file(&mut self, ctx: &egui::Context, content: Vec) { - self.import(ctx, content, "text/plain; charset=utf-8", "Uploading parts file…".into()); + self.import(ctx, content, "text/plain; charset=utf-8", tr("Uploading parts file…").into()); } fn import(&mut self, ctx: &egui::Context, body: Vec, content_type: &str, status: String) { @@ -167,14 +168,14 @@ impl ServerClient { let mut req = ehttp::Request::put(self.endpoint(&api::part_path(&part.number)), body); req.headers.insert("Content-Type", "application/json"); let req = self.authorized(req); - self.send(ctx, req, format!("Saving {}…", part.number), |r| Reply::Saved(decode(r).map(Box::new))); + self.send(ctx, req, tr_fmt!("Saving {}…", part.number), |r| Reply::Saved(decode(r).map(Box::new))); } /// DELETE /api/v1/parts/{number} pub fn delete(&mut self, ctx: &egui::Context, number: &str) { let req = self.authorized(ehttp::Request::delete(&self.endpoint(&api::part_path(number)))); let n = number.to_string(); - self.send(ctx, req, format!("Deleting {number}…"), move |r| Reply::Deleted(n, check(r).map(|_| ()))); + self.send(ctx, req, tr_fmt!("Deleting {}…", number), move |r| Reply::Deleted(n, check(r).map(|_| ()))); } /// Takes the finished requests and updates `status` / `info`. @@ -194,7 +195,7 @@ impl ServerClient { /// True if the status line shows an error. pub fn failed(&self) -> bool { - self.status.starts_with("Parts server:") + self.status.starts_with(tr("Parts server: {}").split("{}").next().unwrap_or_default()) } } diff --git a/crates/openecraft-ui/src/language.rs b/crates/openecraft-ui/src/language.rs new file mode 100644 index 00000000..406a7de3 --- /dev/null +++ b/crates/openecraft-ui/src/language.rs @@ -0,0 +1,21 @@ +//! Language selection shared by the editor and the parts manager. + +use openecraft_i18n::{tr, lang, set_lang, Lang}; + + + +/// Key under which the applications persist the language code. +pub const STORAGE_KEY: &str = "language"; + +/// Menu with all languages (each in its own name); returns true if the language changed. +pub fn menu(ui: &mut egui::Ui) -> bool { + let before = lang(); + ui.menu_button(tr("Language"), |ui| { + for l in Lang::ALL { + if ui.selectable_label(lang() == l, l.native_name()).clicked() { + set_lang(l); + } + } + }); + lang() != before +} diff --git a/crates/openecraft-ui/src/lib.rs b/crates/openecraft-ui/src/lib.rs index 282ed35e..ff7ae6ce 100644 --- a/crates/openecraft-ui/src/lib.rs +++ b/crates/openecraft-ui/src/lib.rs @@ -3,7 +3,9 @@ //! - [`part_editor`] – part tree, tabbed part editor, 2D / 3D model previews //! - [`client`] – client of the parts server (`openecraft-server`) //! - [`io`] – file dialogs on desktop, file picker and downloads in the browser +//! - [`language`] – language menu (UI texts are translated with `openecraft-i18n`) pub mod client; pub mod io; +pub mod language; pub mod part_editor; diff --git a/crates/openecraft-ui/src/part_editor.rs b/crates/openecraft-ui/src/part_editor.rs index 9434a0eb..e4bc6a28 100644 --- a/crates/openecraft-ui/src/part_editor.rs +++ b/crates/openecraft-ui/src/part_editor.rs @@ -1,6 +1,7 @@ //! Part widgets: product group tree, tabbed part editor, read only summary and //! previews of the 2D front view and the 3D model. +use openecraft_i18n::{tr, tr_fmt}; use crate::io::{short_name, FileKind}; use egui::{vec2, Color32, Pos2, RichText, Sense, Shape, Stroke}; use openecraft_parts::vec3::{cross, dot, norm, sub, Orbit}; @@ -94,7 +95,7 @@ pub fn part_tree(ui: &mut egui::Ui, id: &str, parts: &[&Part], filter: &str, sel }); } if tree.is_empty() { - ui.weak("No parts found."); + ui.weak(tr("No parts found.")); } activated } @@ -117,13 +118,13 @@ pub fn part_editor(ui: &mut egui::Ui, part: &mut Part, state: &mut EditorState, let mut request = None; ui.horizontal_wrapped(|ui| { for (t, name) in [ - (PartTab::General, "General"), - (PartTab::Commercial, "Prices / other"), - (PartTab::Technical, "Technical data"), - (PartTab::Mounting, "Mounting data"), - (PartTab::Functions, "Function template"), - (PartTab::Accessories, "Accessories"), - (PartTab::Graphics, "Graphics"), + (PartTab::General, tr("General")), + (PartTab::Commercial, tr("Prices / other")), + (PartTab::Technical, tr("Technical data")), + (PartTab::Mounting, tr("Mounting data")), + (PartTab::Functions, tr("Function template")), + (PartTab::Accessories, tr("Accessories")), + (PartTab::Graphics, tr("Graphics")), ] { ui.selectable_value(&mut state.tab, t, name); } @@ -132,29 +133,29 @@ pub fn part_editor(ui: &mut egui::Ui, part: &mut Part, state: &mut EditorState, egui::ScrollArea::vertical().id_salt("part_editor").auto_shrink([false, false]).show(ui, |ui| match state.tab { PartTab::General => { egui::Grid::new("pg").num_columns(2).spacing([10.0, 6.0]).show(ui, |ui| { - ui.label("Part number"); + ui.label(tr("Part number")); ui.vertical(|ui| { ui.add(egui::TextEdit::singleline(&mut part.number).desired_width(f32::INFINITY).font(egui::TextStyle::Monospace)); if duplicate { - ui.colored_label(Color32::from_rgb(220, 60, 60), "Part number already exists"); + ui.colored_label(Color32::from_rgb(220, 60, 60), tr("Part number already exists")); } }); ui.end_row(); - text_row(ui, "Type number", &mut part.type_number); - text_row(ui, "Order number", &mut part.order_number); - text_row(ui, "Manufacturer", &mut part.manufacturer); - text_row(ui, "Supplier", &mut part.supplier); - ui.label("Description"); + text_row(ui, tr("Type number"), &mut part.type_number); + text_row(ui, tr("Order number"), &mut part.order_number); + text_row(ui, tr("Manufacturer"), &mut part.manufacturer); + text_row(ui, tr("Supplier"), &mut part.supplier); + ui.label(tr("Description")); ui.add(egui::TextEdit::multiline(&mut part.description).desired_rows(2).desired_width(f32::INFINITY)); ui.end_row(); - ui.label("Product top group"); + ui.label(tr("Product top group")); egui::ComboBox::from_id_salt("top").selected_text(part.top_group.title()).show_ui(ui, |ui| { for t in TopGroup::ALL { ui.selectable_value(&mut part.top_group, t, t.title()); } }); ui.end_row(); - ui.label("Product group"); + ui.label(tr("Product group")); ui.horizontal(|ui| { ui.add(egui::TextEdit::singleline(&mut part.group).desired_width(200.0)); egui::ComboBox::from_id_salt("grp").selected_text("…").width(24.0).show_ui(ui, |ui| { @@ -166,7 +167,7 @@ pub fn part_editor(ui: &mut egui::Ui, part: &mut Part, state: &mut EditorState, }); }); ui.end_row(); - ui.label("Product subgroup"); + ui.label(tr("Product subgroup")); ui.horizontal(|ui| { ui.add(egui::TextEdit::singleline(&mut part.subgroup).desired_width(200.0)); let subs = PRODUCT_GROUPS.iter().find(|(g, _)| *g == part.group).map(|(_, s)| *s).unwrap_or(&[]); @@ -181,66 +182,66 @@ pub fn part_editor(ui: &mut egui::Ui, part: &mut Part, state: &mut EditorState, } }); ui.end_row(); - ui.label("Identifier"); + ui.label(tr("Identifier")); ui.add(egui::TextEdit::singleline(&mut part.identifier).desired_width(50.0)) - .on_hover_text("Identifying letter of devices using this part (K, Q, S …)"); + .on_hover_text(tr("Identifying letter of devices using this part (K, Q, S …)")); ui.end_row(); - ui.label("Note"); + ui.label(tr("Note")); ui.add(egui::TextEdit::multiline(&mut part.note).desired_rows(2).desired_width(f32::INFINITY)); ui.end_row(); }); } PartTab::Commercial => { egui::Grid::new("pc").num_columns(2).spacing([10.0, 6.0]).show(ui, |ui| { - ui.label("Price"); + ui.label(tr("Price")); ui.horizontal(|ui| { ui.add(egui::DragValue::new(&mut part.price).speed(0.1).range(0.0..=1.0e7).fixed_decimals(2)); ui.add(egui::TextEdit::singleline(&mut part.currency).desired_width(40.0)); }); ui.end_row(); - ui.label("Price unit"); - ui.add(egui::DragValue::new(&mut part.price_unit).range(1..=100000)).on_hover_text("The price refers to this many units"); + ui.label(tr("Price unit")); + ui.add(egui::DragValue::new(&mut part.price_unit).range(1..=100000)).on_hover_text(tr("The price refers to this many units")); ui.end_row(); - ui.label("Packaging quantity"); + ui.label(tr("Packaging quantity")); ui.add(egui::DragValue::new(&mut part.pack_quantity).range(1..=100000)); ui.end_row(); - ui.label("Quantity unit"); + ui.label(tr("Quantity unit")); ui.add(egui::TextEdit::singleline(&mut part.quantity_unit).desired_width(60.0)); ui.end_row(); - text_row(ui, "Certificates", &mut part.certificates); - text_row(ui, "Datasheet (URL)", &mut part.datasheet); + text_row(ui, tr("Certificates"), &mut part.certificates); + text_row(ui, tr("Datasheet (URL)"), &mut part.datasheet); }); if part.datasheet.starts_with("http") { - ui.hyperlink_to("Open datasheet", &part.datasheet); + ui.hyperlink_to(tr("Open datasheet"), &part.datasheet); } } PartTab::Technical => { egui::Grid::new("pt").num_columns(2).spacing([10.0, 6.0]).show(ui, |ui| { - text_row(ui, "Voltage", &mut part.voltage); - text_row(ui, "Current", &mut part.current); - text_row(ui, "Power", &mut part.power); - ui.label("Technical data"); + text_row(ui, tr("Voltage"), &mut part.voltage); + text_row(ui, tr("Current"), &mut part.current); + text_row(ui, tr("Power"), &mut part.power); + ui.label(tr("Technical data")); ui.add(egui::TextEdit::multiline(&mut part.tech_data).desired_rows(5).desired_width(f32::INFINITY)); ui.end_row(); }); } PartTab::Mounting => { egui::Grid::new("pm").num_columns(2).spacing([10.0, 6.0]).show(ui, |ui| { - num_row(ui, "Width", &mut part.width, " mm"); - num_row(ui, "Height", &mut part.height, " mm"); - num_row(ui, "Depth", &mut part.depth, " mm"); - num_row(ui, "Weight", &mut part.weight, " kg"); - text_row(ui, "Mounting", &mut part.mounting); + num_row(ui, tr("Width"), &mut part.width, " mm"); + num_row(ui, tr("Height"), &mut part.height, " mm"); + num_row(ui, tr("Depth"), &mut part.depth, " mm"); + num_row(ui, tr("Weight"), &mut part.weight, " kg"); + text_row(ui, tr("Mounting"), &mut part.mounting); }); } PartTab::Functions => { - ui.weak("Functions the part provides. Used for device selection, the contact image (reserve contacts), the project check and to assign connection designations. Designations are listed in symbol connection order, separated by blanks."); + ui.weak(tr("Functions the part provides. Used for device selection, the contact image (reserve contacts), the project check and to assign connection designations. Designations are listed in symbol connection order, separated by blanks.")); ui.add_space(4.0); let mut remove = None; egui::Grid::new("pf").num_columns(4).striped(true).spacing([8.0, 4.0]).show(ui, |ui| { - ui.label(RichText::new("Function").strong()); - ui.label(RichText::new("Connection designations").strong()); - ui.label(RichText::new("Description").strong()); + ui.label(RichText::new(tr("Function")).strong()); + ui.label(RichText::new(tr("Connection designations")).strong()); + ui.label(RichText::new(tr("Description")).strong()); ui.label(""); ui.end_row(); for (i, f) in part.functions.iter_mut().enumerate() { @@ -260,7 +261,7 @@ pub fn part_editor(ui: &mut egui::Ui, part: &mut Part, state: &mut EditorState, if let Some(i) = remove { part.functions.remove(i); } - if ui.button("➕ Add function").clicked() { + if ui.button(tr("➕ Add function")).clicked() { part.functions.push(FunctionTemplate::new(FnKind::No, "")); } } @@ -279,7 +280,7 @@ pub fn part_editor(ui: &mut egui::Ui, part: &mut Part, state: &mut EditorState, part.accessories.remove(i); } let mut add = None; - egui::ComboBox::from_id_salt("acc").selected_text("➕ Add accessory").width(240.0).show_ui(ui, |ui| { + egui::ComboBox::from_id_salt("acc").selected_text(tr("➕ Add accessory")).width(240.0).show_ui(ui, |ui| { for n in all_numbers { if *n != part.number && !part.accessories.contains(n) && ui.selectable_label(false, n).clicked() { add = Some(n.clone()); @@ -298,26 +299,26 @@ pub fn part_editor(ui: &mut egui::Ui, part: &mut Part, state: &mut EditorState, /// 2D front view and 3D model of a part. fn graphics_tab(ui: &mut egui::Ui, part: &mut Part, model_scale: &mut f32) -> Option { let mut request = None; - ui.weak("The 2D front view is used in the panel front view and on mounting layout pages, the 3D model in the 3D panel view. Both are fitted to the mounting data (width × height × depth)."); + ui.weak(tr("The 2D front view is used in the panel front view and on mounting layout pages, the 3D model in the 3D panel view. Both are fitted to the mounting data (width × height × depth).")); ui.add_space(4.0); - ui.label(RichText::new("2D front view").strong()); + ui.label(RichText::new(tr("2D front view")).strong()); ui.horizontal(|ui| { model_2d_preview(ui, part.model_2d.as_ref(), vec2(180.0, 140.0)); ui.vertical(|ui| { match &part.model_2d { - Some(m) => ui.label(format!("{:.1} × {:.1} mm, {} elements", m.width, m.height, m.prims.len())), - None => ui.weak("none – a plain rectangle is drawn"), + Some(m) => ui.label(tr_fmt!("{} × {} mm, {} elements", format!("{:.1}", m.width), format!("{:.1}", m.height), m.prims.len())), + None => ui.weak(tr("none – a plain rectangle is drawn")), }; - if ui.button("Import SVG…").clicked() { + if ui.button(tr("Import SVG…")).clicked() { request = Some(ModelKind::Front2d); } - if part.model_2d.is_some() && ui.button("🗑 Remove").clicked() { + if part.model_2d.is_some() && ui.button(tr("🗑 Remove")).clicked() { part.model_2d = None; } }); }); ui.separator(); - ui.label(RichText::new("3D model").strong()); + ui.label(RichText::new(tr("3D model")).strong()); ui.horizontal(|ui| { match &part.model_3d { Some(m) => mesh_preview(ui, m, vec2(180.0, 160.0)), @@ -329,32 +330,32 @@ fn graphics_tab(ui: &mut egui::Ui, part: &mut Part, model_scale: &mut f32) -> Op match &part.model_3d { Some(m) => { let s = m.size(); - ui.label(format!("{:.1} × {:.1} × {:.1} mm, {} triangles", s[0], s[1], s[2], m.triangles.len())); + ui.label(tr_fmt!("{} × {} × {} mm, {} triangles", format!("{:.1}", s[0]), format!("{:.1}", s[1]), format!("{:.1}", s[2]), m.triangles.len())); } None => { - ui.weak("none – a box of the mounting dimensions is drawn"); + ui.weak(tr("none – a box of the mounting dimensions is drawn")); } } - if ui.button("Import STL / OBJ…").clicked() { + if ui.button(tr("Import STL / OBJ…")).clicked() { request = Some(ModelKind::Mesh3d); } - if part.model_3d.is_some() && ui.button("🗑 Remove").clicked() { + if part.model_3d.is_some() && ui.button(tr("🗑 Remove")).clicked() { part.model_3d = None; } }); }); if let Some(m) = &mut part.model_3d { ui.horizontal_wrapped(|ui| { - ui.label("Rotate 90°:"); + ui.label(tr("Rotate 90°:")); for (axis, label) in [(0, "X"), (1, "Y"), (2, "Z")] { - if ui.button(label).on_hover_text("Turn the model so that its front faces the viewer (+Z) and its top is +Y").clicked() { + if ui.button(label).on_hover_text(tr("Turn the model so that its front faces the viewer (+Z) and its top is +Y")).clicked() { m.rotate90(axis); } } ui.separator(); - ui.label("Scale ×"); + ui.label(tr("Scale ×")); ui.add(egui::DragValue::new(model_scale).speed(0.01).range(0.001..=10000.0)); - if ui.button("Apply").on_hover_text("e.g. 25.4 for models in inch, 1000 for models in metres").clicked() { + if ui.button(tr("Apply")).on_hover_text(tr("e.g. 25.4 for models in inch, 1000 for models in metres")).clicked() { m.scale(*model_scale); } }); @@ -363,12 +364,17 @@ fn graphics_tab(ui: &mut egui::Ui, part: &mut Part, model_scale: &mut f32) -> Op if differs { ui.colored_label( Color32::from_rgb(220, 140, 0), - format!( - "The model ({:.1} × {:.1} × {:.1}) differs from the mounting data ({:.1} × {:.1} × {:.1}); it is stretched to the mounting data.", - s[0], s[1], s[2], part.width, part.height, part.depth + tr_fmt!( + "The model ({} × {} × {}) differs from the mounting data ({} × {} × {}); it is stretched to the mounting data.", + format!("{:.1}", s[0]), + format!("{:.1}", s[1]), + format!("{:.1}", s[2]), + format!("{:.1}", part.width), + format!("{:.1}", part.height), + format!("{:.1}", part.depth) ), ); - if ui.button("Use model size as mounting data").clicked() { + if ui.button(tr("Use model size as mounting data")).clicked() { part.width = (s[0] * 10.0).round() / 10.0; part.height = (s[1] * 10.0).round() / 10.0; part.depth = (s[2] * 10.0).round() / 10.0; @@ -385,14 +391,14 @@ pub fn apply_model(part: &mut Part, kind: ModelKind, name: &str, bytes: &[u8]) - match kind { ModelKind::Front2d => { let m = parse_svg(&String::from_utf8_lossy(bytes))?; - let msg = format!("{file}: 2D front view with {} elements assigned to {number}", m.prims.len()); + let msg = tr_fmt!("{}: 2D front view with {} elements assigned to {}", file, m.prims.len(), number); part.model_2d = Some(m); Ok(msg) } ModelKind::Mesh3d => { let m = parse_mesh(file, bytes)?; let s = m.size(); - let msg = format!("{file}: 3D model with {} triangles ({:.1} × {:.1} × {:.1} mm) assigned to {number}", m.triangles.len(), s[0], s[1], s[2]); + let msg = tr_fmt!("{}: 3D model with {} triangles ({} × {} × {} mm) assigned to {}", file, m.triangles.len(), format!("{:.1}", s[0]), format!("{:.1}", s[1]), format!("{:.1}", s[2]), number); // Parts without mounting data take the model size. if part.width <= 0.0 || part.height <= 0.0 { part.width = s[0]; @@ -511,15 +517,15 @@ pub fn part_summary(ui: &mut egui::Ui, p: &Part) { ui.label(&p.description); egui::Grid::new("sum").num_columns(2).show(ui, |ui| { for (k, v) in [ - ("Manufacturer", p.manufacturer.clone()), - ("Type number", p.type_number.clone()), - ("Order number", p.order_number.clone()), - ("Product group", format!("{} / {}", p.group, p.subgroup)), - ("Voltage / current", format!("{} {}", p.voltage, p.current)), - ("Price", format!("{:.2} {} / {} {}", p.price, p.currency, p.price_unit, p.quantity_unit)), - ("Dimensions", format!("{} × {} × {} mm", p.width, p.height, p.depth)), - ("Functions", p.template_summary()), - ("Accessories", p.accessories.join(", ")), + (tr("Manufacturer"), p.manufacturer.clone()), + (tr("Type number"), p.type_number.clone()), + (tr("Order number"), p.order_number.clone()), + (tr("Product group"), format!("{} / {}", p.group, p.subgroup)), + (tr("Voltage / current"), format!("{} {}", p.voltage, p.current)), + (tr("Price"), format!("{:.2} {} / {} {}", p.price, p.currency, p.price_unit, p.quantity_unit)), + (tr("Dimensions"), tr_fmt!("{} × {} × {} mm", p.width, p.height, p.depth)), + (tr("Functions"), p.template_summary()), + (tr("Accessories"), p.accessories.join(", ")), ] { if !v.trim().is_empty() && v.trim() != "/" { ui.label(RichText::new(k).weak()); diff --git a/parts-manager/Cargo.toml b/parts-manager/Cargo.toml index a853feb8..940d858a 100644 --- a/parts-manager/Cargo.toml +++ b/parts-manager/Cargo.toml @@ -1,4 +1,4 @@ -[package] +[package] name = "openecraft-parts-manager" version = "0.1.0" edition = "2021" @@ -24,6 +24,7 @@ egui = { version = "0.37", features = ["monochrome_emoji_fonts"] } serde_json = "1" log = "0.4" openecraft-parts = { path = "../crates/openecraft-parts" } +openecraft-i18n = { path = "../crates/openecraft-i18n" } openecraft-ui = { path = "../crates/openecraft-ui" } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] @@ -32,4 +33,4 @@ env_logger = "0.11" [target.'cfg(target_arch = "wasm32")'.dependencies] wasm-bindgen = "0.2" wasm-bindgen-futures = "0.4" -web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlCanvasElement"] } +web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlCanvasElement", "Navigator"] } diff --git a/parts-manager/src/app.rs b/parts-manager/src/app.rs index 120abb97..61a6eb62 100644 --- a/parts-manager/src/app.rs +++ b/parts-manager/src/app.rs @@ -1,5 +1,6 @@ //! Main window of the parts manager: connection, part tree, part editor. +use openecraft_i18n::{tr, tr_fmt}; use crate::session::{FollowUp, Session}; use egui::{Color32, Key, KeyboardShortcut, Modifiers, RichText}; use openecraft_parts::to_csv; @@ -19,7 +20,7 @@ pub enum Purpose { impl FileKind for Purpose { fn filter(self) -> (&'static str, &'static [&'static str]) { match self { - Purpose::Parts => ("Parts (CSV, JSON)", &["csv", "json", "txt"]), + Purpose::Parts => (tr("Parts (CSV, JSON)"), &["csv", "json", "txt"]), Purpose::Model(kind) => kind.filter(), } } @@ -51,6 +52,7 @@ const URL_KEY: &str = "server_url"; impl ManagerApp { pub fn new(cc: &eframe::CreationContext<'_>) -> ManagerApp { let mut client = ServerClient::default(); + openecraft_i18n::init(cc.storage.and_then(|s| eframe::get_value::(s, openecraft_ui::language::STORAGE_KEY)).as_deref()); if let Some(url) = cc.storage.and_then(|s| eframe::get_value::(s, URL_KEY)) { client.url = url; } @@ -92,9 +94,9 @@ impl ManagerApp { let draft = self.session.draft.as_mut().filter(|d| Some(&d.part.number) == target.as_ref()); self.client.status = match draft { Some(d) => pe::apply_model(&mut d.part, kind, &loaded.name, &loaded.bytes) - .map(|m| format!("{m} – save to upload it")) - .unwrap_or_else(|e| format!("Model import failed: {e}")), - None => format!("{}: the part is no longer open", short_name(&loaded.name)), + .map(|m| tr_fmt!("{} – save to upload it", m)) + .unwrap_or_else(|e| tr_fmt!("Model import failed: {}", e)), + None => tr_fmt!("{}: the part is no longer open", short_name(&loaded.name)), }; } } @@ -126,25 +128,25 @@ impl ManagerApp { ("parts.json", ("JSON", "json"), serde_json::to_string_pretty(&self.session.database()).unwrap_or_default()) }; self.client.status = match self.io.save_as(name, filter, &content) { - Ok(Some(path)) => format!("Exported {} parts to {}", self.session.parts.len(), short_name(&path)), + Ok(Some(path)) => tr_fmt!("Exported {} parts to {}", self.session.parts.len(), short_name(&path)), Ok(None) => return, - Err(e) => format!("Export failed: {e}"), + Err(e) => tr_fmt!("Export failed: {}", e), }; } fn connection_bar(&mut self, ui: &mut egui::Ui) { let ctx = ui.ctx().clone(); ui.horizontal_wrapped(|ui| { - ui.label(RichText::new("OpenECraft parts manager").strong()); + ui.label(RichText::new(tr("OpenECraft parts manager")).strong()); ui.separator(); - ui.label("Server"); + ui.label(tr("Server")); let url = ui.add(egui::TextEdit::singleline(&mut self.client.url).desired_width(240.0)); - ui.label("Access token"); + ui.label(tr("Access token")); let token = ui.add( - egui::TextEdit::singleline(&mut self.client.token).password(true).desired_width(160.0).hint_text("needed for changes"), + egui::TextEdit::singleline(&mut self.client.token).password(true).desired_width(160.0).hint_text(tr("needed for changes")), ); let enter = (url.lost_focus() || token.lost_focus()) && ui.input(|i| i.key_pressed(Key::Enter)); - if ui.add_enabled(!self.client.busy(), egui::Button::new("Connect")).clicked() || enter { + if ui.add_enabled(!self.client.busy(), egui::Button::new(tr("Connect"))).clicked() || enter { self.client.check(&ctx); } ui.separator(); @@ -152,22 +154,22 @@ impl ManagerApp { Some(info) => { ui.label(format!("{} {}", info.name, info.version)); if info.writable { - ui.label(RichText::new("writable with token").color(Color32::from_rgb(60, 160, 90))); + ui.label(RichText::new(tr("writable with token")).color(Color32::from_rgb(60, 160, 90))); } else { - ui.label(RichText::new("read-only server").color(Color32::from_rgb(220, 140, 0))) - .on_hover_text("Start openecraft-server with --token to allow changes"); + ui.label(RichText::new(tr("read-only server")).color(Color32::from_rgb(220, 140, 0))) + .on_hover_text(tr("Start openecraft-server with --token to allow changes")); } } None => { - ui.weak("not connected"); + ui.weak(tr("not connected")); } } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let mut pref = ui.ctx().options(|o| o.theme_preference); egui::ComboBox::from_id_salt("theme").selected_text(format!("{pref:?}")).width(70.0).show_ui(ui, |ui| { - ui.selectable_value(&mut pref, egui::ThemePreference::System, "System"); - ui.selectable_value(&mut pref, egui::ThemePreference::Light, "Light"); - ui.selectable_value(&mut pref, egui::ThemePreference::Dark, "Dark"); + ui.selectable_value(&mut pref, egui::ThemePreference::System, tr("System")); + ui.selectable_value(&mut pref, egui::ThemePreference::Light, tr("Light")); + ui.selectable_value(&mut pref, egui::ThemePreference::Dark, tr("Dark")); }); if pref != ui.ctx().options(|o| o.theme_preference) { ui.ctx().set_theme(pref); @@ -183,45 +185,46 @@ impl ManagerApp { let has_draft = self.session.draft.is_some(); let dirty = self.session.dirty(); ui.horizontal_wrapped(|ui| { - if ui.add_enabled(connected, egui::Button::new("➕ New")).clicked() { + if ui.add_enabled(connected, egui::Button::new(tr("➕ New"))).clicked() { self.open(None); } - if ui.add_enabled(has_draft, egui::Button::new("⎘ Copy")).on_hover_text("New part based on the open one").clicked() { + if ui.add_enabled(has_draft, egui::Button::new(tr("⎘ Copy"))).on_hover_text(tr("New part based on the open one")).clicked() { self.session.copy_part(); } let save = ui - .add_enabled(writable && dirty && self.session.save_problem().is_none(), egui::Button::new("✔ Save")) - .on_hover_text("Create / update the part on the server (Ctrl+S)"); + .add_enabled(writable && dirty && self.session.save_problem().is_none(), egui::Button::new(tr("✔ Save"))) + .on_hover_text(tr("Create / update the part on the server (Ctrl+S)")); if save.clicked() { self.save(&ctx); } - if ui.add_enabled(dirty, egui::Button::new("⟲ Revert")).on_hover_text("Discard the changes").clicked() { + if ui.add_enabled(dirty, egui::Button::new(tr("⟲ Revert"))).on_hover_text(tr("Discard the changes")).clicked() { self.session.revert(); } let deletable = self.session.draft.as_ref().and_then(|d| d.original.clone()); - if ui.add_enabled(writable && deletable.is_some(), egui::Button::new("🗑 Delete")).clicked() { + if ui.add_enabled(writable && deletable.is_some(), egui::Button::new(tr("🗑 Delete"))).clicked() { self.confirm = deletable.map(Confirm::Delete); } ui.separator(); - if ui.add_enabled(!self.client.busy() && connected, egui::Button::new("⟳ Reload")).on_hover_text("Load all parts from the server again").clicked() { + if ui.add_enabled(!self.client.busy() && connected, egui::Button::new(tr("⟳ Reload"))).on_hover_text(tr("Load all parts from the server again")).clicked() { self.client.download(&ctx); } - ui.menu_button("Import / export", |ui| { + ui.menu_button(tr("Import / export"), |ui| { if ui - .add_enabled(writable, egui::Button::new("⬆ Upload parts file (CSV / JSON)…")) - .on_hover_text("Adds new parts and replaces existing ones on the server") + .add_enabled(writable, egui::Button::new(tr("⬆ Upload parts file (CSV / JSON)…"))) + .on_hover_text(tr("Adds new parts and replaces existing ones on the server")) .clicked() { self.io.open(&ctx, Purpose::Parts); } ui.separator(); - if ui.add_enabled(connected, egui::Button::new("Export as CSV…")).clicked() { + if ui.add_enabled(connected, egui::Button::new(tr("Export as CSV…"))).clicked() { self.export(true); } - if ui.add_enabled(connected, egui::Button::new("Export as JSON…")).clicked() { + if ui.add_enabled(connected, egui::Button::new(tr("Export as JSON…"))).clicked() { self.export(false); } }); + openecraft_ui::language::menu(ui); if self.client.busy() { ui.spinner(); } @@ -229,10 +232,10 @@ impl ManagerApp { } fn part_list(&mut self, ui: &mut egui::Ui) { - ui.add(egui::TextEdit::singleline(&mut self.filter).hint_text("Filter (number, type, manufacturer, text …)")); - ui.label(RichText::new(format!("{} parts", self.session.parts.len())).weak()); + ui.add(egui::TextEdit::singleline(&mut self.filter).hint_text(tr("Filter (number, type, manufacturer, text …)"))); + ui.label(RichText::new(tr_fmt!("{} parts", self.session.parts.len())).weak()); if let Some(d) = self.session.draft.as_ref().filter(|d| d.original.is_none()) { - ui.label(RichText::new(format!("➕ {} (not saved)", d.part.number)).italics()); + ui.label(RichText::new(tr_fmt!("➕ {} (not saved)", d.part.number)).italics()); } egui::ScrollArea::vertical().id_salt("tree").auto_shrink([false, false]).show(ui, |ui| { let refs: Vec<_> = self.session.parts.iter().collect(); @@ -249,11 +252,11 @@ impl ManagerApp { if !self.session.loaded { ui.vertical_centered(|ui| { ui.add_space(60.0); - ui.heading("Connect to a parts server"); - ui.label("Enter the address of an openecraft-server and click Connect."); - ui.label("The access token is only needed for changes; it is not stored."); + ui.heading(tr("Connect to a parts server")); + ui.label(tr("Enter the address of an openecraft-server and click Connect.")); + ui.label(tr("The access token is only needed for changes; it is not stored.")); ui.add_space(8.0); - ui.weak("Start a server with: openecraft-server --token "); + ui.weak(tr("Start a server with: openecraft-server --token ")); }); return; } @@ -261,18 +264,18 @@ impl ManagerApp { let problem = self.session.save_problem(); let dirty = self.session.dirty(); let Some(d) = self.session.draft.as_mut() else { - ui.weak("Select a part in the tree or create a new one."); + ui.weak(tr("Select a part in the tree or create a new one.")); return; }; ui.horizontal(|ui| { ui.heading(&d.part.number); match (&d.original, dirty) { - (None, _) => ui.label(RichText::new("new part, not saved").color(Color32::from_rgb(220, 140, 0))), - (Some(_), true) => ui.label(RichText::new("changed, not saved").color(Color32::from_rgb(220, 140, 0))), - (Some(_), false) => ui.weak("saved"), + (None, _) => ui.label(RichText::new(tr("new part, not saved")).color(Color32::from_rgb(220, 140, 0))), + (Some(_), true) => ui.label(RichText::new(tr("changed, not saved")).color(Color32::from_rgb(220, 140, 0))), + (Some(_), false) => ui.weak(tr("saved")), }; if let Some(original) = d.original.as_ref().filter(|o| **o != d.part.number) { - ui.weak(format!("(renamed from {original})")); + ui.weak(tr_fmt!("(renamed from {})", original)); } }); ui.separator(); @@ -289,9 +292,9 @@ impl ManagerApp { let (text, button) = match confirm { Confirm::Discard(_) => { let n = self.session.draft.as_ref().map(|d| d.part.number.clone()).unwrap_or_default(); - (format!("Discard the unsaved changes of {n}?"), "Discard") + (tr_fmt!("Discard the unsaved changes of {}?", n), "Discard") } - Confirm::Delete(n) => (format!("Delete part {n} from the server? This cannot be undone."), "🗑 Delete"), + Confirm::Delete(n) => (tr_fmt!("Delete part {} from the server? This cannot be undone.", n), "🗑 Delete"), }; let mut answer = None; egui::Modal::new(egui::Id::unique("confirm")).show(ctx, |ui| { @@ -302,7 +305,7 @@ impl ManagerApp { if ui.button(button).clicked() { answer = Some(true); } - if ui.button("Cancel").clicked() || ui.input(|i| i.key_pressed(Key::Escape)) { + if ui.button(tr("Cancel")).clicked() || ui.input(|i| i.key_pressed(Key::Escape)) { answer = Some(false); } }); @@ -353,5 +356,7 @@ impl eframe::App for ManagerApp { fn save(&mut self, storage: &mut dyn eframe::Storage) { eframe::set_value(storage, URL_KEY, &self.client.url); + eframe::set_value(storage, openecraft_ui::language::STORAGE_KEY, &openecraft_i18n::lang().code()); + eframe::set_value(storage, openecraft_ui::language::STORAGE_KEY, &openecraft_i18n::lang().code()); } } diff --git a/parts-manager/src/main.rs b/parts-manager/src/main.rs index ec7222c7..2a24f15c 100644 --- a/parts-manager/src/main.rs +++ b/parts-manager/src/main.rs @@ -25,6 +25,9 @@ fn main() -> eframe::Result { fn main() { use wasm_bindgen::JsCast; eframe::WebLogger::init(log::LevelFilter::Info).ok(); + if let Some(lang) = web_sys::window().and_then(|w| w.navigator().language()).and_then(|code| openecraft_i18n::Lang::from_code(&code)) { + openecraft_i18n::set_lang(lang); + } wasm_bindgen_futures::spawn_local(async { let document = web_sys::window().expect("no window").document().expect("no document"); let canvas = document diff --git a/src/app.rs b/src/app.rs index f9afb344..dac03eef 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1,6 +1,7 @@ //! Main application window: menus, toolbar, navigators, symbol library, property //! editor, reports and dialogs. +use openecraft_i18n::{tr, tr_fmt}; use crate::editor::{symbol_icon, Editor, Tool}; use crate::index::Index; use crate::io::{self, FileIo, Purpose, PROJECT_EXT}; @@ -41,6 +42,7 @@ pub struct App { history: History, analysis: Analysis, analysis_rev: u64, + analysis_lang: openecraft_i18n::Lang, saved_rev: u64, file_name: Option, io: FileIo, @@ -77,13 +79,16 @@ impl App { let mut parts_db: Option = None; let mut server_url: Option = None; let mut macro_lib = None; + let mut language: Option = None; if let Some(storage) = cc.storage { + language = eframe::get_value(storage, openecraft_ui::language::STORAGE_KEY); prj = eframe::get_value(storage, "project"); file_name = eframe::get_value(storage, "file_name").flatten(); parts_db = eframe::get_value(storage, "parts_db"); server_url = eframe::get_value(storage, "parts_server_url"); macro_lib = eframe::get_value(storage, "macros"); } + openecraft_i18n::init(language.as_deref()); let parts_db = parts_db.unwrap_or_default(); let mut parts_ui = PartsUi::default(); if let Some(url) = server_url { @@ -100,6 +105,7 @@ impl App { history, analysis: Analysis::default(), analysis_rev: 0, + analysis_lang: openecraft_i18n::lang(), saved_rev: rev, file_name, io: FileIo::default(), @@ -202,20 +208,20 @@ impl App { }; match result { Ok(Some(path)) => { - self.notify(ctx, format!("Saved {}", io::short_name(&path))); + self.notify(ctx, tr_fmt!("Saved {}", io::short_name(&path))); self.file_name = Some(path); self.saved_rev = self.history.rev; } Ok(None) => {} - Err(e) => self.notify(ctx, format!("Saving failed: {e}")), + Err(e) => self.notify(ctx, tr_fmt!("Saving failed: {}", e)), } } fn export(&mut self, ctx: &egui::Context, name: String, filter: (&str, &str), content: String) { match self.io.save_as(&name, filter, &content) { - Ok(Some(path)) => self.notify(ctx, format!("Exported {}", io::short_name(&path))), + Ok(Some(path)) => self.notify(ctx, tr_fmt!("Exported {}", io::short_name(&path))), Ok(None) => {} - Err(e) => self.notify(ctx, format!("Export failed: {e}")), + Err(e) => self.notify(ctx, tr_fmt!("Export failed: {}", e)), } } @@ -224,7 +230,7 @@ impl App { if matches!(loaded.purpose, Purpose::Model(_)) { let msg = match self.parts_ui.apply_model(&loaded, &mut self.parts_db, &mut self.prj) { Ok(m) => m, - Err(e) => format!("Model import failed: {e}"), + Err(e) => tr_fmt!("Model import failed: {}", e), }; self.notify(ctx, msg); return; @@ -236,9 +242,9 @@ impl App { match lib { Ok(lib) => { let n = self.macro_lib.merge(lib); - self.notify(ctx, format!("Imported {n} macros")); + self.notify(ctx, tr_fmt!("Imported {} macros", n)); } - Err(e) => self.notify(ctx, format!("Not a macro file: {e}")), + Err(e) => self.notify(ctx, tr_fmt!("Not a macro file: {}", e)), } return; } @@ -250,9 +256,9 @@ impl App { Ok(lib) => { let (added, replaced) = crate::symlib::merge(&mut self.prj.symbols, lib); self.symed.open = true; - self.notify(ctx, format!("{added} symbols added, {replaced} replaced")); + self.notify(ctx, tr_fmt!("{} symbols added, {} replaced", added, replaced)); } - Err(e) => self.notify(ctx, format!("Not a symbol library: {e}")), + Err(e) => self.notify(ctx, tr_fmt!("Not a symbol library: {}", e)), } return; } @@ -266,16 +272,16 @@ impl App { None => self.prj.forms.title_blocks.push(f), } } - self.notify(ctx, format!("Imported {n} title blocks")); + self.notify(ctx, tr_fmt!("Imported {} title blocks", n)); } - Err(e) => self.notify(ctx, format!("Not a title block file: {e}")), + Err(e) => self.notify(ctx, tr_fmt!("Not a title block file: {}", e)), } return; } if loaded.purpose == Purpose::PlcTable { match crate::plc::import_symbol_table(&mut self.prj, &loaded.text()) { - Ok(n) => self.notify(ctx, format!("{n} PLC function texts updated")), - Err(e) => self.notify(ctx, format!("Symbol table import failed: {e}")), + Ok(n) => self.notify(ctx, tr_fmt!("{} PLC function texts updated", n)), + Err(e) => self.notify(ctx, tr_fmt!("Symbol table import failed: {}", e)), } return; } @@ -287,18 +293,18 @@ impl App { self.parts_db.upsert(p); } self.parts_db.sort(); - self.notify(ctx, format!("Imported {n} parts into the database")); + self.notify(ctx, tr_fmt!("Imported {} parts into the database", n)); } - Err(e) => self.notify(ctx, format!("Parts import failed: {e}")), + Err(e) => self.notify(ctx, tr_fmt!("Parts import failed: {}", e)), } return; } match serde_json::from_str::(&loaded.text()) { Ok(prj) => { self.replace_project(prj, Some(loaded.name.clone())); - self.notify(ctx, format!("Opened {}", io::short_name(&loaded.name))); + self.notify(ctx, tr_fmt!("Opened {}", io::short_name(&loaded.name))); } - Err(e) => self.notify(ctx, format!("Not a valid project file: {e}")), + Err(e) => self.notify(ctx, tr_fmt!("Not a valid project file: {}", e)), } } } @@ -313,12 +319,12 @@ impl App { fn add_page(&mut self, kind: PageKind) { let id = self.prj.new_id(); let desc = match kind { - PageKind::Schematic => "Schematic".to_string(), - PageKind::Cover => "Cover sheet".to_string(), + PageKind::Schematic => tr("Schematic").to_string(), + PageKind::Cover => tr("Cover sheet").to_string(), PageKind::Report(r) => r.title().to_string(), PageKind::Mounting(id) => { let name = self.prj.layout.enclosures.iter().find(|e| e.id == id).map(|e| e.name.clone()).unwrap_or_default(); - format!("Mounting layout {name}") + tr_fmt!("Mounting layout {}", name) } }; let page = Page::new(id, &self.next_page_name(), &desc, kind); @@ -333,110 +339,110 @@ impl App { fn menu_bar(&mut self, ui: &mut egui::Ui) { let ctx = ui.ctx().clone(); egui::MenuBar::new().ui(ui, |ui| { - ui.menu_button("File", |ui| { - if ui.button("New project").clicked() { + ui.menu_button(tr("File"), |ui| { + if ui.button(tr("New project")).clicked() { self.replace_project(Project::default(), None); } - if ui.button("Open… Ctrl+O").clicked() { + if ui.button(tr("Open… Ctrl+O")).clicked() { self.io.open(&ctx, Purpose::Project); } - if ui.button("Open demo project").clicked() { + if ui.button(tr("Open demo project")).clicked() { self.replace_project(sample::demo_project(), None); } ui.separator(); - let save_label = if FileIo::can_save_in_place() { "Save Ctrl+S" } else { "Download project Ctrl+S" }; + let save_label = if FileIo::can_save_in_place() { tr("Save Ctrl+S") } else { tr("Download project Ctrl+S") }; if ui.button(save_label).clicked() { self.save(&ctx, false); } - if FileIo::can_save_in_place() && ui.button("Save as…").clicked() { + if FileIo::can_save_in_place() && ui.button(tr("Save as…")).clicked() { self.save(&ctx, true); } ui.separator(); - if ui.button("Export page as SVG…").clicked() { + if ui.button(tr("Export page as SVG…")).clicked() { let svg = svg::page_svg(&self.prj, self.page); let name = format!("{}_page_{}.svg", self.suggested_name("x").trim_end_matches(".x"), self.prj.pages[self.page].name); - self.export(&ctx, name, ("SVG image", "svg"), svg); + self.export(&ctx, name, (tr("SVG image"), "svg"), svg); } - if ui.button("Export all pages for printing (HTML/PDF)…").clicked() { + if ui.button(tr("Export all pages for printing (HTML/PDF)…")).clicked() { let html = svg::print_document(&self.prj); - self.export(&ctx, self.suggested_name("html"), ("HTML document", "html"), html); + self.export(&ctx, self.suggested_name("html"), (tr("HTML document"), "html"), html); } - if ui.button("Export as PDF (bookmarks, linked cross references)…").clicked() { + if ui.button(tr("Export as PDF (bookmarks, linked cross references)…")).clicked() { let pdf = crate::pdf::document(&self.prj); - self.export(&ctx, self.suggested_name("pdf"), ("PDF document", "pdf"), pdf); + self.export(&ctx, self.suggested_name("pdf"), (tr("PDF document"), "pdf"), pdf); } - if ui.button("Export page as DXF…").clicked() { + if ui.button(tr("Export page as DXF…")).clicked() { let dxf = crate::dxf::pages_dxf(&self.prj, &[self.page]); let name = format!("{}_page_{}.dxf", self.suggested_name("x").trim_end_matches(".x"), self.prj.pages[self.page].name); - self.export(&ctx, name, ("DXF drawing", "dxf"), dxf); + self.export(&ctx, name, (tr("DXF drawing"), "dxf"), dxf); } - if ui.button("Export all pages as DXF…").clicked() { + if ui.button(tr("Export all pages as DXF…")).clicked() { let all: Vec = (0..self.prj.pages.len()).collect(); let dxf = crate::dxf::pages_dxf(&self.prj, &all); - self.export(&ctx, self.suggested_name("dxf"), ("DXF drawing", "dxf"), dxf); + self.export(&ctx, self.suggested_name("dxf"), (tr("DXF drawing"), "dxf"), dxf); } - if ui.button("Export production wire list (CSV)…").on_hover_text("Wire numbers, ends, colour, cross-section, routed length, cable cores").clicked() { + if ui.button(tr("Export production wire list (CSV)…")).on_hover_text(tr("Wire numbers, ends, colour, cross-section, routed length, cable cores")).clicked() { let csv = crate::reports::production_wire_list(&self.prj, &self.analysis).to_csv(); self.export(&ctx, "wire_list.csv".into(), ("CSV", "csv"), csv); } #[cfg(not(target_arch = "wasm32"))] { ui.separator(); - if ui.button("Quit").clicked() { + if ui.button(tr("Quit")).clicked() { ctx.send_viewport_cmd(egui::ViewportCommand::Close); } } }); - ui.menu_button("Edit", |ui| { - if ui.add_enabled(self.history.can_undo(), egui::Button::new("Undo Ctrl+Z")).clicked() { + ui.menu_button(tr("Edit"), |ui| { + if ui.add_enabled(self.history.can_undo(), egui::Button::new(tr("Undo Ctrl+Z"))).clicked() { self.history.undo(&mut self.prj); } - if ui.add_enabled(self.history.can_redo(), egui::Button::new("Redo Ctrl+Y")).clicked() { + if ui.add_enabled(self.history.can_redo(), egui::Button::new(tr("Redo Ctrl+Y"))).clicked() { self.history.redo(&mut self.prj); } ui.separator(); let has_sel = !self.editor.selection.is_empty(); - if ui.add_enabled(has_sel, egui::Button::new("Rotate R")).clicked() { + if ui.add_enabled(has_sel, egui::Button::new(tr("Rotate R"))).clicked() { ops::rotate(&mut self.prj.pages[self.page], &self.editor.selection); } - if ui.add_enabled(has_sel, egui::Button::new("Mirror M")).clicked() { + if ui.add_enabled(has_sel, egui::Button::new(tr("Mirror M"))).clicked() { ops::mirror(&mut self.prj.pages[self.page], &self.editor.selection); } - if ui.add_enabled(has_sel, egui::Button::new("Delete Del")).clicked() { + if ui.add_enabled(has_sel, egui::Button::new(tr("Delete Del"))).clicked() { ops::delete(&mut self.prj.pages[self.page], &self.editor.selection); self.editor.selection.clear(); } - if ui.button("Select all Ctrl+A").clicked() { + if ui.button(tr("Select all Ctrl+A")).clicked() { self.editor.selection = ops::all_ids(&self.prj.pages[self.page]).into_iter().collect(); } - ui.label(RichText::new("Copy / paste: Ctrl+C, Ctrl+X, Ctrl+V").weak()); + ui.label(RichText::new(tr("Copy / paste: Ctrl+C, Ctrl+X, Ctrl+V")).weak()); ui.separator(); - if ui.add_enabled(has_sel, egui::Button::new("Save selection as macro…")).clicked() { + if ui.add_enabled(has_sel, egui::Button::new(tr("Save selection as macro…"))).clicked() { self.save_as_macro(false); } }); - ui.menu_button("Insert", |ui| { - if ui.button("Macro…").clicked() { + ui.menu_button(tr("Insert"), |ui| { + if ui.button(tr("Macro…")).clicked() { self.eng.show_macros = true; } ui.separator(); - if ui.button("Wire W").clicked() { + if ui.button(tr("Wire W")).clicked() { self.editor.set_tool(Tool::Wire); } - if ui.button("Text T").clicked() { + if ui.button(tr("Text T")).clicked() { self.editor.set_tool(Tool::Text); } - if ui.button("Graphic line").clicked() { + if ui.button(tr("Graphic line")).clicked() { self.editor.set_tool(Tool::Line); } - if ui.button("Graphic rectangle").clicked() { + if ui.button(tr("Graphic rectangle")).clicked() { self.editor.set_tool(Tool::Rect); } ui.separator(); for cat in Category::ALL { ui.menu_button(cat.title(), |ui| { for def in symbols::library().iter().filter(|d| d.category == cat) { - if ui.button(def.name).clicked() { + if ui.button(tr(def.name)).clicked() { self.editor.set_tool(Tool::Place(def.key)); } } @@ -446,28 +452,28 @@ impl App { if !user.is_empty() { ui.menu_button(Category::User.title(), |ui| { for def in user { - if ui.button(format!("{} ({})", def.name, def.library)).clicked() { + if ui.button(format!("{} ({})", tr(def.name), def.library)).clicked() { self.editor.set_tool(Tool::Place(def.key)); } } }); } }); - ui.menu_button("Page", |ui| { - if ui.button("New schematic page").clicked() { + ui.menu_button(tr("Page"), |ui| { + if ui.button(tr("New schematic page")).clicked() { self.add_page(PageKind::Schematic); } - if ui.button("New cover sheet").clicked() { + if ui.button(tr("New cover sheet")).clicked() { self.add_page(PageKind::Cover); } - ui.menu_button("New report page", |ui| { + ui.menu_button(tr("New report page"), |ui| { for k in ReportKind::ALL { if ui.button(k.title()).clicked() { self.add_page(PageKind::Report(k)); } } }); - ui.menu_button("New mounting layout page", |ui| { + ui.menu_button(tr("New mounting layout page"), |ui| { let encs: Vec<(u64, String)> = self.prj.layout.enclosures.iter().map(|e| (e.id, e.name.clone())).collect(); for (id, name) in encs { if ui.button(name).clicked() { @@ -475,70 +481,70 @@ impl App { } } if self.prj.layout.enclosures.is_empty() { - ui.weak("Create an enclosure in the panel layout first."); + ui.weak(tr("Create an enclosure in the panel layout first.")); } }); ui.separator(); - if ui.button("Page properties…").clicked() { + if ui.button(tr("Page properties…")).clicked() { self.page_props = Some(self.page); } - if ui.button("Save page as macro…").clicked() { + if ui.button(tr("Save page as macro…")).clicked() { self.save_as_macro(true); } - if ui.add_enabled(self.page > 0, egui::Button::new("Move page up")).clicked() { + if ui.add_enabled(self.page > 0, egui::Button::new(tr("Move page up"))).clicked() { self.prj.pages.swap(self.page, self.page - 1); self.page -= 1; } - if ui.add_enabled(self.page + 1 < self.prj.pages.len(), egui::Button::new("Move page down")).clicked() { + if ui.add_enabled(self.page + 1 < self.prj.pages.len(), egui::Button::new(tr("Move page down"))).clicked() { self.prj.pages.swap(self.page, self.page + 1); self.page += 1; } - if ui.add_enabled(self.prj.pages.len() > 1, egui::Button::new("Delete page")).clicked() { + if ui.add_enabled(self.prj.pages.len() > 1, egui::Button::new(tr("Delete page"))).clicked() { self.prj.pages.remove(self.page); self.page = self.page.min(self.prj.pages.len() - 1); self.editor.selection.clear(); } }); - ui.menu_button("Project", |ui| { - if ui.button("Project properties…").clicked() { + ui.menu_button(tr("Project"), |ui| { + if ui.button(tr("Project properties…")).clicked() { self.show_project = true; } - if ui.button("Parts management…").clicked() { + if ui.button(tr("Parts management…")).clicked() { self.parts_ui.open = true; } - if ui.button("Cables…").clicked() { + if ui.button(tr("Cables…")).clicked() { self.show_cables = true; } - if ui.button("Wire numbering…").clicked() { + if ui.button(tr("Wire numbering…")).clicked() { self.show_numbering = true; } - if ui.button("Harnesses…").clicked() { + if ui.button(tr("Harnesses…")).clicked() { self.harness_ui.open = true; } - if ui.button("Terminal strips…").clicked() { + if ui.button(tr("Terminal strips…")).clicked() { self.eng.show_strips = true; } - if ui.button("PLC overview…").clicked() { + if ui.button(tr("PLC overview…")).clicked() { self.eng.show_plc = true; } - if ui.button("Revisions…").clicked() { + if ui.button(tr("Revisions…")).clicked() { self.eng.show_revisions = true; } - if ui.button("Macros…").clicked() { + if ui.button(tr("Macros…")).clicked() { self.eng.show_macros = true; } ui.separator(); - if ui.button("Symbol editor…").clicked() { + if ui.button(tr("Symbol editor…")).clicked() { self.symed.open = true; } - if ui.button("Title blocks and report forms…").clicked() { + if ui.button(tr("Title blocks and report forms…")).clicked() { self.forms_ui.open = true; } - if ui.button("Check project").clicked() { + if ui.button(tr("Check project")).clicked() { self.left_tab = LeftTab::Check; } }); - ui.menu_button("Reports", |ui| { + ui.menu_button(tr("Reports"), |ui| { for k in ReportKind::ALL { if ui.button(k.title()).clicked() { self.report_kind = k; @@ -546,26 +552,27 @@ impl App { } } }); - ui.menu_button("View", |ui| { - if ui.button("Fit page F").clicked() { + ui.menu_button(tr("View"), |ui| { + if ui.button(tr("Fit page F")).clicked() { self.editor.fit_pending = true; } - ui.checkbox(&mut self.editor.show_grid, "Grid"); - ui.checkbox(&mut self.editor.show_pins, "Connection points"); - ui.checkbox(&mut self.editor.show_revision_marks, "Revision marks"); + ui.checkbox(&mut self.editor.show_grid, tr("Grid")); + ui.checkbox(&mut self.editor.show_pins, tr("Connection points")); + ui.checkbox(&mut self.editor.show_revision_marks, tr("Revision marks")); ui.separator(); + openecraft_ui::language::menu(ui); let mut pref = ui.ctx().options(|o| o.theme_preference); ui.horizontal(|ui| { - ui.selectable_value(&mut pref, egui::ThemePreference::System, "System"); - ui.selectable_value(&mut pref, egui::ThemePreference::Light, "Light"); - ui.selectable_value(&mut pref, egui::ThemePreference::Dark, "Dark"); + ui.selectable_value(&mut pref, egui::ThemePreference::System, tr("System")); + ui.selectable_value(&mut pref, egui::ThemePreference::Light, tr("Light")); + ui.selectable_value(&mut pref, egui::ThemePreference::Dark, tr("Dark")); }); if pref != ui.ctx().options(|o| o.theme_preference) { ui.ctx().set_theme(pref); } }); - ui.menu_button("Help", |ui| { - if ui.button("Shortcuts & usage").clicked() { + ui.menu_button(tr("Help"), |ui| { + if ui.button(tr("Shortcuts & usage")).clicked() { self.show_help = true; } }); @@ -574,18 +581,18 @@ impl App { fn toolbar(&mut self, ui: &mut egui::Ui) { ui.horizontal_wrapped(|ui| { - ui.selectable_value(&mut self.workspace, Workspace::Schematic, RichText::new("🗋 Schematic").strong()); - ui.selectable_value(&mut self.workspace, Workspace::Panel, RichText::new("🗄 Panel layout").strong()); + ui.selectable_value(&mut self.workspace, Workspace::Schematic, RichText::new(tr("🗋 Schematic")).strong()); + ui.selectable_value(&mut self.workspace, Workspace::Panel, RichText::new(tr("🗄 Panel layout")).strong()); ui.separator(); if self.workspace == Workspace::Panel { - if ui.add_enabled(self.history.can_undo(), egui::Button::new("↩")).on_hover_text("Undo (Ctrl+Z)").clicked() { + if ui.add_enabled(self.history.can_undo(), egui::Button::new("↩")).on_hover_text(tr("Undo (Ctrl+Z)")).clicked() { self.history.undo(&mut self.prj); } - if ui.add_enabled(self.history.can_redo(), egui::Button::new("↪")).on_hover_text("Redo (Ctrl+Y)").clicked() { + if ui.add_enabled(self.history.can_redo(), egui::Button::new("↪")).on_hover_text(tr("Redo (Ctrl+Y)")).clicked() { self.history.redo(&mut self.prj); } ui.separator(); - if ui.button("📊 Reports").clicked() { + if ui.button(tr("📊 Reports")).clicked() { self.report_kind = ReportKind::PanelWiring; self.show_reports = true; } @@ -597,47 +604,47 @@ impl App { self.editor.set_tool(t); } }; - tbtn(ui, Tool::Select, "⬉ Select", "Select / move (Esc)"); - tbtn(ui, Tool::Wire, "✏ Wire", "Draw connections (W)"); - tbtn(ui, Tool::Text, "T Text", "Place text (T)"); - tbtn(ui, Tool::Line, "— Line", "Graphic line"); - tbtn(ui, Tool::Rect, "☐ Rect", "Graphic rectangle"); + tbtn(ui, Tool::Select, tr("⬉ Select"), tr("Select / move (Esc)")); + tbtn(ui, Tool::Wire, tr("✏ Wire"), tr("Draw connections (W)")); + tbtn(ui, Tool::Text, tr("T Text"), tr("Place text (T)")); + tbtn(ui, Tool::Line, tr("— Line"), tr("Graphic line")); + tbtn(ui, Tool::Rect, tr("☐ Rect"), tr("Graphic rectangle")); if let Tool::Place(key) = tool { if let Some(def) = symbols::get(key) { - ui.label(RichText::new(format!("Placing: {}", def.name)).strong()); + ui.label(RichText::new(tr_fmt!("Placing: {}", tr(def.name))).strong()); } } ui.separator(); - if ui.add_enabled(self.history.can_undo(), egui::Button::new("↩")).on_hover_text("Undo (Ctrl+Z)").clicked() { + if ui.add_enabled(self.history.can_undo(), egui::Button::new("↩")).on_hover_text(tr("Undo (Ctrl+Z)")).clicked() { self.history.undo(&mut self.prj); } - if ui.add_enabled(self.history.can_redo(), egui::Button::new("↪")).on_hover_text("Redo (Ctrl+Y)").clicked() { + if ui.add_enabled(self.history.can_redo(), egui::Button::new("↪")).on_hover_text(tr("Redo (Ctrl+Y)")).clicked() { self.history.redo(&mut self.prj); } let has_sel = !self.editor.selection.is_empty(); - if ui.add_enabled(has_sel, egui::Button::new("⟳")).on_hover_text("Rotate (R)").clicked() { + if ui.add_enabled(has_sel, egui::Button::new("⟳")).on_hover_text(tr("Rotate (R)")).clicked() { ops::rotate(&mut self.prj.pages[self.page], &self.editor.selection); } - if ui.add_enabled(has_sel, egui::Button::new("🗑")).on_hover_text("Delete (Del)").clicked() { + if ui.add_enabled(has_sel, egui::Button::new("🗑")).on_hover_text(tr("Delete (Del)")).clicked() { ops::delete(&mut self.prj.pages[self.page], &self.editor.selection); self.editor.selection.clear(); } ui.separator(); - if ui.button("⛶ Fit").on_hover_text("Fit page (F)").clicked() { + if ui.button(tr("⛶ Fit")).on_hover_text(tr("Fit page (F)")).clicked() { self.editor.fit_pending = true; } - ui.label(format!("{:.0}%", self.editor.zoom / 3.78 * 100.0)).on_hover_text("100% ≈ real size on a 96 dpi screen"); + ui.label(format!("{:.0}%", self.editor.zoom / 3.78 * 100.0)).on_hover_text(tr("100% ≈ real size on a 96 dpi screen")); ui.separator(); - if ui.add_enabled(self.page > 0, egui::Button::new("◀")).on_hover_text("Previous page (Page Up)").clicked() { + if ui.add_enabled(self.page > 0, egui::Button::new("◀")).on_hover_text(tr("Previous page (Page Up)")).clicked() { self.goto(self.page - 1, 0); } let pg = &self.prj.pages[self.page]; - ui.label(RichText::new(format!("Page {} {}", structure::page_full_name(pg), pg.description)).strong()); - if ui.add_enabled(self.page + 1 < self.prj.pages.len(), egui::Button::new("▶")).on_hover_text("Next page (Page Down)").clicked() { + ui.label(RichText::new(tr_fmt!("Page {} {}", structure::page_full_name(pg), pg.description)).strong()); + if ui.add_enabled(self.page + 1 < self.prj.pages.len(), egui::Button::new("▶")).on_hover_text(tr("Next page (Page Down)")).clicked() { self.goto(self.page + 1, 0); } ui.separator(); - if ui.button("📊 Reports").clicked() { + if ui.button(tr("📊 Reports")).clicked() { self.show_reports = true; } }); @@ -645,20 +652,20 @@ impl App { fn navigator(&mut self, ui: &mut egui::Ui, idx: &Index) { ui.horizontal(|ui| { - ui.selectable_value(&mut self.left_tab, LeftTab::Pages, "Pages"); - ui.selectable_value(&mut self.left_tab, LeftTab::Devices, "Devices"); + ui.selectable_value(&mut self.left_tab, LeftTab::Pages, tr("Pages")); + ui.selectable_value(&mut self.left_tab, LeftTab::Devices, tr("Devices")); let n_err = self.analysis.issues.iter().filter(|i| i.severity == Severity::Error).count(); - let label = if n_err > 0 { RichText::new(format!("Check ({n_err})")).color(Color32::from_rgb(220, 60, 60)) } else { RichText::new("Check") }; + let label = if n_err > 0 { RichText::new(tr_fmt!("Check ({})", n_err)).color(Color32::from_rgb(220, 60, 60)) } else { RichText::new(tr("Check")) }; ui.selectable_value(&mut self.left_tab, LeftTab::Check, label); }); ui.separator(); match self.left_tab { LeftTab::Pages => { ui.horizontal(|ui| { - if ui.button("+ Page").on_hover_text("New schematic page after the current one").clicked() { + if ui.button(tr("+ Page")).on_hover_text(tr("New schematic page after the current one")).clicked() { self.add_page(PageKind::Schematic); } - if ui.button("⚙").on_hover_text("Page properties").clicked() { + if ui.button("⚙").on_hover_text(tr("Page properties")).clicked() { self.page_props = Some(self.page); } if ui.add_enabled(self.page > 0, egui::Button::new("⏶")).clicked() { @@ -693,7 +700,7 @@ impl App { }); } LeftTab::Devices => { - ui.add(egui::TextEdit::singleline(&mut self.device_filter).hint_text("Filter devices…")); + ui.add(egui::TextEdit::singleline(&mut self.device_filter).hint_text(tr("Filter devices…"))); egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { let mut jump = None; let f = self.device_filter.to_lowercase(); @@ -713,11 +720,11 @@ impl App { let dev = &idx.devices[tag]; let title = if structured { Dt::parse(tag).name } else { tag.clone() }; egui::CollapsingHeader::new(RichText::new(title).monospace().strong()).id_salt(tag).show(ui, |ui| { - for (kind, locs) in [("Main", &dev.mains), ("Aux", &dev.auxs), ("", &dev.others)] { + for (kind, locs) in [(tr("Main"), &dev.mains), (tr("Aux"), &dev.auxs), ("", &dev.others)] { for loc in locs { let inst = prj.pages[loc.page].symbols.iter().find(|s| s.id == loc.sym_id); let Some(inst) = inst else { continue }; - let name = symbols::get(&inst.sym).map(|d| d.name).unwrap_or("?"); + let name = symbols::get(&inst.sym).map(|d| tr(d.name)).unwrap_or("?"); let extra = if inst.label.is_empty() { inst.pins.join("-") } else { inst.label.clone() }; let text = format!("{} {kind} {name} {extra}", loc.reference(prj)); if ui.link(text.trim()).clicked() { @@ -742,7 +749,7 @@ impl App { } } if idx.devices.is_empty() { - ui.weak("No devices yet. Pick a symbol from the library on the right and click into the page."); + ui.weak(tr("No devices yet. Pick a symbol from the library on the right and click into the page.")); } if let Some((pg, id)) = jump { self.goto(pg, id); @@ -769,13 +776,13 @@ impl App { ui.horizontal_wrapped(|ui| { ui.label(RichText::new(icon).color(color)); let r = ui.add(egui::Label::new(&issue.message).sense(egui::Sense::click())); - if r.on_hover_text("Click to show").clicked() { + if r.on_hover_text(tr("Click to show")).clicked() { jump = issue.target; } }); } if issues.is_empty() { - ui.label("✔ No problems found."); + ui.label(tr("✔ No problems found.")); } if let Some((pg, id)) = jump { self.goto(pg, id); @@ -787,8 +794,8 @@ impl App { fn library(&mut self, ui: &mut egui::Ui) { ui.horizontal(|ui| { - ui.heading("Symbols"); - ui.add(egui::TextEdit::singleline(&mut self.lib_filter).hint_text("Search…").desired_width(f32::INFINITY)); + ui.heading(tr("Symbols")); + ui.add(egui::TextEdit::singleline(&mut self.lib_filter).hint_text(tr("Search…")).desired_width(f32::INFINITY)); }); let f = self.lib_filter.to_lowercase(); let user = self.user_symbols(); @@ -800,7 +807,7 @@ impl App { .map(|lib| (format!("{}: {lib}", Category::User.title()), user.iter().copied().filter(|d| d.library == *lib).collect::>())) .chain(Category::ALL.into_iter().map(|cat| (cat.title().to_string(), symbols::library().iter().filter(|d| d.category == cat).collect()))); for (title, defs) in groups { - let defs: Vec<&symbols::SymbolDef> = defs.into_iter().filter(|d| f.is_empty() || d.name.to_lowercase().contains(&f)).collect(); + let defs: Vec<&symbols::SymbolDef> = defs.into_iter().filter(|d| f.is_empty() || (d.name.to_lowercase().contains(&f) || tr(d.name).to_lowercase().contains(&f))).collect(); if defs.is_empty() { continue; } @@ -811,7 +818,7 @@ impl App { let active = self.editor.tool == Tool::Place(def.key); ui.horizontal(|ui| { let icon = symbol_icon(ui, def.key, egui::vec2(40.0, 30.0)); - let lbl = ui.selectable_label(active, format!("{} ({})", def.name, if def.letter.is_empty() { "–" } else { def.letter })); + let lbl = ui.selectable_label(active, format!("{} ({})", tr(def.name), if def.letter.is_empty() { "–" } else { def.letter })); if icon.clicked() || lbl.clicked() { self.editor.set_tool(Tool::Place(def.key)); self.editor.place_rot = 0; @@ -832,19 +839,19 @@ impl App { } fn properties(&mut self, ui: &mut egui::Ui, idx: &Index) { - ui.heading("Properties"); + ui.heading(tr("Properties")); let sel: Vec = self.editor.selection.iter().copied().collect(); let pi = self.page; if self.prj.pages[pi].locked { - ui.label(RichText::new("🔒 Released page – read only").color(Color32::from_rgb(220, 140, 0))); + ui.label(RichText::new(tr("🔒 Released page – read only")).color(Color32::from_rgb(220, 140, 0))); ui.disable(); } if sel.is_empty() { let pg = &mut self.prj.pages[pi]; - ui.label(RichText::new(format!("Page {} – {}", structure::page_full_name(pg), pg.kind.label())).strong()); - ui.label("Description"); + ui.label(RichText::new(tr_fmt!("Page {} – {}", structure::page_full_name(pg), pg.kind.label())).strong()); + ui.label(tr("Description")); ui.text_edit_singleline(&mut pg.description); - if ui.link("Structure (function / location)…").on_hover_text("Page properties").clicked() { + if ui.link(tr("Structure (function / location)…")).on_hover_text(tr("Page properties")).clicked() { self.page_props = Some(pi); } ui.add_space(6.0); @@ -852,12 +859,12 @@ impl App { return; } if sel.len() > 1 { - ui.label(format!("{} objects selected", sel.len())); + ui.label(tr_fmt!("{} objects selected", sel.len())); ui.horizontal(|ui| { - if ui.button("⟳ Rotate").clicked() { + if ui.button(tr("⟳ Rotate")).clicked() { ops::rotate(&mut self.prj.pages[pi], &self.editor.selection); } - if ui.button("🗑 Delete").clicked() { + if ui.button(tr("🗑 Delete")).clicked() { ops::delete(&mut self.prj.pages[pi], &self.editor.selection); self.editor.selection.clear(); } @@ -865,14 +872,14 @@ impl App { let wires: Vec = self.prj.pages[pi].wires.iter().filter(|w| self.editor.selection.contains(&w.id)).map(|w| w.id).collect(); if !wires.is_empty() { ui.separator(); - ui.label(format!("{} wires", wires.len())); + ui.label(tr_fmt!("{} wires", wires.len())); let first = self.prj.pages[pi].wires.iter().find(|w| w.id == wires[0]).cloned().unwrap_or_default(); let (mut color, mut cs) = (first.color.clone(), first.cross_section.clone()); egui::Grid::new("wprops").num_columns(2).show(ui, |ui| { - ui.label("Colour"); + ui.label(tr("Colour")); ui.text_edit_singleline(&mut color); ui.end_row(); - ui.label("Cross-section"); + ui.label(tr("Cross-section")); ui.text_edit_singleline(&mut cs); ui.end_row(); }); @@ -885,19 +892,19 @@ impl App { let cables: Vec = self.prj.cables.iter().map(|c| c.tag.clone()).collect(); let mut assign = None; ui.horizontal(|ui| { - ui.menu_button("Assign to cable", |ui| { + ui.menu_button(tr("Assign to cable"), |ui| { for c in &cables { if ui.button(c).clicked() { assign = Some(c.clone()); } } if cables.is_empty() { - ui.weak("No cables yet – Project › Cables…"); + ui.weak(tr("No cables yet – Project › Cables…")); } }) .response - .on_hover_text("The wires get the free cores of the cable in order (left to right)"); - if ui.button("Remove from cable").clicked() { + .on_hover_text(tr("The wires get the free cores of the cable in order (left to right)")); + if ui.button(tr("Remove from cable")).clicked() { for w in self.prj.pages[pi].wires.iter_mut().filter(|w| wires.contains(&w.id)) { w.cable.clear(); w.core.clear(); @@ -907,19 +914,19 @@ impl App { let harnesses: Vec = self.prj.harnesses.iter().map(|h| h.tag.clone()).collect(); let mut to_harness = None; ui.horizontal(|ui| { - ui.menu_button("Assign to harness", |ui| { + ui.menu_button(tr("Assign to harness"), |ui| { for h in &harnesses { if ui.button(h).clicked() { to_harness = Some(h.clone()); } } if harnesses.is_empty() { - ui.weak("No harnesses yet – Project › Harnesses…"); + ui.weak(tr("No harnesses yet – Project › Harnesses…")); } }) .response - .on_hover_text("Connections whose two ends are both on selected wires"); - if ui.button("Remove from harness").clicked() { + .on_hover_text(tr("Connections whose two ends are both on selected wires")); + if ui.button(tr("Remove from harness")).clicked() { to_harness = Some(String::new()); } }); @@ -937,14 +944,13 @@ impl App { crate::harness::assign(&mut self.prj, a, b, &tag); } let ctx = ui.ctx().clone(); - let what = if tag.is_empty() { "removed from their harness".to_string() } else { format!("assigned to {tag}") }; - self.notify(&ctx, format!("{} connections {what}", ends.len())); + self.notify(&ctx, if tag.is_empty() { tr_fmt!("{} connections removed from their harness", ends.len()) } else { tr_fmt!("{} connections assigned to {}", ends.len(), tag) }); } if let Some(c) = assign { let sel: std::collections::BTreeSet = wires.iter().copied().collect(); let n = ops::assign_cores(&mut self.prj, pi, &sel, &c); let ctx = ui.ctx().clone(); - self.notify(&ctx, format!("{n} of {} wires assigned to cores of {c}", wires.len())); + self.notify(&ctx, tr_fmt!("{} of {} wires assigned to cores of {}", n, wires.len(), c)); } } return; @@ -956,13 +962,13 @@ impl App { } else if let Some(wi) = page.wires.iter().position(|w| w.id == id) { let net = self.analysis.netlist.net_of_wire(id); if let Some(net) = net { - ui.label(RichText::new(format!("Potential: {}", net.name)).strong()); - ui.label("Connected to:"); + ui.label(RichText::new(tr_fmt!("Potential: {}", net.name)).strong()); + ui.label(tr("Connected to:")); let mut v: Vec = net.pins.iter().map(|p| pin_designation(&self.prj, *p)).collect(); v.sort_by(|a, b| natural_cmp(a, b)); v.dedup(); ui.label(RichText::new(v.join(", ")).monospace()); - ui.weak("All wires of this potential are highlighted."); + ui.weak(tr("All wires of this potential are highlighted.")); } ui.separator(); let open_net = self.analysis.open.wire_net.get(&id).map(|&n| self.analysis.open.nets[n].clone()); @@ -993,16 +999,16 @@ impl App { let mut harness_change = None; let w = &mut self.prj.pages[pi].wires[wi]; egui::Grid::new("wprops1").num_columns(2).show(ui, |ui| { - ui.label("Wire number"); + ui.label(tr("Wire number")); ui.horizontal(|ui| { - ui.add(egui::TextEdit::singleline(&mut number).hint_text("not numbered").desired_width(90.0)) - .on_hover_text("Applies to all wires of this connection; automatic numbering keeps manual numbers"); + ui.add(egui::TextEdit::singleline(&mut number).hint_text(tr("not numbered")).desired_width(90.0)) + .on_hover_text(tr("Applies to all wires of this connection; automatic numbering keeps manual numbers")); if w.number_fixed { - ui.weak("manual"); + ui.weak(tr("manual")); } }); ui.end_row(); - ui.label("Cable"); + ui.label(tr("Cable")); let shown = if w.cable.is_empty() { "(none)".to_string() } else { structure::relative(&here, &w.cable) }; egui::ComboBox::from_id_salt("wcable").selected_text(shown).show_ui(ui, |ui| { if ui.selectable_label(w.cable.is_empty(), "(none)").clicked() { @@ -1018,25 +1024,25 @@ impl App { }); ui.end_row(); if let Some((_, cores)) = cables.iter().find(|(t, _)| *t == w.cable) { - ui.label("Core"); + ui.label(tr("Core")); egui::ComboBox::from_id_salt("wcore").selected_text(w.core.clone()).show_ui(ui, |ui| { for c in cores { - let text = if used.contains(c) { format!("{c} (used)") } else { c.clone() }; + let text = if used.contains(c) { tr_fmt!("{} (used)", c) } else { c.clone() }; ui.selectable_value(&mut w.core, c.clone(), text); } }); ui.end_row(); } - ui.label("Colour"); - ui.add(egui::TextEdit::singleline(&mut w.color).hint_text("e.g. BU, BK, GNYE")); + ui.label(tr("Colour")); + ui.add(egui::TextEdit::singleline(&mut w.color).hint_text(tr("e.g. BU, BK, GNYE"))); ui.end_row(); - ui.label("Cross-section"); - ui.add(egui::TextEdit::singleline(&mut w.cross_section).hint_text("e.g. 1.5 mm²")); + ui.label(tr("Cross-section")); + ui.add(egui::TextEdit::singleline(&mut w.cross_section).hint_text(tr("e.g. 1.5 mm²"))); ui.end_row(); - ui.label("From"); + ui.label(tr("From")); ui.label(format!("{:.0} / {:.0}", w.a.x, w.a.y)); ui.end_row(); - ui.label("To"); + ui.label(tr("To")); ui.label(format!("{:.0} / {:.0}", w.b.x, w.b.y)); ui.end_row(); }); @@ -1047,7 +1053,7 @@ impl App { } if !conns.is_empty() { ui.separator(); - ui.label(RichText::new("Connections / harness").strong()).on_hover_text("Each point-to-point connection can belong to a harness"); + ui.label(RichText::new(tr("Connections / harness")).strong()).on_hover_text(tr("Each point-to-point connection can belong to a harness")); egui::Grid::new("wharness").num_columns(2).show(ui, |ui| { for (i, (a, b, h)) in conns.iter().enumerate() { ui.label(RichText::new(format!("{a} – {b}")).monospace()); @@ -1070,36 +1076,36 @@ impl App { crate::harness::assign(&mut self.prj, &a, &b, &tag); } } else if let Some(t) = self.prj.pages[pi].texts.iter_mut().find(|t| t.id == id) { - ui.label("Text"); + ui.label(tr("Text")); ui.add(egui::TextEdit::multiline(&mut t.text).desired_rows(3)); - ui.add(egui::Slider::new(&mut t.size, 1.5..=20.0).text("Height (mm)")); + ui.add(egui::Slider::new(&mut t.size, 1.5..=20.0).text(tr("Height (mm)"))); } else if let Some(s) = self.prj.pages[pi].shapes.iter_mut().find(|s| s.id == id) { ui.label(match s.kind { - ShapeKind::Line => "Graphic line", - ShapeKind::Rect => "Graphic rectangle", + ShapeKind::Line => tr("Graphic line"), + ShapeKind::Rect => tr("Graphic rectangle"), }); - ui.checkbox(&mut s.dashed, "Dashed"); + ui.checkbox(&mut s.dashed, tr("Dashed")); } } fn symbol_properties(&mut self, ui: &mut egui::Ui, idx: &Index, pi: usize, si: usize) { let s = self.prj.pages[pi].symbols[si].clone(); let Some(def) = symbols::get(&s.sym) else { - ui.label(format!("Unknown symbol {}", s.sym)); + ui.label(tr_fmt!("Unknown symbol {}", s.sym)); return; }; - ui.label(RichText::new(def.name).strong()); + ui.label(RichText::new(tr(def.name)).strong()); let mut edited = s.clone(); let here = Page { function: self.prj.pages[pi].function.clone(), location: self.prj.pages[pi].location.clone(), ..Default::default() }; egui::Grid::new("sprops").num_columns(2).spacing([8.0, 4.0]).show(ui, |ui| { if def.func.has_tag() { - ui.label(if def.func == Func::Terminal { "Terminal strip" } else if def.func == Func::Plc { "PLC card" } else { "Device tag" }); + ui.label(if def.func == Func::Terminal { tr("Terminal strip") } else if def.func == Func::Plc { tr("PLC card") } else { tr("Device tag") }); ui.horizontal(|ui| { // Shown relative to the page structure, stored complete. let mut shown = structure::relative(&here, &edited.tag); let before = shown.clone(); ui.add(egui::TextEdit::singleline(&mut shown).desired_width(90.0).font(egui::TextStyle::Monospace)) - .on_hover_text(format!("Complete tag: {}\nAspects missing here are taken from the page (=function +location).", edited.tag)); + .on_hover_text(tr_fmt!("Complete tag: {}\nAspects missing here are taken from the page (=function +location).", edited.tag)); if shown != before { edited.tag = if shown.trim().is_empty() { String::new() } else { structure::complete(&here, &shown) }; } @@ -1118,15 +1124,15 @@ impl App { } }) .response - .on_hover_text("Assign to existing device"); + .on_hover_text(tr("Assign to existing device")); }); ui.end_row(); } let label_name = match def.func { - Func::Terminal => Some("Terminal number"), - Func::Plc => Some("Address"), - Func::Potential => Some("Potential name"), - Func::Interruption => Some("Name"), + Func::Terminal => Some(tr("Terminal number")), + Func::Plc => Some(tr("Address")), + Func::Potential => Some(tr("Potential name")), + Func::Interruption => Some(tr("Name")), _ => None, }; if let Some(name) = label_name { @@ -1135,12 +1141,12 @@ impl App { ui.end_row(); } if def.func.has_tag() { - ui.label("Function text"); + ui.label(tr("Function text")); ui.add(egui::TextEdit::multiline(&mut edited.function_text).desired_rows(2).desired_width(160.0)); ui.end_row(); } if def.show_pin_labels { - ui.label("Connection points"); + ui.label(tr("Connection points")); ui.horizontal_wrapped(|ui| { for pin in edited.pins.iter_mut() { ui.add(egui::TextEdit::singleline(pin).desired_width(32.0)); @@ -1148,7 +1154,7 @@ impl App { }); ui.end_row(); } - ui.label("Orientation"); + ui.label(tr("Orientation")); ui.horizontal(|ui| { if ui.button("⟲").clicked() { edited.rot = (edited.rot + 3) % 4; @@ -1157,15 +1163,15 @@ impl App { if ui.button("⟳").clicked() { edited.rot = (edited.rot + 1) % 4; } - ui.checkbox(&mut edited.mirror, "Mirror"); + ui.checkbox(&mut edited.mirror, tr("Mirror")); }); ui.end_row(); - ui.label("Position"); - ui.label(format!("{:.0} / {:.0} mm (column {})", s.pos.x, s.pos.y, column_of(s.pos))); + ui.label(tr("Position")); + ui.label(tr_fmt!("{} / {} mm (column {})", format!("{:.0}", s.pos.x), format!("{:.0}", s.pos.y), column_of(s.pos))); ui.end_row(); }); if let Func::Aux(kind) = def.func { - if def.auto_number && ui.button("Renumber contact").on_hover_text("Next free contact numbers on this device").clicked() { + if def.auto_number && ui.button(tr("Renumber contact")).on_hover_text(tr("Next free contact numbers on this device")).clicked() { edited.pins = ops::next_contact_pins(&self.prj, &edited.tag, kind, Some(s.id)); } } @@ -1176,15 +1182,15 @@ impl App { // Device data if def.func.has_tag() && !edited.tag.is_empty() { ui.separator(); - ui.label(RichText::new(format!("Device {}", edited.tag)).strong()); + ui.label(RichText::new(tr_fmt!("Device {}", edited.tag)).strong()); let mut data = self.prj.devices.get(&edited.tag).cloned().unwrap_or_default(); let before = data.clone(); ui.horizontal(|ui| { - ui.label("Description"); + ui.label(tr("Description")); ui.text_edit_singleline(&mut data.description); }); // Part assignment (several parts per device, e.g. contactor + auxiliary block) - ui.label(RichText::new("Parts").strong()); + ui.label(RichText::new(tr("Parts")).strong()); let mut remove = None; let mut show_part = None; egui::Grid::new("devparts").num_columns(2).striped(true).show(ui, |ui| { @@ -1193,14 +1199,14 @@ impl App { let link = ui.link(RichText::new(&r.number).monospace()); let link = match known { Some(p) => link.on_hover_text(format!("{}\n{}", p.description, p.template_summary())), - None => link.on_hover_text("Not in the project parts – synchronize in parts management"), + None => link.on_hover_text(tr("Not in the project parts – synchronize in parts management")), }; if link.clicked() { show_part = Some(r.number.clone()); } ui.horizontal(|ui| { ui.add(egui::DragValue::new(&mut r.count).range(1..=999).prefix("× ")); - if ui.small_button("🗑").on_hover_text("Remove part").clicked() { + if ui.small_button("🗑").on_hover_text(tr("Remove part")).clicked() { remove = Some(i); } }); @@ -1214,13 +1220,13 @@ impl App { self.parts_ui.show_part(&n, true); } ui.horizontal(|ui| { - if ui.button("➕ Add part…").on_hover_text("Part selection from the parts database").clicked() { + if ui.button(tr("➕ Add part…")).on_hover_text(tr("Part selection from the parts database")).clicked() { self.parts_ui.select_for(&edited.tag); } if !data.parts.is_empty() && ui - .button("Apply designations") - .on_hover_text("Takes the connection point designations of all functions of this device from the function templates of its parts") + .button(tr("Apply designations")) + .on_hover_text(tr("Takes the connection point designations of all functions of this device from the function templates of its parts")) .clicked() { parts::apply_designations(&mut self.prj, Some(&self.parts_db), &edited.tag); @@ -1231,7 +1237,7 @@ impl App { } if let Some((ei, _)) = self.prj.layout.find_device(&edited.tag) { let enc = self.prj.layout.enclosures[ei].name.clone(); - if ui.button(format!("🗄 Show in panel layout ({enc})")).clicked() && self.panel_ui.show_device(&self.prj, &edited.tag) { + if ui.button(tr_fmt!("🗄 Show in panel layout ({})", enc)).clicked() && self.panel_ui.show_device(&self.prj, &edited.tag) { self.workspace = Workspace::Panel; } } @@ -1249,7 +1255,7 @@ impl App { } else { ui.visuals().text_color() }; - ui.label(RichText::new(txt).small().color(color)).on_hover_text("placed / provided by the parts"); + ui.label(RichText::new(txt).small().color(color)).on_hover_text(tr("placed / provided by the parts")); } }); } @@ -1258,7 +1264,7 @@ impl App { let mut new_tag: String = ui.data_mut(|d| d.get_temp(rename_id)).unwrap_or_else(|| edited.tag.clone()); ui.horizontal(|ui| { ui.add(egui::TextEdit::singleline(&mut new_tag).desired_width(90.0)); - if ui.button("Rename device").on_hover_text("Changes the tag of all functions of this device").clicked() { + if ui.button(tr("Rename device")).on_hover_text(tr("Changes the tag of all functions of this device")).clicked() { ops::rename_device(&mut self.prj, &edited.tag, &new_tag); } }); @@ -1267,13 +1273,13 @@ impl App { // Cross references if let Some(dev) = idx.devices.get(&edited.tag) { ui.separator(); - ui.label(RichText::new("Cross references").strong()); + ui.label(RichText::new(tr("Cross references")).strong()); let mut jump = None; - for (kind, locs) in [("Main", &dev.mains), ("Aux", &dev.auxs), ("", &dev.others)] { + for (kind, locs) in [(tr("Main"), &dev.mains), (tr("Aux"), &dev.auxs), ("", &dev.others)] { for loc in locs { let inst = self.prj.pages[loc.page].symbols.iter().find(|x| x.id == loc.sym_id); let Some(inst) = inst else { continue }; - let dname = symbols::get(&inst.sym).map(|d| d.name).unwrap_or("?"); + let dname = symbols::get(&inst.sym).map(|d| tr(d.name)).unwrap_or("?"); let extra = if inst.label.is_empty() { inst.pins.join("-") } else { inst.label.clone() }; let me = if loc.sym_id == s.id { " ◀" } else { "" }; if ui.link(format!("{} {kind} {dname} {extra}{me}", loc.reference(&self.prj))).clicked() { @@ -1290,7 +1296,7 @@ impl App { // Potentials at the connection points if !def.pins.is_empty() { ui.separator(); - ui.label(RichText::new("Connections").strong()); + ui.label(RichText::new(tr("Connections")).strong()); egui::Grid::new("pinnets").num_columns(2).striped(true).show(ui, |ui| { for i in 0..def.pins.len() { let pin = PinRef { page: pi, sym: si, pin: i }; @@ -1298,7 +1304,7 @@ impl App { let net = self.analysis.netlist.pin_net.get(&(s.id, i)).map(|&n| self.analysis.netlist.nets[n].name.clone()); let unconnected = self.analysis.netlist.unconnected.iter().any(|&(_, id, p)| id == s.id && p == i); if unconnected { - ui.label(RichText::new("open").color(Color32::from_rgb(220, 120, 0))); + ui.label(RichText::new(tr("open")).color(Color32::from_rgb(220, 120, 0))); } else { ui.label(net.unwrap_or_default()); } @@ -1315,7 +1321,7 @@ impl App { let mut jump = None; let mut export = None; let mut add_page = None; - egui::Window::new("Reports").open(&mut open).default_size([900.0, 520.0]).show(ctx, |ui| { + egui::Window::new(tr("Reports")).open(&mut open).default_size([900.0, 520.0]).show(ctx, |ui| { ui.horizontal_wrapped(|ui| { for k in ReportKind::ALL { ui.selectable_value(&mut self.report_kind, k, k.title()); @@ -1324,13 +1330,13 @@ impl App { ui.separator(); let kind = self.report_kind; ui.horizontal(|ui| { - if ui.button("⬇ Export CSV").clicked() { + if ui.button(tr("⬇ Export CSV")).clicked() { export = Some(kind); } - if ui.button("➕ Insert as report page").clicked() { + if ui.button(tr("➕ Insert as report page")).clicked() { add_page = Some(kind); } - if ui.button("Form…").on_hover_text("Columns, order and rows of the report pages").clicked() { + if ui.button(tr("Form…")).on_hover_text(tr("Columns, order and rows of the report pages")).clicked() { self.forms_ui.open_report(kind); } }); @@ -1355,7 +1361,7 @@ impl App { } }); if table.rows.is_empty() { - ui.weak("(no entries)"); + ui.weak(tr("(no entries)")); } }); }); @@ -1379,28 +1385,28 @@ impl App { if self.show_project { let mut open = true; let prj_tb_names = crate::forms::names(&self.prj); - egui::Window::new("Project properties").open(&mut open).resizable(false).show(ctx, |ui| { + egui::Window::new(tr("Project properties")).open(&mut open).resizable(false).show(ctx, |ui| { let info = &mut self.prj.info; egui::Grid::new("prj").num_columns(2).show(ui, |ui| { - ui.label("Project name"); + ui.label(tr("Project name")); ui.text_edit_singleline(&mut info.name); ui.end_row(); - ui.label("Description"); + ui.label(tr("Description")); ui.text_edit_multiline(&mut info.description); ui.end_row(); - ui.label("Company"); + ui.label(tr("Company")); ui.text_edit_singleline(&mut info.company); ui.end_row(); - ui.label("Created by"); + ui.label(tr("Created by")); ui.text_edit_singleline(&mut info.creator); ui.end_row(); - ui.label("Date"); + ui.label(tr("Date")); ui.text_edit_singleline(&mut info.date); ui.end_row(); - ui.label("Revision"); + ui.label(tr("Revision")); ui.text_edit_singleline(&mut info.revision); ui.end_row(); - ui.label("Title block"); + ui.label(tr("Title block")); let forms = &mut self.prj.forms; let current = if forms.default_title_block.is_empty() { crate::forms::STANDARD.to_string() } else { forms.default_title_block.clone() }; egui::ComboBox::from_id_salt("prjtb").selected_text(¤t).show_ui(ui, |ui| { @@ -1413,7 +1419,7 @@ impl App { ui.end_row(); }); ui.separator(); - ui.label(RichText::new("Project properties").strong()).on_hover_text("Shown in title blocks with {prop:Name}"); + ui.label(RichText::new(tr("Project properties")).strong()).on_hover_text(tr("Shown in title blocks with {prop:Name}")); let props = &mut self.prj.info.properties; let mut remove = None; let mut rename = None; @@ -1440,7 +1446,7 @@ impl App { if let Some(k) = remove { props.remove(&k); } - if ui.button("➕ Property").clicked() { + if ui.button(tr("➕ Property")).clicked() { let mut n = props.len() + 1; while props.contains_key(&format!("Property{n}")) { n += 1; @@ -1475,16 +1481,16 @@ impl App { let mut apply_structure = None; if pi < self.prj.pages.len() { let tb_names = crate::forms::names(&self.prj); - egui::Window::new("Page properties").open(&mut open).resizable(false).show(ctx, |ui| { + egui::Window::new(tr("Page properties")).open(&mut open).resizable(false).show(ctx, |ui| { let pg = &mut self.prj.pages[pi]; egui::Grid::new("pgprops").num_columns(2).show(ui, |ui| { - ui.label("Page name / number"); + ui.label(tr("Page name / number")); ui.text_edit_singleline(&mut pg.name); ui.end_row(); - ui.label("Description"); + ui.label(tr("Description")); ui.text_edit_singleline(&mut pg.description); ui.end_row(); - ui.label("Page type"); + ui.label(tr("Page type")); egui::ComboBox::from_id_salt("pgkind").selected_text(pg.kind.label()).show_ui(ui, |ui| { ui.selectable_value(&mut pg.kind, PageKind::Schematic, PageKind::Schematic.label()); ui.selectable_value(&mut pg.kind, PageKind::Cover, PageKind::Cover.label()); @@ -1492,44 +1498,44 @@ impl App { ui.selectable_value(&mut pg.kind, PageKind::Report(k), PageKind::Report(k).label()); } for e in &self.prj.layout.enclosures { - ui.selectable_value(&mut pg.kind, PageKind::Mounting(e.id), format!("Mounting layout {}", e.name)); + ui.selectable_value(&mut pg.kind, PageKind::Mounting(e.id), tr_fmt!("Mounting layout {}", e.name)); } }); ui.end_row(); }); ui.horizontal(|ui| { - ui.label("Title block"); + ui.label(tr("Title block")); let shown = if pg.title_block.is_empty() { "(project default)".to_string() } else { pg.title_block.clone() }; egui::ComboBox::from_id_salt("pgtb").selected_text(shown).show_ui(ui, |ui| { - ui.selectable_value(&mut pg.title_block, String::new(), "(project default)"); + ui.selectable_value(&mut pg.title_block, String::new(), tr("(project default)")); for n in &tb_names { ui.selectable_value(&mut pg.title_block, n.clone(), n); } }); }); if pg.kind != PageKind::Schematic && !pg.is_empty() { - ui.colored_label(Color32::from_rgb(220, 140, 0), "This page contains schematic content which is not evaluated on non-schematic pages."); + ui.colored_label(Color32::from_rgb(220, 140, 0), tr("This page contains schematic content which is not evaluated on non-schematic pages.")); } ui.separator(); - ui.label(RichText::new("Structure (IEC 81346)").strong()); + ui.label(RichText::new(tr("Structure (IEC 81346)")).strong()); let key = ui.scope_id().with(("page_structure", pi)); let (mut function, mut location, mut move_devices): (String, String, bool) = ui.data_mut(|d| d.get_temp(key)).unwrap_or_else(|| (pg.function.clone(), pg.location.clone(), true)); egui::Grid::new("pgstruct").num_columns(2).show(ui, |ui| { - ui.label("Function ="); - ui.add(egui::TextEdit::singleline(&mut function).hint_text("e.g. A1, PUMP.2")); + ui.label(tr("Function =")); + ui.add(egui::TextEdit::singleline(&mut function).hint_text(tr("e.g. A1, PUMP.2"))); ui.end_row(); - ui.label("Location +"); - ui.add(egui::TextEdit::singleline(&mut location).hint_text("e.g. CAB1, FIELD")); + ui.label(tr("Location +")); + ui.add(egui::TextEdit::singleline(&mut location).hint_text(tr("e.g. CAB1, FIELD"))); ui.end_row(); }); - ui.checkbox(&mut move_devices, "Move the devices of this page into the new structure") - .on_hover_text("Renames the devices (all their functions, also on other pages)"); + ui.checkbox(&mut move_devices, tr("Move the devices of this page into the new structure")) + .on_hover_text(tr("Renames the devices (all their functions, also on other pages)")); let changed = structure::clean_aspect(&function) != pg.function || structure::clean_aspect(&location) != pg.location; - if ui.add_enabled(changed, egui::Button::new("Apply structure")).clicked() { + if ui.add_enabled(changed, egui::Button::new(tr("Apply structure"))).clicked() { apply_structure = Some((function.clone(), location.clone(), move_devices)); } - ui.weak("Devices placed on the page get its structure; their tags are shown without it."); + ui.weak(tr("Devices placed on the page get its structure; their tags are shown without it.")); ui.data_mut(|d| d.insert_temp(key, (function, location, move_devices))); }); } else { @@ -1545,40 +1551,40 @@ impl App { if self.show_help { let mut open = true; - egui::Window::new("OpenECraft – usage").open(&mut open).default_width(520.0).show(ctx, |ui| { - ui.label(RichText::new("Workflow").strong()); - ui.label("1. Pick a symbol in the library (right) and click into the page to place it. Device tags (-K1, -S2 …) are assigned automatically."); - ui.label("2. Select a coil, then place contacts: they are assigned to that coil and numbered (13/14, 21/22 …). Cross references and the contact image update live."); - ui.label("3. Draw wires with the wire tool (W). Wires end automatically on connection points. T-junctions get a connection dot."); - ui.label("4. Potentials (L1, +24V …) and interruption points name the nets across pages. Select a wire to highlight its potential."); - ui.label("5. Assign parts in the property panel; generate reports (device list, BOM, terminal diagram, connection list, PLC list) and insert them as report pages."); - ui.label("6. Structure: give pages a function (=A1) and location (+CAB1) in the page properties. Devices placed there get it (=A1+CAB1-K1); on the page only the differing part is shown."); - ui.label("7. Cables: define them in Project › Cables…, select wires and use Assign to cable. Wire numbers: Project › Wire numbering…, or type a number in the wire properties."); - ui.label("8. Macros: select items › Edit › Save selection as macro; insert them from Insert › Macro…. Placeholders {NAME} are filled from value sets."); - ui.label("9. Project › Terminal strips / PLC overview / Revisions: strip order, jumpers and spares; PLC addresses and symbol tables; revisions with change marks and released (locked) pages."); - ui.label("10. Project › Symbol editor: draw your own symbols (or copy built-in ones) with connection points and function; they are saved in the project and can be exchanged as library files."); - ui.label("11. Project › Title blocks and report forms: own title blocks with placeholders ({project}, {page}, {prop:Name} …) and the columns of report pages."); - ui.label("12. Panel layout: busbars and cutouts; the enclosure properties export the drilling pattern (NC data as DXF / CSV). The production wire list contains stripping lengths and ferrules."); - ui.label("13. Harnesses: Project › Harnesses…; select the wires between two devices › Assign to harness, or per connection in the wire properties. Harness data report with lengths, connectors and bundle diameter, KBL export."); - ui.label("14. Door: switch the panel front view to Door and place command / signal devices there; their door cutouts are generated. Collisions are checked with the parts' 3D models."); + egui::Window::new(tr("OpenECraft – usage")).open(&mut open).default_width(520.0).show(ctx, |ui| { + ui.label(RichText::new(tr("Workflow")).strong()); + ui.label(tr("1. Pick a symbol in the library (right) and click into the page to place it. Device tags (-K1, -S2 …) are assigned automatically.")); + ui.label(tr("2. Select a coil, then place contacts: they are assigned to that coil and numbered (13/14, 21/22 …). Cross references and the contact image update live.")); + ui.label(tr("3. Draw wires with the wire tool (W). Wires end automatically on connection points. T-junctions get a connection dot.")); + ui.label(tr("4. Potentials (L1, +24V …) and interruption points name the nets across pages. Select a wire to highlight its potential.")); + ui.label(tr("5. Assign parts in the property panel; generate reports (device list, BOM, terminal diagram, connection list, PLC list) and insert them as report pages.")); + ui.label(tr("6. Structure: give pages a function (=A1) and location (+CAB1) in the page properties. Devices placed there get it (=A1+CAB1-K1); on the page only the differing part is shown.")); + ui.label(tr("7. Cables: define them in Project › Cables…, select wires and use Assign to cable. Wire numbers: Project › Wire numbering…, or type a number in the wire properties.")); + ui.label(tr("8. Macros: select items › Edit › Save selection as macro; insert them from Insert › Macro…. Placeholders {NAME} are filled from value sets.")); + ui.label(tr("9. Project › Terminal strips / PLC overview / Revisions: strip order, jumpers and spares; PLC addresses and symbol tables; revisions with change marks and released (locked) pages.")); + ui.label(tr("10. Project › Symbol editor: draw your own symbols (or copy built-in ones) with connection points and function; they are saved in the project and can be exchanged as library files.")); + ui.label(tr("11. Project › Title blocks and report forms: own title blocks with placeholders ({project}, {page}, {prop:Name} …) and the columns of report pages.")); + ui.label(tr("12. Panel layout: busbars and cutouts; the enclosure properties export the drilling pattern (NC data as DXF / CSV). The production wire list contains stripping lengths and ferrules.")); + ui.label(tr("13. Harnesses: Project › Harnesses…; select the wires between two devices › Assign to harness, or per connection in the wire properties. Harness data report with lengths, connectors and bundle diameter, KBL export.")); + ui.label(tr("14. Door: switch the panel front view to Door and place command / signal devices there; their door cutouts are generated. Collisions are checked with the parts' 3D models.")); ui.separator(); - ui.label(RichText::new("Shortcuts").strong()); + ui.label(RichText::new(tr("Shortcuts")).strong()); egui::Grid::new("keys").striped(true).show(ui, |ui| { for (k, v) in [ - ("Esc", "Cancel / select tool / clear selection"), - ("W / T", "Wire tool / text tool"), - ("R / M", "Rotate / mirror (selection or symbol being placed)"), - ("Space", "Toggle corner direction while drawing wires"), - ("Del", "Delete selection"), - ("Arrows", "Move selection by one grid step"), - ("Ctrl+C / X / V", "Copy / cut / paste (devices get new tags)"), - ("Ctrl+A", "Select all"), - ("Ctrl+Z / Ctrl+Y", "Undo / redo"), - ("Ctrl+S / Ctrl+O", "Save / open"), - ("F / Home", "Fit page"), - ("Page Up / Down", "Previous / next page"), - ("Wheel / right or middle drag", "Zoom / pan"), - ("Shift + click / drag", "Add to selection"), + (tr("Esc"), tr("Cancel / select tool / clear selection")), + ("W / T", tr("Wire tool / text tool")), + ("R / M", tr("Rotate / mirror (selection or symbol being placed)")), + (tr("Space"), tr("Toggle corner direction while drawing wires")), + (tr("Del"), tr("Delete selection")), + (tr("Arrows"), tr("Move selection by one grid step")), + (tr("Ctrl+C / X / V"), tr("Copy / cut / paste (devices get new tags)")), + (tr("Ctrl+A"), tr("Select all")), + (tr("Ctrl+Z / Ctrl+Y"), tr("Undo / redo")), + (tr("Ctrl+S / Ctrl+O"), tr("Save / open")), + (tr("F / Home"), tr("Fit page")), + (tr("Page Up / Down"), tr("Previous / next page")), + (tr("Wheel / right or middle drag"), tr("Zoom / pan")), + (tr("Shift + click / drag"), tr("Add to selection")), ] { ui.label(RichText::new(k).monospace()); ui.label(v); @@ -1604,23 +1610,23 @@ impl App { used.entry(w.cable.clone()).or_default().insert(w.core.clone()); } let structure = structure::page_structure(&self.prj.pages[self.page]); - egui::Window::new("Cables").open(&mut open).default_size([1000.0, 360.0]).show(ctx, |ui| { + egui::Window::new(tr("Cables")).open(&mut open).default_size([1000.0, 360.0]).show(ctx, |ui| { ui.horizontal_wrapped(|ui| { - if ui.button("➕ New cable").on_hover_text("In the structure of the current page").clicked() { + if ui.button(tr("➕ New cable")).on_hover_text(tr("In the structure of the current page")).clicked() { let tag = self.prj.next_tag(&structure, "W"); let id = self.prj.new_id(); self.prj.cables.push(Cable { id, tag, cores: "BN BK GY GNYE".into(), cross_section: "1.5 mm²".into(), ..Default::default() }); } - if ui.button("📊 Cable overview").clicked() { + if ui.button(tr("📊 Cable overview")).clicked() { overview = true; } - ui.weak("Assign wires: select them in the schematic › Assign to cable."); + ui.weak(tr("Assign wires: select them in the schematic › Assign to cable.")); }); ui.separator(); let cable_parts: Vec<&parts::Part> = self.parts_db.parts.iter().filter(|p| p.group == "Cables").collect(); egui::ScrollArea::both().auto_shrink([false, false]).show(ui, |ui| { egui::Grid::new("cables").striped(true).num_columns(9).spacing([8.0, 4.0]).show(ui, |ui| { - for h in ["Cable", "Type", "Cores", "Cross-section", "Length", "Part", "Description", "Used", ""] { + for h in [tr("Cable"), tr("Type"), tr("Cores"), tr("Cross-section"), tr("Length"), tr("Part"), tr("Description"), tr("Used"), ""] { ui.label(RichText::new(h).strong()); } ui.end_row(); @@ -1631,7 +1637,7 @@ impl App { renamed.push((old.clone(), c.tag.clone())); } ui.add_sized([120.0, 20.0], egui::TextEdit::singleline(&mut c.cable_type)); - ui.add_sized([140.0, 20.0], egui::TextEdit::singleline(&mut c.cores)).on_hover_text("Core designations separated by blanks"); + ui.add_sized([140.0, 20.0], egui::TextEdit::singleline(&mut c.cores)).on_hover_text(tr("Core designations separated by blanks")); ui.add_sized([70.0, 20.0], egui::TextEdit::singleline(&mut c.cross_section)); ui.add(egui::DragValue::new(&mut c.length).speed(0.5).range(0.0..=100000.0).suffix(" m")); ui.horizontal(|ui| { @@ -1651,21 +1657,21 @@ impl App { } } if cable_parts.is_empty() { - ui.weak("No parts of the product group Cables in the parts database."); + ui.weak(tr("No parts of the product group Cables in the parts database.")); } }); }); ui.add_sized([160.0, 20.0], egui::TextEdit::singleline(&mut c.description)); let n = used.get(&old).map(|s| s.len()).unwrap_or(0); ui.label(format!("{n}/{}", c.core_list().len())); - if ui.small_button("🗑").on_hover_text("Delete cable (its wires are removed from it)").clicked() { + if ui.small_button("🗑").on_hover_text(tr("Delete cable (its wires are removed from it)")).clicked() { remove = Some(i); } ui.end_row(); } }); if self.prj.cables.is_empty() { - ui.weak("No cables defined."); + ui.weak(tr("No cables defined.")); } }); }); @@ -1700,35 +1706,35 @@ impl App { let nets: Vec<&crate::netlist::Net> = self.analysis.open.nets.iter().filter(|n| !n.wires.is_empty() && !n.pins.is_empty()).collect(); let numbered = nets.iter().filter(|n| !wirenum::number_of(&self.prj, n).is_empty()).count(); let total = nets.len(); - egui::Window::new("Wire numbering").open(&mut open).resizable(false).show(ctx, |ui| { + egui::Window::new(tr("Wire numbering")).open(&mut open).resizable(false).show(ctx, |ui| { let s = &mut self.prj.wire_numbering; - ui.label("Every connection gets one number for all its wires; the two sides of a terminal are separate connections."); + ui.label(tr("Every connection gets one number for all its wires; the two sides of a terminal are separate connections.")); ui.add_space(4.0); for scheme in NumberScheme::ALL { ui.radio_value(&mut s.scheme, scheme, scheme.title()); } egui::Grid::new("numbering").num_columns(2).show(ui, |ui| { - ui.label("Prefix"); - ui.add(egui::TextEdit::singleline(&mut s.prefix).desired_width(60.0).hint_text("e.g. W")); + ui.label(tr("Prefix")); + ui.add(egui::TextEdit::singleline(&mut s.prefix).desired_width(60.0).hint_text(tr("e.g. W"))); ui.end_row(); - ui.label("Start at"); + ui.label(tr("Start at")); ui.add(egui::DragValue::new(&mut s.start).range(0..=1_000_000)); ui.end_row(); }); - ui.checkbox(&mut self.numbering_overwrite, "Include manually set numbers"); - ui.label(format!("{numbered} of {total} connections numbered")); + ui.checkbox(&mut self.numbering_overwrite, tr("Include manually set numbers")); + ui.label(tr_fmt!("{} of {} connections numbered", numbered, total)); ui.horizontal(|ui| { - number = ui.button("Number wires").clicked(); - remove = ui.button("Remove numbers").clicked(); + number = ui.button(tr("Number wires")).clicked(); + remove = ui.button(tr("Remove numbers")).clicked(); }); }); if number { let n = wirenum::renumber(&mut self.prj, &self.analysis.open, &self.analysis.netlist, self.numbering_overwrite); - self.notify(ctx, format!("{n} connections numbered")); + self.notify(ctx, tr_fmt!("{} connections numbered", n)); } if remove { let n = wirenum::clear(&mut self.prj, self.numbering_overwrite); - self.notify(ctx, format!("Numbers removed from {n} wires")); + self.notify(ctx, tr_fmt!("Numbers removed from {} wires", n)); } self.show_numbering = open; } @@ -1798,9 +1804,10 @@ impl eframe::App for App { if !self.symed.busy() { crate::symlib::register(&self.prj.symbols); } - if self.analysis_rev != self.history.rev { + if self.analysis_rev != self.history.rev || self.analysis_lang != openecraft_i18n::lang() { self.analysis = Analysis::build(&self.prj); self.analysis_rev = self.history.rev; + self.analysis_lang = openecraft_i18n::lang(); } let idx = Index::build(&self.prj); @@ -1861,7 +1868,7 @@ impl eframe::App for App { let what = if face == crate::panel::Face::Door { "door" } else { "plate" }; if dxf { let content = crate::production::nc_dxf(&self.prj, ei, face); - self.export(&ctx, format!("{what}{base}.dxf"), ("DXF drawing", "dxf"), content); + self.export(&ctx, format!("{what}{base}.dxf"), (tr("DXF drawing"), "dxf"), content); } else { let content = crate::production::nc_csv(&self.prj, ei, face); self.export(&ctx, format!("{what}{base}_drilling.csv"), ("CSV", "csv"), content); @@ -1897,5 +1904,6 @@ impl eframe::App for App { eframe::set_value(storage, "parts_db", &self.parts_db); eframe::set_value(storage, "parts_server_url", &self.parts_ui.server.url); eframe::set_value(storage, "macros", &self.macro_lib); + eframe::set_value(storage, openecraft_ui::language::STORAGE_KEY, &openecraft_i18n::lang().code()); } } diff --git a/src/app/engineering.rs b/src/app/engineering.rs index a42d72da..d04096b2 100644 --- a/src/app/engineering.rs +++ b/src/app/engineering.rs @@ -1,5 +1,6 @@ //! Engineering windows: macros, terminal strips, PLC overview and revisions. +use openecraft_i18n::{tr, tr_fmt}; use super::App; use crate::editor::{EguiDraw, Palette, Tool}; use crate::io::Purpose; @@ -91,30 +92,30 @@ impl App { fn save_macro_dialog(&mut self, ctx: &egui::Context) { let Some(m) = &mut self.eng.saving else { return }; let (mut save, mut cancel) = (false, false); - egui::Window::new("Save as macro").collapsible(false).resizable(false).show(ctx, |ui| { - ui.label(format!("{} macro: {}", if m.kind == MacroKind::Page { "Page" } else { "Window" }, m.summary())); + egui::Window::new(tr("Save as macro")).collapsible(false).resizable(false).show(ctx, |ui| { + ui.label(if m.kind == MacroKind::Page { tr_fmt!("Page macro: {}", m.summary()) } else { tr_fmt!("Window macro: {}", m.summary()) }); egui::Grid::new("savemacro").num_columns(2).show(ui, |ui| { - ui.label("Name"); + ui.label(tr("Name")); ui.text_edit_singleline(&mut m.name); ui.end_row(); - ui.label("Category"); - ui.add(egui::TextEdit::singleline(&mut m.category).hint_text("e.g. Motors")); + ui.label(tr("Category")); + ui.add(egui::TextEdit::singleline(&mut m.category).hint_text(tr("e.g. Motors"))); ui.end_row(); - ui.label("Description"); + ui.label(tr("Description")); ui.text_edit_multiline(&mut m.description); ui.end_row(); }); - ui.weak("Placeholders like {MOTOR} in tags, texts and function texts are filled in when inserting."); + ui.weak(tr("Placeholders like {MOTOR} in tags, texts and function texts are filled in when inserting.")); ui.horizontal(|ui| { - save = ui.add_enabled(!m.name.trim().is_empty(), egui::Button::new("💾 Save")).clicked(); - cancel = ui.button("Cancel").clicked(); + save = ui.add_enabled(!m.name.trim().is_empty(), egui::Button::new(tr("💾 Save"))).clicked(); + cancel = ui.button(tr("Cancel")).clicked(); }); }); if save { let m = self.eng.saving.take().unwrap(); let replaced = self.macro_lib.macros.iter().any(|x| x.name == m.name); self.eng.macro_sel = Some(m.name.clone()); - self.notify(ctx, format!("Macro {} {}", m.name, if replaced { "replaced" } else { "saved" })); + self.notify(ctx, if replaced { tr_fmt!("Macro {} replaced", m.name) } else { tr_fmt!("Macro {} saved", m.name) }); self.macro_lib.upsert(m); self.eng.show_macros = true; } @@ -131,20 +132,20 @@ impl App { let mut action = None; let can_save_selection = !self.editor.selection.is_empty() && self.prj.pages[self.page].kind == PageKind::Schematic; let mut save = None; - egui::Window::new("Macros").open(&mut open).default_size([820.0, 480.0]).show(ctx, |ui| { + egui::Window::new(tr("Macros")).open(&mut open).default_size([820.0, 480.0]).show(ctx, |ui| { ui.horizontal_wrapped(|ui| { - ui.add(egui::TextEdit::singleline(&mut self.eng.macro_filter).hint_text("Filter…").desired_width(160.0)); - if ui.add_enabled(can_save_selection, egui::Button::new("💾 Save selection as macro…")).clicked() { + ui.add(egui::TextEdit::singleline(&mut self.eng.macro_filter).hint_text(tr("Filter…")).desired_width(160.0)); + if ui.add_enabled(can_save_selection, egui::Button::new(tr("💾 Save selection as macro…"))).clicked() { save = Some(false); } - if ui.button("Save page as macro…").clicked() { + if ui.button(tr("Save page as macro…")).clicked() { save = Some(true); } - ui.menu_button("Library", |ui| { - if ui.button("Export macros (JSON)…").clicked() { + ui.menu_button(tr("Library"), |ui| { + if ui.button(tr("Export macros (JSON)…")).clicked() { action = Some(MacroAction::Export); } - if ui.button("Import macros…").clicked() { + if ui.button(tr("Import macros…")).clicked() { action = Some(MacroAction::Import); } }); @@ -174,14 +175,14 @@ impl App { }); } if self.macro_lib.macros.is_empty() { - ui.weak("No macros yet. Select items in a schematic and save them as a macro."); + ui.weak(tr("No macros yet. Select items in a schematic and save them as a macro.")); } }); }); ui.separator(); ui.vertical(|ui| { let Some(i) = self.eng.macro_sel.as_ref().and_then(|n| self.macro_lib.macros.iter().position(|m| &m.name == n)) else { - ui.weak("Select a macro."); + ui.weak(tr("Select a macro.")); return; }; let values = &mut self.eng.macro_values; @@ -192,14 +193,14 @@ impl App { ui.weak(if m.kind == MacroKind::Page { "page macro" } else { "window macro" }); }); egui::Grid::new("macroprops").num_columns(2).show(ui, |ui| { - ui.label("Category"); + ui.label(tr("Category")); ui.text_edit_singleline(&mut m.category); ui.end_row(); - ui.label("Description"); + ui.label(tr("Description")); ui.text_edit_multiline(&mut m.description); ui.end_row(); if m.kind == MacroKind::Page { - ui.label("Page description"); + ui.label(tr("Page description")); ui.text_edit_singleline(&mut m.page_description); ui.end_row(); } @@ -209,10 +210,10 @@ impl App { let placeholders = m.placeholders(); if !placeholders.is_empty() { ui.separator(); - ui.label(RichText::new("Value sets").strong()); + ui.label(RichText::new(tr("Value sets")).strong()); let mut remove = None; egui::Grid::new("valuesets").striped(true).num_columns(placeholders.len() + 2).show(ui, |ui| { - ui.label(RichText::new("Name").strong()); + ui.label(RichText::new(tr("Name")).strong()); for ph in &placeholders { ui.label(RichText::new(format!("{{{ph}}}")).strong()); } @@ -232,14 +233,14 @@ impl App { if let Some(vi) = remove { m.value_sets.remove(vi); } - if ui.button("➕ Value set").clicked() { + if ui.button(tr("➕ Value set")).clicked() { let name = format!("Set {}", m.value_sets.len() + 1); m.value_sets.push(macros::ValueSet { name, values: values.clone() }); } ui.separator(); ui.horizontal(|ui| { - ui.label(RichText::new("Insert with").strong()); - egui::ComboBox::from_id_salt("useset").selected_text("value set…").show_ui(ui, |ui| { + ui.label(RichText::new(tr("Insert with")).strong()); + egui::ComboBox::from_id_salt("useset").selected_text(tr("value set…")).show_ui(ui, |ui| { for vs in &m.value_sets { if ui.button(&vs.name).clicked() { *values = vs.values.clone(); @@ -257,11 +258,11 @@ impl App { } ui.add_space(6.0); ui.horizontal(|ui| { - let label = if m.kind == MacroKind::Page { "➕ Insert as new page" } else { "➕ Insert (click into the page)" }; + let label = if m.kind == MacroKind::Page { tr("➕ Insert as new page") } else { tr("➕ Insert (click into the page)") }; if ui.button(label).clicked() { action = Some(MacroAction::Insert(i)); } - if ui.button("🗑 Delete macro").clicked() { + if ui.button(tr("🗑 Delete macro")).clicked() { action = Some(MacroAction::Delete(i)); } }); @@ -279,7 +280,7 @@ impl App { if m.kind == MacroKind::Page { let at = macros::insert_page(&mut self.prj, self.page, &m, &self.eng.macro_values); self.goto(at, 0); - self.notify(ctx, format!("Page macro {} inserted as page {}", m.name, self.prj.pages[at].name)); + self.notify(ctx, tr_fmt!("Page macro {} inserted as page {}", m.name, self.prj.pages[at].name)); } else { self.editor.insert = Some(m.resolve(&self.eng.macro_values)); self.editor.set_tool(Tool::Insert); @@ -316,30 +317,30 @@ impl App { let mut moved = None; let mut relabel: Vec<(usize, usize, String, String)> = Vec::new(); let mut jump = None; - egui::Window::new("Terminal strips").open(&mut open).default_size([900.0, 420.0]).show(ctx, |ui| { + egui::Window::new(tr("Terminal strips")).open(&mut open).default_size([900.0, 420.0]).show(ctx, |ui| { if tags.is_empty() { - ui.weak("No terminal strips: place terminals in a schematic first."); + ui.weak(tr("No terminal strips: place terminals in a schematic first.")); return; } ui.horizontal_wrapped(|ui| { - ui.label("Strip"); + ui.label(tr("Strip")); egui::ComboBox::from_id_salt("strip").selected_text(&strip).show_ui(ui, |ui| { for t in &tags { ui.selectable_value(&mut self.eng.strip, t.clone(), t); } }); ui.separator(); - ui.label("Spare terminals"); + ui.label(tr("Spare terminals")); ui.add(egui::DragValue::new(&mut data.spares).range(0..=500)); ui.separator(); - renumber = ui.button("Renumber 1 … n").on_hover_text("In strip order; PE and other non-numeric terminals keep their designation").clicked(); - sort = ui.button("Sort by designation").clicked(); + renumber = ui.button(tr("Renumber 1 … n")).on_hover_text(tr("In strip order; PE and other non-numeric terminals keep their designation")).clicked(); + sort = ui.button(tr("Sort by designation")).clicked(); }); - ui.weak("Terminals with the same jumper number are bridged (same potential). Spare terminals are counted in the bill of materials."); + ui.weak(tr("Terminals with the same jumper number are bridged (same potential). Spare terminals are counted in the bill of materials.")); ui.separator(); egui::ScrollArea::both().auto_shrink([false, false]).show(ui, |ui| { egui::Grid::new("strip").striped(true).num_columns(8).spacing([10.0, 4.0]).show(ui, |ui| { - for h in ["", "Terminal", "Jumper", "External (top)", "Internal (bottom)", "Potential", "Function text", "Location"] { + for h in ["", tr("Terminal"), tr("Jumper"), tr("External (top)"), tr("Internal (bottom)"), tr("Potential"), tr("Function text"), tr("Location")] { ui.label(RichText::new(h).strong()); } ui.end_row(); @@ -349,7 +350,7 @@ impl App { ui.label(""); ui.weak(&r.label); ui.label(""); - ui.weak("spare"); + ui.weak(tr("spare")); ui.end_row(); continue; }; @@ -367,7 +368,7 @@ impl App { relabel.push((t.page, t.sym, r.label.clone(), label)); } let mut j = data.jumpers.get(&r.label).copied().unwrap_or(0); - if ui.add(egui::DragValue::new(&mut j).range(0..=99)).on_hover_text("0 = no jumper").changed() { + if ui.add(egui::DragValue::new(&mut j).range(0..=99)).on_hover_text(tr("0 = no jumper")).changed() { if j == 0 { data.jumpers.remove(&r.label); } else { @@ -411,7 +412,7 @@ impl App { } if renumber { let n = strips::renumber(&mut self.prj, &strip); - self.notify(ctx, format!("{strip}: {n} terminals renumbered")); + self.notify(ctx, tr_fmt!("{}: {} terminals renumbered", strip, n)); } if let Some((pg, id)) = jump { self.goto(pg, id); @@ -435,36 +436,36 @@ impl App { let (mut readdress, mut export, mut import) = (false, false, false); let mut edits: Vec<(usize, usize, Option, Option)> = Vec::new(); let mut jump = None; - egui::Window::new("PLC overview").open(&mut open).default_size([900.0, 420.0]).show(ctx, |ui| { + egui::Window::new(tr("PLC overview")).open(&mut open).default_size([900.0, 420.0]).show(ctx, |ui| { ui.horizontal_wrapped(|ui| { - ui.label("Card"); + ui.label(tr("Card")); egui::ComboBox::from_id_salt("plccard").selected_text(if card.is_empty() { "all cards" } else { &card }).show_ui(ui, |ui| { - ui.selectable_value(&mut self.eng.card, String::new(), "all cards"); + ui.selectable_value(&mut self.eng.card, String::new(), tr("all cards")); for c in &cards { ui.selectable_value(&mut self.eng.card, c.clone(), c); } }); ui.separator(); - export = ui.button("⬇ Export symbol table (CSV)…").on_hover_text("Name; Data Type; Logical Address; Comment – for PLC programming tools").clicked(); - import = ui.button("⬆ Import symbol table…").on_hover_text("Takes the comments as function texts (matched by address)").clicked(); + export = ui.button(tr("⬇ Export symbol table (CSV)…")).on_hover_text(tr("Name; Data Type; Logical Address; Comment – for PLC programming tools")).clicked(); + import = ui.button(tr("⬆ Import symbol table…")).on_hover_text(tr("Takes the comments as function texts (matched by address)")).clicked(); }); if !card.is_empty() { ui.horizontal_wrapped(|ui| { - ui.label("Start byte"); + ui.label(tr("Start byte")); ui.add(egui::DragValue::new(&mut data.start_byte).range(0..=65535)); - ui.label("Rack"); + ui.label(tr("Rack")); ui.add(egui::TextEdit::singleline(&mut data.rack).desired_width(40.0)); - ui.label("Slot"); + ui.label(tr("Slot")); ui.add(egui::TextEdit::singleline(&mut data.slot).desired_width(40.0)); - ui.label("Description"); + ui.label(tr("Description")); ui.add(egui::TextEdit::singleline(&mut data.description).desired_width(180.0)); - readdress = ui.button("Readdress card").on_hover_text("Consecutive addresses from the start byte, in schematic order").clicked(); + readdress = ui.button(tr("Readdress card")).on_hover_text(tr("Consecutive addresses from the start byte, in schematic order")).clicked(); }); } ui.separator(); egui::ScrollArea::both().auto_shrink([false, false]).show(ui, |ui| { egui::Grid::new("plcpoints").striped(true).num_columns(6).spacing([10.0, 4.0]).show(ui, |ui| { - for h in ["Card", "Address", "Type", "Function text", "Connected to", "Location"] { + for h in [tr("Card"), tr("Address"), tr("Type"), tr("Function text"), tr("Connected to"), tr("Location")] { ui.label(RichText::new(h).strong()); } ui.end_row(); @@ -486,7 +487,7 @@ impl App { } }); if points.is_empty() { - ui.weak("No PLC inputs / outputs placed."); + ui.weak(tr("No PLC inputs / outputs placed.")); } }); }); @@ -505,7 +506,7 @@ impl App { } if readdress { let n = plc::readdress(&mut self.prj, &card); - self.notify(ctx, format!("{card}: {n} addresses changed")); + self.notify(ctx, tr_fmt!("{}: {} addresses changed", card, n)); } if export { let csv = plc::symbol_table(&self.prj, &self.analysis.netlist); @@ -534,11 +535,11 @@ impl App { self.eng.rev_author = self.prj.info.creator.clone(); } let locked = self.prj.pages.iter().filter(|p| p.locked).count(); - egui::Window::new("Revisions").open(&mut open).default_size([640.0, 480.0]).show(ctx, |ui| { + egui::Window::new(tr("Revisions")).open(&mut open).default_size([640.0, 480.0]).show(ctx, |ui| { egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { - ui.label(RichText::new("Revisions").strong()); + ui.label(RichText::new(tr("Revisions")).strong()); egui::Grid::new("revs").striped(true).num_columns(4).show(ui, |ui| { - for h in ["Index", "Date", "Author", "Description"] { + for h in [tr("Index"), tr("Date"), tr("Author"), tr("Description")] { ui.label(RichText::new(h).strong()); } ui.end_row(); @@ -551,53 +552,53 @@ impl App { } }); if self.prj.revisions.is_empty() { - ui.weak("No revision yet. Changes are tracked from the first revision on."); + ui.weak(tr("No revision yet. Changes are tracked from the first revision on.")); } ui.separator(); - ui.label(RichText::new("New revision").strong()); + ui.label(RichText::new(tr("New revision")).strong()); egui::Grid::new("newrev").num_columns(2).show(ui, |ui| { - ui.label("Index"); + ui.label(tr("Index")); ui.add(egui::TextEdit::singleline(&mut self.eng.rev_name).desired_width(60.0)); ui.end_row(); - ui.label("Date"); - ui.add(egui::TextEdit::singleline(&mut self.eng.rev_date).hint_text("YYYY-MM-DD").desired_width(100.0)); + ui.label(tr("Date")); + ui.add(egui::TextEdit::singleline(&mut self.eng.rev_date).hint_text(tr("YYYY-MM-DD")).desired_width(100.0)); ui.end_row(); - ui.label("Author"); + ui.label(tr("Author")); ui.text_edit_singleline(&mut self.eng.rev_author); ui.end_row(); - ui.label("Description"); + ui.label(tr("Description")); ui.text_edit_multiline(&mut self.eng.rev_description); ui.end_row(); }); - ui.checkbox(&mut self.eng.rev_release, "Release: lock all pages"); - create = ui.add_enabled(!self.eng.rev_name.trim().is_empty(), egui::Button::new("Create revision")).clicked(); + ui.checkbox(&mut self.eng.rev_release, tr("Release: lock all pages")); + create = ui.add_enabled(!self.eng.rev_name.trim().is_empty(), egui::Button::new(tr("Create revision"))).clicked(); ui.separator(); ui.horizontal_wrapped(|ui| { - ui.label(format!("{locked} of {} pages locked", self.prj.pages.len())); - if ui.button("Lock all").clicked() { + ui.label(tr_fmt!("{} of {} pages locked", locked, self.prj.pages.len())); + if ui.button(tr("Lock all")).clicked() { lock = Some(true); } - if ui.button("Unlock all").clicked() { + if ui.button(tr("Unlock all")).clicked() { lock = Some(false); } let pg = &mut self.prj.pages[self.page]; - ui.checkbox(&mut pg.locked, format!("Page {} locked", pg.name)); + ui.checkbox(&mut pg.locked, tr_fmt!("Page {} locked", pg.name)); }); ui.separator(); ui.horizontal(|ui| { let since = self.prj.revisions.last().map(|r| r.name.clone()).unwrap_or_default(); - ui.label(RichText::new(if since.is_empty() { "Changes".to_string() } else { format!("Changes since revision {since}") }).strong()); - ui.checkbox(&mut self.editor.show_revision_marks, "Revision marks"); - overview = ui.button("📊 Revision overview").clicked(); + ui.label(RichText::new(if since.is_empty() { "Changes".to_string() } else { tr_fmt!("Changes since revision {}", since) }).strong()); + ui.checkbox(&mut self.editor.show_revision_marks, tr("Revision marks")); + overview = ui.button(tr("📊 Revision overview")).clicked(); }); for pc in &self.analysis.changes { let title = match pc.page { - Some(_) => format!("Page {} ({})", pc.name, pc.changes.len()), - None => format!("Page {} (deleted)", pc.name), + Some(_) => tr_fmt!("Page {} ({})", pc.name, pc.changes.len()), + None => tr_fmt!("Page {} (deleted)", pc.name), }; egui::CollapsingHeader::new(title).id_salt(("chg", pc.page_id)).show(ui, |ui| { for c in &pc.changes { - let text = format!("{} {} {}", c.what, c.kind.title(), c.label); + let text = format!("{} {} {}", tr(c.what), c.kind.title(), c.label); match pc.page { Some(pi) if c.kind != revision::ChangeKind::Removed => { if ui.link(text.trim()).clicked() { @@ -612,7 +613,7 @@ impl App { }); } if self.analysis.changes.is_empty() && !self.prj.revisions.is_empty() { - ui.weak("No changes since the last revision."); + ui.weak(tr("No changes since the last revision.")); } }); }); @@ -620,7 +621,7 @@ impl App { if create { let e = &self.eng; revision::create(&mut self.prj, e.rev_name.trim(), &e.rev_date, &e.rev_author, &e.rev_description, e.rev_release); - self.notify(ctx, format!("Revision {} created", self.eng.rev_name.trim())); + self.notify(ctx, tr_fmt!("Revision {} created", self.eng.rev_name.trim())); self.eng.rev_name.clear(); self.eng.rev_description.clear(); } diff --git a/src/app/forms_ui.rs b/src/app/forms_ui.rs index 4be42334..80f76d8a 100644 --- a/src/app/forms_ui.rs +++ b/src/app/forms_ui.rs @@ -1,6 +1,7 @@ //! Forms window: title block editor (lines, rectangles, texts with placeholders) //! and report forms (columns, order, rows per page). +use openecraft_i18n::{tr, tr_fmt}; use super::App; use crate::editor::{EguiDraw, Palette}; use crate::forms::{self, Form, FormItem, FormLibrary, ReportForm}; @@ -54,10 +55,10 @@ impl App { } let mut open = true; let mut action = None; - egui::Window::new("Forms – title blocks and reports").open(&mut open).default_size([1150.0, 560.0]).show(ctx, |ui| { + egui::Window::new(tr("Forms – title blocks and reports")).open(&mut open).default_size([1150.0, 560.0]).show(ctx, |ui| { ui.horizontal(|ui| { - ui.selectable_value(&mut self.forms_ui.tab, Tab::TitleBlocks, RichText::new("Title blocks").strong()); - ui.selectable_value(&mut self.forms_ui.tab, Tab::Reports, RichText::new("Report forms").strong()); + ui.selectable_value(&mut self.forms_ui.tab, Tab::TitleBlocks, RichText::new(tr("Title blocks")).strong()); + ui.selectable_value(&mut self.forms_ui.tab, Tab::Reports, RichText::new(tr("Report forms")).strong()); }); ui.separator(); match self.forms_ui.tab { @@ -71,7 +72,7 @@ impl App { Some(Action::Export) => { let lib = FormLibrary { title_blocks: self.prj.forms.title_blocks.clone() }; let json = serde_json::to_string_pretty(&lib).unwrap_or_default(); - self.export(ctx, "title_blocks.json".into(), ("OpenECraft title blocks", "json"), json); + self.export(ctx, "title_blocks.json".into(), (tr("OpenECraft title blocks"), "json"), json); } None => {} } @@ -88,7 +89,7 @@ impl App { } let custom = prj.forms.title_blocks.iter().position(|f| f.name == fu.form); ui.horizontal_wrapped(|ui| { - ui.label("Title block"); + ui.label(tr("Title block")); egui::ComboBox::from_id_salt("tbsel").selected_text(&fu.form).width(180.0).show_ui(ui, |ui| { for n in &names { let tag = if prj.forms.title_blocks.iter().any(|f| &f.name == n) { "" } else { " (built-in)" }; @@ -98,7 +99,7 @@ impl App { } } }); - if ui.button("Copy as new").on_hover_text("Editable copy of this title block").clicked() { + if ui.button(tr("Copy as new")).on_hover_text(tr("Editable copy of this title block")).clicked() { let mut f = forms::find(prj, &fu.form).into_owned(); let mut name = format!("{} (copy)", f.name); while names.contains(&name) { @@ -109,7 +110,7 @@ impl App { fu.form = name; fu.item = None; } - if ui.button("New empty").clicked() { + if ui.button(tr("New empty")).clicked() { let mut name = "My title block".to_string(); while names.contains(&name) { name.push('+'); @@ -120,11 +121,11 @@ impl App { fu.item = None; } let is_default = prj.forms.default_title_block == fu.form || (prj.forms.default_title_block.is_empty() && fu.form == forms::STANDARD); - if ui.add_enabled(!is_default, egui::Button::new("Use for all pages")).on_hover_text("Project default; pages can choose their own in the page properties").clicked() { + if ui.add_enabled(!is_default, egui::Button::new(tr("Use for all pages"))).on_hover_text(tr("Project default; pages can choose their own in the page properties")).clicked() { prj.forms.default_title_block = if fu.form == forms::STANDARD { String::new() } else { fu.form.clone() }; } if let Some(ci) = custom { - if ui.button("🗑 Delete").on_hover_text("Pages using it get the project default").clicked() { + if ui.button(tr("🗑 Delete")).on_hover_text(tr("Pages using it get the project default")).clicked() { let name = prj.forms.title_blocks.remove(ci).name; for pg in prj.pages.iter_mut().filter(|pg| pg.title_block == name) { pg.title_block.clear(); @@ -137,20 +138,20 @@ impl App { } } ui.separator(); - if ui.button("⬆ Import…").clicked() { + if ui.button(tr("⬆ Import…")).clicked() { action = Some(Action::Import); } - if ui.add_enabled(!prj.forms.title_blocks.is_empty(), egui::Button::new("⬇ Export…")).on_hover_text("The project's own title blocks").clicked() { + if ui.add_enabled(!prj.forms.title_blocks.is_empty(), egui::Button::new(tr("⬇ Export…"))).on_hover_text(tr("The project's own title blocks")).clicked() { action = Some(Action::Export); } }); let used = (0..prj.pages.len()).filter(|&i| forms::title_block(prj, i).name == fu.form).count(); - ui.weak(format!("Used on {used} of {} pages", prj.pages.len())); + ui.weak(tr_fmt!("Used on {} of {} pages", used, prj.pages.len())); let custom = prj.forms.title_blocks.iter().position(|f| f.name == fu.form); let page = self.page.min(prj.pages.len().saturating_sub(1)); match custom { None => { - ui.colored_label(Color32::from_rgb(220, 140, 0), "Built-in title blocks are read only – use “Copy as new” to make your own."); + ui.colored_label(Color32::from_rgb(220, 140, 0), tr("Built-in title blocks are read only – use “Copy as new” to make your own.")); let mut form = forms::find(prj, &fu.form).into_owned(); preview(ui, fu, prj, page, &mut form, false); } @@ -158,7 +159,7 @@ impl App { let mut form = prj.forms.title_blocks[ci].clone(); let old_name = form.name.clone(); ui.horizontal(|ui| { - ui.label("Name"); + ui.label(tr("Name")); ui.text_edit_singleline(&mut form.name); }); preview(ui, fu, prj, page, &mut form, true); @@ -169,10 +170,10 @@ impl App { ui.horizontal_wrapped(|ui| { let mid = p(forms::AREA_W / 2.0, forms::AREA_H / 2.0); let new = [ - ("➕ Line", FormItem::Line { a: mid - p(20.0, 0.0), b: mid + p(20.0, 0.0), width: 0.25 }), - ("➕ Rectangle", FormItem::Rect { a: mid - p(20.0, 8.0), b: mid + p(20.0, 8.0), width: 0.25, fill: false }), - ("➕ Text", FormItem::Text { pos: mid, text: "{project}".into(), size: 2.5, anchor: Anchor::Left, label: false, max_width: 0.0 }), - ("➕ Label", FormItem::Text { pos: mid, text: "Label".into(), size: 1.6, anchor: Anchor::Left, label: true, max_width: 0.0 }), + (tr("➕ Line"), FormItem::Line { a: mid - p(20.0, 0.0), b: mid + p(20.0, 0.0), width: 0.25 }), + (tr("➕ Rectangle"), FormItem::Rect { a: mid - p(20.0, 8.0), b: mid + p(20.0, 8.0), width: 0.25, fill: false }), + (tr("➕ Text"), FormItem::Text { pos: mid, text: "{project}".into(), size: 2.5, anchor: Anchor::Left, label: false, max_width: 0.0 }), + (tr("➕ Label"), FormItem::Text { pos: mid, text: "Label".into(), size: 1.6, anchor: Anchor::Left, label: true, max_width: 0.0 }), ]; for (label, item) in new { if ui.button(label).clicked() { @@ -200,8 +201,8 @@ impl App { }); ui.separator(); ui.vertical(|ui| { - ui.label(RichText::new("Placeholders").strong()); - ui.weak("Click to add to the selected text."); + ui.label(RichText::new(tr("Placeholders")).strong()); + ui.weak(tr("Click to add to the selected text.")); egui::ScrollArea::vertical().id_salt("tbph").max_height(240.0).show(ui, |ui| { for (ph, meaning) in forms::PLACEHOLDERS { ui.horizontal(|ui| { @@ -210,7 +211,7 @@ impl App { text.push_str(ph); } } - ui.weak(meaning); + ui.weak(tr(meaning)); }); } }); @@ -240,7 +241,7 @@ impl App { let fu = &mut self.forms_ui; let kind = *fu.report.get_or_insert(ReportKind::DeviceList); ui.horizontal(|ui| { - ui.label("Report"); + ui.label(tr("Report")); egui::ComboBox::from_id_salt("rfkind").selected_text(kind.title()).width(240.0).show_ui(ui, |ui| { for k in ReportKind::ALL { ui.selectable_value(&mut fu.report, Some(k), k.title()); @@ -251,10 +252,10 @@ impl App { let headers: Vec<&str> = table.headers.clone(); let mut form = self.prj.forms.reports.get(&kind).cloned().unwrap_or_default(); egui::Grid::new("rform").num_columns(2).spacing([10.0, 6.0]).show(ui, |ui| { - ui.label("Page heading"); + ui.label(tr("Page heading")); ui.add(egui::TextEdit::singleline(&mut form.title).hint_text(kind.title()).desired_width(320.0)); ui.end_row(); - ui.label("Rows per page"); + ui.label(tr("Rows per page")); let mut rows = if form.rows == 0 { crate::render::REPORT_ROWS_PER_PAGE } else { form.rows }; if ui.add(egui::DragValue::new(&mut rows).range(5..=80)).changed() { form.rows = if rows == crate::render::REPORT_ROWS_PER_PAGE { 0 } else { rows }; @@ -262,7 +263,7 @@ impl App { ui.end_row(); }); ui.add_space(4.0); - ui.label(RichText::new("Columns").strong()); + ui.label(RichText::new(tr("Columns")).strong()); // Shown columns in their order, then the hidden ones. let shown: Vec = forms::report_columns(Some(&form), &headers); let mut order: Vec<(usize, bool)> = shown.iter().map(|&c| (c, true)).collect(); @@ -291,10 +292,10 @@ impl App { form.columns = if all_in_order || cols.is_empty() { Vec::new() } else { cols.iter().map(|&c| headers[c].to_string()).collect() }; } ui.horizontal(|ui| { - if ui.button("Reset to standard").clicked() { + if ui.button(tr("Reset to standard")).clicked() { form = ReportForm::default(); } - ui.weak("Applies to report pages, the PDF and the print export."); + ui.weak(tr("Applies to report pages, the PDF and the print export.")); }); let stored = self.prj.forms.reports.get(&kind).cloned().unwrap_or_default(); if form != stored { @@ -334,7 +335,7 @@ fn preview(ui: &mut egui::Ui, fu: &mut FormsUi, prj: &crate::model::Project, pag /// Properties of the selected title block element. fn item_properties(ui: &mut egui::Ui, fu: &mut FormsUi, form: &mut Form) { let Some(i) = fu.item.filter(|i| *i < form.items.len()) else { - ui.weak("Select an element in the list or the drawing."); + ui.weak(tr("Select an element in the list or the drawing.")); return; }; let mut delete = false; @@ -350,52 +351,52 @@ fn item_properties(ui: &mut egui::Ui, fu: &mut FormsUi, form: &mut Form) { ui.label(RichText::new(form.items[i].kind_name()).strong()); egui::Grid::new("tbitem").num_columns(2).spacing([8.0, 4.0]).show(ui, |ui| match &mut form.items[i] { FormItem::Line { a, b, width } => { - pt(ui, "Start", a); - pt(ui, "End", b); - ui.label("Line width"); + pt(ui, tr("Start"), a); + pt(ui, tr("End"), b); + ui.label(tr("Line width")); ui.add(egui::DragValue::new(width).speed(0.05).range(0.05..=2.0).suffix(" mm")); ui.end_row(); } FormItem::Rect { a, b, width, fill } => { - pt(ui, "Corner", a); - pt(ui, "Corner", b); - ui.label("Line width"); + pt(ui, tr("Corner"), a); + pt(ui, tr("Corner"), b); + ui.label(tr("Line width")); ui.add(egui::DragValue::new(width).speed(0.05).range(0.0..=2.0).suffix(" mm")); ui.end_row(); - ui.label("Filled"); + ui.label(tr("Filled")); ui.checkbox(fill, ""); ui.end_row(); } FormItem::Text { pos, text, size, anchor, label, max_width } => { - ui.label("Text"); + ui.label(tr("Text")); ui.add(egui::TextEdit::multiline(text).desired_rows(2).desired_width(220.0)); ui.end_row(); - pt(ui, "Position", pos); - ui.label("Size"); + pt(ui, tr("Position"), pos); + ui.label(tr("Size")); ui.add(egui::DragValue::new(size).speed(0.1).range(0.8..=20.0).suffix(" mm")); ui.end_row(); - ui.label("Alignment"); + ui.label(tr("Alignment")); ui.horizontal(|ui| { - ui.selectable_value(anchor, Anchor::Left, "Left"); - ui.selectable_value(anchor, Anchor::Center, "Centre"); - ui.selectable_value(anchor, Anchor::Right, "Right"); + ui.selectable_value(anchor, Anchor::Left, tr("Left")); + ui.selectable_value(anchor, Anchor::Center, tr("Centre")); + ui.selectable_value(anchor, Anchor::Right, tr("Right")); }); ui.end_row(); - ui.label("Style"); + ui.label(tr("Style")); ui.horizontal(|ui| { - ui.selectable_value(label, false, "Value"); - ui.selectable_value(label, true, "Label (grey)"); + ui.selectable_value(label, false, tr("Value")); + ui.selectable_value(label, true, tr("Label (grey)")); }); ui.end_row(); - ui.label("Max. width"); + ui.label(tr("Max. width")); ui.add(egui::DragValue::new(max_width).speed(0.5).range(0.0..=forms::AREA_W).suffix(" mm")) - .on_hover_text("Longer values are drawn smaller (0 = no limit)"); + .on_hover_text(tr("Longer values are drawn smaller (0 = no limit)")); ui.end_row(); } }); ui.horizontal(|ui| { - duplicate = ui.button("Duplicate").clicked(); - delete = ui.button("🗑 Delete").clicked(); + duplicate = ui.button(tr("Duplicate")).clicked(); + delete = ui.button(tr("🗑 Delete")).clicked(); }); if duplicate { let mut copy = form.items[i].clone(); diff --git a/src/app/harness_ui.rs b/src/app/harness_ui.rs index 16fb55fc..26ad34db 100644 --- a/src/app/harness_ui.rs +++ b/src/app/harness_ui.rs @@ -1,6 +1,7 @@ //! Harness window: harnesses with their wires, connectors (pin assignment), lengths //! and bundle diameter; KBL export. +use openecraft_i18n::{tr, tr_fmt}; use super::App; use crate::harness::{self, Harness}; use crate::model::ReportKind; @@ -25,17 +26,17 @@ impl App { let mut unassign: Option<(String, [String; 2])> = None; let (mut kbl, mut report) = (false, false); let structure = structure::page_structure(&self.prj.pages[self.page]); - egui::Window::new("Harnesses").open(&mut open).default_size([900.0, 460.0]).show(ctx, |ui| { + egui::Window::new(tr("Harnesses")).open(&mut open).default_size([900.0, 460.0]).show(ctx, |ui| { ui.horizontal_wrapped(|ui| { - if ui.button("➕ New harness").on_hover_text("In the structure of the current page").clicked() { + if ui.button(tr("➕ New harness")).on_hover_text(tr("In the structure of the current page")).clicked() { let tag = self.prj.next_tag(&structure, "WH"); let id = self.prj.new_id(); self.harness_ui.sel = Some(tag.clone()); self.prj.harnesses.push(Harness { id, tag, ..Default::default() }); } - report = ui.button("📊 Harness data").on_hover_text("Report with all harness wires").clicked(); - kbl = ui.add_enabled(!self.prj.harnesses.is_empty(), egui::Button::new("⬇ Export KBL (XML)…")).on_hover_text("Simplified KBL (VDA 4964) for harness manufacturing").clicked(); - ui.weak("Assign connections: select the wires between two devices in the schematic › Assign to harness."); + report = ui.button(tr("📊 Harness data")).on_hover_text(tr("Report with all harness wires")).clicked(); + kbl = ui.add_enabled(!self.prj.harnesses.is_empty(), egui::Button::new(tr("⬇ Export KBL (XML)…"))).on_hover_text(tr("Simplified KBL (VDA 4964) for harness manufacturing")).clicked(); + ui.weak(tr("Assign connections: select the wires between two devices in the schematic › Assign to harness.")); }); ui.separator(); let an = &self.analysis; @@ -50,7 +51,7 @@ impl App { }) .collect(); egui::Grid::new("harnesses").striped(true).num_columns(8).spacing([8.0, 4.0]).show(ui, |ui| { - for h in ["Harness", "Description", "Field length", "Part", "Wires", "Connectors", "Bundle Ø", ""] { + for h in [tr("Harness"), tr("Description"), tr("Field length"), tr("Part"), tr("Wires"), tr("Connectors"), tr("Bundle Ø"), ""] { ui.label(RichText::new(h).strong()); } ui.end_row(); @@ -58,7 +59,7 @@ impl App { let old = h.tag.clone(); let sel = self.harness_ui.sel.as_deref() == Some(old.as_str()); ui.horizontal(|ui| { - if ui.selectable_label(sel, "▶").on_hover_text("Show connectors").clicked() { + if ui.selectable_label(sel, "▶").on_hover_text(tr("Show connectors")).clicked() { self.harness_ui.sel = Some(old.clone()); } ui.add_sized([100.0, 20.0], egui::TextEdit::singleline(&mut h.tag).font(egui::TextStyle::Monospace)); @@ -68,40 +69,40 @@ impl App { } ui.add_sized([180.0, 20.0], egui::TextEdit::singleline(&mut h.description)); ui.add(egui::DragValue::new(&mut h.length).speed(0.1).range(0.0..=1000.0).suffix(" m")) - .on_hover_text("Length of wires that are not routed in the panel layout"); - ui.add_sized([110.0, 20.0], egui::TextEdit::singleline(&mut h.part).hint_text("part number")); + .on_hover_text(tr("Length of wires that are not routed in the panel layout")); + ui.add_sized([110.0, 20.0], egui::TextEdit::singleline(&mut h.part).hint_text(tr("part number"))); let (n, c, dia) = stats[i]; ui.label(n.to_string()); ui.label(c.to_string()); ui.label(format!("{dia:.1} mm")); - if ui.small_button("🗑").on_hover_text("Delete harness (its wires are removed from it)").clicked() { + if ui.small_button("🗑").on_hover_text(tr("Delete harness (its wires are removed from it)")).clicked() { remove = Some(i); } ui.end_row(); } }); if self.prj.harnesses.is_empty() { - ui.weak("No harnesses defined."); + ui.weak(tr("No harnesses defined.")); } // Connectors of the selected harness if let Some(tag) = self.harness_ui.sel.clone().filter(|t| self.prj.harnesses.iter().any(|h| &h.tag == t)) { ui.separator(); let ws = harness::wires(&self.prj, an, &tag); let total: f32 = ws.iter().map(|w| w.length).sum(); - ui.label(RichText::new(format!("{tag}: {} wires, {:.2} m wire in total", ws.len(), total / 1000.0)).strong()); + ui.label(RichText::new(tr_fmt!("{}: {} wires, {} m wire in total", tag, ws.len(), format!("{:.2}", total / 1000.0))).strong()); if ws.iter().any(|w| w.length <= 0.0) { - ui.colored_label(Color32::from_rgb(220, 140, 0), "Some wires have no length: place their devices in the panel layout or set the field length."); + ui.colored_label(Color32::from_rgb(220, 140, 0), tr("Some wires have no length: place their devices in the panel layout or set the field length.")); } let stale = harness::stale(&self.prj, an); - ui.collapsing(format!("Connections ({})", self.prj.harnesses.iter().find(|h| h.tag == tag).map(|h| h.connections.len()).unwrap_or(0)), |ui| { + ui.collapsing(tr_fmt!("Connections ({})", self.prj.harnesses.iter().find(|h| h.tag == tag).map(|h| h.connections.len()).unwrap_or(0)), |ui| { egui::ScrollArea::vertical().id_salt("hlist").max_height(160.0).show(ui, |ui| { for k in self.prj.harnesses.iter().find(|h| h.tag == tag).map(|h| h.connections.clone()).unwrap_or_default() { ui.horizontal(|ui| { ui.monospace(format!("{} – {}", k[0], k[1])); if stale.iter().any(|(t, c)| *t == tag && *c == k) { - ui.colored_label(Color32::from_rgb(220, 140, 0), "not in the schematic"); + ui.colored_label(Color32::from_rgb(220, 140, 0), tr("not in the schematic")); } - if ui.small_button("🗑").on_hover_text("Remove from the harness").clicked() { + if ui.small_button("🗑").on_hover_text(tr("Remove from the harness")).clicked() { unassign = Some((tag.clone(), k.clone())); } }); @@ -148,7 +149,7 @@ impl App { } if kbl { let xml = harness::kbl(&self.prj, &self.analysis); - self.export(ctx, self.suggested_name("kbl"), ("KBL harness data (XML)", "kbl"), xml); + self.export(ctx, self.suggested_name("kbl"), (tr("KBL harness data (XML)"), "kbl"), xml); } self.harness_ui.open = open; } diff --git a/src/app/symbol_editor.rs b/src/app/symbol_editor.rs index 2f792e6f..fb506761 100644 --- a/src/app/symbol_editor.rs +++ b/src/app/symbol_editor.rs @@ -1,6 +1,7 @@ //! Symbol editor: user symbols of the project (graphics, connection points, //! function), copies of built-in symbols and symbol library files. +use openecraft_i18n::{tr, tr_const, tr_fmt}; use super::App; use crate::editor::{EguiDraw, Palette, Tool}; use crate::geom::{p, P, GRID}; @@ -26,14 +27,14 @@ pub enum SymTool { impl SymTool { const ALL: [(SymTool, &'static str, &'static str); 8] = [ - (SymTool::Select, "⬉ Select", "Select and drag elements; Del deletes"), - (SymTool::Line, "— Line", "Click start and end point"), - (SymTool::Rect, "☐ Rect", "Click two corners"), - (SymTool::Circle, "○ Circle", "Click centre, then a point on the circle"), - (SymTool::Text, "T Text", "Click to place the text from the field below"), - (SymTool::Pin, "• Connection point", "Click on the 4 mm grid"), - (SymTool::TagField, "Tag field", "Position of the device tag (instead of the tag block)"), - (SymTool::LabelField, "Label field", "Position of the label (terminal number, address …)"), + (SymTool::Select, tr_const!("⬉ Select"), tr_const!("Select and drag elements; Del deletes")), + (SymTool::Line, tr_const!("— Line"), tr_const!("Click start and end point")), + (SymTool::Rect, tr_const!("☐ Rect"), tr_const!("Click two corners")), + (SymTool::Circle, tr_const!("○ Circle"), tr_const!("Click centre, then a point on the circle")), + (SymTool::Text, tr_const!("T Text"), tr_const!("Click to place the text from the field below")), + (SymTool::Pin, tr_const!("• Connection point"), tr_const!("Click on the 4 mm grid")), + (SymTool::TagField, tr_const!("Tag field"), tr_const!("Position of the device tag (instead of the tag block)")), + (SymTool::LabelField, tr_const!("Label field"), tr_const!("Position of the label (terminal number, address …)")), ]; } @@ -89,13 +90,13 @@ impl App { se.sel = prj.symbols.first().map(|u| u.key.clone()); se.hit = None; } - egui::Window::new("Symbol editor").open(&mut open).default_size([960.0, 520.0]).show(ctx, |ui| { + egui::Window::new(tr("Symbol editor")).open(&mut open).default_size([960.0, 520.0]).show(ctx, |ui| { ui.horizontal_top(|ui| { // ------------------------------------------------ symbol list ui.vertical(|ui| { ui.set_width(180.0); ui.horizontal_wrapped(|ui| { - if ui.button("➕ New").clicked() { + if ui.button(tr("➕ New")).clicked() { let mut u = UserSymbol::default(); u.key = symlib::new_key(&prj.symbols, &u.name); u.prims.push(Prim::Poly { pts: vec![p(-4.0, -4.0), p(4.0, -4.0), p(4.0, 4.0), p(-4.0, 4.0)], closed: true, fill: false }); @@ -105,12 +106,12 @@ impl App { se.sel = Some(u.key.clone()); prj.symbols.push(u); } - ui.menu_button("Copy built-in…", |ui| { + ui.menu_button(tr("Copy built-in…"), |ui| { egui::ScrollArea::vertical().max_height(400.0).show(ui, |ui| { for cat in symbols::Category::ALL { ui.menu_button(cat.title(), |ui| { for def in symbols::library().iter().filter(|d| d.category == cat) { - if ui.button(def.name).clicked() { + if ui.button(tr(def.name)).clicked() { let u = symlib::from_def(def, &prj.symbols); se.sel = Some(u.key.clone()); prj.symbols.push(u); @@ -123,10 +124,10 @@ impl App { }); }); ui.horizontal(|ui| { - if ui.button("⬆ Import…").on_hover_text("Merge a symbol library file").clicked() { + if ui.button(tr("⬆ Import…")).on_hover_text(tr("Merge a symbol library file")).clicked() { action = Some(Action::Import); } - if ui.add_enabled(!prj.symbols.is_empty(), egui::Button::new("⬇ Export…")).on_hover_text("All user symbols as library file").clicked() { + if ui.add_enabled(!prj.symbols.is_empty(), egui::Button::new(tr("⬇ Export…"))).on_hover_text(tr("All user symbols as library file")).clicked() { action = Some(Action::Export); } }); @@ -152,7 +153,7 @@ impl App { se.start = None; } if prj.symbols.is_empty() { - ui.weak("No user symbols yet. Create one or copy a built-in symbol."); + ui.weak(tr("No user symbols yet. Create one or copy a built-in symbol.")); } }); }); @@ -164,20 +165,20 @@ impl App { ui.vertical(|ui| { ui.horizontal_wrapped(|ui| { for (t, label, tip) in SymTool::ALL { - if ui.selectable_label(se.tool == t, label).on_hover_text(tip).clicked() { + if ui.selectable_label(se.tool == t, tr(label)).on_hover_text(tr(tip)).clicked() { se.set_tool(t); } } }); if se.tool == SymTool::Text { ui.horizontal(|ui| { - ui.label("Text"); + ui.label(tr("Text")); ui.text_edit_singleline(&mut se.text); }); } let u = &mut prj.symbols[si]; canvas(ui, se, u); - ui.weak("Wheel: zoom · right click: cancel · graphics snap to 0.5 mm, connection points to the 4 mm grid"); + ui.weak(tr("Wheel: zoom · right click: cancel · graphics snap to 0.5 mm, connection points to the 4 mm grid")); }); ui.separator(); // ------------------------------------------------ properties @@ -193,15 +194,15 @@ impl App { for msg in symlib::problems(u) { ui.colored_label(Color32::from_rgb(220, 140, 0), format!("⚠ {msg}")); } - ui.label(format!("Placed {usage}× in the project")); + ui.label(tr_fmt!("Placed {}× in the project", usage)); ui.horizontal(|ui| { - if ui.add_enabled(symlib::problems(u).is_empty(), egui::Button::new("✏ Place in schematic")).clicked() { + if ui.add_enabled(symlib::problems(u).is_empty(), egui::Button::new(tr("✏ Place in schematic"))).clicked() { action = Some(Action::Place(u.key.clone())); } - if ui.button("Duplicate").clicked() { + if ui.button(tr("Duplicate")).clicked() { action = Some(Action::Duplicate(si)); } - let del = ui.add_enabled(usage == 0, egui::Button::new("🗑 Delete")).on_disabled_hover_text("The symbol is placed in the project"); + let del = ui.add_enabled(usage == 0, egui::Button::new(tr("🗑 Delete"))).on_disabled_hover_text(tr("The symbol is placed in the project")); if del.clicked() { action = Some(Action::Delete(si)); } @@ -216,14 +217,14 @@ impl App { Some(Action::Export) => { let lib = SymbolLibrary { symbols: self.prj.symbols.clone() }; let json = serde_json::to_string_pretty(&lib).unwrap_or_default(); - self.export(ctx, "symbols.json".into(), ("OpenECraft symbol library", "json"), json); + self.export(ctx, "symbols.json".into(), (tr("OpenECraft symbol library"), "json"), json); } Some(Action::Place(key)) => { symlib::register(&self.prj.symbols); if let Some(def) = symbols::get(&key) { self.workspace = super::Workspace::Schematic; self.editor.set_tool(Tool::Place(def.key)); - self.notify(ctx, format!("Click into the page to place {}", def.name)); + self.notify(ctx, tr_fmt!("Click into the page to place {}", tr(def.name))); } } Some(Action::Duplicate(si)) => { @@ -244,43 +245,43 @@ impl App { } fn symbol_properties(ui: &mut egui::Ui, u: &mut UserSymbol) { - ui.label(RichText::new("Symbol").strong()); + ui.label(RichText::new(tr("Symbol")).strong()); egui::Grid::new("symprops_grid").num_columns(2).spacing([8.0, 4.0]).show(ui, |ui| { - ui.label("Name"); + ui.label(tr("Name")); ui.text_edit_singleline(&mut u.name); ui.end_row(); - ui.label("Library"); - ui.text_edit_singleline(&mut u.library).on_hover_text("Group in the symbol list, e.g. your company"); + ui.label(tr("Library")); + ui.text_edit_singleline(&mut u.library).on_hover_text(tr("Group in the symbol list, e.g. your company")); ui.end_row(); - ui.label("Function"); + ui.label(tr("Function")); egui::ComboBox::from_id_salt("symfunc").selected_text(u.func.title()).width(200.0).show_ui(ui, |ui| { for f in Func::ALL { ui.selectable_value(&mut u.func, f, f.title()); } }); ui.end_row(); - ui.label("Identifying letter"); - ui.add(egui::TextEdit::singleline(&mut u.letter).desired_width(60.0).hint_text("K, Q, MM …")); + ui.label(tr("Identifying letter")); + ui.add(egui::TextEdit::singleline(&mut u.letter).desired_width(60.0).hint_text(tr("K, Q, MM …"))); ui.end_row(); - ui.label("Default label"); - ui.add(egui::TextEdit::singleline(&mut u.default_label).desired_width(80.0)).on_hover_text("Terminal number, PLC address, potential name …"); + ui.label(tr("Default label")); + ui.add(egui::TextEdit::singleline(&mut u.default_label).desired_width(80.0)).on_hover_text(tr("Terminal number, PLC address, potential name …")); ui.end_row(); }); - ui.checkbox(&mut u.show_tag, "Show device tag and cross references"); - ui.checkbox(&mut u.show_pin_labels, "Show connection point designations"); + ui.checkbox(&mut u.show_tag, tr("Show device tag and cross references")); + ui.checkbox(&mut u.show_pin_labels, tr("Show connection point designations")); if matches!(u.func, Func::Aux(_)) { - ui.checkbox(&mut u.auto_number, "Number contacts automatically (13/14, 21/22 …)"); + ui.checkbox(&mut u.auto_number, tr("Number contacts automatically (13/14, 21/22 …)")); } if u.func == Func::Terminal && u.pins.len() >= 2 { let mut bridged = u.bridges.contains(&(0, 1)); - if ui.checkbox(&mut bridged, "Connection points 1 and 2 are connected inside").changed() { + if ui.checkbox(&mut bridged, tr("Connection points 1 and 2 are connected inside")).changed() { u.bridges.retain(|b| *b != (0, 1)); if bridged { u.bridges.push((0, 1)); } } } - ui.weak(format!("Key: {}", u.key)); + ui.weak(tr_fmt!("Key: {}", u.key)); } fn point_edit(ui: &mut egui::Ui, label: &str, q: &mut P, speed: f32) { @@ -296,39 +297,39 @@ fn element_properties(ui: &mut egui::Ui, se: &mut SymbolEditor, u: &mut UserSymb let mut delete = false; match se.hit { Some(Hit::Pin(i)) if i < u.pins.len() => { - ui.label(RichText::new(format!("Connection point {}", i + 1)).strong()); + ui.label(RichText::new(tr_fmt!("Connection point {}", i + 1)).strong()); egui::Grid::new("pinprops").num_columns(2).show(ui, |ui| { - ui.label("Designation"); + ui.label(tr("Designation")); ui.text_edit_singleline(&mut u.pins[i].label); ui.end_row(); - point_edit(ui, "Position", &mut u.pins[i].pos, GRID); + point_edit(ui, tr("Position"), &mut u.pins[i].pos, GRID); }); u.pins[i].pos = symlib::snap(u.pins[i].pos, GRID); - delete = ui.button("🗑 Delete connection point").clicked(); + delete = ui.button(tr("🗑 Delete connection point")).clicked(); } Some(Hit::Prim(i)) if i < u.prims.len() => { let prim = &mut u.prims[i]; let kind = match prim { - Prim::Line { .. } => "Line", - Prim::Poly { .. } => "Polyline / rectangle", - Prim::Circle { .. } => "Circle", - Prim::Text { .. } => "Text", - Prim::Field { .. } => "Field", + Prim::Line { .. } => tr("Line"), + Prim::Poly { .. } => tr("Polyline / rectangle"), + Prim::Circle { .. } => tr("Circle"), + Prim::Text { .. } => tr("Text"), + Prim::Field { .. } => tr("Field"), }; ui.label(RichText::new(kind).strong()); egui::Grid::new("primprops").num_columns(2).show(ui, |ui| match prim { Prim::Line { a, b, dashed } => { - point_edit(ui, "Start", a, 0.1); - point_edit(ui, "End", b, 0.1); - ui.label("Dashed"); + point_edit(ui, tr("Start"), a, 0.1); + point_edit(ui, tr("End"), b, 0.1); + ui.label(tr("Dashed")); ui.checkbox(dashed, ""); ui.end_row(); } Prim::Poly { pts, closed, fill } => { - ui.label("Points"); + ui.label(tr("Points")); ui.label(pts.len().to_string()); ui.end_row(); - ui.label("Closed / filled"); + ui.label(tr("Closed / filled")); ui.horizontal(|ui| { ui.checkbox(closed, ""); ui.checkbox(fill, ""); @@ -336,42 +337,42 @@ fn element_properties(ui: &mut egui::Ui, se: &mut SymbolEditor, u: &mut UserSymb ui.end_row(); } Prim::Circle { c, r, fill } => { - point_edit(ui, "Centre", c, 0.1); - ui.label("Radius"); + point_edit(ui, tr("Centre"), c, 0.1); + ui.label(tr("Radius")); ui.add(egui::DragValue::new(r).speed(0.1).range(0.1..=100.0)); ui.end_row(); - ui.label("Filled"); + ui.label(tr("Filled")); ui.checkbox(fill, ""); ui.end_row(); } Prim::Text { pos, text, size, anchor } => { - ui.label("Text"); + ui.label(tr("Text")); ui.text_edit_singleline(text); ui.end_row(); - point_edit(ui, "Position", pos, 0.1); - ui.label("Size"); + point_edit(ui, tr("Position"), pos, 0.1); + ui.label(tr("Size")); ui.add(egui::DragValue::new(size).speed(0.1).range(0.5..=20.0)); ui.end_row(); anchor_edit(ui, anchor); } Prim::Field { kind, pos, size, anchor } => { - ui.label("Shows"); + ui.label(tr("Shows")); ui.horizontal(|ui| { - ui.selectable_value(kind, FieldKind::Tag, "Device tag"); - ui.selectable_value(kind, FieldKind::Label, "Label"); + ui.selectable_value(kind, FieldKind::Tag, tr("Device tag")); + ui.selectable_value(kind, FieldKind::Label, tr("Label")); }); ui.end_row(); - point_edit(ui, "Position", pos, 0.1); - ui.label("Size"); + point_edit(ui, tr("Position"), pos, 0.1); + ui.label(tr("Size")); ui.add(egui::DragValue::new(size).speed(0.1).range(0.5..=20.0)); ui.end_row(); anchor_edit(ui, anchor); } }); - delete = ui.button("🗑 Delete element").clicked(); + delete = ui.button(tr("🗑 Delete element")).clicked(); } _ => { - ui.weak("Click an element in the drawing to edit it."); + ui.weak(tr("Click an element in the drawing to edit it.")); } } if delete { @@ -380,11 +381,11 @@ fn element_properties(ui: &mut egui::Ui, se: &mut SymbolEditor, u: &mut UserSymb } fn anchor_edit(ui: &mut egui::Ui, anchor: &mut Anchor) { - ui.label("Alignment"); + ui.label(tr("Alignment")); ui.horizontal(|ui| { - ui.selectable_value(anchor, Anchor::Left, "Left"); - ui.selectable_value(anchor, Anchor::Center, "Centre"); - ui.selectable_value(anchor, Anchor::Right, "Right"); + ui.selectable_value(anchor, Anchor::Left, tr("Left")); + ui.selectable_value(anchor, Anchor::Center, tr("Centre")); + ui.selectable_value(anchor, Anchor::Right, tr("Right")); }); ui.end_row(); } diff --git a/src/conventions/tests.rs b/src/conventions/tests.rs index 93f8d7fb..af4a1513 100644 --- a/src/conventions/tests.rs +++ b/src/conventions/tests.rs @@ -100,3 +100,53 @@ fn all_workspace_crates_are_checked() { assert!(dirs.iter().any(|d| d.ends_with(member)), "{member} missing in {dirs:?}"); } } + +/// UI crates (the others have no user-visible texts of their own). +fn ui_source_files() -> Vec { + ["src", "crates/openecraft-ui/src", "parts-manager/src"] + .iter() + .flat_map(|d| rust_files(&root().join(d))) + .filter(|p| !is_test_file(p)) + .collect() +} + +/// Texts shown to the user go through `tr` / `tr_fmt!` (see AGENTS.md, languages): a +/// widget call with a plain string literal is an untranslated text. +#[test] +fn ui_texts_are_translated() { + let calls = [ + ".button(\"", ".small_button(\"", ".label(\"", ".heading(\"", ".weak(\"", ".strong(\"", ".link(\"", ".menu_button(\"", + ".collapsing(\"", ".on_hover_text(\"", ".hint_text(\"", ".selectable_label(", ".selected_text(\"", ".hyperlink_to(\"", + "Button::new(\"", "RichText::new(\"", "Window::new(\"", + ]; + let mut violations = Vec::new(); + for path in ui_source_files() { + let text = std::fs::read_to_string(&path).unwrap(); + for (i, line) in text.lines().enumerate() { + let t = line.trim(); + if t.starts_with("//") { + continue; + } + for call in calls { + let mut rest = t; + while let Some(at) = rest.find(call) { + let after = &rest[at + call.len()..]; + rest = after; + if !call.ends_with('"') { + continue; + } + let literal: String = after.chars().take_while(|c| *c != '"').collect(); + let letters = literal.chars().filter(|c| c.is_alphabetic()).count(); + if letters >= 3 { + violations.push(format!("{}:{}: {t}", display(&path), i + 1)); + } + } + } + } + } + assert!( + violations.is_empty(), + "texts shown in the UI must be translated: wrap them in `tr(\"…\")` / `tr_fmt!(…)` and add them to crates/openecraft-i18n/src/catalog/extra.tsv (English, German, French, Spanish):\n{}", + violations.join("\n") + ); +} diff --git a/src/editor.rs b/src/editor.rs index d2a9bc1f..66b1098b 100644 --- a/src/editor.rs +++ b/src/editor.rs @@ -1,6 +1,7 @@ //! Interactive schematic canvas: pan/zoom, selection, moving, placing symbols, //! drawing wires, texts and graphics. +use openecraft_i18n::{tr, tr_fmt}; use crate::geom::{dist_to_segment, p, P, R, GRID}; use crate::index::Index; use crate::model::*; @@ -26,12 +27,12 @@ pub enum Tool { impl Tool { pub fn hint(&self) -> &'static str { match self { - Tool::Select => "Click to select, drag to move, drag on empty space for window selection. Right/middle drag pans, wheel zooms.", - Tool::Place(_) => "Click to place · R rotate · M mirror · Esc finish", - Tool::Wire => "Click start and corner points · Space toggles corner direction · ends automatically on a connection · Right click / Esc finish", - Tool::Text => "Click to place a text", - Tool::Line | Tool::Rect => "Click start point, click end point", - Tool::Insert => "Click to insert the macro · Esc cancel", + Tool::Select => tr("Click to select, drag to move, drag on empty space for window selection. Right/middle drag pans, wheel zooms."), + Tool::Place(_) => tr("Click to place · R rotate · M mirror · Esc finish"), + Tool::Wire => tr("Click start and corner points · Space toggles corner direction · ends automatically on a connection · Right click / Esc finish"), + Tool::Text => tr("Click to place a text"), + Tool::Line | Tool::Rect => tr("Click start point, click end point"), + Tool::Insert => tr("Click to insert the macro · Esc cancel"), } } } @@ -517,21 +518,21 @@ impl Editor { } } if !editable { - let msg = if locked { "Released page – unlock it in Project › Revisions to change it" } else { "Generated page – edit via page properties" }; + let msg = if locked { tr("Released page – unlock it in Project › Revisions to change it") } else { tr("Generated page – edit via page properties") }; painter.text(rect.left_top() + vec2(10.0, 10.0), Align2::LEFT_TOP, msg, FontId::proportional(13.0), pal.frame); } // Status line self.status = match (world, snapped) { (Some(w), Some(_)) => { - let mut s = format!("X {:7.1} Y {:7.1} mm Column {} Row {}", w.x, w.y, column_of(w), row_of(w)); + let mut s = tr_fmt!("X {} Y {} mm Column {} Row {}", format!("{:7.1}", w.x), format!("{:7.1}", w.y), column_of(w), row_of(w)); if let Some(id) = self.hit(&prj.pages[page_i], w) { let page = &prj.pages[page_i]; if let Some(sym) = page.symbols.iter().find(|s| s.id == id) { - let name = symbols::get(&sym.sym).map(|d| d.name).unwrap_or("?"); + let name = symbols::get(&sym.sym).map(|d| tr(d.name)).unwrap_or("?"); s += &format!(" | {} {} {}", sym.tag, name, sym.label); } else if let Some(net) = an.netlist.net_of_wire(id) { - s += &format!(" | Potential {}", net.name); + s += &tr_fmt!(" | Potential {}", net.name); } } s diff --git a/src/forms.rs b/src/forms.rs index 3976e3d7..03b469e0 100644 --- a/src/forms.rs +++ b/src/forms.rs @@ -4,6 +4,7 @@ //! own title blocks and share them as files; report forms choose the columns, their //! order and the rows per report page. +use openecraft_i18n::{tr, tr_const}; use crate::geom::{p, P}; use crate::model::{PageKind, Project, ReportKind, FRAME_X0, FRAME_X1, FRAME_Y1, TITLE_Y0}; use crate::render::{Draw, Ink, VAnchor}; @@ -52,9 +53,9 @@ pub enum FormItem { impl FormItem { pub fn kind_name(&self) -> &'static str { match self { - FormItem::Line { .. } => "Line", - FormItem::Rect { .. } => "Rectangle", - FormItem::Text { .. } => "Text", + FormItem::Line { .. } => tr("Line"), + FormItem::Rect { .. } => tr("Rectangle"), + FormItem::Text { .. } => tr("Text"), } } @@ -130,8 +131,8 @@ pub struct FormLibrary { pub title_blocks: Vec
, } -fn label(items: &mut Vec, x: f32, y: f32, text: &str) { - items.push(FormItem::Text { pos: p(x + 1.0, y + 1.8), text: text.into(), size: 1.6, anchor: Anchor::Left, label: true, max_width: 0.0 }); +fn label(items: &mut Vec, x: f32, y: f32, text: &'static str) { + items.push(FormItem::Text { pos: p(x + 1.0, y + 1.8), text: tr(text).into(), size: 1.6, anchor: Anchor::Left, label: true, max_width: 0.0 }); } fn value(items: &mut Vec, x: f32, y: f32, text: &str, size: f32, max_width: f32) { @@ -248,10 +249,10 @@ pub fn placeholder(prj: &Project, page_i: usize, name: &str) -> Option { "page.function" => page.function.clone(), "page.location" => page.location.clone(), "page.type" => match page.kind { - PageKind::Schematic => "Schematic", - PageKind::Cover => "Cover", - PageKind::Report(_) => "Report", - PageKind::Mounting(_) => "Mounting", + PageKind::Schematic => tr("Schematic"), + PageKind::Cover => tr("Cover"), + PageKind::Report(_) => tr("Report"), + PageKind::Mounting(_) => tr("Mounting"), } .into(), "sheet" => (page_i + 1).to_string(), @@ -267,28 +268,28 @@ pub fn placeholder(prj: &Project, page_i: usize, name: &str) -> Option { /// Placeholders offered in the title block editor: (placeholder, meaning). pub const PLACEHOLDERS: [(&str, &str); 22] = [ - ("{project}", "Project name"), - ("{project.description}", "Project description"), - ("{company}", "Company"), - ("{creator}", "Created by"), - ("{date}", "Date"), - ("{revision}", "Project revision"), - ("{software}", "OpenECraft"), - ("{page}", "Full page name (=A1+CAB1/3)"), - ("{page.name}", "Page number"), - ("{page.description}", "Page description"), - ("{page.structure}", "Page structure (=A1+CAB1)"), - ("{page.function}", "Function of the page"), - ("{page.location}", "Location of the page"), - ("{page.type}", "Page type"), - ("{sheet}", "Sheet number"), - ("{sheets}", "Number of sheets"), - ("{rev.name}", "Last revision"), - ("{rev.date}", "Date of the last revision"), - ("{rev.author}", "Author of the last revision"), - ("{rev.description}", "Description of the last revision"), + ("{project}", tr_const!("Project name")), + ("{project.description}", tr_const!("Project description")), + ("{company}", tr_const!("Company")), + ("{creator}", tr_const!("Created by")), + ("{date}", tr_const!("Date")), + ("{revision}", tr_const!("Project revision")), + ("{software}", tr_const!("OpenECraft")), + ("{page}", tr_const!("Full page name (=A1+CAB1/3)")), + ("{page.name}", tr_const!("Page number")), + ("{page.description}", tr_const!("Page description")), + ("{page.structure}", tr_const!("Page structure (=A1+CAB1)")), + ("{page.function}", tr_const!("Function of the page")), + ("{page.location}", tr_const!("Location of the page")), + ("{page.type}", tr_const!("Page type")), + ("{sheet}", tr_const!("Sheet number")), + ("{sheets}", tr_const!("Number of sheets")), + ("{rev.name}", tr_const!("Last revision")), + ("{rev.date}", tr_const!("Date of the last revision")), + ("{rev.author}", tr_const!("Author of the last revision")), + ("{rev.description}", tr_const!("Description of the last revision")), ("{prop:Name}", "Project property \"Name\""), - ("{{ }}", "Literal braces"), + ("{{ }}", tr_const!("Literal braces")), ]; /// Replaces the placeholders of a text; unknown ones stay as they are. diff --git a/src/glyphs/tests.rs b/src/glyphs/tests.rs index 484ac5ce..02a6042c 100644 --- a/src/glyphs/tests.rs +++ b/src/glyphs/tests.rs @@ -61,3 +61,26 @@ fn scanner_finds_literals_and_skips_comments() { let found: String = literal_chars(src).into_iter().map(|(_, c)| c).collect(); assert_eq!(found, "x→y✔ϑ"); } + +#[test] +fn translations_only_use_characters_of_the_bundled_fonts() { + let mut fonts = Fonts::new(TextOptions::default(), FontDefinitions::default()); + let font = FontId::new(14.0, FontFamily::Proportional); + let mut missing: BTreeMap = BTreeMap::new(); + let mut checked = 0; + for entry in openecraft_i18n::catalog_entries() { + for text in entry { + for c in text.chars().filter(|c| !c.is_ascii() && !c.is_whitespace()) { + checked += 1; + if !fonts.has_glyph(&font, c) { + missing.entry(c).or_insert_with(|| entry[0].to_string()); + } + } + } + } + assert!(checked > 100, "no non-ASCII characters in the catalog – check broken?"); + let report: Vec = missing.iter().map(|(c, text)| format!("'{c}' (U+{:04X}) in the translation of {text:?}", *c as u32)).collect(); + assert!(missing.is_empty(), "translation characters without glyph in the bundled fonts: +{}", report.join(" +")); +} diff --git a/src/io.rs b/src/io.rs index d5e0749a..21894629 100644 --- a/src/io.rs +++ b/src/io.rs @@ -2,6 +2,7 @@ //! implemented in `openecraft_ui::io`. pub use openecraft_ui::io::short_name; +use openecraft_i18n::tr; use openecraft_ui::io::FileKind; use openecraft_ui::part_editor::ModelKind; @@ -26,13 +27,13 @@ pub enum Purpose { impl FileKind for Purpose { fn filter(self) -> (&'static str, &'static [&'static str]) { match self { - Purpose::Project => ("OpenECraft project", &[PROJECT_EXT, "json"]), - Purpose::Parts => ("Parts (CSV, JSON)", &["csv", "json", "txt"]), + Purpose::Project => (tr("OpenECraft project"), &[PROJECT_EXT, "json"]), + Purpose::Parts => (tr("Parts (CSV, JSON)"), &["csv", "json", "txt"]), Purpose::Model(kind) => kind.filter(), - Purpose::Macros => ("OpenECraft macros (JSON)", &["json"]), + Purpose::Macros => (tr("OpenECraft macros (JSON)"), &["json"]), Purpose::PlcTable => ("PLC symbol table (CSV)", &["csv", "txt"]), - Purpose::Symbols => ("OpenECraft symbol library (JSON)", &["json"]), - Purpose::Forms => ("OpenECraft title blocks (JSON)", &["json"]), + Purpose::Symbols => (tr("OpenECraft symbol library (JSON)"), &["json"]), + Purpose::Forms => (tr("OpenECraft title blocks (JSON)"), &["json"]), } } } diff --git a/src/macros.rs b/src/macros.rs index e262158c..ba5e728c 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -2,6 +2,7 @@ //! macro a complete page. Placeholders `{NAME}` in tags, texts, function texts, //! designations and connection points are filled from value sets when inserting. +use openecraft_i18n::tr_fmt; use crate::model::*; use crate::ops::{self, Clip}; use serde::{Deserialize, Serialize}; @@ -125,7 +126,7 @@ impl Macro { /// Number of symbols / wires / texts and graphics. pub fn summary(&self) -> String { let c = &self.clip; - format!("{} symbols, {} wires, {} texts / graphics", c.symbols.len(), c.wires.len(), c.texts.len() + c.shapes.len()) + tr_fmt!("{} symbols, {} wires, {} texts / graphics", c.symbols.len(), c.wires.len(), c.texts.len() + c.shapes.len()) } } diff --git a/src/main.rs b/src/main.rs index 681870ef..977527c2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -57,6 +57,9 @@ fn main() -> eframe::Result { fn main() { use wasm_bindgen::JsCast; eframe::WebLogger::init(log::LevelFilter::Info).ok(); + if let Some(lang) = web_sys::window().and_then(|w| w.navigator().language()).and_then(|code| openecraft_i18n::Lang::from_code(&code)) { + openecraft_i18n::set_lang(lang); + } wasm_bindgen_futures::spawn_local(async { let document = web_sys::window().expect("no window").document().expect("no document"); let canvas = document diff --git a/src/model.rs b/src/model.rs index 3348bd5a..9ed2891e 100644 --- a/src/model.rs +++ b/src/model.rs @@ -4,6 +4,7 @@ //! tag belong to the same device: one *main function* (e.g. the coil) and any number //! of *auxiliary functions* (e.g. its contacts). Cross references are derived from that. +use openecraft_i18n::{tr, tr_fmt}; use crate::geom::{p, P}; pub use crate::panel::Layout; pub use openecraft_parts::natural_cmp; @@ -142,10 +143,10 @@ pub enum PageKind { impl PageKind { pub fn label(self) -> String { match self { - PageKind::Schematic => "Schematic (multi-line)".into(), - PageKind::Cover => "Cover sheet".into(), - PageKind::Report(r) => format!("Report: {}", r.title()), - PageKind::Mounting(_) => "Mounting layout".into(), + PageKind::Schematic => tr("Schematic (multi-line)").into(), + PageKind::Cover => tr("Cover sheet").into(), + PageKind::Report(r) => tr_fmt!("Report: {}", r.title()), + PageKind::Mounting(_) => tr("Mounting layout").into(), } } } @@ -184,18 +185,18 @@ impl ReportKind { pub fn title(self) -> &'static str { match self { - ReportKind::TableOfContents => "Table of contents", - ReportKind::DeviceList => "Device list", - ReportKind::BillOfMaterials => "Bill of materials", - ReportKind::TerminalDiagram => "Terminal diagram", - ReportKind::ConnectionList => "Connection list", - ReportKind::PlcAssignment => "PLC assignment list", - ReportKind::PotentialList => "Potential overview", - ReportKind::PanelWiring => "Wire list (panel routing)", - ReportKind::CableOverview => "Cable overview", - ReportKind::CableDiagram => "Cable diagram", - ReportKind::RevisionOverview => "Revision overview (changes)", - ReportKind::HarnessData => "Harness data", + ReportKind::TableOfContents => tr("Table of contents"), + ReportKind::DeviceList => tr("Device list"), + ReportKind::BillOfMaterials => tr("Bill of materials"), + ReportKind::TerminalDiagram => tr("Terminal diagram"), + ReportKind::ConnectionList => tr("Connection list"), + ReportKind::PlcAssignment => tr("PLC assignment list"), + ReportKind::PotentialList => tr("Potential overview"), + ReportKind::PanelWiring => tr("Wire list (panel routing)"), + ReportKind::CableOverview => tr("Cable overview"), + ReportKind::CableDiagram => tr("Cable diagram"), + ReportKind::RevisionOverview => tr("Revision overview (changes)"), + ReportKind::HarnessData => tr("Harness data"), } } } @@ -353,9 +354,9 @@ impl NumberScheme { pub fn title(self) -> &'static str { match self { - NumberScheme::Sequential => "Sequential (1, 2, 3 …)", - NumberScheme::PageColumn => "Page / column (3.4.1)", - NumberScheme::Potential => "Potential name (L1, +24V, otherwise counted)", + NumberScheme::Sequential => tr("Sequential (1, 2, 3 …)"), + NumberScheme::PageColumn => tr("Page / column (3.4.1)"), + NumberScheme::Potential => tr("Potential name (L1, +24V, otherwise counted)"), } } } diff --git a/src/panel.rs b/src/panel.rs index 6dfec4f8..4995551e 100644 --- a/src/panel.rs +++ b/src/panel.rs @@ -8,6 +8,7 @@ //! door's front view: origin at the top left corner of the enclosure front, `z` is the //! distance behind the door. +use openecraft_i18n::tr; use crate::geom::{p, P, R}; use crate::model::Project; use crate::netlist::{connections, Netlist}; @@ -52,8 +53,8 @@ pub enum Face { impl Face { pub fn title(self) -> &'static str { match self { - Face::Plate => "Mounting plate", - Face::Door => "Door", + Face::Plate => tr("Mounting plate"), + Face::Door => tr("Door"), } } @@ -85,11 +86,11 @@ pub enum ItemKind { impl ItemKind { pub fn title(self) -> &'static str { match self { - ItemKind::Device => "Device", - ItemKind::Rail => "Mounting rail", - ItemKind::Duct => "Cable duct", - ItemKind::Busbar => "Busbar system", - ItemKind::Cutout => "Cutout", + ItemKind::Device => tr("Device"), + ItemKind::Rail => tr("Mounting rail"), + ItemKind::Duct => tr("Cable duct"), + ItemKind::Busbar => tr("Busbar system"), + ItemKind::Cutout => tr("Cutout"), } } diff --git a/src/panel_ui.rs b/src/panel_ui.rs index e52648b0..e5336e37 100644 --- a/src/panel_ui.rs +++ b/src/panel_ui.rs @@ -1,6 +1,7 @@ //! Panel layout workspace: enclosure navigator, 2D mounting plate editor, 3D view //! and property editor. +use openecraft_i18n::{tr, tr_fmt}; use crate::editor::{EguiDraw, Palette}; use crate::geom::{p, P}; use crate::model::{natural_cmp, Project}; @@ -142,9 +143,9 @@ impl PanelUi { self.select_wire(w.key()); self.status = if candidates.len() > 1 { let pos = candidates.iter().position(|c| *c == i).unwrap_or(0) + 1; - format!("Wire {} – {} ({pos} of {} here, click again for the next)", w.from, w.to, candidates.len()) + tr_fmt!("Wire {} – {} ({} of {} here, click again for the next)", w.from, w.to, pos, candidates.len()) } else { - format!("Wire {} – {} {:.0} mm", w.from, w.to, w.length) + tr_fmt!("Wire {} – {} {} mm", w.from, w.to, format!("{:.0}", w.length)) }; } } @@ -179,8 +180,8 @@ impl PanelUi { pub fn navigator(&mut self, ui: &mut egui::Ui, prj: &mut Project, db: &PartsDb) { ui.horizontal(|ui| { - ui.heading("Enclosures"); - if ui.button("➕").on_hover_text("New enclosure").clicked() { + ui.heading(tr("Enclosures")); + if ui.button("➕").on_hover_text(tr("New enclosure")).clicked() { let part = if db.get(panel::ENCLOSURE_PART).is_some() { panel::ENCLOSURE_PART } else { "" }; let mut ne = NewEnclosure { name: format!("+CAB{}", prj.layout.enclosures.len() + 1), @@ -202,7 +203,7 @@ impl PanelUi { self.selection.clear(); self.fit_pending = true; } - if ui.small_button("🗑").on_hover_text("Delete enclosure").clicked() { + if ui.small_button("🗑").on_hover_text(tr("Delete enclosure")).clicked() { remove = Some(i); } }); @@ -212,12 +213,12 @@ impl PanelUi { self.selection.clear(); } if prj.layout.enclosures.is_empty() { - ui.weak("No enclosure yet – create one with ➕."); + ui.weak(tr("No enclosure yet – create one with ➕.")); return; } ui.separator(); - ui.heading("Devices to place"); - ui.add(egui::TextEdit::singleline(&mut self.device_filter).hint_text("Filter…")); + ui.heading(tr("Devices to place")); + ui.add(egui::TextEdit::singleline(&mut self.device_filter).hint_text(tr("Filter…"))); let todo = panel::devices_to_place(prj); let f = self.device_filter.to_lowercase(); egui::ScrollArea::vertical().id_salt("todo").max_height(ui.available_height() * 0.5).auto_shrink([false, true]).show(ui, |ui| { @@ -232,17 +233,17 @@ impl PanelUi { } } if todo.is_empty() { - ui.weak("All devices with mounting data are placed."); + ui.weak(tr("All devices with mounting data are placed.")); } }); ui.separator(); - ui.heading("Placed"); + ui.heading(tr("Placed")); let Some(ei) = self.enclosure_index(prj) else { return }; let mut placed: Vec<&PanelItem> = prj.layout.enclosures[ei].items.iter().filter(|i| i.kind == ItemKind::Device).collect(); placed.sort_by(|a, b| natural_cmp(&a.tag, &b.tag)); egui::ScrollArea::vertical().id_salt("placed").auto_shrink([false, false]).show(ui, |ui| { for it in placed { - let text = if it.face == Face::Door { format!("{} (door)", it.tag) } else { it.tag.clone() }; + let text = if it.face == Face::Door { tr_fmt!("{} (door)", it.tag) } else { it.tag.clone() }; if ui.selectable_label(self.selection.contains(&it.id), text).clicked() { self.face = it.face; self.select_item(it.id); @@ -254,7 +255,7 @@ impl PanelUi { // ------------------------------------------------------------------ properties pub fn properties(&mut self, ui: &mut egui::Ui, prj: &mut Project, an: &Analysis) { - ui.heading("Properties"); + ui.heading(tr("Properties")); let Some(ei) = self.enclosure_index(prj) else { return }; if let Some(wi) = self.wire_index(an) { self.wire_properties(ui, prj, an, wi); @@ -262,12 +263,12 @@ impl PanelUi { } let sel: Vec = self.selection.iter().copied().collect(); if sel.len() > 1 { - ui.label(format!("{} items selected", sel.len())); + ui.label(tr_fmt!("{} items selected", sel.len())); ui.horizontal(|ui| { - if ui.button("⟳ Rotate").clicked() { + if ui.button(tr("⟳ Rotate")).clicked() { rotate(&mut prj.layout.enclosures[ei], &self.selection); } - if ui.button("🗑 Delete").clicked() { + if ui.button(tr("🗑 Delete")).clicked() { prj.layout.enclosures[ei].items.retain(|i| !self.selection.contains(&i.id)); self.selection.clear(); } @@ -284,16 +285,16 @@ impl PanelUi { ui.label(RichText::new(it.kind.title()).strong()); egui::Grid::new("pitem").num_columns(2).spacing([10.0, 5.0]).show(ui, |ui| { if it.kind == ItemKind::Device { - ui.label("Device"); + ui.label(tr("Device")); ui.horizontal(|ui| { ui.label(RichText::new(&it.tag).monospace().strong()); - if ui.small_button("Show in schematic").clicked() { + if ui.small_button(tr("Show in schematic")).clicked() { self.goto_schematic = Some(it.tag.clone()); } }); ui.end_row(); } - ui.label("Part"); + ui.label(tr("Part")); ui.label(RichText::new(if it.part.is_empty() { "–" } else { &it.part }).monospace()); ui.end_row(); ui.label("X / Y"); @@ -303,17 +304,17 @@ impl PanelUi { }); ui.end_row(); if it.kind == ItemKind::Device { - ui.label("Width × height"); + ui.label(tr("Width × height")); ui.horizontal(|ui| { ui.add(egui::DragValue::new(&mut it.w).speed(0.5).range(1.0..=5000.0)); ui.add(egui::DragValue::new(&mut it.h).speed(0.5).range(1.0..=5000.0)); }); ui.end_row(); - ui.label("Mounted on"); + ui.label(tr("Mounted on")); let before = it.face; ui.horizontal(|ui| { - ui.selectable_value(&mut it.face, Face::Plate, "Mounting plate"); - ui.selectable_value(&mut it.face, Face::Door, "Door"); + ui.selectable_value(&mut it.face, Face::Plate, tr("Mounting plate")); + ui.selectable_value(&mut it.face, Face::Door, tr("Door")); }); if it.face != before { // Keep the position in front view; door devices sit directly on the door. @@ -324,26 +325,26 @@ impl PanelUi { self.face = it.face; } ui.end_row(); - ui.label("Depth / mounted at"); + ui.label(tr("Depth / mounted at")); ui.horizontal(|ui| { ui.add(egui::DragValue::new(&mut it.d).speed(0.5).range(1.0..=2000.0)); ui.add(egui::DragValue::new(&mut it.z).speed(0.5).range(0.0..=2000.0).prefix("z ")); }); ui.end_row(); } else if it.kind == ItemKind::Cutout { - ui.label("Shape"); + ui.label(tr("Shape")); ui.horizontal(|ui| { - ui.selectable_value(&mut it.round, false, "Rectangular"); - ui.selectable_value(&mut it.round, true, "Round"); + ui.selectable_value(&mut it.round, false, tr("Rectangular")); + ui.selectable_value(&mut it.round, true, tr("Round")); }); ui.end_row(); if it.round { - ui.label("Diameter"); + ui.label(tr("Diameter")); if ui.add(egui::DragValue::new(&mut it.w).speed(0.5).range(1.0..=2000.0).suffix(" mm")).changed() { it.h = it.w; } } else { - ui.label("Width × height"); + ui.label(tr("Width × height")); ui.horizontal(|ui| { ui.add(egui::DragValue::new(&mut it.w).speed(0.5).range(1.0..=5000.0)); ui.add(egui::DragValue::new(&mut it.h).speed(0.5).range(1.0..=5000.0)); @@ -354,7 +355,7 @@ impl PanelUi { it.h = it.w; } } else { - ui.label("Length"); + ui.label(tr("Length")); let mut len = it.length(); if ui.add(egui::DragValue::new(&mut len).speed(5.0).range(10.0..=5000.0).suffix(" mm")).changed() { if it.horizontal() { @@ -364,16 +365,16 @@ impl PanelUi { } } ui.end_row(); - ui.label("Orientation"); + ui.label(tr("Orientation")); ui.label(if it.horizontal() { "horizontal" } else { "vertical" }); ui.end_row(); } }); ui.horizontal(|ui| { - if ui.button("⟳ Rotate").on_hover_text("R").clicked() { + if ui.button(tr("⟳ Rotate")).on_hover_text("R").clicked() { it.rotate(); } - if ui.button("🗑 Delete").on_hover_text("Del").clicked() { + if ui.button(tr("🗑 Delete")).on_hover_text(tr("Del")).clicked() { self.selection.clear(); } }); @@ -387,11 +388,11 @@ impl PanelUi { let wires: Vec<_> = an.wiring.iter().filter(|w| w.items.0 == it.id || w.items.1 == it.id).collect(); if !wires.is_empty() { ui.separator(); - ui.label(RichText::new("Wires").strong()); + ui.label(RichText::new(tr("Wires")).strong()); let mut clicked = None; egui::Grid::new("pwires").striped(true).num_columns(2).show(ui, |ui| { for w in wires { - if ui.selectable_label(false, format!("{} – {}", w.from, w.to)).on_hover_text("Show this wire").clicked() { + if ui.selectable_label(false, format!("{} – {}", w.from, w.to)).on_hover_text(tr("Show this wire")).clicked() { clicked = Some(w.key()); } ui.label(format!("{:.0} mm", w.length)); @@ -407,94 +408,94 @@ impl PanelUi { } // Enclosure properties let e = &mut prj.layout.enclosures[ei]; - ui.label(RichText::new("Enclosure").strong()); + ui.label(RichText::new(tr("Enclosure")).strong()); egui::Grid::new("penc").num_columns(2).spacing([10.0, 5.0]).show(ui, |ui| { - ui.label("Location"); + ui.label(tr("Location")); ui.text_edit_singleline(&mut e.name); ui.end_row(); - ui.label("Part"); + ui.label(tr("Part")); ui.label(RichText::new(if e.part.is_empty() { "–" } else { &e.part }).monospace()); ui.end_row(); - ui.label("Width × height"); + ui.label(tr("Width × height")); ui.horizontal(|ui| { ui.add(egui::DragValue::new(&mut e.width).speed(5.0).range(100.0..=5000.0)); ui.add(egui::DragValue::new(&mut e.height).speed(5.0).range(100.0..=5000.0)); }); ui.end_row(); - ui.label("Depth"); + ui.label(tr("Depth")); ui.add(egui::DragValue::new(&mut e.depth).speed(5.0).range(60.0..=2000.0).suffix(" mm")); ui.end_row(); - ui.label("Door clearance"); + ui.label(tr("Door clearance")); ui.add(egui::DragValue::new(&mut e.door_clearance).speed(1.0).range(0.0..=500.0).suffix(" mm")) - .on_hover_text("Space behind the door that devices must keep free (door-mounted devices, handles)"); + .on_hover_text(tr("Space behind the door that devices must keep free (door-mounted devices, handles)")); ui.end_row(); let (pw, ph) = e.plate_size(); - ui.label("Mounting plate"); + ui.label(tr("Mounting plate")); ui.label(format!("{pw:.0} × {ph:.0} mm")); ui.end_row(); }); ui.horizontal(|ui| { - ui.label("Wire reserve per connection"); + ui.label(tr("Wire reserve per connection")); ui.add(egui::DragValue::new(&mut prj.layout.wire_reserve).speed(5.0).range(0.0..=2000.0).suffix(" mm")); }); - ui.checkbox(&mut prj.layout.ferrules, "Wire ends with ferrules").on_hover_text("Production wire list and bill of materials"); + ui.checkbox(&mut prj.layout.ferrules, tr("Wire ends with ferrules")).on_hover_text(tr("Production wire list and bill of materials")); let e = &prj.layout.enclosures[ei]; let devices = e.items.iter().filter(|i| i.kind == ItemKind::Device).count(); let wires: Vec<_> = an.wiring.iter().filter(|w| w.enclosure == ei).collect(); let total: f32 = wires.iter().map(|w| w.length).sum(); ui.separator(); - ui.label(format!("{devices} devices placed, {} wires routed ({:.1} m)", wires.len(), total / 1000.0)); + ui.label(tr_fmt!("{} devices placed, {} wires routed ({} m)", devices, wires.len(), format!("{:.1}", total / 1000.0))); let problems = panel::collisions(e, &prj.parts).len() + panel::outside(e).len() + crate::production::clearance_violations(e, &prj.parts).len(); let holes = crate::production::holes(e, &prj.parts).len(); let cutouts = e.items.iter().filter(|i| i.kind == ItemKind::Cutout).count(); - ui.label(format!("Mounting plate: {holes} holes, {cutouts} cutouts")); + ui.label(tr_fmt!("Mounting plate: {} holes, {} cutouts", holes, cutouts)); ui.horizontal(|ui| { - if ui.button("⬇ NC data (DXF)").on_hover_text("Plate outline, holes per diameter, cutouts").clicked() { + if ui.button(tr("⬇ NC data (DXF)")).on_hover_text(tr("Plate outline, holes per diameter, cutouts")).clicked() { self.export = Some((ei, Face::Plate, true)); } - if ui.button("⬇ Drilling list (CSV)").clicked() { + if ui.button(tr("⬇ Drilling list (CSV)")).clicked() { self.export = Some((ei, Face::Plate, false)); } }); let door_devices = e.items.iter().filter(|i| i.face == Face::Door && i.kind == ItemKind::Device).count(); - ui.label(format!("Door: {door_devices} devices, {} cutouts", crate::production::openings(e, &prj.parts, Face::Door).len())); + ui.label(tr_fmt!("Door: {} devices, {} cutouts", door_devices, crate::production::openings(e, &prj.parts, Face::Door).len())); ui.horizontal(|ui| { - if ui.button("⬇ Door NC data (DXF)").clicked() { + if ui.button(tr("⬇ Door NC data (DXF)")).clicked() { self.export = Some((ei, Face::Door, true)); } - if ui.button("⬇ Door cutouts (CSV)").clicked() { + if ui.button(tr("⬇ Door cutouts (CSV)")).clicked() { self.export = Some((ei, Face::Door, false)); } }); if problems > 0 { - ui.colored_label(Color32::from_rgb(220, 60, 60), format!("{problems} placement problems (red) – see Check")); + ui.colored_label(Color32::from_rgb(220, 60, 60), tr_fmt!("{} placement problems (red) – see Check", problems)); } - if ui.button("➕ Insert mounting layout page").clicked() { + if ui.button(tr("➕ Insert mounting layout page")).clicked() { self.add_page = Some(e.id); } } fn wire_properties(&mut self, ui: &mut egui::Ui, prj: &Project, an: &Analysis, wi: usize) { let w = &an.wiring[wi]; - ui.label(RichText::new("Wire").strong()); + ui.label(RichText::new(tr("Wire")).strong()); egui::Grid::new("pwire").num_columns(2).spacing([10.0, 5.0]).show(ui, |ui| { - ui.label("From"); + ui.label(tr("From")); ui.label(RichText::new(&w.from).monospace().color(WIRE_HIGHLIGHT)); ui.end_row(); - ui.label("To"); + ui.label(tr("To")); ui.label(RichText::new(&w.to).monospace().color(WIRE_HIGHLIGHT)); ui.end_row(); - ui.label("Potential"); + ui.label(tr("Potential")); ui.label(&w.net); ui.end_row(); - ui.label("Length"); + ui.label(tr("Length")); ui.label(format!("{:.0} mm", w.length)); ui.end_row(); - ui.label("Routing"); + ui.label(tr("Routing")); ui.label(if w.route.via_ducts { "via cable ducts" } else { "direct (no ducts)" }); ui.end_row(); if !w.color.is_empty() || !w.cross_section.is_empty() { - ui.label("Colour / cross-section"); + ui.label(tr("Colour / cross-section")); ui.label(format!("{} {}", w.color, w.cross_section)); ui.end_row(); } @@ -504,16 +505,16 @@ impl PanelUi { w.route.plate_length, prj.layout.wire_reserve )).weak()); ui.separator(); - ui.label(RichText::new("Connected devices").strong()); + ui.label(RichText::new(tr("Connected devices")).strong()); let e = &prj.layout.enclosures[w.enclosure]; let mut select = None; for id in [w.items.0, w.items.1] { if let Some(it) = e.item(id) { ui.horizontal(|ui| { - if ui.link(RichText::new(&it.tag).monospace()).on_hover_text("Select device").clicked() { + if ui.link(RichText::new(&it.tag).monospace()).on_hover_text(tr("Select device")).clicked() { select = Some(id); } - if ui.small_button("Show in schematic").clicked() { + if ui.small_button(tr("Show in schematic")).clicked() { self.goto_schematic = Some(it.tag.clone()); } }); @@ -536,18 +537,18 @@ impl PanelUi { .chain(prj.parts.iter()) .filter(|p| p.subgroup == "Enclosure" && p.width > 0.0) .collect(); - egui::Window::new("New enclosure").open(&mut open).resizable(false).collapsible(false).show(ctx, |ui| { + egui::Window::new(tr("New enclosure")).open(&mut open).resizable(false).collapsible(false).show(ctx, |ui| { egui::Grid::new("newenc").num_columns(2).spacing([10.0, 6.0]).show(ui, |ui| { - ui.label("Location"); + ui.label(tr("Location")); ui.text_edit_singleline(&mut ne.name); ui.end_row(); - ui.label("Part"); + ui.label(tr("Part")); let before = ne.part.clone(); egui::ComboBox::from_id_salt("encpart") .selected_text(if ne.part.is_empty() { "(custom size)".to_string() } else { ne.part.clone() }) .width(220.0) .show_ui(ui, |ui| { - ui.selectable_value(&mut ne.part, String::new(), "(custom size)"); + ui.selectable_value(&mut ne.part, String::new(), tr("(custom size)")); for p in &enclosures { ui.selectable_value(&mut ne.part, p.number.clone(), format!("{} – {}", p.number, p.description)); } @@ -557,7 +558,7 @@ impl PanelUi { } ui.end_row(); let custom = ne.part.is_empty(); - ui.label("Width × height × depth"); + ui.label(tr("Width × height × depth")); ui.add_enabled_ui(custom, |ui| { ui.horizontal(|ui| { ui.add(egui::DragValue::new(&mut ne.width).speed(5.0).range(100.0..=5000.0)); @@ -567,7 +568,7 @@ impl PanelUi { }); ui.end_row(); }); - if ui.button("✔ Create").clicked() { + if ui.button(tr("✔ Create")).clicked() { create = true; } }); @@ -596,12 +597,12 @@ impl PanelUi { pub fn canvas(&mut self, ui: &mut egui::Ui, prj: &mut Project, an: &Analysis, db: &PartsDb) { let Some(ei) = self.enclosure_index(prj) else { ui.centered_and_justified(|ui| { - ui.label("Create an enclosure (➕ in the navigator on the left) to start the panel layout."); + ui.label(tr("Create an enclosure (➕ in the navigator on the left) to start the panel layout.")); }); return; }; ui.horizontal(|ui| { - ui.selectable_value(&mut self.view, View::Front, "Front view (2D)"); + ui.selectable_value(&mut self.view, View::Front, tr("Front view (2D)")); ui.selectable_value(&mut self.view, View::ThreeD, "3D"); ui.separator(); if self.view == View::Front { @@ -619,11 +620,11 @@ impl PanelUi { ui.separator(); let tool = self.tool.clone(); for (t, label, tip) in [ - (Tool::Select, "⬉ Select", "Select / move (Esc)"), - (Tool::Rail, "Mounting rail", "Click start and end point"), - (Tool::Duct, "Cable duct", "Click start and end point"), - (Tool::Busbar, "Busbar", "Copper busbar system: click start and end point"), - (Tool::Cutout, "Cutout", "Opening in the mounting plate / door: click two corners (round: in the properties)"), + (Tool::Select, tr("⬉ Select"), tr("Select / move (Esc)")), + (Tool::Rail, tr("Mounting rail"), tr("Click start and end point")), + (Tool::Duct, tr("Cable duct"), tr("Click start and end point")), + (Tool::Busbar, tr("Busbar"), tr("Copper busbar system: click start and end point")), + (Tool::Cutout, tr("Cutout"), tr("Opening in the mounting plate / door: click two corners (round: in the properties)")), ] { if self.face == Face::Door && t.profile().is_some() { continue; @@ -633,12 +634,12 @@ impl PanelUi { } } if let Tool::PlaceDevice(tag) = &tool { - ui.label(RichText::new(format!("Placing {tag}")).strong()); + ui.label(RichText::new(tr_fmt!("Placing {}", tag)).strong()); } ui.separator(); } - ui.checkbox(&mut self.show_wires, "Wires"); - if ui.button("⛶ Fit").clicked() { + ui.checkbox(&mut self.show_wires, tr("Wires")); + if ui.button(tr("⛶ Fit")).clicked() { self.fit_pending = true; self.cam = None; } @@ -818,7 +819,7 @@ impl PanelUi { (Tool::Cutout, Some(sn), _) => { if let Some(a) = self.start { g.rect(a + m, sn + m, 0.5, Ink::Ghost, false); - self.status = format!("Cutout {:.0} × {:.0} mm", (sn.x - a.x).abs(), (sn.y - a.y).abs()); + self.status = tr_fmt!("Cutout {} × {} mm", format!("{:.0}", (sn.x - a.x).abs()), format!("{:.0}", (sn.y - a.y).abs())); } let c = to_screen(sn); painter.line_segment([c - vec2(8.0, 0.0), c + vec2(8.0, 0.0)], Stroke::new(1.0, pal.ghost)); @@ -836,7 +837,7 @@ impl PanelUi { }; g.rect(r0 + m, r1 + m, 0.5, Ink::Ghost, false); let len = if horizontal { (sn.x - a.x).abs() } else { (sn.y - a.y).abs() }; - self.status = format!("Length {len:.0} mm"); + self.status = tr_fmt!("Length {} mm", format!("{len:.0}")); } let c = to_screen(sn); painter.line_segment([c - vec2(8.0, 0.0), c + vec2(8.0, 0.0)], Stroke::new(1.0, pal.ghost)); @@ -853,7 +854,7 @@ impl PanelUi { } if let Some(q) = plate { if self.start.is_none() && !resp.clicked() { - self.status = format!("X {:.0} Y {:.0} mm on the {}", q.x, q.y, self.face.title().to_lowercase()); + self.status = tr_fmt!("X {} Y {} mm on the {}", format!("{:.0}", q.x), format!("{:.0}", q.y), self.face.title().to_lowercase()); } } } @@ -1217,7 +1218,7 @@ impl PanelUi { painter.text( rect.left_bottom() + vec2(10.0, -10.0), egui::Align2::LEFT_BOTTOM, - "Drag: orbit · right/middle drag: pan · wheel: zoom · click: select device or wire", + tr("Drag: orbit · right/middle drag: pan · wheel: zoom · click: select device or wire"), egui::FontId::proportional(12.0), if dark { Color32::GRAY } else { Color32::DARK_GRAY }, ); diff --git a/src/parts_ui.rs b/src/parts_ui.rs index bbda5127..f4be1a46 100644 --- a/src/parts_ui.rs +++ b/src/parts_ui.rs @@ -1,6 +1,7 @@ //! Parts management window and part selection dialog. The part widgets are shared //! with the parts manager (`openecraft_ui::part_editor`). +use openecraft_i18n::{tr, tr_fmt}; use crate::model::Project; use crate::parts::{self, Part, PartRef, PartsDb}; use crate::io::{Loaded, Purpose}; @@ -72,7 +73,7 @@ impl PartsUi { Source::Database => &mut db.parts, Source::Project => &mut prj.parts, }; - let part = list.iter_mut().find(|p| p.number == number).ok_or(format!("part {number} not found"))?; + let part = list.iter_mut().find(|p| p.number == number).ok_or(tr_fmt!("part {} not found", number))?; pe::apply_model(part, kind, &loaded.name, &loaded.bytes) } @@ -84,7 +85,7 @@ impl PartsUi { if let Reply::Parts(Ok(list)) = reply { let n = list.parts.len(); let (added, updated) = db.merge(list.parts); - self.server.status = format!("Downloaded {n} parts (revision {}): {added} new, {updated} updated", list.revision); + self.server.status = tr_fmt!("Downloaded {} parts (revision {}): {} new, {} updated", n, list.revision, added, updated); } message = Some(self.server.status.clone()); } @@ -95,34 +96,34 @@ impl PartsUi { fn server_panel(&mut self, ui: &mut egui::Ui, db: &PartsDb, selected: Option) { let ctx = ui.ctx().clone(); egui::Grid::new("server").num_columns(2).spacing([10.0, 6.0]).show(ui, |ui| { - ui.label("Server URL"); + ui.label(tr("Server URL")); ui.add(egui::TextEdit::singleline(&mut self.server.url).desired_width(320.0)); ui.end_row(); - ui.label("Access token"); - ui.add(egui::TextEdit::singleline(&mut self.server.token).password(true).desired_width(320.0).hint_text("only needed for uploads")); + ui.label(tr("Access token")); + ui.add(egui::TextEdit::singleline(&mut self.server.token).password(true).desired_width(320.0).hint_text(tr("only needed for uploads"))); ui.end_row(); }); let busy = self.server.busy(); ui.horizontal_wrapped(|ui| { - if ui.add_enabled(!busy, egui::Button::new("Test connection")).clicked() { + if ui.add_enabled(!busy, egui::Button::new(tr("Test connection"))).clicked() { self.server.check(&ctx); } if ui - .add_enabled(!busy, egui::Button::new("⬇ Download into database")) - .on_hover_text("Adds new parts and updates existing ones in the local parts database") + .add_enabled(!busy, egui::Button::new(tr("⬇ Download into database"))) + .on_hover_text(tr("Adds new parts and updates existing ones in the local parts database")) .clicked() { self.server.download(&ctx); } - let upload_one = ui.add_enabled(!busy && selected.is_some(), egui::Button::new("⬆ Upload selected part")); + let upload_one = ui.add_enabled(!busy && selected.is_some(), egui::Button::new(tr("⬆ Upload selected part"))); if upload_one.clicked() { if let Some(p) = &selected { self.server.upload(&ctx, std::slice::from_ref(p)); } } if ui - .add_enabled(!busy && !db.parts.is_empty(), egui::Button::new(format!("⬆ Upload database ({})", db.parts.len()))) - .on_hover_text("Adds / replaces all parts of the local database on the server") + .add_enabled(!busy && !db.parts.is_empty(), egui::Button::new(tr_fmt!("⬆ Upload database ({})", db.parts.len()))) + .on_hover_text(tr("Adds / replaces all parts of the local database on the server")) .clicked() { self.server.upload(&ctx, &db.parts); @@ -157,36 +158,36 @@ impl PartsUi { return actions; } let mut open = true; - egui::Window::new("Parts management").open(&mut open).default_size([1000.0, 620.0]).show(ctx, |ui| { + egui::Window::new(tr("Parts management")).open(&mut open).default_size([1000.0, 620.0]).show(ctx, |ui| { // ---------------------------------------------------------- toolbar ui.horizontal(|ui| { - ui.selectable_value(&mut self.source, Source::Database, "🗄 Parts database"); - ui.selectable_value(&mut self.source, Source::Project, format!("📁 Project parts ({})", prj.parts.len())); + ui.selectable_value(&mut self.source, Source::Database, tr("🗄 Parts database")); + ui.selectable_value(&mut self.source, Source::Project, tr_fmt!("📁 Project parts ({})", prj.parts.len())); ui.separator(); let list: &mut Vec = match self.source { Source::Database => &mut db.parts, Source::Project => &mut prj.parts, }; - if ui.button("➕ New").clicked() { + if ui.button(tr("➕ New")).clicked() { let number = parts::unique_number(list, "NEW.PART"); list.push(Part { number: number.clone(), manufacturer: "NEW".into(), ..Default::default() }); self.selected = Some(number); self.editor.tab = PartTab::General; } let sel_idx = self.selected.as_ref().and_then(|n| list.iter().position(|p| &p.number == n)); - if ui.add_enabled(sel_idx.is_some(), egui::Button::new("⎘ Copy")).clicked() { + if ui.add_enabled(sel_idx.is_some(), egui::Button::new(tr("⎘ Copy"))).clicked() { let mut p = list[sel_idx.unwrap()].clone(); p.number = parts::unique_number(list, &format!("{}_COPY", p.number)); self.selected = Some(p.number.clone()); list.push(p); } - if ui.add_enabled(sel_idx.is_some(), egui::Button::new("🗑 Delete")).clicked() { + if ui.add_enabled(sel_idx.is_some(), egui::Button::new(tr("🗑 Delete"))).clicked() { list.remove(sel_idx.unwrap()); self.selected = None; } ui.separator(); - ui.menu_button("Extras", |ui| { - if ui.button("Import parts (CSV / JSON)…").clicked() { + ui.menu_button(tr("Extras"), |ui| { + if ui.button(tr("Import parts (CSV / JSON)…")).clicked() { actions.push(PartsAction::Import); } let src = match self.source { @@ -194,30 +195,30 @@ impl PartsUi { Source::Project => prj.parts.clone(), }; let base = if self.source == Source::Database { "parts_database" } else { "project_parts" }; - if ui.button("Export as CSV…").clicked() { + if ui.button(tr("Export as CSV…")).clicked() { actions.push(PartsAction::Export { name: format!("{base}.csv"), filter: ("CSV", "csv"), content: parts::to_csv(&src) }); } - if ui.button("Export as JSON…").clicked() { + if ui.button(tr("Export as JSON…")).clicked() { let json = serde_json::to_string_pretty(&PartsDb { parts: src }).unwrap_or_default(); actions.push(PartsAction::Export { name: format!("{base}.json"), filter: ("JSON", "json"), content: json }); } ui.separator(); - if ui.button("Synchronize project parts from database").on_hover_text("Updates the project parts with the current database data").clicked() { + if ui.button(tr("Synchronize project parts from database")).on_hover_text(tr("Updates the project parts with the current database data")).clicked() { let n = parts::sync_project_from_db(prj, db); - actions.push(PartsAction::Message(format!("{n} project parts updated"))); + actions.push(PartsAction::Message(tr_fmt!("{} project parts updated", n))); } - if ui.button("Transfer project parts to database").on_hover_text("Adds parts that only exist in the project to the database").clicked() { + if ui.button(tr("Transfer project parts to database")).on_hover_text(tr("Adds parts that only exist in the project to the database")).clicked() { let n = parts::transfer_project_to_db(prj, db); - actions.push(PartsAction::Message(format!("{n} parts added to the database"))); + actions.push(PartsAction::Message(tr_fmt!("{} parts added to the database", n))); } - if ui.button("Remove unused project parts").clicked() { + if ui.button(tr("Remove unused project parts")).clicked() { let n = parts::purge_unused(prj); - actions.push(PartsAction::Message(format!("{n} unused project parts removed"))); + actions.push(PartsAction::Message(tr_fmt!("{} unused project parts removed", n))); } ui.separator(); if ui - .button("Refresh example catalog parts (GEN.*)") - .on_hover_text("Replaces the GEN.* parts in the database with the current example catalog (including models)") + .button(tr("Refresh example catalog parts (GEN.*)")) + .on_hover_text(tr("Replaces the GEN.* parts in the database with the current example catalog (including models)")) .clicked() { let catalog = parts::default_catalog(); @@ -226,9 +227,9 @@ impl PartsUi { db.upsert(p); } db.sort(); - actions.push(PartsAction::Message(format!("{n} example catalog parts refreshed"))); + actions.push(PartsAction::Message(tr_fmt!("{} example catalog parts refreshed", n))); } - if ui.button("Add missing parts of the example catalog").clicked() { + if ui.button(tr("Add missing parts of the example catalog")).clicked() { let mut n = 0; for p in parts::default_catalog() { if db.get(&p.number).is_none() { @@ -236,12 +237,12 @@ impl PartsUi { n += 1; } } - actions.push(PartsAction::Message(format!("{n} catalog parts added"))); + actions.push(PartsAction::Message(tr_fmt!("{} catalog parts added", n))); } }); ui.separator(); - ui.toggle_value(&mut self.show_server, "🌐 Parts server") - .on_hover_text("Exchange parts with a global parts database (openecraft-server)"); + ui.toggle_value(&mut self.show_server, tr("🌐 Parts server")) + .on_hover_text(tr("Exchange parts with a global parts database (openecraft-server)")); }); ui.separator(); if self.show_server { @@ -262,8 +263,8 @@ impl PartsUi { let h = ui.available_height(); ui.horizontal_top(|ui| { ui.allocate_ui_with_layout(vec2(300.0, h), egui::Layout::top_down(egui::Align::Min), |ui| { - ui.add(egui::TextEdit::singleline(&mut self.filter).hint_text("Filter (number, type, manufacturer, text …)")); - ui.label(RichText::new(format!("{} parts", list.len())).weak()); + ui.add(egui::TextEdit::singleline(&mut self.filter).hint_text(tr("Filter (number, type, manufacturer, text …)"))); + ui.label(RichText::new(tr_fmt!("{} parts", list.len())).weak()); egui::ScrollArea::vertical().id_salt("ptree").auto_shrink([false, false]).show(ui, |ui| { let refs: Vec<&Part> = list.iter().collect(); pe::part_tree(ui, "mgr", &refs, &self.filter, &mut self.selected); @@ -285,11 +286,11 @@ impl PartsUi { } } None => { - ui.weak("Select a part in the tree or create a new one."); + ui.weak(tr("Select a part in the tree or create a new one.")); ui.add_space(8.0); match self.source { - Source::Database => ui.label("The parts database is shared by all projects. Parts are copied into a project when they are assigned to a device."), - Source::Project => ui.label("Project parts are the copies stored in this project; they are used for the bill of materials and the project check."), + Source::Database => ui.label(tr("The parts database is shared by all projects. Parts are copied into a project when they are assigned to a device.")), + Source::Project => ui.label(tr("Project parts are the copies stored in this project; they are used for the bill of materials and the project check.")), }; } } @@ -315,11 +316,11 @@ impl PartsUi { } let placed = parts::placed_functions(prj, &tag); let main = parts::main_kind(prj, &tag); - egui::Window::new(format!("Part selection – {tag}")).open(&mut open).default_size([760.0, 480.0]).collapsible(false).show(ctx, |ui| { + egui::Window::new(tr_fmt!("Part selection – {}", tag)).open(&mut open).default_size([760.0, 480.0]).collapsible(false).show(ctx, |ui| { ui.horizontal(|ui| { - ui.add(egui::TextEdit::singleline(&mut self.sel_filter).hint_text("Filter…").desired_width(220.0)); - ui.checkbox(&mut self.sel_matching, "Device selection") - .on_hover_text("Only parts whose function template provides the device's main function"); + ui.add(egui::TextEdit::singleline(&mut self.sel_filter).hint_text(tr("Filter…")).desired_width(220.0)); + ui.checkbox(&mut self.sel_matching, tr("Device selection")) + .on_hover_text(tr("Only parts whose function template provides the device's main function")); }); ui.separator(); let shown: Vec<&Part> = all @@ -340,17 +341,17 @@ impl PartsUi { match self.sel_part.as_ref().and_then(|n| all.iter().find(|p| &p.number == n)) { Some(p) => pe::part_summary(ui, p), None => { - ui.weak("Select a part. Double click adds it to the device."); + ui.weak(tr("Select a part. Double click adds it to the device.")); } } }); }); ui.separator(); ui.horizontal(|ui| { - if ui.add_enabled(self.sel_part.is_some(), egui::Button::new("✔ Add to device")).clicked() { + if ui.add_enabled(self.sel_part.is_some(), egui::Button::new(tr("✔ Add to device"))).clicked() { chosen = self.sel_part.clone(); } - if ui.button("Cancel").clicked() { + if ui.button(tr("Cancel")).clicked() { self.select = None; } }); diff --git a/src/render.rs b/src/render.rs index 208ff04d..041a1b78 100644 --- a/src/render.rs +++ b/src/render.rs @@ -1,6 +1,7 @@ //! Backend independent page rendering. The same code draws to the egui canvas and //! to SVG export, so what you see is what you print. +use openecraft_i18n::{tr, tr_fmt}; use crate::geom::{p, P, R}; use crate::index::{Index, Loc}; use crate::model::*; @@ -486,13 +487,13 @@ fn draw_cover(d: &mut dyn Draw, prj: &Project) { d.text(p(cx, 100.0 + i as f32 * 8.0), l, 5.0, Anchor::Center, VAnchor::Middle, Ink::Text); } let rows = [ - ("Company", info.company.as_str()), - ("Created by", info.creator.as_str()), - ("Date", info.date.as_str()), - ("Revision", info.revision.as_str()), + (tr("Company"), info.company.as_str()), + (tr("Created by"), info.creator.as_str()), + (tr("Date"), info.date.as_str()), + (tr("Revision"), info.revision.as_str()), ]; let pages = prj.pages.len().to_string(); - let rows = rows.iter().copied().chain(std::iter::once(("Number of pages", pages.as_str()))); + let rows = rows.iter().copied().chain(std::iter::once((tr("Number of pages"), pages.as_str()))); for (i, (k, v)) in rows.enumerate() { let y = 160.0 + i as f32 * 9.0; d.text(p(cx - 5.0, y), k, 3.5, Anchor::Right, VAnchor::Middle, Ink::FrameText); @@ -547,7 +548,7 @@ fn draw_report(d: &mut dyn Draw, prj: &Project, an: &Analysis, kind: ReportKind) } d.rect(p(x0, 34.0), p(x1, y), 0.3, Ink::Frame, false); if table.rows.len() > per_page { - let more = format!("… {} more rows – see Reports window / CSV export", table.rows.len() - per_page); + let more = tr_fmt!("… {} more rows – see Reports window / CSV export", table.rows.len() - per_page); d.text(p(x0, y + 5.0), &more, 2.5, Anchor::Left, VAnchor::Middle, Ink::FrameText); } if table.rows.is_empty() { @@ -786,7 +787,7 @@ pub fn drawing_scale(real: (f32, f32), space: (f32, f32)) -> f32 { fn draw_mounting_page(d: &mut dyn Draw, prj: &Project, id: u64) { let Some(e) = prj.layout.enclosures.iter().find(|e| e.id == id) else { - let msg = "Enclosure not found - choose another one in the page properties"; + let msg = tr("Enclosure not found - choose another one in the page properties"); d.text(p(30.0, 40.0), msg, 4.0, Anchor::Left, VAnchor::Middle, Ink::Error); return; }; @@ -803,8 +804,8 @@ fn draw_mounting_page(d: &mut dyn Draw, prj: &Project, id: u64) { if door { let o = origin + p(w + gap * k, 0.0); draw_enclosure(d, e, Face::Door, o, k, &BTreeSet::new(), &BTreeSet::new(), &prj.parts); - d.text(p(origin.x + w / 2.0, origin.y - 3.0), "Mounting plate", 3.0, Anchor::Center, VAnchor::Bottom, Ink::Text); - d.text(p(o.x + w / 2.0, o.y - 3.0), "Door (front view)", 3.0, Anchor::Center, VAnchor::Bottom, Ink::Text); + d.text(p(origin.x + w / 2.0, origin.y - 3.0), tr("Mounting plate"), 3.0, Anchor::Center, VAnchor::Bottom, Ink::Text); + d.text(p(o.x + w / 2.0, o.y - 3.0), tr("Door (front view)"), 3.0, Anchor::Center, VAnchor::Bottom, Ink::Text); } // Dimensions let bottom = origin.y + h + 6.0; diff --git a/src/reports.rs b/src/reports.rs index c77099a7..0f38b5ba 100644 --- a/src/reports.rs +++ b/src/reports.rs @@ -1,5 +1,6 @@ //! Reports (device list, BOM, terminal diagram, ...) and the project check. +use openecraft_i18n::{tr, tr_fmt}; use crate::index::Index; use crate::panel::{self, ItemKind, OpenWire, RoutedWire}; use crate::model::*; @@ -125,7 +126,7 @@ fn loc_str(prj: &Project, page: usize, pos: crate::geom::P) -> String { } fn toc(prj: &Project) -> Table { - let mut t = Table::new(&[("Page", 1.0), ("Description", 4.0), ("Type", 2.0), ("Devices", 1.0)]); + let mut t = Table::new(&[(tr("Page"), 1.0), (tr("Description"), 4.0), (tr("Type"), 2.0), (tr("Devices"), 1.0)]); for (i, pg) in prj.pages.iter().enumerate() { t.push( vec![pg.name.clone(), pg.description.clone(), pg.kind.label(), pg.symbols.len().to_string()], @@ -137,13 +138,13 @@ fn toc(prj: &Project) -> Table { fn device_list(prj: &Project, idx: &Index) -> Table { let mut t = Table::new(&[ - ("Device tag", 1.2), - ("Main function", 2.0), - ("Function text", 2.0), - ("Location", 1.0), - ("Aux. functions", 1.6), - ("Part number", 1.6), - ("Description", 3.0), + (tr("Device tag"), 1.2), + (tr("Main function"), 2.0), + (tr("Function text"), 2.0), + (tr("Location"), 1.0), + (tr("Aux. functions"), 1.6), + (tr("Part number"), 1.6), + (tr("Description"), 3.0), ]); for tag in idx.sorted_tags() { let dev = &idx.devices[tag]; @@ -151,7 +152,7 @@ fn device_list(prj: &Project, idx: &Index) -> Table { let Some(loc) = first else { continue }; let inst = prj.pages[loc.page].symbols.iter().find(|s| s.id == loc.sym_id); let (name, ftext) = inst - .map(|s| (symbols::get(&s.sym).map(|d| d.name).unwrap_or("?").to_string(), s.function_text.clone())) + .map(|s| (symbols::get(&s.sym).map(|d| tr(d.name)).unwrap_or("?").to_string(), s.function_text.clone())) .unwrap_or_default(); let name = if dev.mains.is_empty() && !dev.others.is_empty() { format!("{name} ×{}", dev.others.len()) @@ -194,16 +195,16 @@ fn device_list(prj: &Project, idx: &Index) -> Table { fn bom(prj: &Project, idx: &Index, wiring: &[RoutedWire]) -> Table { let mut t = Table::new(&[ - ("Pos", 0.5), - ("Qty", 0.6), - ("Unit", 0.5), - ("Part number", 1.8), - ("Type number", 1.4), - ("Manufacturer", 1.0), - ("Description", 3.2), - ("Devices", 2.0), - ("Unit price", 0.9), - ("Total", 0.9), + (tr("Pos"), 0.5), + (tr("Qty"), 0.6), + (tr("Unit"), 0.5), + (tr("Part number"), 1.8), + (tr("Type number"), 1.4), + (tr("Manufacturer"), 1.0), + (tr("Description"), 3.2), + (tr("Devices"), 2.0), + (tr("Unit price"), 0.9), + (tr("Total"), 0.9), ]); let mut groups: BTreeMap)> = BTreeMap::new(); for tag in idx.sorted_tags() { @@ -289,7 +290,7 @@ fn bom(prj: &Project, idx: &Index, wiring: &[RoutedWire]) -> Table { } if !groups.is_empty() { let mut last = vec![String::new(); 10]; - last[6] = "Sum".into(); + last[6] = tr("Sum").into(); last[9] = format!("{sum:.2}"); t.push(last, None); } @@ -298,15 +299,15 @@ fn bom(prj: &Project, idx: &Index, wiring: &[RoutedWire]) -> Table { fn panel_wiring(prj: &Project, wiring: &[RoutedWire], open: &[OpenWire]) -> Table { let mut t = Table::new(&[ - ("Enclosure", 0.8), - ("Wire no.", 0.7), - ("From", 1.4), - ("To", 1.4), - ("Potential", 0.9), - ("Colour", 0.6), + (tr("Enclosure"), 0.8), + (tr("Wire no."), 0.7), + (tr("From"), 1.4), + (tr("To"), 1.4), + (tr("Potential"), 0.9), + (tr("Colour"), 0.6), ("Cross-section", 0.9), - ("Length (mm)", 0.9), - ("Routing", 1.2), + (tr("Length (mm)"), 0.9), + (tr("Routing"), 1.2), ]); let mut total = 0.0; for w in wiring { @@ -328,7 +329,7 @@ fn panel_wiring(prj: &Project, wiring: &[RoutedWire], open: &[OpenWire]) -> Tabl } if !wiring.is_empty() { let mut last = vec![String::new(); 9]; - last[6] = "Total".into(); + last[6] = tr("Total").into(); last[7] = format!("{total:.0}"); t.push(last, None); } @@ -349,26 +350,26 @@ fn check_layout(prj: &Project) -> Vec { } for d in panel::devices_to_place(prj) { let target = prj.pages.iter().enumerate().find_map(|(pi, pg)| pg.symbols.iter().find(|s| s.tag == d.tag).map(|s| (pi, s.id))); - v.push(Issue { severity: Severity::Info, message: format!("{}: not placed in the panel layout", d.tag), target }); + v.push(Issue { severity: Severity::Info, message: tr_fmt!("{}: not placed in the panel layout", d.tag), target }); } for e in &prj.layout.enclosures { let name = |id: u64| { e.item(id).map(|i| if i.kind == ItemKind::Device { i.tag.clone() } else { i.kind.title().to_string() }).unwrap_or_default() }; for (a, b) in panel::collisions(e, &prj.parts) { - v.push(Issue { severity: Severity::Warning, message: format!("{}: {} collides with {}", e.name, name(a), name(b)), target: None }); + v.push(Issue { severity: Severity::Warning, message: tr_fmt!("{}: {} collides with {}", e.name, name(a), name(b)), target: None }); } for id in panel::outside(e) { v.push(Issue { severity: Severity::Warning, - message: format!("{}: {} outside the mounting plate / enclosure", e.name, name(id)), + message: tr_fmt!("{}: {} outside the mounting plate / enclosure", e.name, name(id)), target: None, }); } for (a, b) in crate::production::clearance_violations(e, &prj.parts) { v.push(Issue { severity: Severity::Warning, - message: format!("{}: {} is inside the required clearance of {}", e.name, name(b), name(a)), + message: tr_fmt!("{}: {} is inside the required clearance of {}", e.name, name(b), name(a)), target: None, }); } @@ -378,14 +379,14 @@ fn check_layout(prj: &Project) -> Vec { fn terminal_diagram(prj: &Project, nl: &Netlist, open: &Netlist) -> Table { let mut t = Table::new(&[ - ("Strip", 0.8), - ("Terminal", 0.7), - ("Jumper", 0.5), - ("External (top)", 3.0), - ("Internal (bottom)", 3.0), - ("Potential", 1.0), - ("Location", 0.8), - ("Function text", 1.6), + (tr("Strip"), 0.8), + (tr("Terminal"), 0.7), + (tr("Jumper"), 0.5), + (tr("External (top)"), 3.0), + (tr("Internal (bottom)"), 3.0), + (tr("Potential"), 1.0), + (tr("Location"), 0.8), + (tr("Function text"), 1.6), ]); for strip in crate::strips::strip_tags(prj) { for r in crate::strips::rows(prj, &strip, nl, open) { @@ -398,15 +399,15 @@ fn terminal_diagram(prj: &Project, nl: &Netlist, open: &Netlist) -> Table { } fn connection_list(prj: &Project, conns: &[Connection]) -> Table { let mut t = Table::new(&[ - ("Wire no.", 0.8), - ("Potential", 1.0), - ("From", 1.6), - ("To", 1.6), - ("Page", 0.8), - ("Colour", 0.8), + (tr("Wire no."), 0.8), + (tr("Potential"), 1.0), + (tr("From"), 1.6), + (tr("To"), 1.6), + (tr("Page"), 0.8), + (tr("Colour"), 0.8), ("Cross-section", 1.0), - ("Cable", 1.0), - ("Core", 0.6), + (tr("Cable"), 1.0), + (tr("Core"), 0.6), ]); for c in conns { let s = &prj.pages[c.a.page].symbols[c.a.sym]; @@ -456,15 +457,15 @@ fn sorted_cables(prj: &Project) -> Vec<&Cable> { fn cable_overview(prj: &Project, conns: &[Connection]) -> Table { let mut t = Table::new(&[ - ("Cable", 1.0), - ("Type", 1.6), - ("Cores used", 0.8), + (tr("Cable"), 1.0), + (tr("Type"), 1.6), + (tr("Cores used"), 0.8), ("Cross-section", 0.9), - ("Length (m)", 0.8), - ("From", 1.6), - ("To", 1.6), - ("Part number", 1.4), - ("Description", 2.0), + (tr("Length (m)"), 0.8), + (tr("From"), 1.6), + (tr("To"), 1.6), + (tr("Part number"), 1.4), + (tr("Description"), 2.0), ]); for cable in sorted_cables(prj) { let used = cable_connections(prj, conns, &cable.tag); @@ -496,12 +497,12 @@ fn cable_overview(prj: &Project, conns: &[Connection]) -> Table { fn cable_diagram(prj: &Project, conns: &[Connection]) -> Table { let mut t = Table::new(&[ - ("Cable", 1.0), - ("Core", 0.6), - ("From", 1.6), - ("To", 1.6), - ("Potential", 1.0), - ("Wire no.", 0.8), + (tr("Cable"), 1.0), + (tr("Core"), 0.6), + (tr("From"), 1.6), + (tr("To"), 1.6), + (tr("Potential"), 1.0), + (tr("Wire no."), 0.8), ("Cross-section", 0.9), ]); for cable in sorted_cables(prj) { @@ -546,11 +547,11 @@ fn check_wires(prj: &Project, nl: &Netlist, open: &Netlist) -> Vec { for c in &prj.cables { *tags.entry(c.tag.as_str()).or_default() += 1; if c.tag.trim().is_empty() { - issue(Severity::Error, "Cable without tag".into(), None); + issue(Severity::Error, tr("Cable without tag").into(), None); } } for (tag, n) in tags.iter().filter(|(t, n)| **n > 1 && !t.is_empty()) { - issue(Severity::Error, format!("Cable {tag} defined {n} times"), None); + issue(Severity::Error, tr_fmt!("Cable {} defined {} times", tag, n), None); } // Cable cores: known cable, listed core, one connection per core. let mut core_use: BTreeMap<(String, String), Vec> = BTreeMap::new(); @@ -562,10 +563,10 @@ fn check_wires(prj: &Project, nl: &Netlist, open: &Netlist) -> Vec { } let at = Some((*pi, w.id)); match prj.cable(&w.cable) { - None => issue(Severity::Error, format!("Wire assigned to unknown cable {}", w.cable), at), - Some(_) if w.core.is_empty() => issue(Severity::Warning, format!("{}: wire without core designation", w.cable), at), + None => issue(Severity::Error, tr_fmt!("Wire assigned to unknown cable {}", w.cable), at), + Some(_) if w.core.is_empty() => issue(Severity::Warning, tr_fmt!("{}: wire without core designation", w.cable), at), Some(c) if !c.core_list().contains(&w.core) => { - issue(Severity::Warning, format!("{}: core {} is not a core of the cable ({})", w.cable, w.core, c.cores), at) + issue(Severity::Warning, tr_fmt!("{}: core {} is not a core of the cable ({})", w.cable, w.core, c.cores), at) } Some(_) => {} } @@ -578,7 +579,7 @@ fn check_wires(prj: &Project, nl: &Netlist, open: &Netlist) -> Vec { for ((cable, core), nets) in &core_use { if nets.len() > 1 && !core.is_empty() { let at = open.nets[nets[1]].wires.first().copied(); - issue(Severity::Error, format!("{cable}: core {core} used for {} connections", nets.len()), at); + issue(Severity::Error, tr_fmt!("{}: core {} used for {} connections", cable, core, nets.len()), at); } } // Wire numbers: one per connection, not shared by different potentials. @@ -587,7 +588,7 @@ fn check_wires(prj: &Project, nl: &Netlist, open: &Netlist) -> Vec { let numbers = crate::wirenum::numbers_of(prj, net); let at = net.wires.first().copied(); if numbers.len() > 1 { - issue(Severity::Warning, format!("Different wire numbers in one connection: {}", numbers.join(", ")), at); + issue(Severity::Warning, tr_fmt!("Different wire numbers in one connection: {}", numbers.join(", ")), at); } let potential = net.pins.first().and_then(|p| nl.pin_net.get(&(prj.pages[p.page].symbols[p.sym].id, p.pin)).copied()); if let (Some(n), Some(pot)) = (numbers.first(), potential) { @@ -595,13 +596,13 @@ fn check_wires(prj: &Project, nl: &Netlist, open: &Netlist) -> Vec { } } for (number, pots) in by_number.iter().filter(|(_, p)| p.len() > 1) { - issue(Severity::Warning, format!("Wire number {number} is used for {} different potentials", pots.len()), None); + issue(Severity::Warning, tr_fmt!("Wire number {} is used for {} different potentials", number, pots.len()), None); } // Device tags need a device name after the structure. for (pi, pg) in prj.pages.iter().enumerate() { for s in pg.symbols.iter().filter(|s| !s.tag.is_empty()) { if crate::structure::Dt::parse(&s.tag).name.is_empty() { - issue(Severity::Error, format!("{}: device tag without device name", s.tag), Some((pi, s.id))); + issue(Severity::Error, tr_fmt!("{}: device tag without device name", s.tag), Some((pi, s.id))); } } } @@ -610,12 +611,12 @@ fn check_wires(prj: &Project, nl: &Netlist, open: &Netlist) -> Vec { fn plc_list(prj: &Project, nl: &Netlist) -> Table { let mut t = Table::new(&[ - ("PLC card", 1.0), - ("Address", 1.0), - ("Type", 0.8), - ("Function text", 2.5), - ("Connected to", 3.0), - ("Location", 0.8), + (tr("PLC card"), 1.0), + (tr("Address"), 1.0), + (tr("Type"), 0.8), + (tr("Function text"), 2.5), + (tr("Connected to"), 3.0), + (tr("Location"), 0.8), ]); for p in crate::plc::points(prj, nl) { let kind = if p.input { "DI" } else { "DO" }; @@ -626,7 +627,7 @@ fn plc_list(prj: &Project, nl: &Netlist) -> Table { fn revision_overview(prj: &Project) -> Table { let since = prj.revisions.last().map(|r| r.name.as_str()).unwrap_or("-"); - let mut t = Table::new(&[("Page", 0.8), ("Change", 0.8), ("Item", 0.8), (if since.is_empty() { "Description" } else { "Description (since last revision)" }, 3.0)]); + let mut t = Table::new(&[(tr("Page"), 0.8), (tr("Change"), 0.8), (tr("Item"), 0.8), (if since.is_empty() { tr("Description") } else { tr("Description (since last revision)") }, 3.0)]); for (page, kind, what, label, target) in crate::revision::overview(prj) { t.push(vec![page, kind, what, label], target); } @@ -640,18 +641,18 @@ fn revision_overview(prj: &Project) -> Table { /// (machine batches). pub fn production_wire_list(prj: &Project, an: &Analysis) -> Table { let mut t = Table::new(&[ - ("Wire no.", 0.8), - ("From", 1.6), - ("To", 1.6), - ("Colour", 0.7), + (tr("Wire no."), 0.8), + (tr("From"), 1.6), + (tr("To"), 1.6), + (tr("Colour"), 0.7), ("Cross-section", 0.9), - ("Length (mm)", 0.9), - ("Strip (mm)", 0.7), - ("Ferrule", 1.6), - ("Ferrule part", 1.0), - ("Cable", 0.8), - ("Core", 0.6), - ("Potential", 1.0), + (tr("Length (mm)"), 0.9), + (tr("Strip (mm)"), 0.7), + (tr("Ferrule"), 1.6), + (tr("Ferrule part"), 1.0), + (tr("Cable"), 0.8), + (tr("Core"), 0.6), + (tr("Potential"), 1.0), ]); // (routed length, cells, jump target) type Row = (Option, Vec, Option<(usize, u64)>); @@ -701,22 +702,22 @@ pub fn production_wire_list(prj: &Project, an: &Analysis) -> Table { /// summary row (wires, connectors, total length, bundle diameter). fn harness_data(prj: &Project, an: &Analysis) -> Table { let mut t = Table::new(&[ - ("Harness", 0.9), - ("Wire no.", 0.7), - ("From", 1.4), - ("To", 1.4), - ("Colour", 0.6), + (tr("Harness"), 0.9), + (tr("Wire no."), 0.7), + (tr("From"), 1.4), + (tr("To"), 1.4), + (tr("Colour"), 0.6), ("Cross-section", 0.9), - ("Length (mm)", 0.8), - ("End treatment", 1.6), + (tr("Length (mm)"), 0.8), + (tr("End treatment"), 1.6), ]); for h in &prj.harnesses { let ws = crate::harness::wires(prj, an, &h.tag); for w in &ws { let end = crate::production::end_treatment(&w.cross_section, prj.layout.ferrules) .map(|e| match e.ferrule { - Some(f) => format!("strip {:.0} mm, ferrule {} mm² {}", e.strip, f.cross_section, f.color), - None => format!("strip {:.0} mm", e.strip), + Some(f) => tr_fmt!("strip {} mm, ferrule {} mm² {}", format!("{:.0}", e.strip), f.cross_section, f.color), + None => tr_fmt!("strip {} mm", format!("{:.0}", e.strip)), }) .unwrap_or_default(); let length = if w.length > 0.0 { format!("{:.0}{}", w.length, if w.routed { "" } else { " *" }) } else { "?".into() }; @@ -730,7 +731,7 @@ fn harness_data(prj: &Project, an: &Analysis) -> Table { crate::harness::connectors(&ws).len(), crate::harness::bundle_diameter(&ws) ); - t.push(vec![h.tag.clone(), String::new(), summary, String::new(), String::new(), "Total".into(), format!("{total:.0}"), h.description.clone()], None); + t.push(vec![h.tag.clone(), String::new(), summary, String::new(), String::new(), tr("Total").into(), format!("{total:.0}"), h.description.clone()], None); } t } @@ -739,11 +740,11 @@ fn harness_data(prj: &Project, an: &Analysis) -> Table { fn check_harnesses(prj: &Project, an: &Analysis) -> Vec { let mut v = Vec::new(); for (tag, [a, b]) in crate::harness::stale(prj, an) { - v.push(Issue { severity: Severity::Warning, message: format!("Harness {tag}: connection {a} – {b} does not exist in the schematic"), target: None }); + v.push(Issue { severity: Severity::Warning, message: tr_fmt!("Harness {}: connection {} – {} does not exist in the schematic", tag, a, b), target: None }); } for h in &prj.harnesses { if !an.connections.iter().any(|c| c.harness == h.tag) { - v.push(Issue { severity: Severity::Info, message: format!("Harness {} has no wires", h.tag), target: None }); + v.push(Issue { severity: Severity::Info, message: tr_fmt!("Harness {} has no wires", h.tag), target: None }); } } v @@ -756,7 +757,7 @@ fn check_strips_and_plc(prj: &Project, nl: &Netlist) -> Vec { let labels: Vec = crate::strips::terminals(prj, strip).into_iter().map(|t| t.label).collect(); for (label, j) in data.jumpers.iter().filter(|(_, j)| **j > 0) { if !labels.contains(label) { - v.push(Issue { severity: Severity::Warning, message: format!("{strip}: jumper {j} on terminal {label}, which is not placed"), target: None }); + v.push(Issue { severity: Severity::Warning, message: tr_fmt!("{}: jumper {} on terminal {}, which is not placed", strip, j, label), target: None }); } } } @@ -766,7 +767,7 @@ fn check_strips_and_plc(prj: &Project, nl: &Netlist) -> Vec { if cards.len() > 1 { v.push(Issue { severity: Severity::Error, - message: format!("PLC address {addr} used on several cards: {}", cards.join(", ")), + message: tr_fmt!("PLC address {} used on several cards: {}", addr, cards.join(", ")), target: Some((points[1].page, points[1].id)), }); } @@ -774,7 +775,7 @@ fn check_strips_and_plc(prj: &Project, nl: &Netlist) -> Vec { v } fn potential_list(prj: &Project, nl: &Netlist) -> Table { - let mut t = Table::new(&[("Potential", 1.0), ("Connection points", 4.0), ("Pages", 1.5)]); + let mut t = Table::new(&[(tr("Potential"), 1.0), (tr("Connection points"), 4.0), (tr("Pages"), 1.5)]); let mut nets: Vec<_> = nl.nets.iter().filter(|n| n.named).collect(); nets.sort_by(|a, b| natural_cmp(&a.name, &b.name)); for net in nets { @@ -804,10 +805,10 @@ pub fn check(prj: &Project, idx: &Index, nl: &Netlist) -> Vec { let dev = &idx.devices[tag]; let t = |l: &crate::index::Loc| Some((l.page, l.sym_id)); if dev.mains.is_empty() && !dev.auxs.is_empty() { - issue(Severity::Error, format!("{tag}: auxiliary function(s) without main function"), t(&dev.auxs[0])); + issue(Severity::Error, tr_fmt!("{}: auxiliary function(s) without main function", tag), t(&dev.auxs[0])); } if dev.mains.len() > 1 { - issue(Severity::Error, format!("{tag}: main function placed {} times", dev.mains.len()), t(&dev.mains[1])); + issue(Severity::Error, tr_fmt!("{}: main function placed {} times", tag, dev.mains.len()), t(&dev.mains[1])); } if !dev.others.is_empty() { // Duplicate terminal numbers / PLC addresses @@ -817,7 +818,7 @@ pub fn check(prj: &Project, idx: &Index, nl: &Netlist) -> Vec { let c = seen.entry(s.label.clone()).or_default(); *c += 1; if *c == 2 { - issue(Severity::Warning, format!("{tag}: designation '{}' used more than once", s.label), t(l)); + issue(Severity::Warning, tr_fmt!("{}: designation '{}' used more than once", tag, s.label), t(l)); } } } @@ -828,7 +829,7 @@ pub fn check(prj: &Project, idx: &Index, nl: &Netlist) -> Vec { let l = dev.mains.first().or(dev.others.first()).or(dev.auxs.first()); issue( Severity::Error, - format!("{tag}: part {} is not in the project parts (Parts management › synchronize)", r.number), + tr_fmt!("{}: part {} is not in the project parts (Parts management › synchronize)", tag, r.number), l.and_then(t), ); } @@ -842,7 +843,7 @@ pub fn check(prj: &Project, idx: &Index, nl: &Netlist) -> Vec { let l = dev.mains.first().or(dev.auxs.first()).or(dev.others.first()); issue( Severity::Warning, - format!("{tag}: {placed}× {} placed, assigned parts provide {avail}", kind.title()), + tr_fmt!("{}: {}× {} placed, assigned parts provide {}", tag, placed, kind.title(), avail), l.and_then(t), ); } @@ -851,14 +852,14 @@ pub fn check(prj: &Project, idx: &Index, nl: &Netlist) -> Vec { let has_part = data.map(|d| !d.parts.is_empty()).unwrap_or(false); if !has_part && (!dev.mains.is_empty() || !dev.others.is_empty()) { let l = dev.mains.first().or(dev.others.first()).unwrap(); - issue(Severity::Info, format!("{tag}: no part assigned"), t(l)); + issue(Severity::Info, tr_fmt!("{}: no part assigned", tag), t(l)); } } for (name, locs) in &idx.interruptions { if locs.len() == 1 { issue( Severity::Warning, - format!("Interruption point '{name}' has no counterpart"), + tr_fmt!("Interruption point '{}' has no counterpart", name), Some((locs[0].page, locs[0].sym_id)), ); } @@ -866,11 +867,11 @@ pub fn check(prj: &Project, idx: &Index, nl: &Netlist) -> Vec { for (pi, pg) in prj.pages.iter().enumerate() { for s in &pg.symbols { let Some(def) = symbols::get(&s.sym) else { - issue(Severity::Error, format!("Unknown symbol '{}'", s.sym), Some((pi, s.id))); + issue(Severity::Error, tr_fmt!("Unknown symbol '{}'", s.sym), Some((pi, s.id))); continue; }; if def.func.has_tag() && s.tag.trim().is_empty() { - issue(Severity::Error, format!("{} without device tag on page {}", def.name, pg.name), Some((pi, s.id))); + issue(Severity::Error, tr_fmt!("{} without device tag on page {}", def.name, pg.name), Some((pi, s.id))); } } } @@ -881,7 +882,7 @@ pub fn check(prj: &Project, idx: &Index, nl: &Netlist) -> Vec { let d = pin_designation(prj, PinRef { page: pi, sym: si, pin }); issue( Severity::Warning, - format!("Open connection point {d} ({})", loc_str(prj, pi, s.pos)), + tr_fmt!("Open connection point {} ({})", d, loc_str(prj, pi, s.pos)), Some((pi, sid)), ); } @@ -889,7 +890,7 @@ pub fn check(prj: &Project, idx: &Index, nl: &Netlist) -> Vec { for net in &nl.nets { if net.name.contains(" / ") { let target = net.pins.first().map(|p| (p.page, prj.pages[p.page].symbols[p.sym].id)); - issue(Severity::Error, format!("Short circuit between potentials {}", net.name), target); + issue(Severity::Error, tr_fmt!("Short circuit between potentials {}", net.name), target); } } v.sort_by_key(|i| i.severity); diff --git a/src/revision.rs b/src/revision.rs index c020c98d..d3500fff 100644 --- a/src/revision.rs +++ b/src/revision.rs @@ -2,6 +2,7 @@ //! since the last revision are listed and marked on the pages. Released pages are //! locked against changes. +use openecraft_i18n::tr; use crate::geom::{p, P}; use crate::model::{natural_cmp, Page, Project}; use serde::{Deserialize, Serialize}; @@ -39,9 +40,9 @@ pub enum ChangeKind { impl ChangeKind { pub fn title(self) -> &'static str { match self { - ChangeKind::Added => "added", - ChangeKind::Removed => "removed", - ChangeKind::Modified => "changed", + ChangeKind::Added => tr("added"), + ChangeKind::Removed => tr("removed"), + ChangeKind::Modified => tr("changed"), } } } @@ -107,7 +108,7 @@ pub fn compare(old: &[Page], new: &[Page]) -> Vec { None => changes.push(Change { kind: ChangeKind::Added, what: "Page", id: n.id, label: n.description.clone(), pos: p(0.0, 0.0) }), Some(o) => { if (&o.name, &o.description, &o.function, &o.location, o.kind) != (&n.name, &n.description, &n.function, &n.location, n.kind) { - changes.push(Change { kind: ChangeKind::Modified, what: "Page", id: n.id, label: "page properties".into(), pos: p(0.0, 0.0) }); + changes.push(Change { kind: ChangeKind::Modified, what: "Page", id: n.id, label: tr("page properties").into(), pos: p(0.0, 0.0) }); } diff(&o.symbols, &n.symbols, |s| s.id, "Symbol", |s| (format!("{} {}", s.tag, s.label).trim().to_string(), s.pos), &mut changes); diff(&o.wires, &n.wires, |w| w.id, "Wire", |w| (w.number.clone(), mid(w.a, w.b)), &mut changes); @@ -175,7 +176,7 @@ pub fn overview(prj: &Project) -> Vec { for pc in pages { for c in &pc.changes { let target = pc.page.map(|pi| (pi, if c.kind == ChangeKind::Removed || c.what == "Page" { 0 } else { c.id })); - rows.push((pc.name.clone(), c.kind.title().to_string(), c.what.to_string(), c.label.clone(), target)); + rows.push((pc.name.clone(), c.kind.title().to_string(), tr(c.what).to_string(), c.label.clone(), target)); } } rows diff --git a/src/symbols.rs b/src/symbols.rs index 1261b20b..5a69bad8 100644 --- a/src/symbols.rs +++ b/src/symbols.rs @@ -5,6 +5,7 @@ //! (current flows top → bottom). Connection points lie on the 4 mm grid relative to //! the symbol origin so that placed symbols connect cleanly to wires. +use openecraft_i18n::tr; use crate::geom::{p, P, R}; use serde::{Deserialize, Serialize}; use std::sync::OnceLock; @@ -59,17 +60,17 @@ impl Func { pub fn title(self) -> &'static str { match self { - Func::Main { mirror: false } => "Main function", - Func::Main { mirror: true } => "Main function with contact image", - Func::Aux(ContactKind::No) => "Auxiliary function: NO contact", - Func::Aux(ContactKind::Nc) => "Auxiliary function: NC contact", - Func::Aux(ContactKind::Changeover) => "Auxiliary function: changeover", - Func::Aux(ContactKind::MainNo) => "Auxiliary function: main contact", - Func::Terminal => "Terminal", - Func::Plc => "PLC connection point", - Func::Potential => "Potential", - Func::Interruption => "Interruption point", - Func::Overview => "Overview / single-line", + Func::Main { mirror: false } => tr("Main function"), + Func::Main { mirror: true } => tr("Main function with contact image"), + Func::Aux(ContactKind::No) => tr("Auxiliary function: NO contact"), + Func::Aux(ContactKind::Nc) => tr("Auxiliary function: NC contact"), + Func::Aux(ContactKind::Changeover) => tr("Auxiliary function: changeover"), + Func::Aux(ContactKind::MainNo) => tr("Auxiliary function: main contact"), + Func::Terminal => tr("Terminal"), + Func::Plc => tr("PLC connection point"), + Func::Potential => tr("Potential"), + Func::Interruption => tr("Interruption point"), + Func::Overview => tr("Overview / single-line"), } } } @@ -113,20 +114,20 @@ impl Category { pub fn title(self) -> &'static str { match self { - Category::Coils => "Coils / Relays", - Category::Contacts => "Contacts", - Category::Switches => "Switches / Sensors", - Category::Protection => "Protective devices", - Category::Loads => "Motors / Loads", - Category::Terminals => "Terminals", - Category::Plc => "PLC", - Category::Potentials => "Potentials / Connectors", - Category::Passive => "Passive components", - Category::BlackBox => "Black boxes / PLC boxes", - Category::SingleLine => "Single-line / overview", - Category::Nfpa => "NFPA / JIC", - Category::Fluid => "Fluid power (ISO 1219)", - Category::User => "User symbols", + Category::Coils => tr("Coils / Relays"), + Category::Contacts => tr("Contacts"), + Category::Switches => tr("Switches / Sensors"), + Category::Protection => tr("Protective devices"), + Category::Loads => tr("Motors / Loads"), + Category::Terminals => tr("Terminals"), + Category::Plc => tr("PLC"), + Category::Potentials => tr("Potentials / Connectors"), + Category::Passive => tr("Passive components"), + Category::BlackBox => tr("Black boxes / PLC boxes"), + Category::SingleLine => tr("Single-line / overview"), + Category::Nfpa => tr("NFPA / JIC"), + Category::Fluid => tr("Fluid power (ISO 1219)"), + Category::User => tr("User symbols"), } } } @@ -579,7 +580,7 @@ fn build_library() -> Vec { b.l(-1.6, -1.6, -0.7, -0.7).l(-1.6, 1.6, -0.7, 0.7); b.field(FieldKind::Tag, -2.2, 0.0, 2.0, Right).field(FieldKind::Label, 1.6, 0.0, 2.2, Left); b.pin(0.0, -4.0, "").pin(0.0, 4.0, ""); - let mut t = def("term_pe", "PE terminal", C::Terminals, "X", Func::Terminal).label("PE"); + let mut t = def("term_pe", "PE terminal", C::Terminals, "X", Func::Terminal).label(tr("PE")); t.show_tag = false; t.bridges = vec![(0, 1)]; v.push(t.build(&mut b)); @@ -620,7 +621,7 @@ fn build_library() -> Vec { b.l(0.0, -4.0, 0.0, 0.0).l(-2.5, 0.0, 2.5, 0.0).l(-1.6, 1.0, 1.6, 1.0).l(-0.7, 2.0, 0.7, 2.0); b.pin(0.0, -4.0, ""); - v.push(def("ground", "Protective earth", C::Potentials, "", Func::Potential).label("PE").build(&mut b)); + v.push(def("ground", "Protective earth", C::Potentials, "", Func::Potential).label(tr("PE")).build(&mut b)); b.l(0.0, 0.0, 0.0, 2.6).poly(&[(-1.5, 1.2), (0.0, 2.7), (1.5, 1.2)], false, false); b.field(FieldKind::Label, 2.2, 1.6, 2.5, Left); diff --git a/src/symlib.rs b/src/symlib.rs index f9dd45c2..b47be39f 100644 --- a/src/symlib.rs +++ b/src/symlib.rs @@ -3,6 +3,7 @@ //! instances refer to them by key. [`register`] makes them known to //! [`symbols::get`](crate::symbols::get). +use openecraft_i18n::{tr, tr_fmt}; use crate::geom::{dist_to_segment, p, P, GRID}; use crate::model::Project; use crate::symbols::{self, Anchor, Category, FieldKind, Func, PinDef, Prim, SymbolDef}; @@ -194,21 +195,21 @@ pub fn merge(list: &mut Vec, lib: SymbolLibrary) -> (usize, usize) { pub fn problems(u: &UserSymbol) -> Vec { let mut v = Vec::new(); if u.name.trim().is_empty() { - v.push("The symbol has no name.".into()); + v.push(tr("The symbol has no name.").into()); } if u.pins.is_empty() && !matches!(u.func, Func::Overview) { - v.push("The symbol has no connection points.".into()); + v.push(tr("The symbol has no connection points.").into()); } for (i, a) in u.pins.iter().enumerate() { if a.pos.x % GRID != 0.0 || a.pos.y % GRID != 0.0 { - v.push(format!("Connection point {} is not on the {GRID} mm grid.", i + 1)); + v.push(tr_fmt!("Connection point {} is not on the {} mm grid.", i + 1, GRID)); } if u.pins[..i].iter().any(|b| b.pos.same(a.pos)) { - v.push(format!("Connection point {} lies on another one.", i + 1)); + v.push(tr_fmt!("Connection point {} lies on another one.", i + 1)); } } if u.func.has_tag() && u.letter.trim().is_empty() { - v.push("No identifying letter for the device tag.".into()); + v.push(tr("No identifying letter for the device tag.").into()); } v }