Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Every popup and panel on the UI library (step 6 of #2016, after the library PR)

Nathan Dane7026248e2572
diff --git a/assets/locales/cs.json b/assets/locales/cs.json
index b7e183ada4..3dc2fb97a5 100644
--- a/assets/locales/cs.json
+++ b/assets/locales/cs.json
@@ -9,6 +9,7 @@
"AI": "AI",
"ARRANGE": "USPOŘÁDAT",
"About SolidCraft": "O aplikaci SolidCraft",
+ "Actions": "Akce",
"Active": "Aktivní",
"Active rule": "Aktivní pravidlo",
"Add": "Přidat",
@@ -16,6 +17,7 @@
"Add Mid Radius": "Přidat střední poloměr",
"Add Row": "Přidat řádek",
"Add condition": "Přidat podmínku",
+ "Add or edit rule": "Přidat nebo upravit pravidlo",
"Alignment": "Zarovnání",
"All Sketch Points": "Všechny body náčrtu",
"All open designs": "Všechny otevřené návrhy",
@@ -27,6 +29,7 @@
"Applied Radius": "Použitý poloměr",
"Apply To": "Použít na",
"Apply to selection": "Použít na výběr",
+ "Apply your appearance first. Exports assigned appearances and materials created in this design.": "Nejprve použijte vzhled. Exportuje přiřazené vzhledy a materiály vytvořené v tomto návrhu.",
"Arc length": "Délka oblouku",
"Area": "Plocha",
"Attachment": "Připojení",
@@ -56,10 +59,12 @@
"Check collisions": "Kontrolovat kolize",
"Checked": "Zaškrtnuto",
"Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "Zvolte novou rovinu. Geometrie a kóty náčrtu zůstanou ve svých dvourozměrných souřadnicích beze změny.",
+ "Choose…": "Vybrat…",
"Circumference": "Obvod",
"Close draft": "Zavřít koncept",
"Collisions": "Kolize",
"Colour": "Barva",
+ "Comment": "Komentář",
"Component1": "Komponenta1",
"Configuration": "Konfigurace",
"Configuration rules": "Pravidla konfigurace",
@@ -83,6 +88,7 @@
"Curvature (G2)": "Křivost (G2)",
"Curvature change (G3)": "Změna křivosti (G3)",
"Customize Toolbar": "Přizpůsobit panel nástrojů",
+ "Delete": "Odstranit",
"Delete all": "Smazat vše",
"Delete rule": "Smazat pravidlo",
"Delete the row": "Smazat řádek",
@@ -98,15 +104,19 @@
"Double-clicking the middle button in the view: Home (the home view, framing what is shown), Fit (frame what is shown, keeping the orientation) or nothing": "Dvojklik prostředním tlačítkem v pohledu: Domů (výchozí pohled se zobrazením všeho), Přizpůsobit (zobrazí vše při zachování natočení) nebo nic",
"Drive Joint": "Pohánět kloub",
"Edges": "Hrany",
+ "Edit": "Upravit",
"Edit Profile Sketch": "Upravit náčrt profilu",
"Enable rule": "Povolit pravidlo",
"Enabled": "Povoleno",
"Explode": "Rozložit",
"Export Animation…": "Exportovat animaci…",
+ "Export CSV…": "Exportovat CSV…",
"Export Current View as DXF": "Exportovat aktuální pohled do DXF",
"Export Current View as DXF…": "Exportovat aktuální pohled do DXF…",
"Export DXF…": "Exportovat DXF…",
+ "Export JSON…": "Exportovat JSON…",
"Export hidden edges as dashed lines": "Exportovat skryté hrany čárkovaně",
+ "Expression": "Výraz",
"Extend to meet": "Prodloužit k protnutí",
"Extents": "Rozsahy",
"FILES": "SOUBORY",
@@ -115,7 +125,9 @@
"Face attachment lost": "Připojení k ploše ztraceno",
"Faces": "Plochy",
"Faces / edges / vertices": "Plochy / hrany / vrcholy",
+ "Favorites": "Oblíbené",
"Favourite": "Oblíbené",
+ "Feature": "Prvek",
"Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "Soubory z mnoha CAD programů mají osu Y nahoru, proto se zde otevřou ležící na zádech (Z nahoru).",
"Filter": "Filtr",
"Find in Browser": "Najít v prohlížeči",
@@ -134,6 +146,7 @@
"Holes (edges on them)": "Otvory (jejich hrany)",
"Home view": "Výchozí pohled",
"IMAGES": "OBRÁZKY",
+ "Import…": "Importovat…",
"In This Design": "V tomto návrhu",
"In place (surfaces)": "Na místě (plochy)",
"In plane": "V rovině",
@@ -154,7 +167,9 @@
"Length units": "Jednotky délky",
"Letter Spacing": "Mezery mezi písmeny",
"Library": "Knihovna",
+ "Library file": "Soubor knihovny",
"Line Spacing": "Řádkování",
+ "Local library": "Místní knihovna",
"Loop": "Smyčka",
"MANAGE": "SPRÁVA",
"MATERIALS": "MATERIÁLY",
@@ -162,20 +177,27 @@
"MOTION": "POHYB",
"Margin": "Okraj",
"Mass": "Hmotnost",
+ "Matched restrictions check the final values.": "Odpovídající omezení kontrolují konečné hodnoty.",
"Material": "Materiál",
"Max": "Max",
"Mid Radius": "Střední poloměr",
"Middle double-click": "Dvojklik prostředním tlačítkem",
"Min": "Min",
"Mitre": "Pokos",
+ "Model Parameters": "Parametry modelu",
"Modeled": "Modelovaný",
"More toolbar panels": "Další panely nástrojů",
"Motion": "Pohyb",
"Move Type": "Typ posunu",
+ "Move down": "Posunout dolů",
"Move earlier": "Posunout dříve",
"Move later": "Posunout později",
+ "Move up": "Posunout nahoru",
"Name": "Název",
+ "New": "Nový",
+ "New rule…": "Nové pravidlo…",
"No crash reports.": "Žádná hlášení o pádech.",
+ "No matching appearance presets.": "Žádné odpovídající předvolby vzhledu.",
"No matching appearances": "Žádné odpovídající vzhledy",
"No visible bodies to export.": "Žádná viditelná tělesa k exportu.",
"None": "Žádné",
@@ -185,11 +207,14 @@
"OUTPUT": "VÝSTUP",
"Opacity": "Neprůhlednost",
"Open GitHub draft": "Otevřít koncept na GitHubu",
+ "Open local libraries in the desktop app. You can export this design's library here.": "Místní knihovny otevřete v desktopové aplikaci. Zde můžete exportovat knihovnu tohoto návrhu.",
"Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "Open-source parametrický 3D CAD v jazyce Rust. Licence MIT OR Apache-2.0.",
+ "Operator": "Operátor",
"Other side": "Druhá strana",
"Other surface (mutual trim)": "Druhá plocha (vzájemné oříznutí)",
"Outside": "Vně",
"Overall length": "Celková délka",
+ "Parameter": "Parametr",
"Parameter values": "Hodnoty parametrů",
"Pass through": "Procházet skrz",
"Path": "Cesta",
@@ -241,6 +266,8 @@
"Roll History Marker Here": "Přesunout značku historie sem",
"Round": "Zaoblený",
"Rule": "Pravidlo",
+ "Rule name": "Název pravidla",
+ "Rules run from top to bottom. Matched drives change effective values.": "Pravidla se spouštějí shora dolů. Odpovídající řídicí pravidla mění účinné hodnoty.",
"SECTION": "ŘEZ",
"SURFACE QUALITY": "KVALITA POVRCHU",
"Save Rule": "Uložit pravidlo",
@@ -249,6 +276,7 @@
"Scale factor": "Měřítko",
"Search": "Hledat",
"Search commands": "Hledat příkazy",
+ "Search this library": "Prohledat tuto knihovnu",
"Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Vybrat jiné: podržte levé tlačítko na modelu (nebo pravé tlačítko › Vybrat jiné…) a zobrazí se vše pod kurzorem; dalším kliknutím na stejné místo vyberete další prvek. Dvojklikem prostředním tlačítkem přejdete na výchozí pohled (Předvolby › Navigace).",
"Select bodies (a face picks its body)": "Vyberte tělesa (plocha vybere své těleso)",
"Select bodies or faces instead": "Vyberte místo toho tělesa nebo plochy",
@@ -303,11 +331,13 @@
"Turn off section analysis before exporting the view.": "Před exportem pohledu vypněte analýzu řezu.",
"Type": "Typ",
"UNTRIM": "ZRUŠIT OŘEZ",
+ "Unit": "Jednotka",
"Updating the preview": "Aktualizace náhledu",
"Use active author placement": "Použít aktivní umístění autora",
"Use fixed plane": "Použít pevnou rovinu",
"Use saved fixed plane": "Použít uloženou pevnou rovinu",
"Use selected face as fixed plane": "Použít vybranou plochu jako pevnou rovinu",
+ "User Parameters": "Uživatelské parametry",
"VIEW": "POHLED",
"VIEWS": "POHLEDY",
"Value": "Hodnota",
@@ -321,6 +351,12 @@
"When": "Když",
"Width": "Šířka",
"Will fail": "Selže",
+ "X angle": "Úhel X",
+ "X distance": "Vzdálenost X",
+ "Y angle": "Úhel Y",
+ "Y distance": "Vzdálenost Y",
+ "Z angle": "Úhel Z",
+ "Z distance": "Vzdálenost Z",
"angle, height": "úhel, výška",
"appearance.dielectric_ior": "Index lomu dielektrika",
"appearance.metallic": "Kovovost",
@@ -329,7 +365,11 @@
"appearance.roughness": "Drsnost",
"appearance.surface_response": "Odezva povrchu",
"browser.body_name": "Těleso{number}",
+ "browser.capture_many": "Byly přesunuty komponenty ({count}), ale jejich polohy nejsou zachyceny.",
+ "browser.capture_note": "Zachycení polohy ponechá novou polohu; vrácení obnoví původní.",
+ "browser.capture_one": "Komponenta byla přesunuta, ale její poloha není zachycena.",
"browser.component_name": "Komponenta{number}",
+ "browser.move_title": "Přesunout: {name}",
"browser.parameters": "Parametry ({count})",
"browser.precision": "Přesnost: {precision}",
"browser.sketch_name": "Náčrt{number}",
@@ -652,6 +692,8 @@
"cmd.view_rename": "Přejmenovat pojmenovaný pohled",
"cmd.view_save": "Nový pojmenovaný pohled",
"command name": "název příkazu",
+ "contact.components_count": "Počet komponent: {count}",
+ "contact.enabled_label": "povoleno",
"coupling.gear_1": "Kolo 1",
"coupling.gear_1_pick": "Kolo 1 (volitelné)",
"coupling.gear_2": "Kolo 2",
@@ -668,8 +710,11 @@
"coupling.rack": "Hřeben",
"coupling.radius_1": "Poloměr 1",
"coupling.radius_2": "Poloměr 2",
+ "delete.and_more": "… a další ({count})",
"dialog.computing": "Výpočet… {seconds} s",
"dialog.custom_axis": "↖ Vlastní osa",
+ "dialog.dimension_insert_hint": "Dvojklikem na jiný řídicí kótu vložíte jeho název",
+ "dialog.dimension_name": "Kóta: {name}",
"dialog.edit_title": "UPRAVIT {title}",
"dialog.select": "↖ Vybrat",
"dialog.selected_count": "↖ Vybráno: {count}",
@@ -696,6 +741,15 @@
"expression, e.g. 25 mm": "výraz, např. 25 mm",
"fits the face, e.g. M8": "odpovídá ploše, např. M8",
"from the rule": "z pravidla",
+ "help.apache": "Licence Apache 2.0",
+ "help.attributions": "Uvedení autorství (ATTRIBUTION.md)",
+ "help.build": "Verze {version} · commit {commit} · sestaveno {date}",
+ "help.font_details": "Rozhraní používá vestavěná písma egui (Ubuntu Light a Hack pod licencemi Ubuntu Font Licence a MIT/Bitstream Vera; Noto Emoji a písmo ikon emoji pod licencemi OFL a MIT). Text náčrtu používá Liberation Sans (SIL OFL 1.1). Volitelný balíček písem craft-fonts od The Crafting Apps (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1) není součástí sestavení SolidCraft.",
+ "help.fonts": "Písma",
+ "help.licences": "Licence",
+ "help.mit": "Licence MIT",
+ "help.notice": "NOTICE",
+ "help.third_party": "Licence třetích stran",
"home.documentation": "Dokumentace",
"home.in_this_browser": "v tomto prohlížeči",
"home.missing": "chybí",
@@ -724,6 +778,18 @@
"joint.from_bodies_hint": "Každé vybrané těleso se přesune do vlastní nové komponenty a zůstane na místě.",
"joint.one_body": "Oba výběry jsou na {body}. Druhý vyberte na jiném dílu.",
"joint.one_component": "Tyto díly jsou tělesy jedné komponenty: {bodies}. Kloub pohybuje jednou komponentou vůči druhé, takže každý díl potřebuje vlastní komponentu.",
+ "keymap.command_id": "ID příkazu",
+ "keymap.empty": "Žádné odpovídající příkazy",
+ "keymap.use_anyway": "Přesto zde použít {key}",
+ "manage.appearance_hint": "Vyberte vzhled pro výběr nebo přetáhněte vzorek na těleso či plochu.",
+ "manage.assign_hint": "Vyberte tělesa a zvolte jejich pravidlo návrhu plastových dílů.",
+ "manage.config_hint": "Upravte řádky, sloupce a pravidla konfigurace a poté řádek aktivujte nebo zobrazte jeho náhled.",
+ "manage.empty": "Žádné odpovídající řádky.",
+ "manage.material_hint": "Vyberte tělesa a zvolte jejich fyzikální materiál.",
+ "manage.parameters_hint": "Upravte výrazy a jednotky. Změny se použijí po stisknutí Enter nebo opuštění pole.",
+ "manage.rules_hint": "Vyberte pravidlo k úpravě nebo vytvořte nové. Potvrzením pravidlo uložíte.",
+ "measure.at": "V bodě",
+ "measure.item": "Položka {number}",
"messages.ago_h": "před {n} h",
"messages.ago_min": "před {n} min",
"messages.ago_s": "před {n} s",
@@ -733,6 +799,14 @@
"messages.menu": "Zprávy…",
"messages.none": "Zatím žádné zprávy.",
"messages.title": "Zprávy",
+ "motion.delete_key": "Odstranit klíčový snímek",
+ "motion.key_here": "Vložit klíčový snímek sem",
+ "motion.key_here_hint": "Přidat v tomto kroku klíčový snímek s aktuální hodnotou kloubu",
+ "motion.step_back": "Krok zpět",
+ "motion.step_forward": "Krok vpřed",
+ "motion.to_end": "Na konec",
+ "motion.to_start": "Na začátek",
+ "motion.track_name": "Stopa {number}",
"nav.touchpad.help": "Podržením Shift a pohybem ukazatele posouváte; podržením Alt/Option a pohybem otáčíte. Tlačítko myši není potřeba. Svislé posouvání přibližuje.",
"nav.touchpad.label": "Touchpad",
"nav.touchpad.orbit": "Otáčení (podržte Alt/Option a pohybujte; bez tlačítka myši)",
@@ -746,6 +820,8 @@
"no interference": "bez kolize",
"no joint that moves yet": "zatím žádný pohyblivý kloub",
"no picture": "bez obrázku",
+ "none": "žádné",
+ "parts.automatic_name": "automaticky",
"pattern.alignment_2": "Zarovnání 2",
"pattern.alignment_hint": "Počty zahrnují originál. Na střed rozloží kopie rovnoměrně; Převrátit volí stranu navíc u sudých počtů.",
"pattern.direction_1": "Směr 1",
@@ -753,6 +829,9 @@
"pattern.flip_direction": "Převrátit směr",
"pick a hole to seat it, or OK places it at the origin": "vyberte otvor pro usazení, nebo OK umístí do počátku",
"pick one or two vertices, edges or faces": "vyberte jeden nebo dva vrcholy, hrany či plochy",
+ "prefs.cpu": "CPU (softwarově)",
+ "prefs.minutes_suffix": " min",
+ "properties.title": "Vlastnosti: {name}",
"render.background": "Pozadí scény",
"render.fit": "Přizpůsobit produktu",
"render.image_cancel": "Zrušit render",
@@ -815,6 +894,10 @@
"settings.reset_intro": "Tato nastavení na tomto počítači nefungují a bránila by spuštění SolidCraftu, proto byla změněna:",
"settings.reset_title": "Nastavení byla změněna",
"settings.supersampling_note": "Vykresluje pohled ve vyšším rozlišení a poté jej zmenšuje: hladší hrany, čáry a mřížka na obrazovkách pod 4K. Stojí výkon GPU: asi 2,25× více pixelů při 1,5× a 4× při 2×.",
+ "shortcut.json_error": "parametry musí být ve formátu JSON: {error}",
+ "shortcut.no_command": "příkaz `{id}` neexistuje; text před JSON musí být ID příkazu",
+ "shortcut.pin": "Připnout nahoru do pole S",
+ "shortcut.unpin": "Odepnout",
"sketch.degrees_of_freedom": "Stupně volnosti: {count}",
"sketch.dof_left": "Zbývající stupně volnosti: {count}",
"sketch.dof_left_one": "Zbývá {count} stupeň volnosti",
@@ -848,6 +931,7 @@
"timeline.reorder_many": "Změnit pořadí prvků",
"timeline.ungroup": "Odebrat složky prvků",
"to the next face": "k další ploše",
+ "toolbar.customize_note": "Karta {tab}. Zaškrtnutím příkazu přidáte jeho tlačítko na panel nástrojů. Můžete také přetáhnout řádek z rozbalovací nabídky panelu na panel nástrojů, odstranit tlačítko přetažením mimo panel nástrojů nebo použít připínáček na řádku rozbalovací nabídky.",
"toolbar.image": "OBRÁZEK",
"toolbar.render": "RENDER",
"toolbar.render_scene": "SCÉNA",
@@ -901,6 +985,7 @@
"ui.agent_chat_new": "Nový chat",
"ui.agent_chat_new_confirm": "Začít nový chat? Aktuální bude vymazán.",
"ui.agent_chat_new_yes": "Nový chat",
+ "ui.agent_chat_next_picture": "Další obrázek",
"ui.agent_chat_no_cli": "Vedle aplikace nebyl nalezen solidcraft-cli, takže agent nemá přístup k návrhu.",
"ui.agent_chat_no_control": "Endpoint chatu s agentem se nespustil, takže agent nemá přístup k návrhu.",
"ui.agent_chat_no_images": "Tento agent nepřijímá obrázky",
@@ -912,6 +997,7 @@
"ui.agent_chat_pick": "Agent",
"ui.agent_chat_placeholder": "Požádejte agenta o změnu návrhu…",
"ui.agent_chat_placeholder_busy": "Zařadit zprávu, až agent skončí (Ctrl+Enter: odeslat hned)",
+ "ui.agent_chat_previous_picture": "Předchozí obrázek",
"ui.agent_chat_privacy": "Nic se nikam neodesílá, jen agentovi, kterého spouštíte pod vlastním účtem.",
"ui.agent_chat_privacy_note": "SolidCraft nic nikam neodesílá: agent, kterého spouštíte, komunikuje se svou službou pod vaším účtem. SolidCraft nikdy nevidí ani neukládá klíč či heslo.",
"ui.agent_chat_queue": "Zařadit",
@@ -965,6 +1051,7 @@
"ui.ai_bad_url": "Zadejte URL začínající http:// nebo https://",
"ui.ai_base_url": "Základní URL",
"ui.ai_button": "AI",
+ "ui.ai_command_hint": "my-agent --acp",
"ui.ai_copy_suffix": "kopie",
"ui.ai_custom_url": "Vlastní URL",
"ui.ai_default": "Výchozí",
@@ -985,8 +1072,10 @@
"ui.ai_mode_edits_note": "Modelovací příkazy běží bez ptaní; ukládání, otevírání, export a další souborové či destruktivní akce se stále ptají.",
"ui.ai_mode_global": "Podle nastavení výše",
"ui.ai_model": "Model",
+ "ui.ai_model_hint": "qwen3:14b",
"ui.ai_modes_scope": "Tato nastavení se týkají nástrojů SolidCraftu. Vlastní nástroje agenta (jeho shell, úpravy souborů) se řídí jeho vlastním režimem, který zvolíte v záhlaví panelu chatu, pokud agent režimy má.",
"ui.ai_name": "Název",
+ "ui.ai_name_hint": "Můj agent",
"ui.ai_need_command": "Zadejte příkaz, který spouští agenta",
"ui.ai_need_model": "Zadejte název modelu",
"ui.ai_no_answer": "Agent neodpověděl včas",
@@ -1017,6 +1106,7 @@
"ui.ai_toolbar_button": "Zobrazit tlačítko na panelu nástrojů",
"ui.ai_toolbar_button_note": "Tlačítko AI na pravém konci panelu nástrojů. Ctrl+Shift+A a nabídka Zobrazit panel otevřou i tak.",
"ui.ai_undo_tip": "Vrátit jedním krokem vše, co agent u této zprávy změnil",
+ "ui.ai_url_hint": "https://example.com/v1",
"ui.all": "Vše",
"ui.analysis": "Analýza",
"ui.angle": "Úhel",
@@ -1577,5 +1667,6 @@
"update.title": "Je k dispozici aktualizace",
"update.up_to_date": "SolidCraft je aktuální.",
"update.update_now": "Aktualizovat nyní",
- "update.you_have": "Máte {version}."
+ "update.you_have": "Máte {version}.",
+ "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ vybrat · Enter / Tab doplnit · Esc zavřít"
}
diff --git a/assets/locales/de.json b/assets/locales/de.json
index a9b92f76fd..7148159530 100644
--- a/assets/locales/de.json
+++ b/assets/locales/de.json
@@ -7,9 +7,12 @@
"AI": "KI",
"ARRANGE": "ANORDNEN",
"Acceleration": "Beschleunigung",
+ "Actions": "Aktionen",
+ "Add or edit rule": "Regel hinzufügen oder bearbeiten",
"Against": "Gegen",
"Alignment": "Ausrichtung",
"All components": "Alle Komponenten",
+ "Apply your appearance first. Exports assigned appearances and materials created in this design.": "Wenden Sie zuerst Ihr Erscheinungsbild an. Exportiert zugewiesene Erscheinungsbilder und in diesem Design erstellte Materialien.",
"Arc length": "Bogenlänge",
"Area": "Fläche",
"BROWSER": "BROWSER",
@@ -21,10 +24,14 @@
"CONSTRAIN": "ABHÄNGIGKEITEN",
"CONTACT": "KONTAKT",
"CONVERT": "KONVERTIEREN",
+ "CSV or JSON: updates existing parameters, adds new ones": "CSV or JSON: updates existing parameters, adds new ones",
"Centre to centre": "Mitte zu Mitte",
"Check collisions": "Kollisionen prüfen",
+ "Choose…": "Auswählen…",
"Circumference": "Umfang",
"Collisions": "Kollisionen",
+ "Comment": "Kommentar",
+ "Configuration rules": "Configuration rules",
"Construction": "Konstruktionslinie",
"Contact sets": "Kontaktsätze",
"Continuity": "Stetigkeit",
@@ -35,24 +42,34 @@
"Current perspective view": "Aktuelle perspektivische Ansicht",
"Curvature (G2)": "Krümmung (G2)",
"Curvature change (G3)": "Krümmungsänderung (G3)",
+ "Delete": "Löschen",
"Direction": "Richtung",
"Do not export hidden edges": "Verdeckte Kanten nicht exportieren",
"Don't ask again": "Nicht mehr fragen",
+ "Double-click to rename": "Double-click to rename",
"Drive Joint": "Gelenk antreiben",
"Duration": "Dauer",
"Edges": "Kanten",
+ "Edit": "Bearbeiten",
"Edit Profile Sketch": "Profile-Skizze bearbeiten",
"Explode Text": "Text auflösen",
"Export Animation…": "Animation exportieren…",
+ "Export CSV…": "CSV exportieren…",
"Export Current View as DXF": "Aktuelle Ansicht als DXF exportieren",
"Export Current View as DXF…": "Aktuelle Ansicht als DXF exportieren…",
"Export DXF…": "DXF exportieren…",
+ "Export JSON…": "JSON exportieren…",
"Export hidden edges as dashed lines": "Verdeckte Kanten gestrichelt exportieren",
+ "Expression": "Ausdruck",
"Extend to meet": "Verlängern, bis sie sich treffen",
"FILES": "DATEIEN",
"FLAT": "ABWICKLUNG",
"Face": "Fläche",
"Faces": "Flächen",
+ "Favorites": "Favoriten",
+ "Favourite": "Favourite",
+ "Feature": "Funktion",
+ "Filter": "Filter",
"Find in Browser": "Im Browser suchen",
"Flat": "Flach",
"From edges": "Ausgangskanten",
@@ -61,6 +78,7 @@
"Holes": "Löcher",
"Holes (edges on them)": "Löcher (ihre Kanten)",
"IMAGES": "BILDER",
+ "Import…": "Importieren…",
"In place (surfaces)": "An Ort und Stelle (Flächen)",
"In plane": "In der Ebene",
"Inside": "Innen",
@@ -70,22 +88,38 @@
"LIBRARY": "BIBLIOTHEK",
"LINKS": "VERKNÜPFUNGEN",
"Length": "Länge",
+ "Length units": "Length units",
+ "Library file": "Bibliotheksdatei",
+ "Local library": "Lokale Bibliothek",
"MANAGE": "VERWALTEN",
"MATERIALS": "MATERIALIEN",
"MODEL": "MODELL",
"MOTION": "BEWEGUNG",
+ "Matched restrictions check the final values.": "Zutreffende Einschränkungen prüfen die endgültigen Werte.",
"Max": "Max",
"Min": "Min",
"Mitre": "Gehrung",
+ "Model Parameters": "Modellparameter",
+ "Move down": "Nach unten",
+ "Move up": "Nach oben",
+ "Name": "Name",
+ "New": "Neu",
+ "New rule…": "Neue Regel…",
"New study": "Neue Untersuchung",
+ "No matching appearance presets.": "Keine passenden Erscheinungsbildvorlagen.",
"No visible bodies to export.": "Keine sichtbaren Körper zum Exportieren.",
"None": "Keine",
"Normal to sketch": "Normal zur Skizze",
"Notch": "Ausklinkung",
"OUTPUT": "AUSGABE",
+ "Open local libraries in the desktop app. You can export this design's library here.": "Öffnen Sie lokale Bibliotheken in der Desktop-App. Die Bibliothek dieses Designs können Sie hier exportieren.",
+ "Operator": "Operator",
+ "Other surface (mutual trim)": "Anderer Flächenkörper (gegenseitig trimmen)",
+ "OUTPUT": "AUSGABE",
"Other surface (mutual trim)": "Anderer Flächenkörper (gegenseitig trimmen)",
"Outside": "Außen",
"Overall length": "Gesamtlänge",
+ "Parameter": "Parameter",
"Pass through": "Durch Punkte",
"Picked": "Ausgewählte",
"Picked point": "Gewählter Punkt",
@@ -105,9 +139,13 @@
"Restore outer boundary": "Äußere Begrenzung wiederherstellen",
"Revert Position": "Position zurücksetzen",
"Round": "Rund",
+ "Rule": "Rule",
+ "Rule name": "Regelname",
+ "Rules run from top to bottom. Matched drives change effective values.": "Regeln werden von oben nach unten ausgeführt. Zutreffende Steuerungen ändern die wirksamen Werte.",
"SECTION": "SCHNITT",
"SURFACE QUALITY": "OBERFLÄCHENQUALITÄT",
"Save the study as an animated GIF, seen as the viewport shows it": "Die Studie als animiertes GIF speichern, so wie der Ansichtsbereich sie zeigt",
+ "Search this library": "Diese Bibliothek durchsuchen",
"Select bodies (a face picks its body)": "Körper auswählen (eine Fläche wählt ihren Körper)",
"Selection filter": "Auswahlfilter",
"Send your report on GitHub": "Bericht auf GitHub senden",
@@ -124,6 +162,7 @@
"TRIM": "TRIMMEN",
"Tangent (G1)": "Tangente (G1)",
"Tear": "Reißen",
+ "Then": "Then",
"Thickness Outside": "Dicke außen",
"Thin": "Dünnwandig",
"Thin Extrude": "Dünnwandig extrudieren",
@@ -132,12 +171,22 @@
"Turn off section analysis before exporting the view.": "Deaktivieren Sie die Schnittanalyse, bevor Sie die Ansicht exportieren.",
"Type": "Typ",
"UNTRIM": "TRIMMEN AUFHEBEN",
+ "Unit": "Einheit",
+ "User Parameters": "Benutzerparameter",
"VIEWS": "ANSICHTEN",
+ "Value": "Value",
"Velocity": "Geschwindigkeit",
"Vertices": "Scheitelpunkte",
"Visible bodies only. Curves use line segments (0.01 mm tolerance).": "Nur sichtbare Körper. Kurven werden durch Liniensegmente angenähert (Toleranz: 0,01 mm).",
"Wall Location": "Wandlage",
"Wall Thickness": "Wandstärke",
+ "When": "When",
+ "X angle": "X-Winkel",
+ "X distance": "X-Abstand",
+ "Y angle": "Y-Winkel",
+ "Y distance": "Y-Abstand",
+ "Z angle": "Z-Winkel",
+ "Z distance": "Z-Abstand",
"appearance.dielectric_ior": "Brechungsindex des Dielektrikums",
"appearance.metallic": "Metallanteil",
"appearance.pbr_help": "Diese Oberfläche in Render oder einem Produkt-PNG ansehen. Keine Brechung oder Transmission.",
@@ -145,7 +194,11 @@
"appearance.roughness": "Rauheit",
"appearance.surface_response": "Oberflächenverhalten",
"browser.body_name": "Körper {number}",
+ "browser.capture_many": "{count} Komponenten wurden verschoben, ihre Positionen sind aber nicht erfasst.",
+ "browser.capture_note": "„Position erfassen“ behält die neue Position bei; „Position zurücksetzen“ stellt die vorherige wieder her.",
+ "browser.capture_one": "Eine Komponente wurde verschoben, ihre Position ist aber nicht erfasst.",
"browser.component_name": "Komponente {number}",
+ "browser.move_title": "Verschieben: {name}",
"browser.parameters": "Parameter ({count})",
"browser.precision": "Genauigkeit: {precision}",
"browser.sketch_name": "Skizze {number}",
@@ -471,6 +524,8 @@
"cmd.view_navigate": "Ansicht navigieren",
"cmd.view_rename": "Benannte Ansicht umbenennen",
"cmd.view_save": "Neue benannte Ansicht",
+ "contact.components_count": "{count} Komponenten",
+ "contact.enabled_label": "aktiviert",
"coupling.gear_1": "Zahnrad 1",
"coupling.gear_1_pick": "Zahnrad 1 (optional)",
"coupling.gear_2": "Zahnrad 2",
@@ -487,6 +542,7 @@
"coupling.rack": "Zahnstange",
"coupling.radius_1": "Radius 1",
"coupling.radius_2": "Radius 2",
+ "delete.and_more": "… und {count} weitere",
"dialog.bodies_count": "{count} Körper",
"dialog.clearance_invalid": "der Abstand muss eine Länge von 0 oder mehr sein",
"dialog.compute": "Berechnen",
@@ -494,6 +550,8 @@
"dialog.computing": "Wird berechnet… {seconds} s",
"dialog.could_not_be_checked": "nicht prüfbar",
"dialog.custom_axis": "↖ Eigene Achse",
+ "dialog.dimension_insert_hint": "Doppelklicken Sie auf eine andere steuernde Bemaßung, um ihren Namen einzufügen",
+ "dialog.dimension_name": "Bemaßung: {name}",
"dialog.edit_title": "{title} bearbeiten",
"dialog.select": "↖ Auswählen",
"dialog.selected_count": "↖ {count} ausgewählt",
@@ -517,6 +575,15 @@
"dxf.progress.write": "DXF schreiben (5/5)",
"dxf.tolerance": "Kurventoleranz",
"dxf.tolerance_help": "Nur sichtbare Körper. Kurven werden durch gerade Segmente angenähert. Eine kleinere Toleranz liefert feinere Kurven und benötigt mehr Zeit und Speicher.",
+ "help.apache": "Apache-Lizenz 2.0",
+ "help.attributions": "Quellenangaben (ATTRIBUTION.md)",
+ "help.build": "Version {version} · Commit {commit} · erstellt am {date}",
+ "help.font_details": "Die Oberfläche verwendet die integrierten Schriftarten von egui (Ubuntu Light und Hack unter der Ubuntu Font Licence und der MIT/Bitstream-Vera-Lizenz; Noto Emoji und die Emoji-Symbolschrift unter OFL und MIT). Skizzentext verwendet Liberation Sans (SIL OFL 1.1). Das optionale Schriftpaket craft-fonts von The Crafting Apps (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1) ist nicht in SolidCraft-Builds enthalten.",
+ "help.fonts": "Schriftarten",
+ "help.licences": "Lizenzen",
+ "help.mit": "MIT-Lizenz",
+ "help.notice": "NOTICE",
+ "help.third_party": "Drittanbieterlizenzen",
"home.documentation": "Dokumentation",
"home.in_this_browser": "in diesem Browser",
"home.missing": "fehlt",
@@ -545,21 +612,47 @@
"joint.from_bodies_hint": "Jeder ausgewählte Körper kommt in eine eigene neue Komponente und bleibt, wo er ist.",
"joint.one_body": "Beide Auswahlen liegen auf {body}. Wählen Sie die zweite auf einem anderen Teil.",
"joint.one_component": "Diese Teile sind Körper einer Komponente: {bodies}. Ein Gelenk bewegt eine Komponente gegenüber einer anderen, daher braucht jedes Teil eine eigene Komponente.",
+ "keymap.command_id": "Befehls-ID",
+ "keymap.empty": "Keine passenden Befehle",
+ "keymap.use_anyway": "{key} hier trotzdem verwenden",
+ "manage.appearance_hint": "Wählen Sie ein Erscheinungsbild für die Auswahl oder ziehen Sie ein Farbmuster auf einen Körper oder eine Fläche.",
+ "manage.assign_hint": "Wählen Sie Körper und deren Kunststoff-Konstruktionsregel aus.",
+ "manage.config_hint": "Bearbeiten Sie Konfigurationszeilen, Spalten und Regeln und aktivieren Sie dann eine Zeile oder zeigen Sie deren Vorschau an.",
+ "manage.empty": "Keine passenden Zeilen.",
+ "manage.material_hint": "Wählen Sie Körper und deren physikalisches Material aus.",
+ "manage.parameters_hint": "Bearbeiten Sie Ausdrücke und Einheiten. Änderungen werden mit der Eingabetaste oder beim Verlassen eines Feldes übernommen.",
+ "manage.rules_hint": "Wählen Sie eine Regel zum Bearbeiten oder erstellen Sie eine neue. Bestätigen Sie, um die Regel zu speichern.",
+ "measure.at": "Bei",
+ "measure.item": "Element {number}",
"motion.checked_to": "Nur bis Schritt {step} geprüft: der Prüfaufwand ist erschöpft",
"motion.collision": "{a} · {b}: Schritte {steps}",
+ "motion.delete_key": "Schlüsselbild löschen",
"motion.duration_hint": "Sekunden (leer: pro Schritt)",
+ "motion.key_here": "Schlüsselbild hier setzen",
+ "motion.key_here_hint": "Ein Schlüsselbild bei diesem Schritt mit dem aktuellen Gelenkwert hinzufügen",
"motion.no_collisions": "Keine Kollisionen in der Untersuchung",
+ "motion.step_back": "Schritt zurück",
+ "motion.step_forward": "Schritt vor",
+ "motion.to_end": "Zum Ende",
+ "motion.to_start": "Zum Anfang",
+ "motion.track_name": "Spur {number}",
"nav.touchpad.help": "Umschalt gedrückt halten und den Zeiger zum Verschieben bewegen; mit Alt/Option drehen. Keine Maustaste nötig. Vertikales Scrollen zoomt.",
"nav.touchpad.label": "Touchpad",
"nav.touchpad.orbit": "Drehen (Alt/Option halten und bewegen; ohne Maustaste)",
"nav.touchpad.pan": "Verschieben (Umschalt halten und bewegen; ohne Maustaste)",
"nav.touchpad.scroll": "Touchpad verwendet vertikales Scrollen zum Zoomen. Die Zwei-Finger-Verschiebung bleibt für andere Vorgaben gespeichert.",
"nav.touchpad.zoom": "Zoom (vertikal scrollen oder Finger spreizen/zusammenziehen)",
+ "new parameter": "new parameter",
+ "none": "keine",
+ "parts.automatic_name": "automatisch",
"pattern.alignment_2": "Ausrichtung 2",
"pattern.alignment_hint": "Die Anzahl enthält das Original. Die zentrierte Anordnung verteilt Kopien auf beide Seiten; bei gerader Anzahl legt die Richtungsumkehr die Seite mit der zusätzlichen Kopie fest.",
"pattern.direction_1": "Richtung 1",
"pattern.direction_2": "Richtung 2",
"pattern.flip_direction": "Richtung umkehren",
+ "prefs.cpu": "CPU (Software)",
+ "prefs.minutes_suffix": " min",
+ "properties.title": "Eigenschaften: {name}",
"render.background": "Szenenhintergrund",
"render.fit": "Produkt einpassen",
"render.image_cancel": "Rendering abbrechen",
@@ -622,6 +715,10 @@
"settings.reset_intro": "Diese Einstellungen funktionieren auf diesem Computer nicht und würden den Start von SolidCraft verhindern. Sie wurden daher geändert:",
"settings.reset_title": "Einstellungen wurden geändert",
"settings.supersampling_note": "Zeichnet die Ansicht in höherer Auflösung und rechnet sie herunter: glattere Kanten, Linien und Raster auf Bildschirmen unter 4K. Kostet GPU-Zeit: etwa 2,25-mal so viele Pixel bei 1,5× und 4-mal bei 2×.",
+ "shortcut.json_error": "Parameter müssen JSON sein: {error}",
+ "shortcut.no_command": "kein Befehl `{id}`; der Text vor dem JSON muss eine Befehls-ID sein",
+ "shortcut.pin": "Oben im S-Feld anheften",
+ "shortcut.unpin": "Loslösen",
"sketch.degrees_of_freedom": "{count} Freiheitsgrade",
"sketch.dof_left": "{count} Freiheitsgrade übrig",
"sketch.dof_left_one": "{count} Freiheitsgrad übrig",
@@ -653,6 +750,7 @@
"timeline.rename_group": "Merkmalsordner umbenennen",
"timeline.reorder_many": "Merkmale neu ordnen",
"timeline.ungroup": "Merkmalsordner entfernen",
+ "toolbar.customize_note": "Registerkarte {tab}. Markieren Sie einen Befehl, um ihm eine Schaltfläche in der Werkzeugleiste zu geben. Sie können auch eine Zeile aus dem Aufklappmenü eines Panels auf die Werkzeugleiste ziehen, eine Schaltfläche zum Entfernen aus der Werkzeugleiste ziehen oder die Stecknadel einer Menüzeile verwenden.",
"toolbar.image": "BILD",
"toolbar.render": "RENDERN",
"toolbar.render_scene": "SZENE",
@@ -699,6 +797,7 @@
"ui.agent_chat_left": "Links",
"ui.agent_chat_limit": "Der Agent hat die Grenze von {limit} Änderungen für eine Nachricht erreicht. Senden Sie eine weitere Nachricht, damit er weitermacht.",
"ui.agent_chat_minimize": "Zu einer Leiste minimieren",
+ "ui.agent_chat_next_picture": "Nächstes Bild",
"ui.agent_chat_no_cli": "solidcraft-cli wurde neben der App nicht gefunden, daher kann der Agent das Design nicht erreichen.",
"ui.agent_chat_no_control": "Der Endpunkt des Agenten-Chats ist nicht gestartet, daher kann der Agent das Design nicht erreichen.",
"ui.agent_chat_no_images": "Dieser Agent nimmt keine Bilder an",
@@ -709,6 +808,7 @@
"ui.agent_chat_permission": "Der Agent möchte ausführen: {title}",
"ui.agent_chat_pick": "Agent",
"ui.agent_chat_placeholder": "Bitten Sie den Agenten, das Design zu ändern…",
+ "ui.agent_chat_previous_picture": "Vorheriges Bild",
"ui.agent_chat_privacy": "Nichts geht irgendwohin außer an den Agenten, den Sie unter Ihrem eigenen Konto ausführen.",
"ui.agent_chat_privacy_note": "SolidCraft sendet nichts irgendwohin: Der Agent, den Sie starten, spricht unter Ihrem eigenen Konto mit seinem eigenen Dienst. SolidCraft sieht und speichert nie einen Schlüssel oder ein Passwort.",
"ui.agent_chat_refresh": "Aktualisieren",
@@ -753,6 +853,7 @@
"ui.ai_bad_url": "Geben Sie eine URL ein, die mit http:// oder https:// beginnt",
"ui.ai_base_url": "Basis-URL",
"ui.ai_button": "KI",
+ "ui.ai_command_hint": "my-agent --acp",
"ui.ai_copy_suffix": "Kopie",
"ui.ai_custom_url": "Eigene URL",
"ui.ai_default": "Standard",
@@ -773,8 +874,10 @@
"ui.ai_mode_edits_note": "Modellierbefehle laufen ohne Nachfrage; Speichern, Öffnen, Exportieren und andere Datei- oder destruktive Aktionen fragen weiterhin.",
"ui.ai_mode_global": "Wie oben eingestellt",
"ui.ai_model": "Modell",
+ "ui.ai_model_hint": "qwen3:14b",
"ui.ai_modes_scope": "Diese Einstellungen gelten für die Werkzeuge von SolidCraft. Die eigenen Werkzeuge eines Agenten (seine Shell, seine Dateiänderungen) folgen seinem eigenen Modus, den Sie im Kopf des Chat-Panels wählen, wenn der Agent Modi hat.",
"ui.ai_name": "Name",
+ "ui.ai_name_hint": "Mein Agent",
"ui.ai_need_command": "Geben Sie den Befehl ein, der den Agenten startet",
"ui.ai_need_model": "Geben Sie den Modellnamen ein",
"ui.ai_no_answer": "Der Agent hat nicht rechtzeitig geantwortet",
@@ -805,6 +908,7 @@
"ui.ai_toolbar_button": "Schaltfläche in der Werkzeugleiste anzeigen",
"ui.ai_toolbar_button_note": "Die KI-Schaltfläche am rechten Ende der Werkzeugleiste. Strg+Umschalt+A und das Ansicht-Menü öffnen das Panel weiterhin.",
"ui.ai_undo_tip": "Alles, was der Agent für diese Nachricht geändert hat, in einem Schritt rückgängig machen",
+ "ui.ai_url_hint": "https://example.com/v1",
"ui.all": "Alle",
"ui.ambient_occlusion": "Umgebungsverdeckung",
"ui.ambient_occlusion_help": "Sanfte Schattierung an Kontaktstellen und in Vertiefungen undurchsichtiger Flächen. Erfordert die GPU-Ansicht.",
@@ -1346,5 +1450,6 @@
"update.title": "Update verfügbar",
"update.up_to_date": "SolidCraft ist aktuell.",
"update.update_now": "Jetzt aktualisieren",
- "update.you_have": "Installiert ist {version}."
+ "update.you_have": "Installiert ist {version}.",
+ "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ auswählen · Eingabe / Tab vervollständigen · Esc schließen"
}
diff --git a/assets/locales/en.json b/assets/locales/en.json
index 3adf554da0..933fbcd17b 100644
--- a/assets/locales/en.json
+++ b/assets/locales/en.json
@@ -11,6 +11,7 @@
"About SolidCraft": "About SolidCraft",
"Acceleration": "Acceleration",
"Access": "Access",
+ "Actions": "Actions",
"Active": "Active",
"Active rule": "Active rule",
"Add": "Add",
@@ -18,6 +19,7 @@
"Add Mid Radius": "Add Mid Radius",
"Add Row": "Add Row",
"Add condition": "Add condition",
+ "Add or edit rule": "Add or edit rule",
"Against": "Against",
"Alignment": "Alignment",
"All Sketch Points": "All Sketch Points",
@@ -31,6 +33,7 @@
"Applied Radius": "Applied Radius",
"Apply To": "Apply To",
"Apply to selection": "Apply to selection",
+ "Apply your appearance first. Exports assigned appearances and materials created in this design.": "Apply your appearance first. Exports assigned appearances and materials created in this design.",
"Arc length": "Arc length",
"Area": "Area",
"As-Built": "As-Built",
@@ -67,11 +70,13 @@
"Check collisions": "Check collisions",
"Checked": "Checked",
"Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.",
+ "Choose…": "Choose…",
"Circular": "Circular",
"Circumference": "Circumference",
"Close draft": "Close draft",
"Collisions": "Collisions",
"Colour": "Colour",
+ "Comment": "Comment",
"Component1": "Component1",
"Config Table": "Config Table",
"Configuration": "Configuration",
@@ -100,6 +105,7 @@
"Curvature (G2)": "Curvature (G2)",
"Curvature change (G3)": "Curvature change (G3)",
"Customize Toolbar": "Customize Toolbar",
+ "Delete": "Delete",
"Delete all": "Delete all",
"Delete rule": "Delete rule",
"Delete the row": "Delete the row",
@@ -118,6 +124,7 @@
"Drive Joint": "Drive Joint",
"Duration": "Duration",
"Edges": "Edges",
+ "Edit": "Edit",
"Edit Profile Sketch": "Edit Profile Sketch",
"Enable rule": "Enable rule",
"Enabled": "Enabled",
@@ -126,11 +133,14 @@
"Explode": "Explode",
"Explode Text": "Explode Text",
"Export Animation…": "Export Animation…",
+ "Export CSV…": "Export CSV…",
"Export Current View as DXF": "Export Current View as DXF",
"Export Current View as DXF…": "Export Current View as DXF…",
"Export DXF": "Export DXF",
"Export DXF…": "Export DXF…",
+ "Export JSON…": "Export JSON…",
"Export hidden edges as dashed lines": "Export hidden edges as dashed lines",
+ "Expression": "Expression",
"Extend to meet": "Extend to meet",
"Extents": "Extents",
"FILES": "FILES",
@@ -140,7 +150,9 @@
"Faces": "Faces",
"Faces / edges / vertices": "Faces / edges / vertices",
"Fastener": "Fastener",
+ "Favorites": "Favorites",
"Favourite": "Favourite",
+ "Feature": "Feature",
"Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "Files from many CAD programs have Y up, so they open lying on their back here (Z up).",
"Filter": "Filter",
"Find in Browser": "Find in Browser",
@@ -164,6 +176,7 @@
"Home view": "Home view",
"Horiz./Vert.": "Horiz./Vert.",
"IMAGES": "IMAGES",
+ "Import…": "Import…",
"In This Design": "In This Design",
"In place (surfaces)": "In place (surfaces)",
"In plane": "In plane",
@@ -185,7 +198,9 @@
"Length units": "Length units",
"Letter Spacing": "Letter Spacing",
"Library": "Library",
+ "Library file": "Library file",
"Line Spacing": "Line Spacing",
+ "Local library": "Local library",
"Loop": "Loop",
"MANAGE": "MANAGE",
"MATERIALS": "MATERIALS",
@@ -194,25 +209,32 @@
"Margin": "Margin",
"Mass": "Mass",
"Mass Center": "Mass Center",
+ "Matched restrictions check the final values.": "Matched restrictions check the final values.",
"Material": "Material",
"Max": "Max",
"Mid Radius": "Mid Radius",
"Middle double-click": "Middle double-click",
"Min": "Min",
"Mitre": "Mitre",
+ "Model Parameters": "Model Parameters",
"Modeled": "Modeled",
"More toolbar panels": "More toolbar panels",
"Motion": "Motion",
"Move / Copy": "Move / Copy",
"Move Type": "Move Type",
+ "Move down": "Move down",
"Move earlier": "Move earlier",
"Move later": "Move later",
+ "Move up": "Move up",
"Name": "Name",
"Nearest": "Nearest",
+ "New": "New",
"New Comp.": "New Comp.",
"New Sketch": "New Sketch",
+ "New rule…": "New rule…",
"New study": "New study",
"No crash reports.": "No crash reports.",
+ "No matching appearance presets.": "No matching appearance presets.",
"No matching appearances": "No matching appearances",
"No visible bodies to export.": "No visible bodies to export.",
"None": "None",
@@ -222,12 +244,15 @@
"OUTPUT": "OUTPUT",
"Opacity": "Opacity",
"Open GitHub draft": "Open GitHub draft",
+ "Open local libraries in the desktop app. You can export this design's library here.": "Open local libraries in the desktop app. You can export this design's library here.",
"Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.",
+ "Operator": "Operator",
"Other side": "Other side",
"Other surface (mutual trim)": "Other surface (mutual trim)",
"Outside": "Outside",
"Overall length": "Overall length",
"Param. Graph": "Param. Graph",
+ "Parameter": "Parameter",
"Parameter values": "Parameter values",
"Parts": "Parts",
"Pass through": "Pass through",
@@ -289,6 +314,8 @@
"Roll History Marker Here": "Roll History Marker Here",
"Round": "Round",
"Rule": "Rule",
+ "Rule name": "Rule name",
+ "Rules run from top to bottom. Matched drives change effective values.": "Rules run from top to bottom. Matched drives change effective values.",
"SECTION": "SECTION",
"SURFACE QUALITY": "SURFACE QUALITY",
"Save Rule": "Save Rule",
@@ -299,6 +326,7 @@
"Scene": "Scene",
"Search": "Search",
"Search commands": "Search commands",
+ "Search this library": "Search this library",
"Section": "Section",
"Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).",
"Select bodies (a face picks its body)": "Select bodies (a face picks its body)",
@@ -360,11 +388,13 @@
"Turn off section analysis before exporting the view.": "Turn off section analysis before exporting the view.",
"Type": "Type",
"UNTRIM": "UNTRIM",
+ "Unit": "Unit",
"Updating the preview": "Updating the preview",
"Use active author placement": "Use active author placement",
"Use fixed plane": "Use fixed plane",
"Use saved fixed plane": "Use saved fixed plane",
"Use selected face as fixed plane": "Use selected face as fixed plane",
+ "User Parameters": "User Parameters",
"VIEW": "VIEW",
"VIEWS": "VIEWS",
"Value": "Value",
@@ -379,6 +409,12 @@
"When": "When",
"Width": "Width",
"Will fail": "Will fail",
+ "X angle": "X angle",
+ "X distance": "X distance",
+ "Y angle": "Y angle",
+ "Y distance": "Y distance",
+ "Z angle": "Z angle",
+ "Z distance": "Z distance",
"Zebra": "Zebra",
"angle, height": "angle, height",
"appearance.dielectric_ior": "Dielectric IOR",
@@ -388,7 +424,13 @@
"appearance.roughness": "Roughness",
"appearance.surface_response": "Surface response",
"browser.body_name": "Body{number}",
+ "browser.calibrate_title": "Calibrate: {name}",
+ "browser.capture_many": "{count} components were moved but their positions aren't captured.",
+ "browser.capture_note": "Capture keeps the new position; Revert puts it back.",
+ "browser.capture_one": "A component was moved but its position isn't captured.",
"browser.component_name": "Component{number}",
+ "browser.edit_canvas_title": "Edit Canvas: {name}",
+ "browser.move_title": "Move: {name}",
"browser.parameters": "Parameters ({count})",
"browser.precision": "Precision: {precision}",
"browser.sketch_name": "Sketch{number}",
@@ -727,6 +769,8 @@
"cmd.view_rename": "Rename Named View",
"cmd.view_save": "New Named View",
"command name": "command name",
+ "contact.components_count": "{count} components",
+ "contact.enabled_label": "enabled",
"coupling.gear_1": "Gear 1",
"coupling.gear_1_pick": "Gear 1 (optional)",
"coupling.gear_2": "Gear 2",
@@ -746,6 +790,18 @@
"crash.detected_time": "Detected {time} UTC",
"crash.previous_session": "An earlier SolidCraft session ended unexpectedly or hit an internal error. Reports from unclean exits are detected at startup. See Help > Crash Reports… for details.",
"crash.unclean_explanation": "Detected on a later launch; the exact exit time was not recorded. A system shutdown or forced stop can also cause an unclean exit.",
+ "crash.announce": "SolidCraft closed unexpectedly or hit an internal error last time. A crash report was saved (Help > Crash Reports…).",
+ "crash.copy_folder": "Copy folder path",
+ "crash.copy_path": "Copy path",
+ "crash.deleted": "Deleted {count} report(s).",
+ "crash.intro": "Crash reports stay on this computer and are never sent anywhere. Report… opens a draft you review before anything is shared.",
+ "crash.kind_command": "Internal error in a command",
+ "crash.kind_internal": "Internal error",
+ "crash.kind_kernel": "Kernel error (recovered)",
+ "crash.kind_unclean": "Closed unexpectedly",
+ "crash.replayable": "replayable",
+ "crash.report": "Report…",
+ "delete.and_more": "… and {count} more",
"dialog.bodies_count": "{count} bodies",
"dialog.clearance_invalid": "the clearance must be a length of 0 or more",
"dialog.compute": "Compute",
@@ -753,6 +809,8 @@
"dialog.computing": "Computing… {seconds} s",
"dialog.could_not_be_checked": "could not be checked",
"dialog.custom_axis": "↖ Custom Axis",
+ "dialog.dimension_insert_hint": "Double-click another driving dimension to insert its name",
+ "dialog.dimension_name": "Dimension: {name}",
"dialog.edit_title": "EDIT {title}",
"dialog.select": "↖ Select",
"dialog.selected_count": "↖ {count} selected",
@@ -777,8 +835,30 @@
"dxf.tolerance": "Curve tolerance",
"dxf.tolerance_help": "Visible bodies only. Curves use straight segments. Smaller tolerance gives finer curves and uses more time and memory.",
"expression, e.g. 25 mm": "expression, e.g. 25 mm",
+ "file_load.built": "Built so far: {built} of {total} features.",
+ "file_load.converting": "Converting solid {done} of {total}",
+ "file_load.inserting": "Inserting geometry",
+ "file_load.opening": "Opening design",
+ "file_load.preparing_thumbnail": "Preparing the thumbnail...",
+ "file_load.preparing_view": "Preparing the view...",
+ "file_load.preview_note": "Saved preview. Geometry is being checked before editing.",
+ "file_load.reading": "Reading the file...",
+ "file_load.reading_percent": "Reading the file... {percent}%",
+ "file_load.rebuilding": "Rebuilding feature {done} of {total}",
+ "file_load.recovering": "Recovering design",
+ "file_load.stopping": "Waiting for the previous operation to stop...",
+ "file_load.waiting": "Waiting for file operation",
"fits the face, e.g. M8": "fits the face, e.g. M8",
"from the rule": "from the rule",
+ "help.apache": "Apache licence 2.0",
+ "help.attributions": "Attributions (ATTRIBUTION.md)",
+ "help.build": "Version {version} · commit {commit} · built {date}",
+ "help.font_details": "The interface uses egui's built-in fonts (Ubuntu Light and Hack, under the Ubuntu Font Licence and the MIT/Bitstream Vera licence; Noto Emoji and the emoji icon font, under the OFL and MIT). Sketch text uses Liberation Sans (SIL OFL 1.1). The Crafting Apps' optional font pack, craft-fonts (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1), is not bundled in SolidCraft builds.",
+ "help.fonts": "Fonts",
+ "help.licences": "Licences",
+ "help.mit": "MIT licence",
+ "help.notice": "NOTICE",
+ "help.third_party": "Third-party licences",
"home.documentation": "Documentation",
"home.in_this_browser": "in this browser",
"home.missing": "missing",
@@ -804,9 +884,30 @@
"install.menu": "Install app…",
"install.steps_intro": "Safari installs web apps from its own menus:",
"install.title": "Install SolidCraft",
+ "issue.body_label": "Report text",
+ "issue.note_image_copied": "Paste the image into the GitHub draft, or save the PNG if image copying is unavailable.",
+ "issue.note_opened": "Review the GitHub draft and attach the screenshot. GitHub's Submit new issue button publishes it.",
+ "issue.note_opened_copied": "Report copied. Paste into the GitHub draft, attach the screenshot, then click Submit new issue on GitHub.",
+ "issue.note_removed": "Screenshot removed from this draft.",
+ "issue.note_report_copied": "Report copied. Paste it into the GitHub draft if needed.",
+ "issue.note_save_failed": "Could not save screenshot: {error}",
+ "issue.note_saved": "Screenshot saved. Attach the PNG in the GitHub draft.",
+ "issue.save_screenshot": "Save screenshot…",
"joint.from_bodies_hint": "Each picked body moves into a new component of its own and stays where it is.",
"joint.one_body": "Both picks are on {body}. Pick the second one on another part.",
"joint.one_component": "These parts are bodies of one component: {bodies}. A joint moves one component against another, so each part needs a component of its own.",
+ "keymap.command_id": "Command ID",
+ "keymap.empty": "No matching commands",
+ "keymap.use_anyway": "Use {key} here anyway",
+ "manage.appearance_hint": "Choose a look for the selection, or drag a swatch onto a body or face.",
+ "manage.assign_hint": "Select bodies and choose their plastic design rule.",
+ "manage.config_hint": "Edit configuration rows, columns and rules, then activate or preview a row.",
+ "manage.empty": "No matching rows.",
+ "manage.material_hint": "Select bodies and choose their physical material.",
+ "manage.parameters_hint": "Edit expressions and units. Changes apply on Enter or when leaving a field.",
+ "manage.rules_hint": "Choose a rule to edit, or create a new rule. Confirm to save the rule.",
+ "measure.at": "At",
+ "measure.item": "Item {number}",
"messages.ago_h": "{n} h ago",
"messages.ago_min": "{n} min ago",
"messages.ago_s": "{n} s ago",
@@ -818,8 +919,16 @@
"messages.title": "Messages",
"motion.checked_to": "Checked to step {step} only: the check ran out of its work budget",
"motion.collision": "{a} · {b}: steps {steps}",
+ "motion.delete_key": "Delete key",
"motion.duration_hint": "seconds (empty: per step)",
+ "motion.key_here": "Key here",
+ "motion.key_here_hint": "Add a key at this step with the joint's value now",
"motion.no_collisions": "No collisions over the study",
+ "motion.step_back": "Step back",
+ "motion.step_forward": "Step on",
+ "motion.to_end": "To the end",
+ "motion.to_start": "To the start",
+ "motion.track_name": "Track {number}",
"nav.touchpad.help": "Hold Shift and move the pointer to pan; hold Alt/Option and move it to orbit. No mouse button is needed. Vertical scroll zooms.",
"nav.touchpad.label": "Touchpad",
"nav.touchpad.orbit": "Orbit (hold Alt/Option and move; no mouse button)",
@@ -835,6 +944,7 @@
"no joint that moves yet": "no joint that moves yet",
"no picture": "no picture",
"none": "none",
+ "parts.automatic_name": "automatic",
"pattern.alignment_2": "Alignment 2",
"pattern.alignment_hint": "Counts include the original. Center balances copies; Flip chooses the extra side for even totals.",
"pattern.direction_1": "Direction 1",
@@ -842,6 +952,15 @@
"pattern.flip_direction": "Flip direction",
"pick a hole to seat it, or OK places it at the origin": "pick a hole to seat it, or OK places it at the origin",
"pick one or two vertices, edges or faces": "pick one or two vertices, edges or faces",
+ "prefs.cpu": "CPU (software)",
+ "prefs.minutes_suffix": " min",
+ "properties.title": "Properties: {name}",
+ "recovery.days_ago": "{count} days ago",
+ "recovery.detail": "{file} · {features} features · autosaved {when}",
+ "recovery.hours_ago": "{count} h ago",
+ "recovery.just_now": "just now",
+ "recovery.min_ago": "{count} min ago",
+ "recovery.never_saved": "never saved",
"render.background": "Scene background",
"render.fit": "Fit Product",
"render.image_cancel": "Cancel Render",
@@ -904,6 +1023,10 @@
"settings.reset_intro": "These settings don't work on this computer and would keep SolidCraft from starting, so they were changed:",
"settings.reset_title": "Settings were changed",
"settings.supersampling_note": "Draws the view at a higher resolution and filters it down: smoother edges, lines and grid on screens below 4K. It costs GPU time: about 2.25× the pixels at 1.5× and 4× at 2×.",
+ "shortcut.json_error": "parameters must be JSON: {error}",
+ "shortcut.no_command": "no command `{id}`; the text before the JSON must be a command id",
+ "shortcut.pin": "Pin to the top of the S box",
+ "shortcut.unpin": "Unpin",
"sketch.degrees_of_freedom": "{count} degrees of freedom",
"sketch.dof_left": "{count} degrees of freedom left",
"sketch.dof_left_one": "{count} degree of freedom left",
@@ -945,6 +1068,7 @@
"timeline.ungroup": "Remove Feature Folders",
"to the face": "to the face",
"to the next face": "to the next face",
+ "toolbar.customize_note": "{tab} tab. Tick a command to give it a toolbar button. You can also drag a row of a panel's drop-down onto the toolbar, drag a button off the toolbar to remove it, or use the pin on a drop-down row.",
"toolbar.image": "IMAGE",
"toolbar.render": "RENDER",
"toolbar.render_scene": "SCENE",
@@ -999,6 +1123,7 @@
"ui.agent_chat_file_error": "{name}: {error}",
"ui.agent_chat_file_heic": "{name}: HEIC pictures can't be read here; export it as JPEG or PNG first",
"ui.agent_chat_file_importing": "Importing into the design…",
+ "ui.agent_chat_file_kinds": "{name}: pictures (PNG, JPEG, GIF, WebP, BMP, TIFF), text files (SVG too) and CAD files (STEP, IGES, FreeCAD, Rhino, STL, 3MF, OBJ, glTF) can be attached",
"ui.agent_chat_file_loading": "Reading the file…",
"ui.agent_chat_file_not_a_file": "{name}: not a file",
"ui.agent_chat_file_not_a_picture": "{name}: not a picture",
@@ -1022,6 +1147,7 @@
"ui.agent_chat_new": "New chat",
"ui.agent_chat_new_confirm": "Start a new chat? The current one is cleared.",
"ui.agent_chat_new_yes": "New chat",
+ "ui.agent_chat_next_picture": "Next picture",
"ui.agent_chat_no_cli": "solidcraft-cli was not found next to the app, so the agent can't reach the design.",
"ui.agent_chat_no_control": "The agent chat's endpoint did not start, so the agent can't reach the design.",
"ui.agent_chat_no_images": "This agent doesn't take pictures",
@@ -1037,6 +1163,7 @@
"ui.agent_chat_placeholder": "Ask the agent to change the design…",
"ui.agent_chat_placeholder_busy": "Queue a message for when the agent is done (Ctrl+Enter: send now)",
"ui.agent_chat_pop_out": "Open in its own window, which you can move to another screen",
+ "ui.agent_chat_previous_picture": "Previous picture",
"ui.agent_chat_privacy": "Nothing goes anywhere except to the agent you run, under your own account.",
"ui.agent_chat_privacy_note": "SolidCraft sends nothing anywhere: the agent you run talks to its own service under your own account. SolidCraft never sees or stores a key or password.",
"ui.agent_chat_queue": "Queue",
@@ -1092,6 +1219,7 @@
"ui.ai_bad_url": "Enter a URL that starts with http:// or https://",
"ui.ai_base_url": "Base URL",
"ui.ai_button": "AI",
+ "ui.ai_command_hint": "my-agent --acp",
"ui.ai_copy_suffix": "copy",
"ui.ai_custom_url": "Custom URL",
"ui.ai_default": "Default",
@@ -1112,8 +1240,10 @@
"ui.ai_mode_edits_note": "Modelling commands run without asking; saving, opening, exporting and other file or destructive actions still ask.",
"ui.ai_mode_global": "As set above",
"ui.ai_model": "Model",
+ "ui.ai_model_hint": "qwen3:14b",
"ui.ai_modes_scope": "These settings cover SolidCraft's tools. An agent's own tools (its shell, its file edits) follow the agent's own mode, which you pick in the chat panel's header when the agent has modes.",
"ui.ai_name": "Name",
+ "ui.ai_name_hint": "My agent",
"ui.ai_need_command": "Enter the command that starts the agent",
"ui.ai_need_model": "Enter the model name",
"ui.ai_no_answer": "The agent did not answer in time",
@@ -1144,6 +1274,7 @@
"ui.ai_toolbar_button": "Show Assistant button in application bar",
"ui.ai_toolbar_button_note": "The Assistant button in the application bar. Ctrl+Shift+A and the View menu still open the panel.",
"ui.ai_undo_tip": "Undo everything the agent changed for this message, as one step",
+ "ui.ai_url_hint": "https://example.com/v1",
"ui.all": "All",
"ui.ambient_occlusion": "Ambient occlusion",
"ui.ambient_occlusion_help": "Soft shading where opaque surfaces meet. Requires the GPU viewport.",
@@ -1765,5 +1896,6 @@
"update.title": "Update available",
"update.up_to_date": "SolidCraft is up to date.",
"update.update_now": "Update now",
- "update.you_have": "You have {version}."
+ "update.you_have": "You have {version}.",
+ "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ choose · Enter / Tab complete · Esc dismiss"
}
diff --git a/assets/locales/es.json b/assets/locales/es.json
index 1d815a4db1..321c059a9a 100644
--- a/assets/locales/es.json
+++ b/assets/locales/es.json
@@ -10,6 +10,7 @@
"ARRANGE": "ORGANIZAR",
"About SolidCraft": "Acerca de SolidCraft",
"Acceleration": "Aceleración",
+ "Actions": "Acciones",
"Active": "Activo",
"Active rule": "Regla activa",
"Add": "Añadir",
@@ -17,6 +18,7 @@
"Add Mid Radius": "Añadir radio intermedio",
"Add Row": "Añadir fila",
"Add condition": "Añadir condición",
+ "Add or edit rule": "Añadir o editar regla",
"Against": "Contra",
"Alignment": "Alineación",
"All Sketch Points": "Todos los puntos del boceto",
@@ -30,6 +32,7 @@
"Applied Radius": "Radio aplicado",
"Apply To": "Aplicar a",
"Apply to selection": "Aplicar a la selección",
+ "Apply your appearance first. Exports assigned appearances and materials created in this design.": "Aplique primero la apariencia. Exporta las apariencias asignadas y los materiales creados en este diseño.",
"Arc length": "Longitud del arco",
"Area": "Área",
"Attachment": "Vinculación",
@@ -59,10 +62,12 @@
"Check collisions": "Comprobar colisiones",
"Checked": "Comprobado",
"Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "Elige un plano nuevo. La geometría y las cotas del boceto se mantienen en sus coordenadas bidimensionales.",
+ "Choose…": "Elegir…",
"Circumference": "Circunferencia",
"Close draft": "Cerrar borrador",
"Collisions": "Colisiones",
"Colour": "Color",
+ "Comment": "Comentario",
"Component1": "Componente1",
"Configuration": "Configuración",
"Configuration rules": "Reglas de configuración",
@@ -87,6 +92,7 @@
"Curvature (G2)": "Curvatura (G2)",
"Curvature change (G3)": "Cambio de curvatura (G3)",
"Customize Toolbar": "Personalizar barra de herramientas",
+ "Delete": "Eliminar",
"Delete all": "Eliminar todo",
"Delete rule": "Eliminar regla",
"Delete the row": "Eliminar la fila",
@@ -104,16 +110,20 @@
"Drive Joint": "Accionar unión",
"Duration": "Duración",
"Edges": "Aristas",
+ "Edit": "Editar",
"Edit Profile Sketch": "Editar boceto del perfil",
"Enable rule": "Activar regla",
"Enabled": "Activado",
"Explode": "Explosionar",
"Explode Text": "Descomponer texto",
"Export Animation…": "Exportar animación…",
+ "Export CSV…": "Exportar CSV…",
"Export Current View as DXF": "Exportar vista actual como DXF",
"Export Current View as DXF…": "Exportar vista actual como DXF…",
"Export DXF…": "Exportar DXF…",
+ "Export JSON…": "Exportar JSON…",
"Export hidden edges as dashed lines": "Exportar aristas ocultas como líneas discontinuas",
+ "Expression": "Expresión",
"Extend to meet": "Extender hasta encontrarla",
"Extents": "Extensión",
"FILES": "ARCHIVOS",
@@ -122,7 +132,9 @@
"Face attachment lost": "Se ha perdido la vinculación de la cara",
"Faces": "Caras",
"Faces / edges / vertices": "Caras / aristas / vértices",
+ "Favorites": "Favoritos",
"Favourite": "Favorito",
+ "Feature": "Operación",
"Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "Los archivos de muchos programas CAD usan Y como eje vertical, por eso aquí se abren tumbados (con Z hacia arriba).",
"Filter": "Filtrar",
"Find in Browser": "Buscar en el explorador",
@@ -141,6 +153,7 @@
"Holes (edges on them)": "Agujeros (aristas que contienen)",
"Home view": "Vista de inicio",
"IMAGES": "IMÁGENES",
+ "Import…": "Importar…",
"In This Design": "En este diseño",
"In place (surfaces)": "En su posición (superficies)",
"In plane": "En el plano",
@@ -161,7 +174,9 @@
"Length units": "Unidades de longitud",
"Letter Spacing": "Espaciado entre letras",
"Library": "Biblioteca",
+ "Library file": "Archivo de biblioteca",
"Line Spacing": "Interlineado",
+ "Local library": "Biblioteca local",
"Loop": "Bucle",
"MANAGE": "GESTIONAR",
"MATERIALS": "MATERIALES",
@@ -169,22 +184,29 @@
"MOTION": "MOVIMIENTO",
"Margin": "Margen",
"Mass": "Masa",
+ "Matched restrictions check the final values.": "Las restricciones que se cumplen comprueban los valores finales.",
"Material": "Material",
"Max": "Máx.",
"Mid Radius": "Radio intermedio",
"Middle double-click": "Doble clic central",
"Min": "Mín.",
"Mitre": "Inglete",
+ "Model Parameters": "Parámetros del modelo",
"Modeled": "Modelado",
"More toolbar panels": "Más paneles de la barra de herramientas",
"Motion": "Movimiento",
"Move Type": "Tipo de movimiento",
+ "Move down": "Mover abajo",
"Move earlier": "Mover antes",
"Move later": "Mover después",
+ "Move up": "Mover arriba",
"Name": "Nombre",
"Nearest": "Más cercano",
+ "New": "Nuevo",
+ "New rule…": "Nueva regla…",
"New study": "Nuevo estudio",
"No crash reports.": "No hay informes de fallos.",
+ "No matching appearance presets.": "No hay preajustes de apariencia coincidentes.",
"No matching appearances": "No hay apariencias coincidentes",
"No visible bodies to export.": "No hay cuerpos visibles para exportar.",
"None": "Ninguno",
@@ -194,11 +216,14 @@
"OUTPUT": "SALIDA",
"Opacity": "Opacidad",
"Open GitHub draft": "Abrir borrador de GitHub",
+ "Open local libraries in the desktop app. You can export this design's library here.": "Abra las bibliotecas locales en la aplicación de escritorio. Aquí puede exportar la biblioteca de este diseño.",
"Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "CAD 3D paramétrico de código abierto desarrollado en Rust. Licencia MIT O Apache-2.0.",
+ "Operator": "Operador",
"Other side": "Lado opuesto",
"Other surface (mutual trim)": "Otra superficie (recorte mutuo)",
"Outside": "Exterior",
"Overall length": "Longitud total",
+ "Parameter": "Parámetro",
"Parameter values": "Valores de parámetros",
"Pass through": "Pasante",
"Path": "Trayectoria",
@@ -254,6 +279,8 @@
"Roll History Marker Here": "Desplazar marcador de la línea de tiempo hasta aquí",
"Round": "Redondo",
"Rule": "Regla",
+ "Rule name": "Nombre de la regla",
+ "Rules run from top to bottom. Matched drives change effective values.": "Las reglas se ejecutan de arriba abajo. Las reglas de control que se cumplen modifican los valores efectivos.",
"SECTION": "SECCIÓN",
"SURFACE QUALITY": "CALIDAD DE SUPERFICIE",
"Save Rule": "Guardar regla",
@@ -262,6 +289,7 @@
"Scale factor": "Factor de escala",
"Search": "Buscar",
"Search commands": "Buscar comandos",
+ "Search this library": "Buscar en esta biblioteca",
"Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Seleccionar otro: mantén pulsado el botón izquierdo sobre el modelo (o haz clic derecho › Seleccionar otro…) para ver todo lo que hay bajo el cursor; vuelve a pulsar en el mismo lugar para seleccionar el siguiente elemento. Haz doble clic con el botón central para volver a Inicio (Preferencias › Navegación).",
"Select bodies (a face picks its body)": "Selecciona cuerpos (al seleccionar una cara se selecciona su cuerpo)",
"Select bodies or faces instead": "Selecciona cuerpos o caras en su lugar",
@@ -318,11 +346,13 @@
"Turn off section analysis before exporting the view.": "Desactiva el análisis de sección antes de exportar la vista.",
"Type": "Tipo",
"UNTRIM": "ANULAR RECORTE",
+ "Unit": "Unidad",
"Updating the preview": "Actualizando vista previa",
"Use active author placement": "Usar posición de autor activa",
"Use fixed plane": "Usar plano fijo",
"Use saved fixed plane": "Usar plano fijo guardado",
"Use selected face as fixed plane": "Usar la cara seleccionada como plano fijo",
+ "User Parameters": "Parámetros de usuario",
"VIEW": "VISTA",
"VIEWS": "VISTAS",
"Value": "Valor",
@@ -337,6 +367,12 @@
"When": "Cuando",
"Width": "Anchura",
"Will fail": "Fallará",
+ "X angle": "Ángulo X",
+ "X distance": "Distancia X",
+ "Y angle": "Ángulo Y",
+ "Y distance": "Distancia Y",
+ "Z angle": "Ángulo Z",
+ "Z distance": "Distancia Z",
"angle, height": "ángulo, altura",
"appearance.dielectric_ior": "Índice de refracción dieléctrico",
"appearance.metallic": "Metalicidad",
@@ -345,7 +381,11 @@
"appearance.roughness": "Rugosidad",
"appearance.surface_response": "Respuesta de la superficie",
"browser.body_name": "Cuerpo{number}",
+ "browser.capture_many": "Se han movido {count} componentes, pero sus posiciones no se han capturado.",
+ "browser.capture_note": "Capturar posición conserva la nueva posición; Revertir posición restaura la anterior.",
+ "browser.capture_one": "Se ha movido un componente, pero su posición no se ha capturado.",
"browser.component_name": "Componente{number}",
+ "browser.move_title": "Mover: {name}",
"browser.parameters": "Parámetros ({count})",
"browser.precision": "Precisión: {precision}",
"browser.sketch_name": "Boceto{number}",
@@ -672,6 +712,8 @@
"cmd.view_rename": "Cambiar nombre de vista guardada",
"cmd.view_save": "Nueva vista guardada",
"command name": "nombre del comando",
+ "contact.components_count": "{count} componentes",
+ "contact.enabled_label": "activado",
"coupling.gear_1": "Engranaje 1",
"coupling.gear_1_pick": "Engranaje 1 (opcional)",
"coupling.gear_2": "Engranaje 2",
@@ -688,8 +730,11 @@
"coupling.rack": "Cremallera",
"coupling.radius_1": "Radio 1",
"coupling.radius_2": "Radio 2",
+ "delete.and_more": "… y {count} más",
"dialog.computing": "Calculando… {seconds} s",
"dialog.custom_axis": "↖ Eje personalizado",
+ "dialog.dimension_insert_hint": "Haga doble clic en otra cota de control para insertar su nombre",
+ "dialog.dimension_name": "Cota: {name}",
"dialog.edit_title": "EDITAR {title}",
"dialog.select": "↖ Seleccionar",
"dialog.selected_count": "↖ {count} seleccionados",
@@ -716,6 +761,15 @@
"expression, e.g. 25 mm": "expresión, p. ej., 25 mm",
"fits the face, e.g. M8": "se ajusta a la cara, p. ej., M8",
"from the rule": "de la regla",
+ "help.apache": "Licencia Apache 2.0",
+ "help.attributions": "Atribuciones (ATTRIBUTION.md)",
+ "help.build": "Versión {version} · commit {commit} · compilada el {date}",
+ "help.font_details": "La interfaz utiliza las fuentes integradas de egui (Ubuntu Light y Hack, bajo las licencias Ubuntu Font Licence y MIT/Bitstream Vera; Noto Emoji y la fuente de iconos emoji, bajo OFL y MIT). El texto de los bocetos utiliza Liberation Sans (SIL OFL 1.1). El paquete opcional de fuentes de The Crafting Apps, craft-fonts (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1), no se incluye en las compilaciones de SolidCraft.",
+ "help.fonts": "Fuentes",
+ "help.licences": "Licencias",
+ "help.mit": "Licencia MIT",
+ "help.notice": "NOTICE",
+ "help.third_party": "Licencias de terceros",
"home.documentation": "Documentación",
"home.in_this_browser": "en este navegador",
"home.missing": "no disponible",
@@ -744,10 +798,30 @@
"joint.from_bodies_hint": "Cada cuerpo seleccionado pasa a un componente nuevo propio y conserva su posición.",
"joint.one_body": "Las dos selecciones pertenecen a {body}. Selecciona la segunda en otra pieza.",
"joint.one_component": "Estas piezas son cuerpos de un mismo componente: {bodies}. Una unión mueve un componente respecto a otro, por lo que cada pieza debe tener su propio componente.",
+ "keymap.command_id": "ID del comando",
+ "keymap.empty": "No hay comandos coincidentes",
+ "keymap.use_anyway": "Usar {key} aquí de todos modos",
+ "manage.appearance_hint": "Elija una apariencia para la selección o arrastre una muestra a un cuerpo o una cara.",
+ "manage.assign_hint": "Seleccione cuerpos y elija su regla de diseño de piezas de plástico.",
+ "manage.config_hint": "Edite las filas, columnas y reglas de configuración y luego active una fila o muestre su vista previa.",
+ "manage.empty": "No hay filas coincidentes.",
+ "manage.material_hint": "Seleccione cuerpos y elija su material físico.",
+ "manage.parameters_hint": "Edite expresiones y unidades. Los cambios se aplican al pulsar Intro o salir de un campo.",
+ "manage.rules_hint": "Elija una regla para editarla o cree una nueva. Confirme para guardar la regla.",
+ "measure.at": "En",
+ "measure.item": "Elemento {number}",
"motion.checked_to": "Comprobado solo hasta el paso {step}: la comprobación agotó su presupuesto de trabajo",
"motion.collision": "{a} · {b}: pasos {steps}",
+ "motion.delete_key": "Eliminar fotograma clave",
"motion.duration_hint": "segundos (vacío: por paso)",
+ "motion.key_here": "Insertar fotograma clave aquí",
+ "motion.key_here_hint": "Añadir un fotograma clave en este paso con el valor actual de la unión",
"motion.no_collisions": "Sin colisiones durante el estudio",
+ "motion.step_back": "Paso atrás",
+ "motion.step_forward": "Paso adelante",
+ "motion.to_end": "Al final",
+ "motion.to_start": "Al inicio",
+ "motion.track_name": "Pista {number}",
"nav.touchpad.help": "Mantén pulsado Mayús y mueve el puntero para encuadrar; mantén Alt/Opción y muévelo para orbitar. No hace falta pulsar ningún botón del ratón. El desplazamiento vertical hace zoom.",
"nav.touchpad.label": "Panel táctil",
"nav.touchpad.orbit": "Orbitar (mantén Alt/Opción y mueve el puntero; sin pulsar botones)",
@@ -761,6 +835,8 @@
"no interference": "sin interferencias",
"no joint that moves yet": "todavía no hay ninguna unión móvil",
"no picture": "sin imagen",
+ "none": "ninguno",
+ "parts.automatic_name": "automático",
"pattern.alignment_2": "Alineación 2",
"pattern.alignment_hint": "Los recuentos incluyen el original. Centrar equilibra las copias; Invertir elige el lado adicional cuando el total es par.",
"pattern.direction_1": "Dirección 1",
@@ -768,6 +844,9 @@
"pattern.flip_direction": "Invertir dirección",
"pick a hole to seat it, or OK places it at the origin": "selecciona un agujero para colocarlo o pulsa Aceptar para situarlo en el origen",
"pick one or two vertices, edges or faces": "selecciona uno o dos vértices, aristas o caras",
+ "prefs.cpu": "CPU (software)",
+ "prefs.minutes_suffix": " min",
+ "properties.title": "Propiedades: {name}",
"render.background": "Fondo de la escena",
"render.fit": "Ajustar producto",
"render.image_cancel": "Cancelar renderizado",
@@ -830,6 +909,10 @@
"settings.reset_intro": "Estos ajustes no funcionan en este ordenador e impedirían iniciar SolidCraft, por lo que se han cambiado:",
"settings.reset_title": "Se han cambiado los ajustes",
"settings.supersampling_note": "Dibuja la vista a mayor resolución y después la reduce: bordes, líneas y cuadrícula más suaves en pantallas inferiores a 4K. Consume recursos de GPU: unos 2,25× píxeles a 1,5× y 4× a 2×.",
+ "shortcut.json_error": "los parámetros deben estar en formato JSON: {error}",
+ "shortcut.no_command": "no existe el comando `{id}`; el texto anterior al JSON debe ser un ID de comando",
+ "shortcut.pin": "Fijar en la parte superior del cuadro S",
+ "shortcut.unpin": "Desfijar",
"sketch.degrees_of_freedom": "{count} grados de libertad",
"sketch.dof_left": "Quedan {count} grados de libertad",
"sketch.dof_left_one": "Queda {count} grado de libertad",
@@ -867,6 +950,7 @@
"timeline.reorder_many": "Reordenar operaciones",
"timeline.ungroup": "Quitar carpetas de operaciones",
"to the next face": "hasta la siguiente cara",
+ "toolbar.customize_note": "Pestaña {tab}. Marque un comando para añadir su botón a la barra de herramientas. También puede arrastrar una fila del desplegable de un panel a la barra, arrastrar un botón fuera de la barra para quitarlo o usar la chincheta de una fila del desplegable.",
"toolbar.image": "IMAGEN",
"toolbar.render": "RENDERIZAR",
"toolbar.render_scene": "ESCENA",
@@ -920,6 +1004,7 @@
"ui.agent_chat_new": "Nuevo chat",
"ui.agent_chat_new_confirm": "¿Iniciar un nuevo chat? Se borrará la conversación actual.",
"ui.agent_chat_new_yes": "Nuevo chat",
+ "ui.agent_chat_next_picture": "Imagen siguiente",
"ui.agent_chat_no_cli": "No se ha encontrado solidcraft-cli junto a la aplicación, por lo que el agente no puede acceder al diseño.",
"ui.agent_chat_no_control": "No se ha iniciado el punto de conexión del chat del agente, por lo que no puede acceder al diseño.",
"ui.agent_chat_no_images": "Este agente no admite imágenes",
@@ -931,6 +1016,7 @@
"ui.agent_chat_pick": "Agente",
"ui.agent_chat_placeholder": "Pide al agente que modifique el diseño…",
"ui.agent_chat_placeholder_busy": "Pon un mensaje en cola para cuando termine el agente (Ctrl+Intro: enviar ahora)",
+ "ui.agent_chat_previous_picture": "Imagen anterior",
"ui.agent_chat_privacy": "Solo se envían datos al agente que ejecutes, con tu propia cuenta.",
"ui.agent_chat_privacy_note": "SolidCraft no envía nada a otros destinos: el agente que ejecutas se comunica con su propio servicio utilizando tu cuenta. SolidCraft nunca ve ni almacena claves o contraseñas.",
"ui.agent_chat_queue": "Poner en cola",
@@ -984,6 +1070,7 @@
"ui.ai_bad_url": "Introduce una URL que empiece por http:// o https://",
"ui.ai_base_url": "URL base",
"ui.ai_button": "AI",
+ "ui.ai_command_hint": "my-agent --acp",
"ui.ai_copy_suffix": "copia",
"ui.ai_custom_url": "URL personalizada",
"ui.ai_default": "Predeterminado",
@@ -1004,8 +1091,10 @@
"ui.ai_mode_edits_note": "Los comandos de modelado se ejecutan sin preguntar; guardar, abrir, exportar y otras acciones sobre archivos o destructivas siguen requiriendo permiso.",
"ui.ai_mode_global": "Según la configuración anterior",
"ui.ai_model": "Modelo",
+ "ui.ai_model_hint": "qwen3:14b",
"ui.ai_modes_scope": "Estos ajustes se aplican a las herramientas de SolidCraft. Las herramientas propias del agente (terminal, edición de archivos) siguen el modo del agente, que puedes elegir en la cabecera del panel de chat si dispone de modos.",
"ui.ai_name": "Nombre",
+ "ui.ai_name_hint": "Mi agente",
"ui.ai_need_command": "Introduce el comando que inicia el agente",
"ui.ai_need_model": "Introduce el nombre del modelo",
"ui.ai_no_answer": "El agente no ha respondido a tiempo",
@@ -1036,6 +1125,7 @@
"ui.ai_toolbar_button": "Mostrar botón en la barra de herramientas",
"ui.ai_toolbar_button_note": "El botón IA situado al extremo derecho de la barra. Ctrl+Mayús+A y el menú Ver también abren el panel.",
"ui.ai_undo_tip": "Deshacer todos los cambios del agente en este mensaje, en un solo paso",
+ "ui.ai_url_hint": "https://example.com/v1",
"ui.all": "Todo",
"ui.analysis": "Análisis",
"ui.angle": "Ángulo",
@@ -1605,5 +1695,6 @@
"update.title": "Actualización disponible",
"update.up_to_date": "SolidCraft está actualizado.",
"update.update_now": "Actualizar ahora",
- "update.you_have": "Tienes la versión {version}."
+ "update.you_have": "Tienes la versión {version}.",
+ "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ elegir · Intro / Tab completar · Esc cerrar"
}
diff --git a/assets/locales/fr.json b/assets/locales/fr.json
index 93ccd9f1b5..dcdf0a314e 100644
--- a/assets/locales/fr.json
+++ b/assets/locales/fr.json
@@ -10,6 +10,7 @@
"ARRANGE": "DISPOSER",
"About SolidCraft": "À propos de SolidCraft",
"Acceleration": "Accélération",
+ "Actions": "Actions",
"Active": "Actif",
"Active rule": "Règle active",
"Add": "Ajouter",
@@ -17,6 +18,7 @@
"Add Mid Radius": "Ajouter un rayon intermédiaire",
"Add Row": "Ajouter une ligne",
"Add condition": "Ajouter une condition",
+ "Add or edit rule": "Ajouter ou modifier une règle",
"Against": "Contre",
"Alignment": "Alignement",
"All Sketch Points": "Tous les points d'esquisse",
@@ -30,6 +32,7 @@
"Applied Radius": "Rayon appliqué",
"Apply To": "Appliquer à",
"Apply to selection": "Appliquer à la sélection",
+ "Apply your appearance first. Exports assigned appearances and materials created in this design.": "Appliquez d’abord votre apparence. Exporte les apparences attribuées et les matériaux créés dans cette conception.",
"Arc length": "Longueur d'arc",
"Area": "Aire",
"Attachment": "Rattachement",
@@ -60,10 +63,12 @@
"Check collisions": "Vérifier les collisions",
"Checked": "Vérifié",
"Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "Choisir un nouveau plan. La géométrie et les cotes de l'esquisse restent inchangées dans ses coordonnées bidimensionnelles.",
+ "Choose…": "Choisir…",
"Circumference": "Circonférence",
"Close draft": "Fermer le brouillon",
"Collisions": "Collisions",
"Colour": "Couleur",
+ "Comment": "Commentaire",
"Component1": "Composant1",
"Configuration": "Configuration",
"Configuration rules": "Règles de configuration",
@@ -89,6 +94,7 @@
"Curvature (G2)": "Courbure (G2)",
"Curvature change (G3)": "Variation de courbure (G3)",
"Customize Toolbar": "Personnaliser la barre d'outils",
+ "Delete": "Supprimer",
"Delete all": "Tout supprimer",
"Delete rule": "Supprimer la règle",
"Delete the row": "Supprimer la ligne",
@@ -106,16 +112,20 @@
"Drive Joint": "Piloter la liaison",
"Duration": "Durée",
"Edges": "Arêtes",
+ "Edit": "Modifier",
"Edit Profile Sketch": "Modifier l'esquisse du profil",
"Enable rule": "Activer la règle",
"Enabled": "Activé",
"Explode": "Éclater",
"Explode Text": "Décomposer le texte",
"Export Animation…": "Exporter l'animation…",
+ "Export CSV…": "Exporter CSV…",
"Export Current View as DXF": "Exporter la vue actuelle en DXF",
"Export Current View as DXF…": "Exporter la vue actuelle en DXF…",
"Export DXF…": "Exporter en DXF…",
+ "Export JSON…": "Exporter JSON…",
"Export hidden edges as dashed lines": "Exporter les arêtes cachées en tirets",
+ "Expression": "Expression",
"Extend to meet": "Prolonger jusqu'à la rencontre",
"Extents": "Étendues",
"FILES": "FICHIERS",
@@ -124,7 +134,9 @@
"Face attachment lost": "Rattachement à la face perdu",
"Faces": "Faces",
"Faces / edges / vertices": "Faces / arêtes / sommets",
+ "Favorites": "Favoris",
"Favourite": "Favori",
+ "Feature": "Fonction",
"Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "Les fichiers de nombreux logiciels de CAO ont Y vers le haut : ils s'ouvrent donc couchés ici (Z vers le haut).",
"Filter": "Filtrer",
"Find in Browser": "Trouver dans le navigateur",
@@ -143,6 +155,7 @@
"Holes (edges on them)": "Trous (par leurs arêtes)",
"Home view": "Vue d'accueil",
"IMAGES": "IMAGES",
+ "Import…": "Importer…",
"In This Design": "Dans cette conception",
"In place (surfaces)": "En place (surfaces)",
"In plane": "Dans le plan",
@@ -163,7 +176,9 @@
"Length units": "Unités de longueur",
"Letter Spacing": "Espacement des lettres",
"Library": "Bibliothèque",
+ "Library file": "Fichier de bibliothèque",
"Line Spacing": "Interligne",
+ "Local library": "Bibliothèque locale",
"Loop": "Boucle",
"MANAGE": "GÉRER",
"MATERIALS": "MATÉRIAUX",
@@ -171,22 +186,29 @@
"MOTION": "MOUVEMENT",
"Margin": "Marge",
"Mass": "Masse",
+ "Matched restrictions check the final values.": "Les restrictions dont les conditions sont remplies vérifient les valeurs finales.",
"Material": "Matériau",
"Max": "Max",
"Mid Radius": "Rayon intermédiaire",
"Middle double-click": "Double-clic milieu",
"Min": "Min",
"Mitre": "Onglet",
+ "Model Parameters": "Paramètres du modèle",
"Modeled": "Modélisé",
"More toolbar panels": "Autres groupes de la barre d'outils",
"Motion": "Mouvement",
"Move Type": "Type de déplacement",
+ "Move down": "Déplacer vers le bas",
"Move earlier": "Déplacer plus tôt",
"Move later": "Déplacer plus tard",
+ "Move up": "Déplacer vers le haut",
"Name": "Nom",
"Nearest": "Corps le plus proche",
+ "New": "Nouveau",
+ "New rule…": "Nouvelle règle…",
"New study": "Nouvelle étude",
"No crash reports.": "Aucun rapport de plantage.",
+ "No matching appearance presets.": "Aucun préréglage d’apparence correspondant.",
"No matching appearances": "Aucune apparence correspondante",
"No visible bodies to export.": "Aucun corps visible à exporter.",
"None": "Aucun",
@@ -196,11 +218,14 @@
"OUTPUT": "SORTIE",
"Opacity": "Opacité",
"Open GitHub draft": "Ouvrir le brouillon GitHub",
+ "Open local libraries in the desktop app. You can export this design's library here.": "Ouvrez les bibliothèques locales dans l’application de bureau. Vous pouvez exporter ici la bibliothèque de cette conception.",
"Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "CAO 3D paramétrique open source en Rust. Sous licence MIT OR Apache-2.0.",
+ "Operator": "Opérateur",
"Other side": "Autre côté",
"Other surface (mutual trim)": "Autre surface (ajustement mutuel)",
"Outside": "Extérieur",
"Overall length": "Longueur hors tout",
+ "Parameter": "Paramètre",
"Parameter values": "Valeurs des paramètres",
"Pass through": "Passer par",
"Path": "Trajectoire",
@@ -256,6 +281,8 @@
"Roll History Marker Here": "Placer le marqueur d'historique ici",
"Round": "Arrondi",
"Rule": "Règle",
+ "Rule name": "Nom de la règle",
+ "Rules run from top to bottom. Matched drives change effective values.": "Les règles s’exécutent de haut en bas. Les règles de pilotage dont les conditions sont remplies modifient les valeurs effectives.",
"SECTION": "COUPE",
"SURFACE QUALITY": "QUALITÉ DE SURFACE",
"Save Rule": "Enregistrer la règle",
@@ -264,6 +291,7 @@
"Scale factor": "Facteur d'échelle",
"Search": "Rechercher",
"Search commands": "Rechercher des commandes",
+ "Search this library": "Rechercher dans cette bibliothèque",
"Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Sélectionner un autre élément : maintenir le bouton gauche immobile sur le modèle (ou clic droit › Sélectionner un autre…) pour lister tout ce qui se trouve sous le curseur ; cliquer de nouveau au même endroit pour sélectionner l'élément suivant. Double-cliquer avec le bouton du milieu pour revenir à l'accueil (Préférences › Navigation).",
"Select bodies (a face picks its body)": "Sélectionner des corps (une face sélectionne son corps)",
"Select bodies or faces instead": "Sélectionner plutôt des corps ou des faces",
@@ -320,11 +348,13 @@
"Turn off section analysis before exporting the view.": "Désactivez l'analyse de coupe avant d'exporter la vue.",
"Type": "Type",
"UNTRIM": "ANNULER L'AJUSTEMENT",
+ "Unit": "Unité",
"Updating the preview": "Mise à jour de l'aperçu",
"Use active author placement": "Utiliser le placement d'auteur actif",
"Use fixed plane": "Utiliser un plan fixe",
"Use saved fixed plane": "Utiliser le plan fixe enregistré",
"Use selected face as fixed plane": "Utiliser la face sélectionnée comme plan fixe",
+ "User Parameters": "Paramètres utilisateur",
"VIEW": "VUE",
"VIEWS": "VUES",
"Value": "Valeur",
@@ -339,6 +369,12 @@
"When": "Quand",
"Width": "Largeur",
"Will fail": "Échouera",
+ "X angle": "Angle X",
+ "X distance": "Distance X",
+ "Y angle": "Angle Y",
+ "Y distance": "Distance Y",
+ "Z angle": "Angle Z",
+ "Z distance": "Distance Z",
"angle, height": "angle, hauteur",
"appearance.dielectric_ior": "Indice de réfraction (diélectrique)",
"appearance.metallic": "Métallique",
@@ -347,7 +383,11 @@
"appearance.roughness": "Rugosité",
"appearance.surface_response": "Réponse de la surface",
"browser.body_name": "Corps{number}",
+ "browser.capture_many": "{count} composants ont été déplacés, mais leurs positions ne sont pas capturées.",
+ "browser.capture_note": "Capturer la position conserve la nouvelle position ; Rétablir la position restaure la précédente.",
+ "browser.capture_one": "Un composant a été déplacé, mais sa position n’est pas capturée.",
"browser.component_name": "Composant{number}",
+ "browser.move_title": "Déplacer : {name}",
"browser.parameters": "Paramètres ({count})",
"browser.precision": "Précision : {precision}",
"browser.sketch_name": "Esquisse{number}",
@@ -679,6 +719,8 @@
"cmd.view_rename": "Renommer la vue nommée",
"cmd.view_save": "Nouvelle vue nommée",
"command name": "nom de la commande",
+ "contact.components_count": "{count} composants",
+ "contact.enabled_label": "activé",
"coupling.gear_1": "Engrenage 1",
"coupling.gear_1_pick": "Engrenage 1 (facultatif)",
"coupling.gear_2": "Engrenage 2",
@@ -695,6 +737,7 @@
"coupling.rack": "Crémaillère",
"coupling.radius_1": "Rayon 1",
"coupling.radius_2": "Rayon 2",
+ "delete.and_more": "… et {count} de plus",
"dialog.bodies_count": "{count} corps",
"dialog.clearance_invalid": "le jeu doit être une longueur positive ou nulle",
"dialog.compute": "Calculer",
@@ -702,6 +745,8 @@
"dialog.computing": "Calcul… {seconds} s",
"dialog.could_not_be_checked": "non vérifiable",
"dialog.custom_axis": "↖ Axe personnalisé",
+ "dialog.dimension_insert_hint": "Double-cliquez sur une autre cote pilotante pour insérer son nom",
+ "dialog.dimension_name": "Cote : {name}",
"dialog.edit_title": "MODIFIER {title}",
"dialog.select": "↖ Sélectionner",
"dialog.selected_count": "↖ {count} sélectionné(s)",
@@ -728,6 +773,15 @@
"expression, e.g. 25 mm": "expression, par ex. 25 mm",
"fits the face, e.g. M8": "adapté à la face, par ex. M8",
"from the rule": "selon la règle",
+ "help.apache": "Licence Apache 2.0",
+ "help.attributions": "Attributions (ATTRIBUTION.md)",
+ "help.build": "Version {version} · commit {commit} · compilée le {date}",
+ "help.font_details": "L’interface utilise les polices intégrées d’egui (Ubuntu Light et Hack, sous les licences Ubuntu Font Licence et MIT/Bitstream Vera ; Noto Emoji et la police d’icônes emoji, sous OFL et MIT). Le texte des esquisses utilise Liberation Sans (SIL OFL 1.1). Le pack de polices facultatif de The Crafting Apps, craft-fonts (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic ; SIL OFL 1.1), n’est pas inclus dans les versions de SolidCraft.",
+ "help.fonts": "Polices",
+ "help.licences": "Licences",
+ "help.mit": "Licence MIT",
+ "help.notice": "NOTICE",
+ "help.third_party": "Licences tierces",
"home.documentation": "Documentation",
"home.in_this_browser": "dans ce navigateur",
"home.missing": "introuvable",
@@ -756,10 +810,30 @@
"joint.from_bodies_hint": "Chaque corps sélectionné passe dans un nouveau composant à lui et reste où il est.",
"joint.one_body": "Les deux sélections sont sur {body}. Choisissez la seconde sur une autre pièce.",
"joint.one_component": "Ces pièces sont des corps d'un même composant : {bodies}. Une liaison déplace un composant par rapport à un autre, chaque pièce a donc besoin de son propre composant.",
+ "keymap.command_id": "ID de commande",
+ "keymap.empty": "Aucune commande correspondante",
+ "keymap.use_anyway": "Utiliser quand même {key} ici",
+ "manage.appearance_hint": "Choisissez une apparence pour la sélection ou faites glisser un échantillon sur un corps ou une face.",
+ "manage.assign_hint": "Sélectionnez des corps et choisissez leur règle de conception plastique.",
+ "manage.config_hint": "Modifiez les lignes, colonnes et règles de configuration, puis activez une ligne ou affichez son aperçu.",
+ "manage.empty": "Aucune ligne correspondante.",
+ "manage.material_hint": "Sélectionnez des corps et choisissez leur matériau physique.",
+ "manage.parameters_hint": "Modifiez les expressions et les unités. Les modifications s’appliquent avec Entrée ou lorsque vous quittez un champ.",
+ "manage.rules_hint": "Choisissez une règle à modifier ou créez-en une. Confirmez pour enregistrer la règle.",
+ "measure.at": "À",
+ "measure.item": "Élément {number}",
"motion.checked_to": "Vérifié jusqu'à l'étape {step} seulement : la vérification a épuisé son budget de calcul",
"motion.collision": "{a} · {b} : étapes {steps}",
+ "motion.delete_key": "Supprimer l’image clé",
"motion.duration_hint": "secondes (vide : par étape)",
+ "motion.key_here": "Placer une image clé ici",
+ "motion.key_here_hint": "Ajouter une image clé à cette étape avec la valeur actuelle de la liaison",
"motion.no_collisions": "Aucune collision au cours de l'étude",
+ "motion.step_back": "Étape précédente",
+ "motion.step_forward": "Étape suivante",
+ "motion.to_end": "À la fin",
+ "motion.to_start": "Au début",
+ "motion.track_name": "Piste {number}",
"nav.touchpad.help": "Maintenir Maj et déplacer le pointeur pour faire un panoramique ; maintenir Alt/Option et le déplacer pour orbiter. Aucun bouton de souris n'est nécessaire. Le défilement vertical zoome.",
"nav.touchpad.label": "Pavé tactile",
"nav.touchpad.orbit": "Orbite (maintenir Alt/Option et déplacer ; sans bouton de souris)",
@@ -775,6 +849,7 @@
"no joint that moves yet": "aucune liaison mobile pour l'instant",
"no picture": "aucune image",
"none": "aucun",
+ "parts.automatic_name": "automatique",
"pattern.alignment_2": "Alignement 2",
"pattern.alignment_hint": "La quantité inclut l’original. Le centrage répartit les copies de chaque côté ; si la quantité est paire, l’inversion choisit le côté qui reçoit la copie supplémentaire.",
"pattern.direction_1": "Direction 1",
@@ -782,6 +857,9 @@
"pattern.flip_direction": "Inverser la direction",
"pick a hole to seat it, or OK places it at the origin": "choisir un trou pour la loger, ou OK la place à l'origine",
"pick one or two vertices, edges or faces": "choisir un ou deux sommets, arêtes ou faces",
+ "prefs.cpu": "CPU (logiciel)",
+ "prefs.minutes_suffix": " min",
+ "properties.title": "Propriétés : {name}",
"render.background": "Arrière-plan de la scène",
"render.fit": "Cadrer le produit",
"render.image_cancel": "Annuler le rendu",
@@ -844,6 +922,10 @@
"settings.reset_intro": "Ces réglages ne fonctionnent pas sur cet ordinateur et empêcheraient SolidCraft de démarrer ; ils ont donc été modifiés :",
"settings.reset_title": "Des réglages ont été modifiés",
"settings.supersampling_note": "Dessine la vue à une résolution plus élevée puis la réduit : arêtes, lignes et grille plus lisses sur les écrans de définition inférieure à la 4K. Cela coûte du temps GPU : environ 2,25× plus de pixels à 1,5× et 4× plus à 2×.",
+ "shortcut.json_error": "les paramètres doivent être au format JSON : {error}",
+ "shortcut.no_command": "la commande `{id}` n’existe pas ; le texte avant le JSON doit être un ID de commande",
+ "shortcut.pin": "Épingler en haut de la boîte S",
+ "shortcut.unpin": "Désépingler",
"sketch.degrees_of_freedom": "{count} degrés de liberté",
"sketch.dof_left": "{count} degrés de liberté restants",
"sketch.dof_left_one": "{count} degré de liberté restant",
@@ -885,6 +967,7 @@
"timeline.ungroup": "Supprimer les dossiers de fonctions",
"to the face": "jusqu'à la face",
"to the next face": "jusqu'à la face suivante",
+ "toolbar.customize_note": "Onglet {tab}. Cochez une commande pour lui attribuer un bouton dans la barre d’outils. Vous pouvez aussi faire glisser une ligne du menu déroulant d’un panneau vers la barre d’outils, retirer un bouton en le faisant glisser hors de la barre ou utiliser l’épingle d’une ligne du menu déroulant.",
"toolbar.image": "IMAGE",
"toolbar.render": "RENDU",
"toolbar.render_scene": "SCÈNE",
@@ -962,6 +1045,7 @@
"ui.agent_chat_new": "Nouveau chat",
"ui.agent_chat_new_confirm": "Démarrer un nouveau chat ? Le chat actuel sera effacé.",
"ui.agent_chat_new_yes": "Nouveau chat",
+ "ui.agent_chat_next_picture": "Image suivante",
"ui.agent_chat_no_cli": "solidcraft-cli est introuvable à côté de l'application : l'agent ne peut donc pas accéder à la conception.",
"ui.agent_chat_no_control": "Le point d'accès du chat de l'agent n'a pas démarré : l'agent ne peut donc pas accéder à la conception.",
"ui.agent_chat_no_images": "Cet agent n'accepte pas les images",
@@ -977,6 +1061,7 @@
"ui.agent_chat_placeholder": "Demander à l'agent de modifier la conception…",
"ui.agent_chat_placeholder_busy": "Mettre un message en file d'attente pour quand l'agent aura terminé (Ctrl+Enter : envoyer maintenant)",
"ui.agent_chat_pop_out": "Ouvrir dans une fenêtre séparée, déplaçable vers un autre écran",
+ "ui.agent_chat_previous_picture": "Image précédente",
"ui.agent_chat_privacy": "Rien n'est envoyé ailleurs qu'à l'agent que vous lancez, sous votre propre compte.",
"ui.agent_chat_privacy_note": "SolidCraft n'envoie rien nulle part : l'agent que vous lancez dialogue avec son propre service, sous votre propre compte. SolidCraft ne voit ni ne stocke jamais de clé ni de mot de passe.",
"ui.agent_chat_queue": "Mettre en file",
@@ -1032,6 +1117,7 @@
"ui.ai_bad_url": "Saisir une URL commençant par http:// ou https://",
"ui.ai_base_url": "URL de base",
"ui.ai_button": "IA",
+ "ui.ai_command_hint": "my-agent --acp",
"ui.ai_copy_suffix": "copie",
"ui.ai_custom_url": "URL personnalisée",
"ui.ai_default": "Par défaut",
@@ -1052,8 +1138,10 @@
"ui.ai_mode_edits_note": "Les commandes de modélisation s'exécutent sans demander ; l'enregistrement, l'ouverture, l'exportation et les autres actions sur les fichiers ou destructrices demandent toujours.",
"ui.ai_mode_global": "Comme défini ci-dessus",
"ui.ai_model": "Modèle",
+ "ui.ai_model_hint": "qwen3:14b",
"ui.ai_modes_scope": "Ces réglages concernent les outils de SolidCraft. Les outils propres à un agent (son shell, ses modifications de fichiers) suivent le mode de l'agent, que vous choisissez dans l'en-tête du panneau de chat lorsque l'agent propose des modes.",
"ui.ai_name": "Nom",
+ "ui.ai_name_hint": "Mon agent",
"ui.ai_need_command": "Saisir la commande qui lance l'agent",
"ui.ai_need_model": "Saisir le nom du modèle",
"ui.ai_no_answer": "L'agent n'a pas répondu à temps",
@@ -1084,6 +1172,7 @@
"ui.ai_toolbar_button": "Afficher le bouton dans la barre d'outils",
"ui.ai_toolbar_button_note": "Le bouton IA à l'extrémité droite de la barre d'outils. Ctrl+Shift+A et le menu Vue ouvrent toujours le panneau.",
"ui.ai_undo_tip": "Annuler tout ce que l'agent a modifié pour ce message, en une seule étape",
+ "ui.ai_url_hint": "https://example.com/v1",
"ui.all": "Tout",
"ui.ambient_occlusion": "Occlusion ambiante",
"ui.ambient_occlusion_help": "Ombrage doux aux jonctions des surfaces opaques. Nécessite la vue GPU.",
@@ -1669,5 +1758,6 @@
"update.title": "Mise à jour disponible",
"update.up_to_date": "SolidCraft est à jour.",
"update.update_now": "Mettre à jour maintenant",
- "update.you_have": "Vous avez la version {version}."
+ "update.you_have": "Vous avez la version {version}.",
+ "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ choisir · Entrée / Tab compléter · Échap fermer"
}
diff --git a/assets/locales/gl.json b/assets/locales/gl.json
index 5d4efc3bcf..a240a0d0ce 100644
--- a/assets/locales/gl.json
+++ b/assets/locales/gl.json
@@ -9,6 +9,7 @@
"AI": "IA",
"ARRANGE": "ORGANIZAR",
"About SolidCraft": "Acerca de SolidCraft",
+ "Actions": "Accións",
"Active": "Activa",
"Active rule": "Regra activa",
"Add": "Engadir",
@@ -16,6 +17,7 @@
"Add Mid Radius": "Engadir raio medio",
"Add Row": "Engadir fila",
"Add condition": "Engadir condición",
+ "Add or edit rule": "Engadir ou editar unha regra",
"Alignment": "Aliñamento",
"All Sketch Points": "Todos os puntos do bosquexo",
"All open designs": "Todos os deseños abertos",
@@ -27,6 +29,7 @@
"Applied Radius": "Raio aplicado",
"Apply To": "Aplicar a",
"Apply to selection": "Aplicar á selección",
+ "Apply your appearance first. Exports assigned appearances and materials created in this design.": "Aplique primeiro a aparencia. Exporta as aparencias asignadas e os materiais creados neste deseño.",
"Arc length": "Lonxitude do arco",
"Area": "Área",
"Attachment": "Ancoraxe",
@@ -56,10 +59,12 @@
"Check collisions": "Comprobar colisións",
"Checked": "Marcado",
"Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "Escolle un plano novo. A xeometría e as cotas do bosquexo mantéñense nas súas coordenadas bidimensionais.",
+ "Choose…": "Escoller…",
"Circumference": "Circunferencia",
"Close draft": "Pechar o borrador",
"Collisions": "Colisións",
"Colour": "Cor",
+ "Comment": "Comentario",
"Component1": "Compoñente1",
"Configuration": "Configuración",
"Configuration rules": "Regras de configuración",
@@ -83,6 +88,7 @@
"Curvature (G2)": "Curvatura (G2)",
"Curvature change (G3)": "Cambio de curvatura (G3)",
"Customize Toolbar": "Personalizar a barra de ferramentas",
+ "Delete": "Eliminar",
"Delete all": "Eliminar todo",
"Delete rule": "Eliminar a regra",
"Delete the row": "Eliminar a fila",
@@ -98,15 +104,19 @@
"Double-clicking the middle button in the view: Home (the home view, framing what is shown), Fit (frame what is shown, keeping the orientation) or nothing": "Dobre clic co botón central na vista: Inicio (a vista de inicio, encadrando o que se mostra), Axustar (encadrar o que se mostra mantendo a orientación) ou nada",
"Drive Joint": "Accionar a unión",
"Edges": "Arestas",
+ "Edit": "Editar",
"Edit Profile Sketch": "Editar o bosquexo do perfil",
"Enable rule": "Activar a regra",
"Enabled": "Activado",
"Explode": "Explosionar",
"Export Animation…": "Exportar animación…",
+ "Export CSV…": "Exportar CSV…",
"Export Current View as DXF": "Exportar a vista actual como DXF",
"Export Current View as DXF…": "Exportar a vista actual como DXF…",
"Export DXF…": "Exportar DXF…",
+ "Export JSON…": "Exportar JSON…",
"Export hidden edges as dashed lines": "Exportar as arestas ocultas como liñas descontinuas",
+ "Expression": "Expresión",
"Extend to meet": "Estender ata atopala",
"Extents": "Extensións",
"FILES": "FICHEIROS",
@@ -115,7 +125,9 @@
"Face attachment lost": "Perdeuse a ancoraxe á cara",
"Faces": "Caras",
"Faces / edges / vertices": "Caras / arestas / vértices",
+ "Favorites": "Favoritos",
"Favourite": "Favorito",
+ "Feature": "Operación",
"Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "Os ficheiros de moitos programas CAD teñen o Y cara arriba, así que aquí ábrense deitados (Z cara arriba).",
"Filter": "Filtro",
"Find in Browser": "Buscar no navegador",
@@ -134,6 +146,7 @@
"Holes (edges on them)": "Furados (arestas sobre eles)",
"Home view": "Vista de inicio",
"IMAGES": "IMAXES",
+ "Import…": "Importar…",
"In This Design": "Neste deseño",
"In place (surfaces)": "No sitio (superficies)",
"In plane": "No plano",
@@ -154,7 +167,9 @@
"Length units": "Unidades de lonxitude",
"Letter Spacing": "Espazado entre letras",
"Library": "Biblioteca",
+ "Library file": "Ficheiro de biblioteca",
"Line Spacing": "Espazado entre liñas",
+ "Local library": "Biblioteca local",
"Loop": "Bucle",
"MANAGE": "XESTIONAR",
"MATERIALS": "MATERIAIS",
@@ -162,20 +177,27 @@
"MOTION": "MOVEMENTO",
"Margin": "Marxe",
"Mass": "Masa",
+ "Matched restrictions check the final values.": "As restricións que se cumpren comproban os valores finais.",
"Material": "Material",
"Max": "Máx.",
"Mid Radius": "Raio medio",
"Middle double-click": "Dobre clic central",
"Min": "Mín.",
"Mitre": "Inglete",
+ "Model Parameters": "Parámetros do modelo",
"Modeled": "Modelado",
"More toolbar panels": "Máis paneis da barra de ferramentas",
"Motion": "Movemento",
"Move Type": "Tipo de movemento",
+ "Move down": "Mover abaixo",
"Move earlier": "Mover antes",
"Move later": "Mover despois",
+ "Move up": "Mover arriba",
"Name": "Nome",
+ "New": "Novo",
+ "New rule…": "Nova regra…",
"No crash reports.": "Non hai informes de fallos.",
+ "No matching appearance presets.": "Non hai preaxustes de aparencia coincidentes.",
"No matching appearances": "Non hai aparencias coincidentes",
"No visible bodies to export.": "Non hai corpos visibles para exportar.",
"None": "Ningún",
@@ -185,11 +207,14 @@
"OUTPUT": "SAÍDA",
"Opacity": "Opacidade",
"Open GitHub draft": "Abrir o borrador de GitHub",
+ "Open local libraries in the desktop app. You can export this design's library here.": "Abra as bibliotecas locais na aplicación de escritorio. Aquí pode exportar a biblioteca deste deseño.",
"Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "CAD 3D paramétrico de código aberto en Rust. Con licenza MIT OR Apache-2.0.",
+ "Operator": "Operador",
"Other side": "Outro lado",
"Other surface (mutual trim)": "Outra superficie (recorte mutuo)",
"Outside": "Fóra",
"Overall length": "Lonxitude total",
+ "Parameter": "Parámetro",
"Parameter values": "Valores dos parámetros",
"Pass through": "Atravesar",
"Path": "Traxectoria",
@@ -241,6 +266,8 @@
"Roll History Marker Here": "Levar o marcador do historial aquí",
"Round": "Redondo",
"Rule": "Regra",
+ "Rule name": "Nome da regra",
+ "Rules run from top to bottom. Matched drives change effective values.": "As regras execútanse de arriba abaixo. As regras de control que se cumpren modifican os valores efectivos.",
"SECTION": "SECCIÓN",
"SURFACE QUALITY": "CALIDADE DA SUPERFICIE",
"Save Rule": "Gardar a regra",
@@ -249,6 +276,7 @@
"Scale factor": "Factor de escala",
"Search": "Buscar",
"Search commands": "Buscar ordes",
+ "Search this library": "Buscar nesta biblioteca",
"Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Seleccionar outro: mantén o botón esquerdo quieto sobre o modelo (ou clic dereito › Seleccionar outro…) para listar todo o que hai baixo o cursor; fai clic de novo no mesmo punto para seleccionar o seguinte. Fai dobre clic co botón central para ir ao Inicio (Preferencias › Navegación).",
"Select bodies (a face picks its body)": "Selecciona corpos (unha cara escolle o seu corpo)",
"Select bodies or faces instead": "Seleccionar corpos ou caras no seu lugar",
@@ -303,11 +331,13 @@
"Turn off section analysis before exporting the view.": "Desactiva a análise de sección antes de exportar a vista.",
"Type": "Tipo",
"UNTRIM": "DESRECORTAR",
+ "Unit": "Unidade",
"Updating the preview": "Actualizando a previsualización",
"Use active author placement": "Usar a colocación de autor activa",
"Use fixed plane": "Usar un plano fixo",
"Use saved fixed plane": "Usar o plano fixo gardado",
"Use selected face as fixed plane": "Usar a cara seleccionada como plano fixo",
+ "User Parameters": "Parámetros de usuario",
"VIEW": "VISTA",
"VIEWS": "VISTAS",
"Value": "Valor",
@@ -321,6 +351,12 @@
"When": "Cando",
"Width": "Largura",
"Will fail": "Fallará",
+ "X angle": "Ángulo X",
+ "X distance": "Distancia X",
+ "Y angle": "Ángulo Y",
+ "Y distance": "Distancia Y",
+ "Z angle": "Ángulo Z",
+ "Z distance": "Distancia Z",
"angle, height": "ángulo, altura",
"appearance.dielectric_ior": "IOR dieléctrico",
"appearance.metallic": "Metálico",
@@ -329,7 +365,11 @@
"appearance.roughness": "Rugosidade",
"appearance.surface_response": "Resposta da superficie",
"browser.body_name": "Corpo{number}",
+ "browser.capture_many": "Movéronse {count} compoñentes, pero as súas posicións non se capturaron.",
+ "browser.capture_note": "Capturar a posición conserva a nova posición; Reverter a posición restaura a anterior.",
+ "browser.capture_one": "Moveuse un compoñente, pero a súa posición non se capturou.",
"browser.component_name": "Compoñente{number}",
+ "browser.move_title": "Mover: {name}",
"browser.parameters": "Parámetros ({count})",
"browser.precision": "Precisión: {precision}",
"browser.sketch_name": "Bosquexo{number}",
@@ -652,6 +692,8 @@
"cmd.view_rename": "Renomear a vista con nome",
"cmd.view_save": "Vista con nome nova",
"command name": "nome da orde",
+ "contact.components_count": "{count} compoñentes",
+ "contact.enabled_label": "activado",
"coupling.gear_1": "Engrenaxe 1",
"coupling.gear_1_pick": "Engrenaxe 1 (opcional)",
"coupling.gear_2": "Engrenaxe 2",
@@ -668,8 +710,11 @@
"coupling.rack": "Cremalleira",
"coupling.radius_1": "Raio 1",
"coupling.radius_2": "Raio 2",
+ "delete.and_more": "… e {count} máis",
"dialog.computing": "Calculando… {seconds} s",
"dialog.custom_axis": "↖ Eixe personalizado",
+ "dialog.dimension_insert_hint": "Faga dobre clic noutra cota de control para inserir o seu nome",
+ "dialog.dimension_name": "Cota: {name}",
"dialog.edit_title": "EDITAR {title}",
"dialog.select": "↖ Seleccionar",
"dialog.selected_count": "↖ {count} seleccionados",
@@ -696,6 +741,15 @@
"expression, e.g. 25 mm": "expresión, p. ex. 25 mm",
"fits the face, e.g. M8": "encaixa na cara, p. ex. M8",
"from the rule": "da regra",
+ "help.apache": "Licenza Apache 2.0",
+ "help.attributions": "Atribucións (ATTRIBUTION.md)",
+ "help.build": "Versión {version} · commit {commit} · compilada o {date}",
+ "help.font_details": "A interface usa as fontes integradas de egui (Ubuntu Light e Hack, baixo as licenzas Ubuntu Font Licence e MIT/Bitstream Vera; Noto Emoji e a fonte de iconas emoji, baixo OFL e MIT). O texto dos bosquexos usa Liberation Sans (SIL OFL 1.1). O paquete opcional de fontes de The Crafting Apps, craft-fonts (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1), non se inclúe nas compilacións de SolidCraft.",
+ "help.fonts": "Fontes",
+ "help.licences": "Licenzas",
+ "help.mit": "Licenza MIT",
+ "help.notice": "NOTICE",
+ "help.third_party": "Licenzas de terceiros",
"home.documentation": "Documentación",
"home.in_this_browser": "neste navegador",
"home.missing": "non atopado",
@@ -724,6 +778,26 @@
"joint.from_bodies_hint": "Cada corpo escollido pasa a un compoñente novo propio e queda onde está.",
"joint.one_body": "As dúas seleccións están en {body}. Escolle a segunda noutra peza.",
"joint.one_component": "Estas pezas son corpos dun mesmo compoñente: {bodies}. Unha unión move un compoñente respecto doutro, así que cada peza precisa o seu propio compoñente.",
+ "keymap.command_id": "ID do comando",
+ "keymap.empty": "Non hai comandos coincidentes",
+ "keymap.use_anyway": "Usar {key} aquí de todos os xeitos",
+ "manage.appearance_hint": "Escolla unha aparencia para a selección ou arrastre unha mostra a un corpo ou unha cara.",
+ "manage.assign_hint": "Seleccione corpos e escolla a súa regra de deseño de pezas de plástico.",
+ "manage.config_hint": "Edite as filas, columnas e regras de configuración e despois active unha fila ou amose a súa vista previa.",
+ "manage.empty": "Non hai filas coincidentes.",
+ "manage.material_hint": "Seleccione corpos e escolla o seu material físico.",
+ "manage.parameters_hint": "Edite expresións e unidades. Os cambios aplícanse ao premer Intro ou saír dun campo.",
+ "manage.rules_hint": "Escolla unha regra para editar ou cree unha nova. Confirme para gardar a regra.",
+ "measure.at": "En",
+ "measure.item": "Elemento {number}",
+ "motion.delete_key": "Eliminar fotograma clave",
+ "motion.key_here": "Inserir fotograma clave aquí",
+ "motion.key_here_hint": "Engadir un fotograma clave neste paso co valor actual da unión",
+ "motion.step_back": "Paso atrás",
+ "motion.step_forward": "Paso adiante",
+ "motion.to_end": "Ao final",
+ "motion.to_start": "Ao inicio",
+ "motion.track_name": "Pista {number}",
"nav.touchpad.help": "Mantén Maiús e move o punteiro para desprazar; mantén Alt/Opción e móveo para orbitar. Non fai falta ningún botón do rato. O desprazamento vertical fai zoom.",
"nav.touchpad.label": "Panel táctil",
"nav.touchpad.orbit": "Orbitar (mantén Alt/Opción e move; sen botón do rato)",
@@ -737,6 +811,8 @@
"no interference": "sen interferencias",
"no joint that moves yet": "aínda non hai ningunha unión que se mova",
"no picture": "sen imaxe",
+ "none": "ningún",
+ "parts.automatic_name": "automático",
"pattern.alignment_2": "Aliñamento 2",
"pattern.alignment_hint": "O número inclúe o orixinal. Centrar equilibra as copias; Inverter escolle o lado da copia extra cando o total é par.",
"pattern.direction_1": "Dirección 1",
@@ -744,6 +820,9 @@
"pattern.flip_direction": "Inverter a dirección",
"pick a hole to seat it, or OK places it at the origin": "escolle un furado onde asentala, ou Aceptar colócaa na orixe",
"pick one or two vertices, edges or faces": "escolle un ou dous vértices, arestas ou caras",
+ "prefs.cpu": "CPU (software)",
+ "prefs.minutes_suffix": " min",
+ "properties.title": "Propiedades: {name}",
"render.background": "Fondo da escena",
"render.fit": "Encadrar o produto",
"render.image_cancel": "Cancelar o render",
@@ -806,6 +885,10 @@
"settings.reset_intro": "Estes axustes non funcionan neste ordenador e impedirían que SolidCraft se iniciase, así que se cambiaron:",
"settings.reset_title": "Cambiáronse os axustes",
"settings.supersampling_note": "Debuxa a vista a unha resolución maior e fíltraa cara abaixo: arestas, liñas e grella máis suaves en pantallas por debaixo de 4K. Consome tempo de GPU: uns 2,25× píxeles a 1,5× e 4× a 2×.",
+ "shortcut.json_error": "os parámetros deben estar en formato JSON: {error}",
+ "shortcut.no_command": "non existe o comando `{id}`; o texto anterior ao JSON debe ser un ID de comando",
+ "shortcut.pin": "Fixar na parte superior da caixa S",
+ "shortcut.unpin": "Desafixar",
"sketch.degrees_of_freedom": "{count} graos de liberdade",
"sketch.dof_left": "Quedan {count} graos de liberdade",
"sketch.dof_left_one": "Queda {count} grao de liberdade",
@@ -839,6 +922,7 @@
"timeline.reorder_many": "Reordenar operacións",
"timeline.ungroup": "Quitar os cartafoles de operacións",
"to the next face": "ata a seguinte cara",
+ "toolbar.customize_note": "Lapela {tab}. Marque un comando para engadir o seu botón á barra de ferramentas. Tamén pode arrastrar unha fila do despregable dun panel á barra, arrastrar un botón fóra da barra para retiralo ou usar a chincheta dunha fila do despregable.",
"toolbar.image": "IMAXE",
"toolbar.render": "RENDER",
"toolbar.render_scene": "ESCENA",
@@ -892,6 +976,7 @@
"ui.agent_chat_new": "Chat novo",
"ui.agent_chat_new_confirm": "Comezar un chat novo? Borrarase o actual.",
"ui.agent_chat_new_yes": "Chat novo",
+ "ui.agent_chat_next_picture": "Imaxe seguinte",
"ui.agent_chat_no_cli": "Non se atopou solidcraft-cli xunto á aplicación, así que o axente non pode chegar ao deseño.",
"ui.agent_chat_no_control": "O punto de acceso do chat co axente non se iniciou, así que o axente non pode chegar ao deseño.",
"ui.agent_chat_no_images": "Este axente non admite imaxes",
@@ -903,6 +988,7 @@
"ui.agent_chat_pick": "Axente",
"ui.agent_chat_placeholder": "Pídelle ao axente que cambie o deseño…",
"ui.agent_chat_placeholder_busy": "Pon unha mensaxe na cola para cando remate o axente (Ctrl+Intro: enviar agora)",
+ "ui.agent_chat_previous_picture": "Imaxe anterior",
"ui.agent_chat_privacy": "Nada vai a ningún sitio agás ao axente que executas, coa túa propia conta.",
"ui.agent_chat_privacy_note": "SolidCraft non envía nada a ningún sitio: o axente que executas fala co seu propio servizo coa túa propia conta. SolidCraft nunca ve nin garda ningunha clave nin contrasinal.",
"ui.agent_chat_queue": "Pór na cola",
@@ -956,6 +1042,7 @@
"ui.ai_bad_url": "Introduce un URL que comece por http:// ou https://",
"ui.ai_base_url": "URL base",
"ui.ai_button": "IA",
+ "ui.ai_command_hint": "my-agent --acp",
"ui.ai_copy_suffix": "copia",
"ui.ai_custom_url": "URL personalizado",
"ui.ai_default": "Predeterminado",
@@ -976,8 +1063,10 @@
"ui.ai_mode_edits_note": "As ordes de modelado execútanse sen preguntar; gardar, abrir, exportar e outras accións con ficheiros ou destrutivas seguen preguntando.",
"ui.ai_mode_global": "Como se definiu arriba",
"ui.ai_model": "Modelo",
+ "ui.ai_model_hint": "qwen3:14b",
"ui.ai_modes_scope": "Estes axustes cobren as ferramentas de SolidCraft. As ferramentas propias dun axente (o seu shell, as súas edicións de ficheiros) seguen o modo propio do axente, que escolles na cabeceira do panel de chat cando o axente ten modos.",
"ui.ai_name": "Nome",
+ "ui.ai_name_hint": "O meu axente",
"ui.ai_need_command": "Introduce a orde que inicia o axente",
"ui.ai_need_model": "Introduce o nome do modelo",
"ui.ai_no_answer": "O axente non respondeu a tempo",
@@ -1008,6 +1097,7 @@
"ui.ai_toolbar_button": "Mostrar o botón na barra de ferramentas",
"ui.ai_toolbar_button_note": "O botón de IA no extremo dereito da barra de ferramentas. Ctrl+Maiús+A e o menú Vista seguen abrindo o panel.",
"ui.ai_undo_tip": "Desfai nun só paso todo o que cambiou o axente para esta mensaxe",
+ "ui.ai_url_hint": "https://example.com/v1",
"ui.all": "Todo",
"ui.analysis": "Análise",
"ui.angle": "Ángulo",
@@ -1568,5 +1658,6 @@
"update.title": "Actualización dispoñible",
"update.up_to_date": "SolidCraft está actualizado.",
"update.update_now": "Actualizar agora",
- "update.you_have": "Tes a versión {version}."
+ "update.you_have": "Tes a versión {version}.",
+ "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ escoller · Intro / Tab completar · Esc pechar"
}
diff --git a/assets/locales/it.json b/assets/locales/it.json
index 3bbdd118a7..e8326dbec1 100644
--- a/assets/locales/it.json
+++ b/assets/locales/it.json
@@ -8,6 +8,7 @@
"AI": "IA",
"About SolidCraft": "Informazioni su SolidCraft",
"Acceleration": "Accelerazione",
+ "Actions": "Azioni",
"Active": "Attivo",
"Active rule": "Regola attiva",
"Add": "Aggiungi",
@@ -15,6 +16,7 @@
"Add Mid Radius": "Aggiungi raggio intermedio",
"Add Row": "Aggiungi riga",
"Add condition": "Aggiungi condizione",
+ "Add or edit rule": "Aggiungi o modifica regola",
"Against": "Rispetto a",
"Alignment": "Allineamento",
"All Sketch Points": "Tutti i punti dello schizzo",
@@ -28,6 +30,7 @@
"Applied Radius": "Raggio applicato",
"Apply To": "Applica a",
"Apply to selection": "Applica alla selezione",
+ "Apply your appearance first. Exports assigned appearances and materials created in this design.": "Applica prima l’aspetto. Esporta gli aspetti assegnati e i materiali creati in questo progetto.",
"Arc length": "Lunghezza dell'arco",
"Area": "Area",
"Attachment": "Collegamento",
@@ -52,10 +55,12 @@
"Check collisions": "Controlla collisioni",
"Checked": "Controllato",
"Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "Scegli un nuovo piano. La geometria e le quote dello schizzo restano invariate nelle sue coordinate bidimensionali.",
+ "Choose…": "Scegli…",
"Circumference": "Circonferenza",
"Close draft": "Chiudi bozza",
"Collisions": "Collisioni",
"Colour": "Colore",
+ "Comment": "Commento",
"Component1": "Componente1",
"Configuration": "Configurazione",
"Configuration rules": "Regole di configurazione",
@@ -81,6 +86,7 @@
"Curvature (G2)": "Curvatura (G2)",
"Curvature change (G3)": "Variazione di curvatura (G3)",
"Customize Toolbar": "Personalizza barra degli strumenti",
+ "Delete": "Elimina",
"Delete all": "Elimina tutto",
"Delete rule": "Elimina regola",
"Delete the row": "Elimina la riga",
@@ -98,22 +104,28 @@
"Drive Joint": "Aziona giunto",
"Duration": "Durata",
"Edges": "Spigoli",
+ "Edit": "Modifica",
"Edit Profile Sketch": "Modifica schizzo del profilo",
"Enable rule": "Abilita regola",
"Enabled": "Abilitato",
"Explode": "Esplodi",
"Explode Text": "Esplodi testo",
"Export Animation…": "Esporta animazione…",
+ "Export CSV…": "Esporta CSV…",
"Export Current View as DXF": "Esporta vista corrente come DXF",
"Export Current View as DXF…": "Esporta vista corrente come DXF…",
"Export DXF…": "Esporta DXF…",
+ "Export JSON…": "Esporta JSON…",
"Export hidden edges as dashed lines": "Esporta gli spigoli nascosti come linee tratteggiate",
+ "Expression": "Espressione",
"Extents": "Estensioni",
"Face": "Faccia",
"Face attachment lost": "Collegamento alla faccia perso",
"Faces": "Facce",
"Faces / edges / vertices": "Facce / spigoli / vertici",
+ "Favorites": "Preferiti",
"Favourite": "Preferito",
+ "Feature": "Lavorazione",
"Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "Molti programmi CAD usano Y come asse verticale: qui, dove l'asse verticale è Z, i loro file si aprono coricati.",
"Filter": "Filtro",
"Find in Browser": "Trova nella struttura",
@@ -130,6 +142,7 @@
"Holes": "Fori",
"Holes (edges on them)": "Fori (spigoli dei fori)",
"Home view": "Vista iniziale",
+ "Import…": "Importa…",
"In This Design": "In questo progetto",
"In place (surfaces)": "In posizione (superfici)",
"In plane": "Nel piano",
@@ -145,26 +158,35 @@
"Length units": "Unità di lunghezza",
"Letter Spacing": "Spaziatura dei caratteri",
"Library": "Libreria",
+ "Library file": "File di libreria",
"Line Spacing": "Interlinea",
+ "Local library": "Libreria locale",
"Loop": "Ciclo",
"Margin": "Margine",
"Mass": "Massa",
+ "Matched restrictions check the final values.": "Le restrizioni le cui condizioni sono soddisfatte verificano i valori finali.",
"Material": "Materiale",
"Max": "Max",
"Mid Radius": "Raggio intermedio",
"Middle double-click": "Doppio clic centrale",
"Min": "Min",
"Mitre": "Giunzione ad angolo",
+ "Model Parameters": "Parametri del modello",
"Modeled": "Modellato",
"More toolbar panels": "Altri pannelli della barra degli strumenti",
"Motion": "Movimento",
"Move Type": "Tipo di spostamento",
+ "Move down": "Sposta giù",
"Move earlier": "Sposta prima",
"Move later": "Sposta dopo",
+ "Move up": "Sposta su",
"Name": "Nome",
"Nearest": "Più vicini",
+ "New": "Nuovo",
+ "New rule…": "Nuova regola…",
"New study": "Nuovo studio",
"No crash reports.": "Nessun rapporto di arresto anomalo.",
+ "No matching appearance presets.": "Nessun predefinito di aspetto corrispondente.",
"No matching appearances": "Nessun aspetto corrispondente",
"No visible bodies to export.": "Nessun corpo visibile da esportare.",
"None": "Nessuno",
@@ -172,10 +194,13 @@
"Notch": "Intaglio",
"Opacity": "Opacità",
"Open GitHub draft": "Apri bozza su GitHub",
+ "Open local libraries in the desktop app. You can export this design's library here.": "Apri le librerie locali nell’applicazione desktop. Qui puoi esportare la libreria di questo progetto.",
"Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "CAD 3D parametrico open source in Rust. Licenza MIT OR Apache-2.0.",
+ "Operator": "Operatore",
"Other side": "Lato opposto",
"Outside": "Esterno",
"Overall length": "Lunghezza complessiva",
+ "Parameter": "Parametro",
"Parameter values": "Valori dei parametri",
"Pass through": "Passante",
"Path": "Percorso",
@@ -229,12 +254,15 @@
"Roll History Marker Here": "Sposta qui il marcatore della cronologia",
"Round": "Arrotondato",
"Rule": "Regola",
+ "Rule name": "Nome della regola",
+ "Rules run from top to bottom. Matched drives change effective values.": "Le regole vengono eseguite dall’alto verso il basso. Le regole di controllo le cui condizioni sono soddisfatte modificano i valori effettivi.",
"Save Rule": "Salva regola",
"Save the study as an animated GIF, seen as the viewport shows it": "Salva lo studio come GIF animata, così come appare nella vista",
"Saved preview. Geometry is being checked before editing.": "Anteprima salvata. Verifica della geometria in corso prima della modifica.",
"Scale factor": "Fattore di scala",
"Search": "Cerca",
"Search commands": "Cerca comandi",
+ "Search this library": "Cerca in questa libreria",
"Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Seleziona altro: tieni premuto il pulsante sinistro senza muovere il puntatore sul modello (o fai clic destro › Seleziona altro…) per elencare gli oggetti sotto il cursore; fai di nuovo clic nello stesso punto per selezionare l'oggetto successivo. Fai doppio clic con il pulsante centrale per tornare alla vista iniziale (Preferenze › Navigazione).",
"Select bodies (a face picks its body)": "Seleziona corpi (una faccia seleziona il corpo a cui appartiene)",
"Select bodies or faces instead": "Seleziona invece corpi o facce",
@@ -287,11 +315,13 @@
"Turn off section analysis before exporting the view.": "Disattiva l'analisi in sezione prima di esportare la vista.",
"Type": "Tipo",
"UNTRIM": "RIPRISTINA SUPERFICIE",
+ "Unit": "Unità",
"Updating the preview": "Aggiornamento dell'anteprima",
"Use active author placement": "Usa posizionamento di creazione attivo",
"Use fixed plane": "Usa piano fisso",
"Use saved fixed plane": "Usa piano fisso salvato",
"Use selected face as fixed plane": "Usa faccia selezionata come piano fisso",
+ "User Parameters": "Parametri utente",
"VIEW": "VISTA",
"Value": "Valore",
"Velocity": "Velocità",
@@ -305,6 +335,12 @@
"When": "Quando",
"Width": "Larghezza",
"Will fail": "Non riuscirà",
+ "X angle": "Angolo X",
+ "X distance": "Distanza X",
+ "Y angle": "Angolo Y",
+ "Y distance": "Distanza Y",
+ "Z angle": "Angolo Z",
+ "Z distance": "Distanza Z",
"angle, height": "angolo, altezza",
"appearance.dielectric_ior": "Indice di rifrazione dielettrico",
"appearance.metallic": "Metallicità",
@@ -313,7 +349,11 @@
"appearance.roughness": "Rugosità",
"appearance.surface_response": "Risposta della superficie",
"browser.body_name": "Corpo{number}",
+ "browser.capture_many": "Sono stati spostati {count} componenti, ma le loro posizioni non sono state acquisite.",
+ "browser.capture_note": "Acquisisci posizione mantiene la nuova posizione; Ripristina posizione riporta a quella precedente.",
+ "browser.capture_one": "Un componente è stato spostato, ma la sua posizione non è stata acquisita.",
"browser.component_name": "Componente{number}",
+ "browser.move_title": "Sposta: {name}",
"browser.parameters": "Parametri ({count})",
"browser.precision": "Precisione: {precision}",
"browser.sketch_name": "Schizzo{number}",
@@ -643,6 +683,8 @@
"cmd.view_rename": "Rinomina vista con nome",
"cmd.view_save": "Nuova vista con nome",
"command name": "nome del comando",
+ "contact.components_count": "{count} componenti",
+ "contact.enabled_label": "abilitato",
"coupling.gear_1": "Ruota dentata 1",
"coupling.gear_1_pick": "Ruota dentata 1 (facoltativa)",
"coupling.gear_2": "Ruota dentata 2",
@@ -659,8 +701,11 @@
"coupling.rack": "Cremagliera",
"coupling.radius_1": "Raggio 1",
"coupling.radius_2": "Raggio 2",
+ "delete.and_more": "… e altri {count}",
"dialog.computing": "Calcolo in corso… {seconds} s",
"dialog.custom_axis": "↖ Asse personalizzato",
+ "dialog.dimension_insert_hint": "Fai doppio clic su un’altra quota di controllo per inserirne il nome",
+ "dialog.dimension_name": "Quota: {name}",
"dialog.edit_title": "MODIFICA {title}",
"dialog.select": "↖ Seleziona",
"dialog.selected_count": "↖ Selezionati: {count}",
@@ -687,6 +732,15 @@
"expression, e.g. 25 mm": "espressione, ad es. 25 mm",
"fits the face, e.g. M8": "adatta alla faccia, ad es. M8",
"from the rule": "dalla regola",
+ "help.apache": "Licenza Apache 2.0",
+ "help.attributions": "Attribuzioni (ATTRIBUTION.md)",
+ "help.build": "Versione {version} · commit {commit} · compilata il {date}",
+ "help.font_details": "L’interfaccia usa i caratteri integrati di egui (Ubuntu Light e Hack, con licenze Ubuntu Font Licence e MIT/Bitstream Vera; Noto Emoji e il carattere per icone emoji, con licenze OFL e MIT). Il testo degli schizzi usa Liberation Sans (SIL OFL 1.1). Il pacchetto di caratteri facoltativo di The Crafting Apps, craft-fonts (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1), non è incluso nelle build di SolidCraft.",
+ "help.fonts": "Caratteri",
+ "help.licences": "Licenze",
+ "help.mit": "Licenza MIT",
+ "help.notice": "NOTICE",
+ "help.third_party": "Licenze di terze parti",
"home.documentation": "Documentazione",
"home.in_this_browser": "in questo browser",
"home.missing": "non presente",
@@ -715,6 +769,18 @@
"joint.from_bodies_hint": "Ogni corpo selezionato viene spostato in un nuovo componente distinto, mantenendo la sua posizione.",
"joint.one_body": "Entrambe le selezioni sono su {body}. Seleziona il secondo elemento su un'altra parte.",
"joint.one_component": "Queste parti sono corpi di un unico componente: {bodies}. Un giunto muove un componente rispetto a un altro, quindi ogni parte richiede un componente distinto.",
+ "keymap.command_id": "ID comando",
+ "keymap.empty": "Nessun comando corrispondente",
+ "keymap.use_anyway": "Usa comunque {key} qui",
+ "manage.appearance_hint": "Scegli un aspetto per la selezione o trascina un campione su un corpo o una faccia.",
+ "manage.assign_hint": "Seleziona i corpi e scegli la loro regola di progettazione per parti in plastica.",
+ "manage.config_hint": "Modifica righe, colonne e regole di configurazione, poi attiva una riga o visualizzane l’anteprima.",
+ "manage.empty": "Nessuna riga corrispondente.",
+ "manage.material_hint": "Seleziona i corpi e scegli il loro materiale fisico.",
+ "manage.parameters_hint": "Modifica espressioni e unità. Le modifiche vengono applicate premendo Invio o uscendo da un campo.",
+ "manage.rules_hint": "Scegli una regola da modificare o creane una nuova. Conferma per salvare la regola.",
+ "measure.at": "In",
+ "measure.item": "Elemento {number}",
"messages.ago_h": "{n} h fa",
"messages.ago_min": "{n} min fa",
"messages.ago_s": "{n} s fa",
@@ -726,8 +792,16 @@
"messages.title": "Messaggi",
"motion.checked_to": "Controllato solo fino al passo {step}: il controllo ha esaurito il limite di calcolo",
"motion.collision": "{a} · {b}: passi {steps}",
+ "motion.delete_key": "Elimina fotogramma chiave",
"motion.duration_hint": "secondi (vuoto: per passo)",
+ "motion.key_here": "Inserisci fotogramma chiave qui",
+ "motion.key_here_hint": "Aggiungi un fotogramma chiave in questo passo con il valore attuale del giunto",
"motion.no_collisions": "Nessuna collisione durante lo studio",
+ "motion.step_back": "Passo indietro",
+ "motion.step_forward": "Passo avanti",
+ "motion.to_end": "Alla fine",
+ "motion.to_start": "All’inizio",
+ "motion.track_name": "Traccia {number}",
"nav.touchpad.help": "Tieni premuto Shift e muovi il puntatore per eseguire una panoramica; tieni premuto Alt/Option e muovilo per orbitare. Non serve premere pulsanti del mouse. Lo scorrimento verticale regola lo zoom.",
"nav.touchpad.label": "Touchpad",
"nav.touchpad.orbit": "Orbita (tieni premuto Alt/Option e muovi il puntatore; senza pulsanti del mouse)",
@@ -741,6 +815,8 @@
"no interference": "nessuna interferenza",
"no joint that moves yet": "nessun giunto mobile ancora presente",
"no picture": "nessuna immagine",
+ "none": "nessuno",
+ "parts.automatic_name": "automatico",
"pattern.alignment_2": "Allineamento 2",
"pattern.alignment_hint": "Il conteggio include l'originale. Centro distribuisce le copie sui due lati; Inverti sceglie il lato con la copia in più per totali pari.",
"pattern.direction_1": "Direzione 1",
@@ -748,6 +824,9 @@
"pattern.flip_direction": "Inverti direzione",
"pick a hole to seat it, or OK places it at the origin": "seleziona un foro in cui inserirlo, oppure premi OK per posizionarlo nell'origine",
"pick one or two vertices, edges or faces": "seleziona uno o due vertici, spigoli o facce",
+ "prefs.cpu": "CPU (software)",
+ "prefs.minutes_suffix": " min",
+ "properties.title": "Proprietà: {name}",
"render.background": "Sfondo della scena",
"render.fit": "Inquadra prodotto",
"render.image_cancel": "Annulla rendering",
@@ -810,6 +889,10 @@
"settings.reset_intro": "Queste impostazioni non funzionano su questo computer e impedirebbero l'avvio di SolidCraft, quindi sono state modificate:",
"settings.reset_title": "Le impostazioni sono state modificate",
"settings.supersampling_note": "Disegna la vista a una risoluzione maggiore e la riduce tramite filtro: spigoli, linee e griglia più uniformi sugli schermi sotto il 4K. Richiede tempo GPU: circa 2.25× i pixel a 1.5× e 4× a 2×.",
+ "shortcut.json_error": "i parametri devono essere in formato JSON: {error}",
+ "shortcut.no_command": "nessun comando `{id}`; il testo prima del JSON deve essere un ID comando",
+ "shortcut.pin": "Fissa in cima al riquadro S",
+ "shortcut.unpin": "Rimuovi fissaggio",
"sketch.degrees_of_freedom": "{count} gradi di libertà",
"sketch.dof_left": "{count} gradi di libertà rimanenti",
"sketch.dof_left_one": "{count} grado di libertà rimanente",
@@ -849,6 +932,7 @@
"timeline.reorder_many": "Riordina lavorazioni",
"timeline.ungroup": "Rimuovi cartelle di lavorazioni",
"to the next face": "fino alla faccia successiva",
+ "toolbar.customize_note": "Scheda {tab}. Seleziona un comando per assegnargli un pulsante nella barra degli strumenti. Puoi anche trascinare una riga dal menu a discesa di un pannello sulla barra, trascinare un pulsante fuori dalla barra per rimuoverlo o usare la puntina di una riga del menu a discesa.",
"toolbar.image": "IMMAGINE",
"toolbar.render": "RENDERING",
"toolbar.render_scene": "SCENA",
@@ -902,6 +986,7 @@
"ui.agent_chat_new": "Nuova chat",
"ui.agent_chat_new_confirm": "Avviare una nuova chat? Quella corrente verrà cancellata.",
"ui.agent_chat_new_yes": "Nuova chat",
+ "ui.agent_chat_next_picture": "Immagine successiva",
"ui.agent_chat_no_cli": "solidcraft-cli non è stato trovato accanto all'applicazione, quindi l'agente non può accedere al progetto.",
"ui.agent_chat_no_control": "L'endpoint della chat con l'agente non si è avviato, quindi l'agente non può accedere al progetto.",
"ui.agent_chat_no_images": "Questo agente non accetta immagini",
@@ -913,6 +998,7 @@
"ui.agent_chat_pick": "Agente",
"ui.agent_chat_placeholder": "Chiedi all'agente di modificare il progetto…",
"ui.agent_chat_placeholder_busy": "Metti in coda un messaggio per quando l'agente avrà terminato (Ctrl+Enter: invia subito)",
+ "ui.agent_chat_previous_picture": "Immagine precedente",
"ui.agent_chat_privacy": "I dati vengono inviati solo all'agente che esegui, con il tuo account.",
"ui.agent_chat_privacy_note": "SolidCraft non invia dati ad alcun servizio: l'agente che esegui comunica con il proprio servizio usando il tuo account. SolidCraft non vede né memorizza mai chiavi o password.",
"ui.agent_chat_queue": "Metti in coda",
@@ -966,6 +1052,7 @@
"ui.ai_bad_url": "Inserisci un URL che inizi con http:// o https://",
"ui.ai_base_url": "URL di base",
"ui.ai_button": "IA",
+ "ui.ai_command_hint": "my-agent --acp",
"ui.ai_copy_suffix": "copia",
"ui.ai_custom_url": "URL personalizzato",
"ui.ai_default": "Predefinito",
@@ -986,8 +1073,10 @@
"ui.ai_mode_edits_note": "I comandi di modellazione vengono eseguiti senza chiedere; salvataggio, apertura, esportazione e altre azioni sui file o distruttive richiedono comunque conferma.",
"ui.ai_mode_global": "Come impostato sopra",
"ui.ai_model": "Modello",
+ "ui.ai_model_hint": "qwen3:14b",
"ui.ai_modes_scope": "Queste impostazioni riguardano gli strumenti di SolidCraft. Gli strumenti dell'agente (shell, modifiche ai file) seguono la modalità dell'agente, selezionabile nell'intestazione del pannello chat quando l'agente supporta le modalità.",
"ui.ai_name": "Nome",
+ "ui.ai_name_hint": "Il mio agente",
"ui.ai_need_command": "Inserisci il comando che avvia l'agente",
"ui.ai_need_model": "Inserisci il nome del modello",
"ui.ai_no_answer": "L'agente non ha risposto in tempo",
@@ -1018,6 +1107,7 @@
"ui.ai_toolbar_button": "Mostra pulsante nella barra degli strumenti",
"ui.ai_toolbar_button_note": "Il pulsante IA all'estremità destra della barra degli strumenti. Ctrl+Shift+A e il menu Vista aprono comunque il pannello.",
"ui.ai_undo_tip": "Annulla in un solo passo tutte le modifiche dell'agente per questo messaggio",
+ "ui.ai_url_hint": "https://example.com/v1",
"ui.all": "Tutti",
"ui.analysis": "Analisi",
"ui.angle": "Angolo",
@@ -1597,5 +1687,6 @@
"update.title": "Aggiornamento disponibile",
"update.up_to_date": "SolidCraft è aggiornato.",
"update.update_now": "Aggiorna ora",
- "update.you_have": "La tua versione è {version}."
+ "update.you_have": "La tua versione è {version}.",
+ "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ scegli · Invio / Tab completa · Esc chiudi"
}
diff --git a/assets/locales/ja.json b/assets/locales/ja.json
index 0c8a593d6b..c7cbe8b610 100644
--- a/assets/locales/ja.json
+++ b/assets/locales/ja.json
@@ -11,6 +11,7 @@
"About SolidCraft": "SolidCraft について",
"Acceleration": "加速度",
"Access": "アクセス性",
+ "Actions": "操作",
"Active": "アクティブ",
"Active rule": "有効なルール",
"Add": "追加",
@@ -18,6 +19,7 @@
"Add Mid Radius": "中間半径を追加",
"Add Row": "行を追加",
"Add condition": "条件を追加",
+ "Add or edit rule": "ルールを追加または編集",
"Against": "相手",
"Alignment": "配置",
"All Sketch Points": "すべてのスケッチ点",
@@ -31,6 +33,7 @@
"Applied Radius": "適用半径",
"Apply To": "適用先",
"Apply to selection": "選択項目に適用",
+ "Apply your appearance first. Exports assigned appearances and materials created in this design.": "先に外観を適用してください。割り当てた外観と、このデザインで作成したマテリアルを書き出します。",
"Arc length": "円弧の長さ",
"Area": "表面積",
"As-Built": "現状位置",
@@ -67,11 +70,13 @@
"Check collisions": "衝突チェック",
"Checked": "チェック済み",
"Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "新しい平面を選択してください。スケッチジオメトリと寸法は2次元座標系のまま維持されます。",
+ "Choose…": "選択…",
"Circular": "円形",
"Circumference": "円周",
"Close draft": "下書きを閉じる",
"Collisions": "衝突",
"Colour": "色",
+ "Comment": "コメント",
"Component1": "コンポーネント1",
"Config Table": "構成テーブル",
"Configuration": "構成",
@@ -100,6 +105,7 @@
"Curvature (G2)": "曲率 (G2)",
"Curvature change (G3)": "曲率変化 (G3)",
"Customize Toolbar": "ツールバーのカスタマイズ",
+ "Delete": "削除",
"Delete all": "すべて削除",
"Delete rule": "ルールを削除",
"Delete the row": "行を削除",
@@ -118,6 +124,7 @@
"Drive Joint": "ジョイントを駆動",
"Duration": "時間",
"Edges": "エッジ",
+ "Edit": "編集",
"Edit Profile Sketch": "プロファイルスケッチを編集",
"Enable rule": "ルールを有効化",
"Enabled": "有効",
@@ -126,11 +133,14 @@
"Explode": "分解",
"Explode Text": "テキストを分解",
"Export Animation…": "アニメーションをエクスポート…",
+ "Export CSV…": "CSVを書き出し…",
"Export Current View as DXF": "現在の表示をDXFでエクスポート",
"Export Current View as DXF…": "現在の表示をDXFでエクスポート…",
"Export DXF": "DXF出力",
"Export DXF…": "DXFをエクスポート…",
+ "Export JSON…": "JSONを書き出し…",
"Export hidden edges as dashed lines": "点線で出力",
+ "Expression": "式",
"Extend to meet": "交わるまで延長",
"Extents": "範囲",
"FILES": "ファイル",
@@ -140,7 +150,9 @@
"Faces": "面",
"Faces / edges / vertices": "面 / エッジ / 頂点",
"Fastener": "締結部品",
+ "Favorites": "お気に入り",
"Favourite": "お気に入り",
+ "Feature": "フィーチャー",
"Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "多くのCADではY軸を上向きとしているため、Z軸を上向きとするSolidCraftでは、読み込んだモデルが横倒しの向きで表示されることがあります。",
"Filter": "フィルター",
"Find in Browser": "ブラウザで検索",
@@ -164,6 +176,7 @@
"Home view": "ホームビュー",
"Horiz./Vert.": "水平 / 垂直",
"IMAGES": "画像",
+ "Import…": "読み込み…",
"In This Design": "このデザイン内",
"In place (surfaces)": "その場で(サーフェス)",
"In plane": "平面内",
@@ -185,7 +198,9 @@
"Length units": "長さの単位",
"Letter Spacing": "文字間隔",
"Library": "ライブラリ",
+ "Library file": "ライブラリファイル",
"Line Spacing": "行間",
+ "Local library": "ローカルライブラリ",
"Loop": "ループ",
"MANAGE": "管理",
"MATERIALS": "材料",
@@ -194,25 +209,32 @@
"Margin": "マージン",
"Mass": "質量",
"Mass Center": "重心",
+ "Matched restrictions check the final values.": "条件に一致する制限ルールが最終値を確認します。",
"Material": "材料",
"Max": "最大",
"Mid Radius": "中間半径",
"Middle double-click": "中ボタンのダブルクリック",
"Min": "最小",
"Mitre": "留め継ぎ",
+ "Model Parameters": "モデルパラメータ",
"Modeled": "モデル化済み",
"More toolbar panels": "その他のツールバーパネル",
"Motion": "モーション",
"Move / Copy": "移動 / コピー",
"Move Type": "移動タイプ",
+ "Move down": "下へ移動",
"Move earlier": "前へ移動",
"Move later": "後へ移動",
+ "Move up": "上へ移動",
"Name": "名前",
"Nearest": "最も近い",
+ "New": "新規",
"New Comp.": "新規コンポーネント",
"New Sketch": "新規スケッチ",
+ "New rule…": "新規ルール…",
"New study": "新規スタディ",
"No crash reports.": "クラッシュレポートはありません。",
+ "No matching appearance presets.": "一致する外観プリセットはありません。",
"No matching appearances": "一致する外観がありません",
"No visible bodies to export.": "出力する表示中のボディがありません。",
"None": "なし",
@@ -222,12 +244,15 @@
"OUTPUT": "出力",
"Opacity": "不透明度",
"Open GitHub draft": "GitHubの下書きを開く",
+ "Open local libraries in the desktop app. You can export this design's library here.": "ローカルライブラリはデスクトップアプリで開いてください。このデザインのライブラリはここで書き出せます。",
"Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "Rust製オープンソース・パラメトリック3D CAD。ライセンス: MIT または Apache-2.0。",
+ "Operator": "演算子",
"Other side": "反対側",
"Other surface (mutual trim)": "相手のサーフェス(相互トリム)",
"Outside": "外側",
"Overall length": "全長",
"Param. Graph": "パラメータ図",
+ "Parameter": "パラメータ",
"Parameter values": "パラメータ値",
"Parts": "部品",
"Pass through": "通過点",
@@ -289,6 +314,8 @@
"Roll History Marker Here": "履歴マーカーをここに移動",
"Round": "丸め",
"Rule": "ルール",
+ "Rule name": "ルール名",
+ "Rules run from top to bottom. Matched drives change effective values.": "ルールは上から順に実行されます。条件に一致する駆動ルールが有効値を変更します。",
"SECTION": "断面",
"SURFACE QUALITY": "サーフェス品質",
"Save Rule": "ルールを保存",
@@ -299,6 +326,7 @@
"Scene": "シーン",
"Search": "検索",
"Search commands": "コマンドを検索",
+ "Search this library": "このライブラリを検索",
"Section": "断面",
"Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "その他を選択: モデル上で左ボタンを長押し(または右クリック › その他を選択…)するとカーソル下の要素が一覧表示されます。同じ場所を再度クリックすると次の要素が選択されます。中ボタンをダブルクリックするとホームビューに戻ります(環境設定 › ナビゲーション)。",
"Select bodies (a face picks its body)": "ボディを選択(面をクリックするとそのボディが選択されます)",
@@ -360,11 +388,13 @@
"Turn off section analysis before exporting the view.": "断面解析をオフにしてからエクスポートしてください。",
"Type": "タイプ",
"UNTRIM": "トリム解除",
+ "Unit": "単位",
"Updating the preview": "プレビューを更新中",
"Use active author placement": "アクティブな作成元配置を使用",
"Use fixed plane": "固定平面を使用",
"Use saved fixed plane": "保存された固定平面を使用",
"Use selected face as fixed plane": "選択した面を固定平面として使用",
+ "User Parameters": "ユーザーパラメータ",
"VIEW": "表示",
"VIEWS": "ビュー",
"Value": "値",
@@ -379,6 +409,12 @@
"When": "条件 (When)",
"Width": "幅",
"Will fail": "失敗します",
+ "X angle": "X角度",
+ "X distance": "X距離",
+ "Y angle": "Y角度",
+ "Y distance": "Y距離",
+ "Z angle": "Z角度",
+ "Z distance": "Z距離",
"Zebra": "ゼブラ",
"angle, height": "角度, 高さ",
"appearance.dielectric_ior": "誘電体の屈折率",
@@ -388,7 +424,13 @@
"appearance.roughness": "粗さ",
"appearance.surface_response": "表面の応答",
"browser.body_name": "ボディ{number}",
+ "browser.calibrate_title": "尺度を設定: {name}",
+ "browser.capture_many": "{count}個のコンポーネントが移動されましたが、位置がキャプチャされていません。",
+ "browser.capture_note": "「位置をキャプチャ」で新しい位置を保持し、「位置を元に戻す」で以前の位置に戻します。",
+ "browser.capture_one": "コンポーネントが移動されましたが、位置がキャプチャされていません。",
"browser.component_name": "コンポーネント{number}",
+ "browser.edit_canvas_title": "キャンバスを編集: {name}",
+ "browser.move_title": "移動: {name}",
"browser.parameters": "パラメータ ({count})",
"browser.precision": "精度: {precision}",
"browser.sketch_name": "スケッチ{number}",
@@ -727,6 +769,8 @@
"cmd.view_rename": "名前付きビューの名前を変更",
"cmd.view_save": "新規名前付きビュー",
"command name": "コマンド名",
+ "contact.components_count": "{count}個のコンポーネント",
+ "contact.enabled_label": "有効",
"coupling.gear_1": "ギア 1",
"coupling.gear_1_pick": "ギア 1 (オプション)",
"coupling.gear_2": "ギア 2",
@@ -746,6 +790,18 @@
"crash.detected_time": "検出日時: {time} UTC",
"crash.previous_session": "以前の SolidCraft セッションが予期せず終了したか、内部エラーが発生しました。正常終了が記録されていないセッションは起動時に検出されます。詳細は ヘルプ > クラッシュレポート… を参照してください。",
"crash.unclean_explanation": "次回以降の起動時に検出されました。正確な終了時刻は記録されていません。システムのシャットダウンや強制停止によっても、正常終了が記録されない場合があります。",
+ "crash.announce": "前回、SolidCraftが予期せず終了したか、内部エラーが発生しました。クラッシュレポートが保存されています(ヘルプ > クラッシュレポート…)。",
+ "crash.copy_folder": "フォルダのパスをコピー",
+ "crash.copy_path": "パスをコピー",
+ "crash.deleted": "{count}件のレポートを削除しました。",
+ "crash.intro": "クラッシュレポートはこのコンピュータ内に保存され、外部に送信されることはありません。「報告…」で下書きが開き、共有前に内容を確認できます。",
+ "crash.kind_command": "コマンド内の内部エラー",
+ "crash.kind_internal": "内部エラー",
+ "crash.kind_kernel": "カーネルエラー(復旧済み)",
+ "crash.kind_unclean": "予期しない終了",
+ "crash.replayable": "再現可能",
+ "crash.report": "報告…",
+ "delete.and_more": "…ほか{count}件",
"dialog.bodies_count": "{count} ボディ",
"dialog.clearance_invalid": "クリアランスは 0 以上の長さにしてください",
"dialog.compute": "計算",
@@ -753,6 +809,8 @@
"dialog.computing": "計算中… {seconds} 秒",
"dialog.could_not_be_checked": "チェックできません",
"dialog.custom_axis": "↖ カスタム軸",
+ "dialog.dimension_insert_hint": "別の駆動寸法をダブルクリックして名前を挿入",
+ "dialog.dimension_name": "寸法: {name}",
"dialog.edit_title": "{title}を編集",
"dialog.select": "↖ 選択",
"dialog.selected_count": "↖ {count} 個選択中",
@@ -777,8 +835,30 @@
"dxf.tolerance": "曲線の許容誤差",
"dxf.tolerance_help": "表示中のボディを出力し、曲線は線分で近似します。許容誤差を小さくすると曲線が滑らかになりますが、処理時間とメモリ使用量が増えます。",
"expression, e.g. 25 mm": "計算式 (例: 25 mm)",
+ "file_load.built": "構築済み: 全{total}フィーチャー中{built}件。",
+ "file_load.converting": "ソリッドを変換中: {done}/{total}",
+ "file_load.inserting": "ジオメトリを挿入中",
+ "file_load.opening": "デザインを開いています",
+ "file_load.preparing_thumbnail": "サムネイルを準備中...",
+ "file_load.preparing_view": "ビューを準備中...",
+ "file_load.preview_note": "保存済みのプレビューです。編集前にジオメトリを確認しています。",
+ "file_load.reading": "ファイルを読み込み中...",
+ "file_load.reading_percent": "ファイルを読み込み中... {percent}%",
+ "file_load.rebuilding": "フィーチャーを再構築中: {done}/{total}",
+ "file_load.recovering": "デザインを復元中",
+ "file_load.stopping": "前の操作の停止を待っています...",
+ "file_load.waiting": "ファイル操作を待っています",
"fits the face, e.g. M8": "面に適合するサイズ (例: M8)",
"from the rule": "ルールから",
+ "help.apache": "Apacheライセンス2.0",
+ "help.attributions": "帰属表示 (ATTRIBUTION.md)",
+ "help.build": "バージョン {version} · コミット {commit} · ビルド日 {date}",
+ "help.font_details": "インターフェースにはegui組み込みのフォントを使用しています(Ubuntu Font LicenceおよびMIT/Bitstream VeraライセンスのUbuntu LightとHack、OFLおよびMITのNoto Emojiと絵文字アイコンフォント)。スケッチのテキストにはLiberation Sans(SIL OFL 1.1)を使用しています。The Crafting Appsのオプションフォントパックcraft-fonts(BIZ UDPGothic、Shippori Mincho、BIZ UDMincho、Noto Sans CJK SC、Noto Sans Arabic、SIL OFL 1.1)はSolidCraftのビルドに同梱されていません。",
+ "help.fonts": "フォント",
+ "help.licences": "ライセンス",
+ "help.mit": "MITライセンス",
+ "help.notice": "NOTICE",
+ "help.third_party": "サードパーティライセンス",
"home.documentation": "ドキュメント",
"home.in_this_browser": "このブラウザ内",
"home.missing": "見つかりません",
@@ -804,9 +884,30 @@
"install.menu": "アプリをインストール…",
"install.steps_intro": "Safari では、Web アプリを Safari 自身のメニューからインストールします:",
"install.title": "SolidCraft をインストール",
+ "issue.body_label": "レポート本文",
+ "issue.note_image_copied": "GitHubの下書きに画像を貼り付けてください。画像をコピーできない場合はPNGを保存してください。",
+ "issue.note_opened": "GitHubの下書きを確認し、スクリーンショットを添付してください。GitHubのSubmit new issueボタンで公開されます。",
+ "issue.note_opened_copied": "レポートをコピーしました。GitHubの下書きに貼り付け、スクリーンショットを添付してから、GitHubでSubmit new issueをクリックしてください。",
+ "issue.note_removed": "この下書きからスクリーンショットを削除しました。",
+ "issue.note_report_copied": "レポートをコピーしました。必要に応じてGitHubの下書きに貼り付けてください。",
+ "issue.note_save_failed": "スクリーンショットを保存できませんでした: {error}",
+ "issue.note_saved": "スクリーンショットを保存しました。GitHubの下書きにPNGを添付してください。",
+ "issue.save_screenshot": "スクリーンショットを保存…",
"joint.from_bodies_hint": "選択した各ボディを、位置はそのままで専用の新しいコンポーネントに移動します。",
"joint.one_body": "両方の選択が {body} 上にあります。2 つ目は別の部品で選択してください。",
"joint.one_component": "これらの部品は 1 つのコンポーネントのボディです: {bodies}。ジョイントはコンポーネント同士を動かすため、部品ごとに専用のコンポーネントが必要です。",
+ "keymap.command_id": "コマンドID",
+ "keymap.empty": "一致するコマンドはありません",
+ "keymap.use_anyway": "ここでは{key}をそのまま使用",
+ "manage.appearance_hint": "選択対象の外観を選ぶか、スウォッチをボディまたは面にドラッグしてください。",
+ "manage.assign_hint": "ボディを選択し、プラスチック設計ルールを指定してください。",
+ "manage.config_hint": "構成の行、列、ルールを編集し、行を有効にするかプレビューしてください。",
+ "manage.empty": "一致する行はありません。",
+ "manage.material_hint": "ボディを選択し、物理マテリアルを指定してください。",
+ "manage.parameters_hint": "式と単位を編集してください。Enterを押すか、フィールドから移動すると変更が適用されます。",
+ "manage.rules_hint": "編集するルールを選ぶか、新規ルールを作成してください。確定するとルールが保存されます。",
+ "measure.at": "位置",
+ "measure.item": "項目 {number}",
"messages.ago_h": "{n} 時間前",
"messages.ago_min": "{n} 分前",
"messages.ago_s": "{n} 秒前",
@@ -818,8 +919,16 @@
"messages.title": "メッセージ",
"motion.checked_to": "ステップ {step} までしか確認していません: 確認の計算量の上限に達しました",
"motion.collision": "{a} · {b}: ステップ {steps}",
+ "motion.delete_key": "キーフレームを削除",
"motion.duration_hint": "秒 (空欄: ステップごと)",
+ "motion.key_here": "ここにキーフレームを追加",
+ "motion.key_here_hint": "このステップにジョイントの現在値でキーフレームを追加",
"motion.no_collisions": "スタディ全体で衝突はありません",
+ "motion.step_back": "前のステップ",
+ "motion.step_forward": "次のステップ",
+ "motion.to_end": "最後へ",
+ "motion.to_start": "最初へ",
+ "motion.track_name": "トラック {number}",
"nav.touchpad.help": "Shift を押しながらポインターを動かすとパン、Alt/Option を押しながら動かすと回転します。マウスボタンは不要です。縦スクロールでズームします。",
"nav.touchpad.label": "タッチパッド",
"nav.touchpad.orbit": "回転(Alt/Option を押しながら移動、マウスボタン不要)",
@@ -835,6 +944,7 @@
"no joint that moves yet": "可動ジョイントがまだありません",
"no picture": "画像なし",
"none": "なし",
+ "parts.automatic_name": "自動",
"pattern.alignment_2": "配置 2",
"pattern.alignment_hint": "個数には元の図形が含まれます。中央配置ではコピーを両側に配置し、反転で偶数個の場合に多く配置する側を切り替えます。",
"pattern.direction_1": "方向 1",
@@ -842,6 +952,15 @@
"pattern.flip_direction": "方向を反転",
"pick a hole to seat it, or OK places it at the origin": "配置先の穴を選択するか、[OK]を押すと原点に配置します。",
"pick one or two vertices, edges or faces": "1つまたは2つの頂点、エッジ、面を選択",
+ "prefs.cpu": "CPU(ソフトウェア)",
+ "prefs.minutes_suffix": " min",
+ "properties.title": "プロパティ: {name}",
+ "recovery.days_ago": "{count}日前",
+ "recovery.detail": "{file} · {features}フィーチャー · 自動保存: {when}",
+ "recovery.hours_ago": "{count}時間前",
+ "recovery.just_now": "たった今",
+ "recovery.min_ago": "{count}分前",
+ "recovery.never_saved": "未保存",
"render.background": "シーンの背景",
"render.fit": "製品を画面に合わせる",
"render.image_cancel": "レンダリングをキャンセル",
@@ -904,6 +1023,10 @@
"settings.reset_intro": "次の設定はこのコンピューターでは使用できず、SolidCraft が起動できなくなるため変更されました:",
"settings.reset_title": "設定が変更されました",
"settings.supersampling_note": "ビューを高い解像度で描画してから縮小します。4K 未満の画面でエッジ、線、グリッドが滑らかになります。GPU の負荷が増えます(1.5× で約 2.25 倍、2× で 4 倍のピクセル)。",
+ "shortcut.json_error": "パラメータはJSON形式で指定してください: {error}",
+ "shortcut.no_command": "コマンド`{id}`がありません。JSONの前のテキストはコマンドIDである必要があります",
+ "shortcut.pin": "Sボックスの先頭にピン留め",
+ "shortcut.unpin": "ピン留めを解除",
"sketch.degrees_of_freedom": "自由度 {count}",
"sketch.dof_left": "残り自由度 {count}",
"sketch.dof_left_one": "残り自由度 {count}",
@@ -945,6 +1068,7 @@
"timeline.ungroup": "フィーチャーフォルダを削除",
"to the face": "面まで",
"to the next face": "次の面まで",
+ "toolbar.customize_note": "{tab}タブ。コマンドにチェックを入れると、ツールバーにボタンが追加されます。パネルのドロップダウンの行をツールバーにドラッグしたり、ボタンをツールバーの外にドラッグして削除したり、ドロップダウンの行のピンを使うこともできます。",
"toolbar.image": "画像",
"toolbar.render": "レンダリング",
"toolbar.render_scene": "シーン",
@@ -999,6 +1123,7 @@
"ui.agent_chat_file_error": "{name}: {error}",
"ui.agent_chat_file_heic": "{name}: HEIC 画像はここでは読めません。先に JPEG か PNG に書き出してください",
"ui.agent_chat_file_importing": "デザインにインポート中…",
+ "ui.agent_chat_file_kinds": "{name}: 添付できるのは画像 (PNG、JPEG、GIF、WebP、BMP、TIFF)、テキストファイル (SVG も)、CAD ファイル (STEP、IGES、FreeCAD、Rhino、STL、3MF、OBJ、glTF) です",
"ui.agent_chat_file_loading": "ファイルを読み込み中…",
"ui.agent_chat_file_not_a_file": "{name}: ファイルではありません",
"ui.agent_chat_file_not_a_picture": "{name}: 画像ではありません",
@@ -1022,6 +1147,7 @@
"ui.agent_chat_new": "新しいチャット",
"ui.agent_chat_new_confirm": "新しいチャットを始めますか? 現在のチャットは消去されます。",
"ui.agent_chat_new_yes": "新しいチャット",
+ "ui.agent_chat_next_picture": "次の画像",
"ui.agent_chat_no_cli": "アプリの隣に solidcraft-cli が見つからないため、エージェントはデザインにアクセスできません。",
"ui.agent_chat_no_control": "エージェントチャットのエンドポイントが起動しなかったため、エージェントはデザインにアクセスできません。",
"ui.agent_chat_no_images": "このエージェントは画像を受け付けません",
@@ -1037,6 +1163,7 @@
"ui.agent_chat_placeholder": "デザインの変更をエージェントに依頼…",
"ui.agent_chat_placeholder_busy": "エージェントの作業が終わったら送るメッセージを入力(Ctrl+Enter: 今すぐ送信)",
"ui.agent_chat_pop_out": "独立したウィンドウで開く(別の画面に移動できます)",
+ "ui.agent_chat_previous_picture": "前の画像",
"ui.agent_chat_privacy": "あなたのアカウントで実行するエージェント以外には、何も送信されません。",
"ui.agent_chat_privacy_note": "SolidCraft はどこにも何も送信しません。あなたが実行するエージェントが、あなた自身のアカウントでそのサービスと通信します。SolidCraft がキーやパスワードを見たり保存したりすることはありません。",
"ui.agent_chat_queue": "待機に追加",
@@ -1092,6 +1219,7 @@
"ui.ai_bad_url": "http:// または https:// で始まる URL を入力してください",
"ui.ai_base_url": "ベース URL",
"ui.ai_button": "AI",
+ "ui.ai_command_hint": "my-agent --acp",
"ui.ai_copy_suffix": "コピー",
"ui.ai_custom_url": "カスタム URL",
"ui.ai_default": "既定",
@@ -1112,8 +1240,10 @@
"ui.ai_mode_edits_note": "モデリングコマンドは確認なしで実行されます。保存・開く・エクスポートなどのファイル操作や破壊的な操作は引き続き確認します。",
"ui.ai_mode_global": "上の設定に従う",
"ui.ai_model": "モデル",
+ "ui.ai_model_hint": "qwen3:14b",
"ui.ai_modes_scope": "これらの設定は SolidCraft のツールに適用されます。エージェント自身のツール(シェル、ファイル編集)は、エージェントにモードがある場合にチャットパネルのヘッダーで選ぶエージェント自身のモードに従います。",
"ui.ai_name": "名前",
+ "ui.ai_name_hint": "マイエージェント",
"ui.ai_need_command": "エージェントを起動するコマンドを入力してください",
"ui.ai_need_model": "モデル名を入力してください",
"ui.ai_no_answer": "エージェントが時間内に応答しませんでした",
@@ -1144,6 +1274,7 @@
"ui.ai_toolbar_button": "アプリケーションバーにアシスタントボタンを表示",
"ui.ai_toolbar_button_note": "アプリケーションバーのアシスタントボタン。Ctrl+Shift+A と表示メニューからもパネルを開けます。",
"ui.ai_undo_tip": "このメッセージでエージェントが行った変更を、1回でまとめて元に戻します",
+ "ui.ai_url_hint": "https://example.com/v1",
"ui.all": "すべて",
"ui.ambient_occlusion": "アンビエントオクルージョン",
"ui.ambient_occlusion_help": "不透明な面が接する部分に柔らかい陰影を加えます。GPUビューポートが必要です。",
@@ -1765,5 +1896,6 @@
"update.title": "アップデートがあります",
"update.up_to_date": "SolidCraft は最新です。",
"update.update_now": "今すぐ更新",
- "update.you_have": "現在のバージョンは {version} です。"
+ "update.you_have": "現在のバージョンは {version} です。",
+ "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ 選択 · Enter / Tab 補完 · Esc 閉じる"
}
diff --git a/assets/locales/ko.json b/assets/locales/ko.json
index 5b008cc2e6..7dd28d7bef 100644
--- a/assets/locales/ko.json
+++ b/assets/locales/ko.json
@@ -7,9 +7,12 @@
"AI": "AI",
"ARRANGE": "배치",
"Acceleration": "가속도",
+ "Actions": "작업",
+ "Add or edit rule": "규칙 추가 또는 편집",
"Against": "상대",
"Alignment": "정렬",
"All components": "모든 구성요소",
+ "Apply your appearance first. Exports assigned appearances and materials created in this design.": "먼저 외관을 적용하세요. 지정된 외관과 이 디자인에서 만든 재질을 내보냅니다.",
"Arc length": "호 길이",
"Area": "면적",
"BROWSER": "브라우저",
@@ -21,10 +24,14 @@
"CONSTRAIN": "구속",
"CONTACT": "접촉",
"CONVERT": "변환",
+ "CSV or JSON: updates existing parameters, adds new ones": "CSV or JSON: updates existing parameters, adds new ones",
"Centre to centre": "중심 간",
"Check collisions": "충돌 확인",
+ "Choose…": "선택…",
"Circumference": "원주",
"Collisions": "충돌",
+ "Comment": "설명",
+ "Configuration rules": "Configuration rules",
"Construction": "구성선",
"Contact sets": "접촉 집합",
"Continuity": "연속성",
@@ -35,24 +42,34 @@
"Current perspective view": "현재 원근 투영 뷰",
"Curvature (G2)": "곡률 (G2)",
"Curvature change (G3)": "곡률 변화 (G3)",
+ "Delete": "삭제",
"Direction": "방향",
"Do not export hidden edges": "숨겨진 모서리 내보내지 않기",
"Don't ask again": "다시 묻지 않기",
+ "Double-click to rename": "Double-click to rename",
"Drive Joint": "조인트 구동",
"Duration": "지속 시간",
"Edges": "모서리",
+ "Edit": "편집",
"Edit Profile Sketch": "윤곽 스케치 편집",
"Explode Text": "텍스트 분해",
"Export Animation…": "애니메이션 내보내기…",
+ "Export CSV…": "CSV 내보내기…",
"Export Current View as DXF": "현재 뷰를 DXF로 내보내기",
"Export Current View as DXF…": "현재 뷰를 DXF로 내보내기…",
"Export DXF…": "DXF 내보내기…",
+ "Export JSON…": "JSON 내보내기…",
"Export hidden edges as dashed lines": "숨겨진 모서리를 파선으로 내보내기",
+ "Expression": "표현식",
"Extend to meet": "만날 때까지 연장",
"FILES": "파일",
"FLAT": "전개",
"Face": "면",
"Faces": "면",
+ "Favorites": "즐겨찾기",
+ "Favourite": "Favourite",
+ "Feature": "피처",
+ "Filter": "Filter",
"Find in Browser": "브라우저에서 찾기",
"Flat": "플랫",
"From edges": "시작 모서리",
@@ -61,6 +78,7 @@
"Holes": "구멍",
"Holes (edges on them)": "구멍 (구멍의 모서리)",
"IMAGES": "이미지",
+ "Import…": "가져오기…",
"In place (surfaces)": "제자리에서 (서피스)",
"In plane": "평면 내",
"Inside": "안쪽",
@@ -70,22 +88,38 @@
"LIBRARY": "라이브러리",
"LINKS": "링크",
"Length": "길이",
+ "Length units": "Length units",
+ "Library file": "라이브러리 파일",
+ "Local library": "로컬 라이브러리",
"MANAGE": "관리",
"MATERIALS": "재질",
"MODEL": "모델",
"MOTION": "동작",
+ "Matched restrictions check the final values.": "조건이 충족된 제한 규칙은 최종 값을 검사합니다.",
"Max": "최대",
"Min": "최소",
"Mitre": "연귀",
+ "Model Parameters": "모델 매개변수",
+ "Move down": "아래로 이동",
+ "Move up": "위로 이동",
+ "Name": "Name",
+ "New": "새로 만들기",
+ "New rule…": "새 규칙…",
"New study": "새 연구",
+ "No matching appearance presets.": "일치하는 외관 프리셋이 없습니다.",
"No visible bodies to export.": "표시된 바디가 없어 내보낼 수 없습니다.",
"None": "없음",
"Normal to sketch": "스케치에 수직",
"Notch": "노치",
"OUTPUT": "출력",
+ "Open local libraries in the desktop app. You can export this design's library here.": "로컬 라이브러리는 데스크톱 앱에서 여세요. 이 디자인의 라이브러리는 여기서 내보낼 수 있습니다.",
+ "Operator": "연산자",
+ "Other surface (mutual trim)": "다른 곡면(상호 트림)",
+ "OUTPUT": "출력",
"Other surface (mutual trim)": "다른 곡면(상호 트림)",
"Outside": "바깥쪽",
"Overall length": "전체 길이",
+ "Parameter": "매개변수",
"Pass through": "통과점",
"Picked": "선택한 항목",
"Picked point": "선택한 점",
@@ -105,9 +139,13 @@
"Restore outer boundary": "외부 경계 복원",
"Revert Position": "위치 복원",
"Round": "둥글게",
+ "Rule": "Rule",
+ "Rule name": "규칙 이름",
+ "Rules run from top to bottom. Matched drives change effective values.": "규칙은 위에서 아래로 실행됩니다. 조건이 충족된 구동 규칙은 유효 값을 변경합니다.",
"SECTION": "단면",
"SURFACE QUALITY": "곡면 품질",
"Save the study as an animated GIF, seen as the viewport shows it": "뷰포트에 보이는 대로 스터디를 애니메이션 GIF로 저장",
+ "Search this library": "이 라이브러리 검색",
"Select bodies (a face picks its body)": "바디 선택(면을 클릭하면 해당 바디 선택)",
"Selection filter": "선택 필터",
"Send your report on GitHub": "GitHub에서 보고서 보내기",
@@ -124,6 +162,7 @@
"TRIM": "트림",
"Tangent (G1)": "접선 (G1)",
"Tear": "찢김",
+ "Then": "Then",
"Thickness Outside": "바깥쪽 두께",
"Thin": "얇은 벽",
"Thin Extrude": "얇은 벽 돌출",
@@ -132,12 +171,22 @@
"Turn off section analysis before exporting the view.": "뷰를 내보내기 전에 단면 분석을 끄세요.",
"Type": "유형",
"UNTRIM": "트림 해제",
+ "Unit": "단위",
+ "User Parameters": "사용자 매개변수",
"VIEWS": "뷰",
+ "Value": "Value",
"Velocity": "속도",
"Vertices": "꼭짓점",
"Visible bodies only. Curves use line segments (0.01 mm tolerance).": "표시된 바디만 내보냅니다. 곡선은 선분으로 근사합니다 (허용오차 0.01 mm).",
"Wall Location": "벽 위치",
"Wall Thickness": "벽 두께",
+ "When": "When",
+ "X angle": "X 각도",
+ "X distance": "X 거리",
+ "Y angle": "Y 각도",
+ "Y distance": "Y 거리",
+ "Z angle": "Z 각도",
+ "Z distance": "Z 거리",
"appearance.dielectric_ior": "유전체 굴절률",
"appearance.metallic": "금속성",
"appearance.pbr_help": "이 표면은 렌더링 작업 공간이나 제품 PNG에서 확인하세요. 굴절과 투과는 지원하지 않습니다.",
@@ -145,7 +194,11 @@
"appearance.roughness": "거칠기",
"appearance.surface_response": "표면 반응",
"browser.body_name": "바디{number}",
+ "browser.capture_many": "구성요소 {count}개가 이동되었지만 위치가 캡처되지 않았습니다.",
+ "browser.capture_note": "위치 캡처는 새 위치를 유지하고, 위치 복원은 이전 위치로 되돌립니다.",
+ "browser.capture_one": "구성요소가 이동되었지만 위치가 캡처되지 않았습니다.",
"browser.component_name": "컴포넌트{number}",
+ "browser.move_title": "이동: {name}",
"browser.parameters": "매개변수 ({count})",
"browser.precision": "정밀도: {precision}",
"browser.sketch_name": "스케치{number}",
@@ -471,6 +524,8 @@
"cmd.view_navigate": "보기 탐색",
"cmd.view_rename": "이름 있는 보기 이름 변경",
"cmd.view_save": "새 이름 있는 보기",
+ "contact.components_count": "구성요소 {count}개",
+ "contact.enabled_label": "활성화됨",
"coupling.gear_1": "기어 1",
"coupling.gear_1_pick": "기어 1 (선택 사항)",
"coupling.gear_2": "기어 2",
@@ -487,6 +542,7 @@
"coupling.rack": "랙",
"coupling.radius_1": "반지름 1",
"coupling.radius_2": "반지름 2",
+ "delete.and_more": "… 외 {count}개",
"dialog.bodies_count": "바디 {count}개",
"dialog.clearance_invalid": "간격은 0 이상의 길이여야 합니다",
"dialog.compute": "계산",
@@ -494,6 +550,8 @@
"dialog.computing": "계산 중… {seconds}초",
"dialog.could_not_be_checked": "확인할 수 없음",
"dialog.custom_axis": "↖ 사용자 정의 축",
+ "dialog.dimension_insert_hint": "다른 구동 치수를 두 번 클릭하여 이름 삽입",
+ "dialog.dimension_name": "치수: {name}",
"dialog.edit_title": "{title} 편집",
"dialog.select": "↖ 선택",
"dialog.selected_count": "↖ {count}개 선택됨",
@@ -517,6 +575,15 @@
"dxf.progress.write": "DXF 쓰는 중 (5/5)",
"dxf.tolerance": "곡선 허용 오차",
"dxf.tolerance_help": "표시된 바디만 내보내며 곡선은 직선 구간으로 근사합니다. 허용 오차가 작을수록 곡선이 매끄러워지지만 처리 시간과 메모리 사용량이 늘어납니다.",
+ "help.apache": "Apache 라이선스 2.0",
+ "help.attributions": "저작자 표시 (ATTRIBUTION.md)",
+ "help.build": "버전 {version} · 커밋 {commit} · 빌드 날짜 {date}",
+ "help.font_details": "인터페이스는 egui의 내장 글꼴을 사용합니다(Ubuntu Font Licence 및 MIT/Bitstream Vera 라이선스의 Ubuntu Light와 Hack, OFL 및 MIT의 Noto Emoji와 이모지 아이콘 글꼴). 스케치 텍스트는 Liberation Sans(SIL OFL 1.1)를 사용합니다. The Crafting Apps의 선택적 글꼴 팩 craft-fonts(BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1)는 SolidCraft 빌드에 포함되지 않습니다.",
+ "help.fonts": "글꼴",
+ "help.licences": "라이선스",
+ "help.mit": "MIT 라이선스",
+ "help.notice": "NOTICE",
+ "help.third_party": "타사 라이선스",
"home.documentation": "문서",
"home.in_this_browser": "이 브라우저에 저장됨",
"home.missing": "찾을 수 없음",
@@ -545,21 +612,47 @@
"joint.from_bodies_hint": "선택한 각 바디가 제자리에 그대로 있으면서 자체의 새 구성 요소로 옮겨집니다.",
"joint.one_body": "두 선택이 모두 {body}에 있습니다. 두 번째는 다른 부품에서 선택하세요.",
"joint.one_component": "이 부품들은 한 구성 요소의 바디입니다: {bodies}. 관절은 한 구성 요소를 다른 구성 요소에 대해 움직이므로 부품마다 자체 구성 요소가 필요합니다.",
+ "keymap.command_id": "명령 ID",
+ "keymap.empty": "일치하는 명령이 없습니다",
+ "keymap.use_anyway": "그래도 여기서 {key} 사용",
+ "manage.appearance_hint": "선택 항목의 외관을 선택하거나 견본을 바디 또는 면으로 끌어다 놓으세요.",
+ "manage.assign_hint": "바디를 선택하고 플라스틱 설계 규칙을 지정하세요.",
+ "manage.config_hint": "구성 행, 열 및 규칙을 편집한 다음 행을 활성화하거나 미리 보세요.",
+ "manage.empty": "일치하는 행이 없습니다.",
+ "manage.material_hint": "바디를 선택하고 물리 재질을 지정하세요.",
+ "manage.parameters_hint": "표현식과 단위를 편집하세요. Enter를 누르거나 필드를 벗어나면 변경 사항이 적용됩니다.",
+ "manage.rules_hint": "편집할 규칙을 선택하거나 새 규칙을 만드세요. 확인하면 규칙이 저장됩니다.",
+ "measure.at": "위치",
+ "measure.item": "항목 {number}",
"motion.checked_to": "{step} 단계까지만 확인했습니다: 확인 작업량 한도에 도달했습니다",
"motion.collision": "{a} · {b}: {steps} 단계",
+ "motion.delete_key": "키프레임 삭제",
"motion.duration_hint": "초 (비우면: 단계당)",
+ "motion.key_here": "여기에 키프레임 추가",
+ "motion.key_here_hint": "이 단계에 조인트의 현재 값으로 키프레임 추가",
"motion.no_collisions": "연구 전체에서 충돌이 없습니다",
+ "motion.step_back": "이전 단계",
+ "motion.step_forward": "다음 단계",
+ "motion.to_end": "끝으로",
+ "motion.to_start": "처음으로",
+ "motion.track_name": "트랙 {number}",
"nav.touchpad.help": "Shift를 누른 채 포인터를 움직이면 화면이 이동하고, Alt/Option을 누른 채 움직이면 회전합니다. 마우스 버튼은 필요 없습니다. 세로 스크롤로 확대/축소합니다.",
"nav.touchpad.label": "터치패드",
"nav.touchpad.orbit": "회전 (Alt/Option을 누르고 이동, 마우스 버튼 불필요)",
"nav.touchpad.pan": "화면 이동 (Shift를 누르고 이동, 마우스 버튼 불필요)",
"nav.touchpad.scroll": "터치패드는 세로 스크롤로 확대/축소합니다. 두 손가락 이동 설정은 다른 프리셋을 위해 유지됩니다.",
"nav.touchpad.zoom": "확대/축소 (세로 스크롤 또는 핀치)",
+ "new parameter": "new parameter",
+ "none": "없음",
+ "parts.automatic_name": "자동",
"pattern.alignment_2": "정렬 2",
"pattern.alignment_hint": "개수에는 원본이 포함됩니다. 가운데 정렬은 복사본을 양쪽에 배치하며, 개수가 짝수이면 방향 반전으로 복사본이 하나 더 배치되는 쪽을 선택합니다.",
"pattern.direction_1": "방향 1",
"pattern.direction_2": "방향 2",
"pattern.flip_direction": "방향 반전",
+ "prefs.cpu": "CPU (소프트웨어)",
+ "prefs.minutes_suffix": " min",
+ "properties.title": "속성: {name}",
"render.background": "장면 배경",
"render.fit": "제품에 맞추기",
"render.image_cancel": "렌더링 취소",
@@ -622,6 +715,10 @@
"settings.reset_intro": "다음 설정은 이 컴퓨터에서 작동하지 않아 SolidCraft를 시작할 수 없게 하므로 변경되었습니다:",
"settings.reset_title": "설정이 변경되었습니다",
"settings.supersampling_note": "뷰를 더 높은 해상도로 그린 뒤 축소합니다. 4K 미만 화면에서 모서리, 선, 그리드가 더 매끄러워집니다. GPU 시간이 듭니다: 1.5×에서 약 2.25배, 2×에서 4배의 픽셀.",
+ "shortcut.json_error": "매개변수는 JSON 형식이어야 합니다: {error}",
+ "shortcut.no_command": "`{id}` 명령이 없습니다. JSON 앞의 텍스트는 명령 ID여야 합니다",
+ "shortcut.pin": "S 상자 맨 위에 고정",
+ "shortcut.unpin": "고정 해제",
"sketch.degrees_of_freedom": "자유도 {count}개",
"sketch.dof_left": "남은 자유도 {count}개",
"sketch.dof_left_one": "남은 자유도 {count}개",
@@ -653,6 +750,7 @@
"timeline.rename_group": "특성 폴더 이름 변경",
"timeline.reorder_many": "특성 순서 변경",
"timeline.ungroup": "특성 폴더 제거",
+ "toolbar.customize_note": "{tab} 탭입니다. 명령을 선택하면 도구 모음에 해당 버튼이 추가됩니다. 패널의 드롭다운에서 행을 도구 모음으로 끌거나, 버튼을 도구 모음 밖으로 끌어 제거하거나, 드롭다운 행의 고정 핀을 사용할 수도 있습니다.",
"toolbar.image": "이미지",
"toolbar.render": "렌더링",
"toolbar.render_scene": "장면",
@@ -699,6 +797,7 @@
"ui.agent_chat_left": "왼쪽",
"ui.agent_chat_limit": "에이전트가 메시지당 변경 한도 {limit}에 도달했습니다. 계속하게 하려면 메시지를 하나 더 보내세요.",
"ui.agent_chat_minimize": "얇은 막대로 최소화",
+ "ui.agent_chat_next_picture": "다음 이미지",
"ui.agent_chat_no_cli": "앱 옆에서 solidcraft-cli를 찾지 못해 에이전트가 디자인에 접근할 수 없습니다.",
"ui.agent_chat_no_control": "에이전트 채팅 엔드포인트가 시작되지 않아 에이전트가 디자인에 접근할 수 없습니다.",
"ui.agent_chat_no_images": "이 에이전트는 이미지를 받지 않습니다",
@@ -709,6 +808,7 @@
"ui.agent_chat_permission": "에이전트가 실행 허락을 요청합니다: {title}",
"ui.agent_chat_pick": "에이전트",
"ui.agent_chat_placeholder": "에이전트에게 디자인 변경을 요청하세요…",
+ "ui.agent_chat_previous_picture": "이전 이미지",
"ui.agent_chat_privacy": "사용자의 계정으로 실행하는 에이전트 외에는 아무 데도 전송되지 않습니다.",
"ui.agent_chat_privacy_note": "SolidCraft는 아무것도 어디로도 보내지 않습니다. 실행한 에이전트가 사용자의 계정으로 자신의 서비스와 통신합니다. SolidCraft는 키나 비밀번호를 보거나 저장하지 않습니다.",
"ui.agent_chat_refresh": "새로 고침",
@@ -753,6 +853,7 @@
"ui.ai_bad_url": "http:// 또는 https://로 시작하는 URL을 입력하세요",
"ui.ai_base_url": "기본 URL",
"ui.ai_button": "AI",
+ "ui.ai_command_hint": "my-agent --acp",
"ui.ai_copy_suffix": "복사본",
"ui.ai_custom_url": "사용자 지정 URL",
"ui.ai_default": "기본값",
@@ -773,8 +874,10 @@
"ui.ai_mode_edits_note": "모델링 명령은 묻지 않고 실행되며, 저장·열기·내보내기 등 파일 작업이나 파괴적인 작업은 계속 묻습니다.",
"ui.ai_mode_global": "위 설정 따름",
"ui.ai_model": "모델",
+ "ui.ai_model_hint": "qwen3:14b",
"ui.ai_modes_scope": "이 설정은 SolidCraft 도구에 적용됩니다. 에이전트 자체 도구(셸, 파일 편집)는 에이전트에 모드가 있을 때 채팅 패널 머리글에서 고르는 에이전트 자체 모드를 따릅니다.",
"ui.ai_name": "이름",
+ "ui.ai_name_hint": "내 에이전트",
"ui.ai_need_command": "에이전트를 시작하는 명령을 입력하세요",
"ui.ai_need_model": "모델 이름을 입력하세요",
"ui.ai_no_answer": "에이전트가 제시간에 응답하지 않았습니다",
@@ -805,6 +908,7 @@
"ui.ai_toolbar_button": "도구 모음에 버튼 표시",
"ui.ai_toolbar_button_note": "도구 모음 오른쪽 끝의 AI 버튼. Ctrl+Shift+A와 보기 메뉴로도 패널을 열 수 있습니다.",
"ui.ai_undo_tip": "이 메시지에서 에이전트가 바꾼 모든 것을 한 번에 실행 취소",
+ "ui.ai_url_hint": "https://example.com/v1",
"ui.all": "모두",
"ui.ambient_occlusion": "앰비언트 오클루전",
"ui.ambient_occlusion_help": "불투명한 표면이 만나는 곳에 부드러운 음영을 추가합니다. GPU 뷰포트가 필요합니다.",
@@ -1342,5 +1446,6 @@
"update.title": "업데이트 사용 가능",
"update.up_to_date": "SolidCraft가 최신 버전입니다.",
"update.update_now": "지금 업데이트",
- "update.you_have": "현재 버전은 {version}입니다."
+ "update.you_have": "현재 버전은 {version}입니다.",
+ "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ 선택 · Enter / Tab 완성 · Esc 닫기"
}
diff --git a/assets/locales/pl.json b/assets/locales/pl.json
index 3b8c02fc04..95e811323b 100644
--- a/assets/locales/pl.json
+++ b/assets/locales/pl.json
@@ -8,6 +8,7 @@
"AI": "AI",
"About SolidCraft": "O programie SolidCraft",
"Acceleration": "Przyspieszenie",
+ "Actions": "Działania",
"Active": "Aktywne",
"Active rule": "Aktywna reguła",
"Add": "Dodaj",
@@ -15,6 +16,7 @@
"Add Mid Radius": "Dodaj promień środkowy",
"Add Row": "Dodaj wiersz",
"Add condition": "Dodaj warunek",
+ "Add or edit rule": "Dodaj lub edytuj regułę",
"Against": "Względem",
"Alignment": "Wyrównanie",
"All Sketch Points": "Wszystkie punkty szkicu",
@@ -28,6 +30,7 @@
"Applied Radius": "Zastosowany promień",
"Apply To": "Zastosuj do",
"Apply to selection": "Zastosuj do zaznaczenia",
+ "Apply your appearance first. Exports assigned appearances and materials created in this design.": "Najpierw zastosuj wygląd. Eksportuje przypisane wyglądy i materiały utworzone w tym projekcie.",
"Arc length": "Długość łuku",
"Area": "Pole powierzchni",
"Attachment": "Zaczepienie",
@@ -52,10 +55,12 @@
"Check collisions": "Sprawdzaj kolizje",
"Checked": "Sprawdzono",
"Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "Wybierz nową płaszczyznę. Geometria i wymiary szkicu pozostają niezmienione w jego dwuwymiarowych współrzędnych.",
+ "Choose…": "Wybierz…",
"Circumference": "Obwód",
"Close draft": "Zamknij szkic zgłoszenia",
"Collisions": "Kolizje",
"Colour": "Kolor",
+ "Comment": "Komentarz",
"Component1": "Komponent1",
"Configuration": "Konfiguracja",
"Configuration rules": "Reguły konfiguracji",
@@ -80,6 +85,7 @@
"Current perspective view": "Bieżący widok perspektywiczny",
"Curvature (G2)": "Krzywizna (G2)",
"Customize Toolbar": "Dostosuj pasek narzędzi",
+ "Delete": "Usuń",
"Delete all": "Usuń wszystko",
"Delete rule": "Usuń regułę",
"Delete the row": "Usuń wiersz",
@@ -97,22 +103,28 @@
"Drive Joint": "Steruj złączem",
"Duration": "Czas trwania",
"Edges": "Krawędzie",
+ "Edit": "Edytuj",
"Edit Profile Sketch": "Edytuj szkic profilu",
"Enable rule": "Włącz regułę",
"Enabled": "Włączone",
"Explode": "Rozstrzel",
"Explode Text": "Rozbij tekst",
"Export Animation…": "Eksportuj animację…",
+ "Export CSV…": "Eksportuj CSV…",
"Export Current View as DXF": "Eksportuj bieżący widok jako DXF",
"Export Current View as DXF…": "Eksportuj bieżący widok jako DXF…",
"Export DXF…": "Eksportuj DXF…",
+ "Export JSON…": "Eksportuj JSON…",
"Export hidden edges as dashed lines": "Eksportuj krawędzie niewidoczne jako linie kreskowe",
+ "Expression": "Wyrażenie",
"Extents": "Zakres",
"Face": "Ściana",
"Face attachment lost": "Utracono zaczepienie do ściany",
"Faces": "Ściany",
"Faces / edges / vertices": "Ściany / krawędzie / wierzchołki",
+ "Favorites": "Ulubione",
"Favourite": "Ulubione",
+ "Feature": "Funkcja",
"Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "Pliki z wielu programów CAD mają oś Y skierowaną w górę, więc otwierają się tutaj leżąc na plecach (oś Z w górę).",
"Filter": "Filtr",
"Find in Browser": "Znajdź w przeglądarce",
@@ -128,6 +140,7 @@
"Holes": "Otwory",
"Holes (edges on them)": "Otwory (krawędzie na nich)",
"Home view": "Widok główny",
+ "Import…": "Importuj…",
"In This Design": "W tym projekcie",
"In place (surfaces)": "W miejscu (powierzchnie)",
"In plane": "W płaszczyźnie",
@@ -143,26 +156,35 @@
"Length units": "Jednostki długości",
"Letter Spacing": "Odstęp między literami",
"Library": "Biblioteka",
+ "Library file": "Plik biblioteki",
"Line Spacing": "Odstęp między wierszami",
+ "Local library": "Biblioteka lokalna",
"Loop": "Pętla",
"Margin": "Margines",
"Mass": "Masa",
+ "Matched restrictions check the final values.": "Ograniczenia, których warunki są spełnione, sprawdzają wartości końcowe.",
"Material": "Materiał",
"Max": "Maks.",
"Mid Radius": "Promień środkowy",
"Middle double-click": "Dwukrotne kliknięcie środkowym",
"Min": "Min.",
"Mitre": "Ukos",
+ "Model Parameters": "Parametry modelu",
"Modeled": "Wymodelowane",
"More toolbar panels": "Więcej paneli paska narzędzi",
"Motion": "Ruch",
"Move Type": "Typ przesunięcia",
+ "Move down": "Przenieś w dół",
"Move earlier": "Przesuń wcześniej",
"Move later": "Przesuń później",
+ "Move up": "Przenieś w górę",
"Name": "Nazwa",
"Nearest": "Najbliższy",
+ "New": "Nowy",
+ "New rule…": "Nowa reguła…",
"New study": "Nowe badanie",
"No crash reports.": "Brak raportów o awariach.",
+ "No matching appearance presets.": "Brak pasujących ustawień wyglądu.",
"No matching appearances": "Brak pasujących wyglądów",
"No visible bodies to export.": "Brak widocznych brył do wyeksportowania.",
"None": "Brak",
@@ -171,10 +193,13 @@
"Notch": "Wycięcie",
"Opacity": "Nieprzezroczystość",
"Open GitHub draft": "Otwórz szkic zgłoszenia na GitHubie",
+ "Open local libraries in the desktop app. You can export this design's library here.": "Otwórz biblioteki lokalne w aplikacji komputerowej. Tutaj możesz wyeksportować bibliotekę tego projektu.",
"Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "Otwartoźródłowy parametryczny CAD 3D w języku Rust. Licencja MIT OR Apache-2.0.",
+ "Operator": "Operator",
"Other side": "Druga strona",
"Outside": "Na zewnątrz",
"Overall length": "Długość całkowita",
+ "Parameter": "Parametr",
"Parameter values": "Wartości parametrów",
"Pass through": "Przechodzi przez",
"Path": "Ścieżka",
@@ -228,12 +253,15 @@
"Roll History Marker Here": "Przesuń tutaj znacznik historii",
"Round": "Okrągłe",
"Rule": "Reguła",
+ "Rule name": "Nazwa reguły",
+ "Rules run from top to bottom. Matched drives change effective values.": "Reguły są wykonywane od góry do dołu. Reguły sterujące, których warunki są spełnione, zmieniają wartości efektywne.",
"Save Rule": "Zapisz regułę",
"Save the study as an animated GIF, seen as the viewport shows it": "Zapisz badanie jako animowany GIF, tak jak widać je w widoku",
"Saved preview. Geometry is being checked before editing.": "Zapisany podgląd. Geometria jest sprawdzana przed edycją.",
"Scale factor": "Współczynnik skali",
"Search": "Szukaj",
"Search commands": "Szukaj poleceń",
+ "Search this library": "Przeszukaj tę bibliotekę",
"Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Wybierz inny: przytrzymaj nieruchomo lewy przycisk na modelu (lub prawy przycisk › Wybierz inny…), aby wyświetlić wszystko pod kursorem; kliknij ponownie w tym samym miejscu, aby zaznaczyć kolejny obiekt. Dwukrotne kliknięcie środkowym przyciskiem przechodzi do widoku głównego (Preferencje › Nawigacja).",
"Select bodies (a face picks its body)": "Zaznacz bryły (ściana wybiera swoją bryłę)",
"Select bodies or faces instead": "Zamiast tego zaznacz bryły lub ściany",
@@ -284,11 +312,13 @@
"Turn off section analysis before exporting the view.": "Przed eksportem widoku wyłącz analizę przekroju.",
"Type": "Typ",
"UNTRIM": "COFNIJ PRZYCIĘCIE",
+ "Unit": "Jednostka",
"Updating the preview": "Aktualizowanie podglądu",
"Use active author placement": "Użyj aktywnego położenia autora",
"Use fixed plane": "Użyj stałej płaszczyzny",
"Use saved fixed plane": "Użyj zapisanej stałej płaszczyzny",
"Use selected face as fixed plane": "Użyj wybranej ściany jako stałej płaszczyzny",
+ "User Parameters": "Parametry użytkownika",
"VIEW": "WIDOK",
"Value": "Wartość",
"Velocity": "Prędkość",
@@ -302,6 +332,12 @@
"When": "Gdy",
"Width": "Szerokość",
"Will fail": "Nie powiedzie się",
+ "X angle": "Kąt X",
+ "X distance": "Odległość X",
+ "Y angle": "Kąt Y",
+ "Y distance": "Odległość Y",
+ "Z angle": "Kąt Z",
+ "Z distance": "Odległość Z",
"angle, height": "kąt, wysokość",
"appearance.dielectric_ior": "Współczynnik załamania dielektryka (IOR)",
"appearance.metallic": "Metaliczność",
@@ -310,7 +346,11 @@
"appearance.roughness": "Chropowatość",
"appearance.surface_response": "Reakcja powierzchni",
"browser.body_name": "Bryła{number}",
+ "browser.capture_many": "Przesunięto komponenty ({count}), ale ich położenia nie zostały zapamiętane.",
+ "browser.capture_note": "Zapamiętaj położenie zachowuje nowe położenie; Przywróć położenie przywraca poprzednie.",
+ "browser.capture_one": "Przesunięto komponent, ale jego położenie nie zostało zapamiętane.",
"browser.component_name": "Komponent{number}",
+ "browser.move_title": "Przesuń: {name}",
"browser.parameters": "Parametry ({count})",
"browser.precision": "Dokładność: {precision}",
"browser.sketch_name": "Szkic{number}",
@@ -639,6 +679,8 @@
"cmd.view_rename": "Zmień nazwę widoku nazwanego",
"cmd.view_save": "Nowy widok nazwany",
"command name": "nazwa polecenia",
+ "contact.components_count": "Liczba komponentów: {count}",
+ "contact.enabled_label": "włączone",
"coupling.gear_1": "Koło zębate 1",
"coupling.gear_1_pick": "Koło zębate 1 (opcjonalnie)",
"coupling.gear_2": "Koło zębate 2",
@@ -655,8 +697,11 @@
"coupling.rack": "Zębatka",
"coupling.radius_1": "Promień 1",
"coupling.radius_2": "Promień 2",
+ "delete.and_more": "… i jeszcze {count}",
"dialog.computing": "Obliczanie… {seconds} s",
"dialog.custom_axis": "↖ Oś niestandardowa",
+ "dialog.dimension_insert_hint": "Kliknij dwukrotnie inny wymiar sterujący, aby wstawić jego nazwę",
+ "dialog.dimension_name": "Wymiar: {name}",
"dialog.edit_title": "EDYCJA: {title}",
"dialog.select": "↖ Zaznacz",
"dialog.selected_count": "↖ Zaznaczono: {count}",
@@ -683,6 +728,15 @@
"expression, e.g. 25 mm": "wyrażenie, np. 25 mm",
"fits the face, e.g. M8": "pasuje do ściany, np. M8",
"from the rule": "z reguły",
+ "help.apache": "Licencja Apache 2.0",
+ "help.attributions": "Uznanie autorstwa (ATTRIBUTION.md)",
+ "help.build": "Wersja {version} · commit {commit} · zbudowano {date}",
+ "help.font_details": "Interfejs używa wbudowanych czcionek egui (Ubuntu Light i Hack na licencjach Ubuntu Font Licence oraz MIT/Bitstream Vera; Noto Emoji i czcionka ikon emoji na licencjach OFL i MIT). Tekst szkicu używa Liberation Sans (SIL OFL 1.1). Opcjonalny pakiet czcionek The Crafting Apps, craft-fonts (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1), nie jest dołączany do kompilacji SolidCraft.",
+ "help.fonts": "Czcionki",
+ "help.licences": "Licencje",
+ "help.mit": "Licencja MIT",
+ "help.notice": "NOTICE",
+ "help.third_party": "Licencje stron trzecich",
"home.documentation": "Dokumentacja",
"home.in_this_browser": "w tej przeglądarce",
"home.missing": "brak",
@@ -711,10 +765,30 @@
"joint.from_bodies_hint": "Każda wybrana bryła trafia do nowego, własnego komponentu i pozostaje na swoim miejscu.",
"joint.one_body": "Oba wybory leżą na {body}. Drugi wybierz na innej części.",
"joint.one_component": "Te części są bryłami jednego komponentu: {bodies}. Złącze porusza jeden komponent względem drugiego, więc każda część potrzebuje własnego komponentu.",
+ "keymap.command_id": "ID polecenia",
+ "keymap.empty": "Brak pasujących poleceń",
+ "keymap.use_anyway": "Mimo to użyj tutaj {key}",
+ "manage.appearance_hint": "Wybierz wygląd dla zaznaczenia lub przeciągnij próbkę na bryłę albo ścianę.",
+ "manage.assign_hint": "Wybierz bryły i ich regułę projektowania części z tworzyw sztucznych.",
+ "manage.config_hint": "Edytuj wiersze, kolumny i reguły konfiguracji, a następnie aktywuj wiersz lub wyświetl jego podgląd.",
+ "manage.empty": "Brak pasujących wierszy.",
+ "manage.material_hint": "Wybierz bryły i ich materiał fizyczny.",
+ "manage.parameters_hint": "Edytuj wyrażenia i jednostki. Zmiany są stosowane po naciśnięciu Enter lub opuszczeniu pola.",
+ "manage.rules_hint": "Wybierz regułę do edycji lub utwórz nową. Potwierdź, aby zapisać regułę.",
+ "measure.at": "W punkcie",
+ "measure.item": "Element {number}",
"motion.checked_to": "Sprawdzono tylko do kroku {step}: sprawdzanie wyczerpało swój budżet obliczeń",
"motion.collision": "{a} · {b}: kroki {steps}",
+ "motion.delete_key": "Usuń klatkę kluczową",
"motion.duration_hint": "sekundy (puste: na krok)",
+ "motion.key_here": "Wstaw klatkę kluczową tutaj",
+ "motion.key_here_hint": "Dodaj klatkę kluczową w tym kroku z bieżącą wartością złącza",
"motion.no_collisions": "Brak kolizji w trakcie badania",
+ "motion.step_back": "Krok wstecz",
+ "motion.step_forward": "Krok naprzód",
+ "motion.to_end": "Na koniec",
+ "motion.to_start": "Na początek",
+ "motion.track_name": "Ścieżka {number}",
"nav.touchpad.help": "Przytrzymaj Shift i poruszaj wskaźnikiem, aby przesuwać; przytrzymaj Alt/Option i poruszaj nim, aby obracać widok. Przycisk myszy nie jest potrzebny. Przewijanie w pionie powiększa.",
"nav.touchpad.label": "Touchpad",
"nav.touchpad.orbit": "Obracanie widoku (przytrzymaj Alt/Option i poruszaj; bez przycisku myszy)",
@@ -728,6 +802,8 @@
"no interference": "brak kolizji",
"no joint that moves yet": "brak jeszcze ruchomego złącza",
"no picture": "brak obrazu",
+ "none": "brak",
+ "parts.automatic_name": "automatycznie",
"pattern.alignment_2": "Wyrównanie 2",
"pattern.alignment_hint": "Liczba obejmuje oryginał. Wyśrodkuj rozkłada kopie po obu stronach; Odwróć wybiera stronę z dodatkową kopią przy parzystej liczbie.",
"pattern.direction_1": "Kierunek 1",
@@ -735,6 +811,9 @@
"pattern.flip_direction": "Odwróć kierunek",
"pick a hole to seat it, or OK places it at the origin": "wybierz otwór, aby go osadzić, lub OK umieszcza go w początku układu",
"pick one or two vertices, edges or faces": "wybierz jeden lub dwa wierzchołki, krawędzie lub ściany",
+ "prefs.cpu": "CPU (programowo)",
+ "prefs.minutes_suffix": " min",
+ "properties.title": "Właściwości: {name}",
"render.background": "Tło sceny",
"render.fit": "Dopasuj produkt",
"render.image_cancel": "Anuluj renderowanie",
@@ -797,6 +876,10 @@
"settings.reset_intro": "Te ustawienia nie działają na tym komputerze i uniemożliwiłyby uruchomienie SolidCraft, więc zostały zmienione:",
"settings.reset_title": "Zmieniono ustawienia",
"settings.supersampling_note": "Rysuje widok w wyższej rozdzielczości i go zmniejsza: gładsze krawędzie, linie i siatka na ekranach poniżej 4K. Kosztuje czas GPU: ok. 2,25× więcej pikseli przy 1,5× i 4× przy 2×.",
+ "shortcut.json_error": "parametry muszą być w formacie JSON: {error}",
+ "shortcut.no_command": "nie ma polecenia `{id}`; tekst przed JSON musi być identyfikatorem polecenia",
+ "shortcut.pin": "Przypnij na górze pola S",
+ "shortcut.unpin": "Odepnij",
"sketch.degrees_of_freedom": "Stopnie swobody: {count}",
"sketch.dof_left": "Pozostałe stopnie swobody: {count}",
"sketch.dof_left_one": "Pozostał {count} stopień swobody",
@@ -836,6 +919,7 @@
"timeline.reorder_many": "Zmień kolejność funkcji",
"timeline.ungroup": "Usuń foldery funkcji",
"to the next face": "do następnej ściany",
+ "toolbar.customize_note": "Karta {tab}. Zaznacz polecenie, aby dodać jego przycisk do paska narzędzi. Możesz też przeciągnąć wiersz z listy rozwijanej panelu na pasek narzędzi, przeciągnąć przycisk poza pasek, aby go usunąć, lub użyć pinezki w wierszu listy rozwijanej.",
"toolbar.image": "OBRAZ",
"toolbar.render": "RENDEROWANIE",
"toolbar.render_scene": "SCENA",
@@ -890,6 +974,7 @@
"ui.agent_chat_new": "Nowy czat",
"ui.agent_chat_new_confirm": "Rozpocząć nowy czat? Bieżący zostanie wyczyszczony.",
"ui.agent_chat_new_yes": "Nowy czat",
+ "ui.agent_chat_next_picture": "Następny obraz",
"ui.agent_chat_no_cli": "Nie znaleziono solidcraft-cli obok aplikacji, więc agent nie ma dostępu do projektu.",
"ui.agent_chat_no_control": "Punkt końcowy czatu z agentem się nie uruchomił, więc agent nie ma dostępu do projektu.",
"ui.agent_chat_no_images": "Ten agent nie przyjmuje obrazów",
@@ -903,6 +988,7 @@
"ui.agent_chat_placeholder": "Poproś agenta o zmianę projektu…",
"ui.agent_chat_placeholder_busy": "Zakolejkuj wiadomość na czas, gdy agent skończy (Ctrl+Enter: wyślij teraz)",
"ui.agent_chat_pop_out": "Otwórz w osobnym oknie, które możesz przenieść na inny ekran",
+ "ui.agent_chat_previous_picture": "Poprzedni obraz",
"ui.agent_chat_privacy": "Nic nie trafia nigdzie poza uruchomionym przez Ciebie agentem, na Twoim własnym koncie.",
"ui.agent_chat_privacy_note": "SolidCraft nigdzie niczego nie wysyła: uruchomiony przez Ciebie agent łączy się z własną usługą na Twoim koncie. SolidCraft nigdy nie widzi ani nie przechowuje klucza ani hasła.",
"ui.agent_chat_queue": "Kolejka",
@@ -956,6 +1042,7 @@
"ui.ai_bad_url": "Wpisz adres URL zaczynający się od http:// lub https://",
"ui.ai_base_url": "Bazowy URL",
"ui.ai_button": "AI",
+ "ui.ai_command_hint": "my-agent --acp",
"ui.ai_copy_suffix": "kopia",
"ui.ai_custom_url": "Niestandardowy URL",
"ui.ai_default": "Domyślny",
@@ -976,8 +1063,10 @@
"ui.ai_mode_edits_note": "Polecenia modelowania działają bez pytania; zapisywanie, otwieranie, eksport oraz inne operacje na plikach lub nieodwracalne nadal wymagają pytania.",
"ui.ai_mode_global": "Jak ustawiono powyżej",
"ui.ai_model": "Model",
+ "ui.ai_model_hint": "qwen3:14b",
"ui.ai_modes_scope": "Te ustawienia dotyczą narzędzi SolidCraft. Własne narzędzia agenta (jego powłoka, edycja plików) podlegają własnemu trybowi agenta, który wybierasz w nagłówku panelu czatu, gdy agent ma tryby.",
"ui.ai_name": "Nazwa",
+ "ui.ai_name_hint": "Mój agent",
"ui.ai_need_command": "Wpisz polecenie uruchamiające agenta",
"ui.ai_need_model": "Wpisz nazwę modelu",
"ui.ai_no_answer": "Agent nie odpowiedział na czas",
@@ -1008,6 +1097,7 @@
"ui.ai_toolbar_button": "Pokaż przycisk na pasku narzędzi",
"ui.ai_toolbar_button_note": "Przycisk AI na prawym końcu paska narzędzi. Ctrl+Shift+A i menu Widok nadal otwierają panel.",
"ui.ai_undo_tip": "Cofnij jednym krokiem wszystko, co agent zmienił w ramach tej wiadomości",
+ "ui.ai_url_hint": "https://example.com/v1",
"ui.all": "Wszystko",
"ui.analysis": "Analiza",
"ui.angle": "Kąt",
@@ -1553,5 +1643,6 @@
"update.title": "Dostępna aktualizacja",
"update.up_to_date": "SolidCraft jest aktualny.",
"update.update_now": "Aktualizuj teraz",
- "update.you_have": "Masz wersję {version}."
+ "update.you_have": "Masz wersję {version}.",
+ "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ wybierz · Enter / Tab uzupełnij · Esc zamknij"
}
diff --git a/assets/locales/pt-BR.json b/assets/locales/pt-BR.json
index 5ae9a02802..f70fe3a7d7 100644
--- a/assets/locales/pt-BR.json
+++ b/assets/locales/pt-BR.json
@@ -9,6 +9,7 @@
"AI": "IA",
"ARRANGE": "ORGANIZAR",
"About SolidCraft": "Sobre o SolidCraft",
+ "Actions": "Ações",
"Active": "Ativo",
"Active rule": "Regra ativa",
"Add": "Adicionar",
@@ -16,6 +17,7 @@
"Add Mid Radius": "Adicionar raio intermediário",
"Add Row": "Adicionar linha",
"Add condition": "Adicionar condição",
+ "Add or edit rule": "Adicionar ou editar regra",
"Alignment": "Alinhamento",
"All Sketch Points": "Todos os pontos do esboço",
"All open designs": "Todos os projetos abertos",
@@ -27,6 +29,7 @@
"Applied Radius": "Raio aplicado",
"Apply To": "Aplicar a",
"Apply to selection": "Aplicar à seleção",
+ "Apply your appearance first. Exports assigned appearances and materials created in this design.": "Aplique a aparência primeiro. Exporta as aparências atribuídas e os materiais criados neste projeto.",
"Arc length": "Comprimento do arco",
"Area": "Área",
"Attachment": "Fixação",
@@ -56,10 +59,12 @@
"Check collisions": "Verificar colisões",
"Checked": "Marcado",
"Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "Escolha um novo plano. A geometria e as cotas do esboço permanecem inalteradas em suas coordenadas bidimensionais.",
+ "Choose…": "Escolher…",
"Circumference": "Circunferência",
"Close draft": "Fechar rascunho",
"Collisions": "Colisões",
"Colour": "Cor",
+ "Comment": "Comentário",
"Component1": "Componente1",
"Configuration": "Configuração",
"Configuration rules": "Regras de configuração",
@@ -83,6 +88,7 @@
"Curvature (G2)": "Curvatura (G2)",
"Curvature change (G3)": "Variação de curvatura (G3)",
"Customize Toolbar": "Personalizar barra de ferramentas",
+ "Delete": "Excluir",
"Delete all": "Excluir tudo",
"Delete rule": "Excluir regra",
"Delete the row": "Excluir a linha",
@@ -98,15 +104,19 @@
"Double-clicking the middle button in the view: Home (the home view, framing what is shown), Fit (frame what is shown, keeping the orientation) or nothing": "Clique duplo com o botão do meio na vista: Início (a vista inicial, enquadrando o que é mostrado), Ajustar (enquadra o que é mostrado, mantendo a orientação) ou nada",
"Drive Joint": "Acionar junta",
"Edges": "Arestas",
+ "Edit": "Editar",
"Edit Profile Sketch": "Editar esboço do perfil",
"Enable rule": "Ativar regra",
"Enabled": "Ativado",
"Explode": "Explodir",
"Export Animation…": "Exportar animação…",
+ "Export CSV…": "Exportar CSV…",
"Export Current View as DXF": "Exportar vista atual como DXF",
"Export Current View as DXF…": "Exportar vista atual como DXF…",
"Export DXF…": "Exportar DXF…",
+ "Export JSON…": "Exportar JSON…",
"Export hidden edges as dashed lines": "Exportar arestas ocultas como linhas tracejadas",
+ "Expression": "Expressão",
"Extend to meet": "Estender até encontrar",
"Extents": "Extensões",
"FILES": "ARQUIVOS",
@@ -115,7 +125,9 @@
"Face attachment lost": "Fixação à face perdida",
"Faces": "Faces",
"Faces / edges / vertices": "Faces / arestas / vértices",
+ "Favorites": "Favoritos",
"Favourite": "Favorito",
+ "Feature": "Recurso",
"Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "Arquivos de muitos programas CAD usam Y para cima, então abrem deitados aqui (Z para cima).",
"Filter": "Filtro",
"Find in Browser": "Localizar no navegador",
@@ -134,6 +146,7 @@
"Holes (edges on them)": "Furos (arestas neles)",
"Home view": "Vista inicial",
"IMAGES": "IMAGENS",
+ "Import…": "Importar…",
"In This Design": "Neste projeto",
"In place (surfaces)": "No lugar (superfícies)",
"In plane": "No plano",
@@ -154,7 +167,9 @@
"Length units": "Unidades de comprimento",
"Letter Spacing": "Espaçamento entre letras",
"Library": "Biblioteca",
+ "Library file": "Arquivo de biblioteca",
"Line Spacing": "Espaçamento entre linhas",
+ "Local library": "Biblioteca local",
"Loop": "Laço",
"MANAGE": "GERENCIAR",
"MATERIALS": "MATERIAIS",
@@ -162,20 +177,27 @@
"MOTION": "MOVIMENTO",
"Margin": "Margem",
"Mass": "Massa",
+ "Matched restrictions check the final values.": "As restrições cujas condições são atendidas verificam os valores finais.",
"Material": "Material",
"Max": "Máx.",
"Mid Radius": "Raio intermediário",
"Middle double-click": "Clique duplo do meio",
"Min": "Mín.",
"Mitre": "Meia-esquadria",
+ "Model Parameters": "Parâmetros do modelo",
"Modeled": "Modelado",
"More toolbar panels": "Mais painéis da barra de ferramentas",
"Motion": "Movimento",
"Move Type": "Tipo de movimento",
+ "Move down": "Mover para baixo",
"Move earlier": "Mover para antes",
"Move later": "Mover para depois",
+ "Move up": "Mover para cima",
"Name": "Nome",
+ "New": "Novo",
+ "New rule…": "Nova regra…",
"No crash reports.": "Nenhum relatório de falha.",
+ "No matching appearance presets.": "Nenhuma predefinição de aparência correspondente.",
"No matching appearances": "Nenhuma aparência correspondente",
"No visible bodies to export.": "Nenhum corpo visível para exportar.",
"None": "Nenhum",
@@ -185,11 +207,14 @@
"OUTPUT": "SAÍDA",
"Opacity": "Opacidade",
"Open GitHub draft": "Abrir rascunho no GitHub",
+ "Open local libraries in the desktop app. You can export this design's library here.": "Abra bibliotecas locais no aplicativo para desktop. Você pode exportar a biblioteca deste projeto aqui.",
"Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "CAD 3D paramétrico de código aberto em Rust. Licenciado sob MIT OU Apache-2.0.",
+ "Operator": "Operador",
"Other side": "Outro lado",
"Other surface (mutual trim)": "Outra superfície (aparo mútuo)",
"Outside": "Fora",
"Overall length": "Comprimento total",
+ "Parameter": "Parâmetro",
"Parameter values": "Valores dos parâmetros",
"Pass through": "Atravessar",
"Path": "Caminho",
@@ -241,6 +266,8 @@
"Roll History Marker Here": "Mover o marcador do histórico para cá",
"Round": "Arredondado",
"Rule": "Regra",
+ "Rule name": "Nome da regra",
+ "Rules run from top to bottom. Matched drives change effective values.": "As regras são executadas de cima para baixo. As regras de controle cujas condições são atendidas alteram os valores efetivos.",
"SECTION": "SEÇÃO",
"SURFACE QUALITY": "QUALIDADE DA SUPERFÍCIE",
"Save Rule": "Salvar regra",
@@ -249,6 +276,7 @@
"Scale factor": "Fator de escala",
"Search": "Pesquisar",
"Search commands": "Pesquisar comandos",
+ "Search this library": "Pesquisar nesta biblioteca",
"Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Selecionar outro: mantenha o botão esquerdo parado sobre o modelo (ou clique com o botão direito › Selecionar outro…) para listar tudo sob o cursor; clique de novo no mesmo ponto para selecionar o próximo item ali. Clique duas vezes com o botão do meio para ir ao Início (Preferências › Navegação).",
"Select bodies (a face picks its body)": "Selecione corpos (uma face seleciona seu corpo)",
"Select bodies or faces instead": "Selecionar corpos ou faces em vez disso",
@@ -303,11 +331,13 @@
"Turn off section analysis before exporting the view.": "Desative a análise de seção antes de exportar a vista.",
"Type": "Tipo",
"UNTRIM": "DESAPARAR",
+ "Unit": "Unidade",
"Updating the preview": "Atualizando a visualização",
"Use active author placement": "Usar o posicionamento de autoria ativo",
"Use fixed plane": "Usar plano fixo",
"Use saved fixed plane": "Usar o plano fixo salvo",
"Use selected face as fixed plane": "Usar a face selecionada como plano fixo",
+ "User Parameters": "Parâmetros do usuário",
"VIEW": "VISTA",
"VIEWS": "VISTAS",
"Value": "Valor",
@@ -321,6 +351,12 @@
"When": "Quando",
"Width": "Largura",
"Will fail": "Vai falhar",
+ "X angle": "Ângulo X",
+ "X distance": "Distância X",
+ "Y angle": "Ângulo Y",
+ "Y distance": "Distância Y",
+ "Z angle": "Ângulo Z",
+ "Z distance": "Distância Z",
"angle, height": "ângulo, altura",
"appearance.dielectric_ior": "IOR dielétrico",
"appearance.metallic": "Metálico",
@@ -329,7 +365,11 @@
"appearance.roughness": "Rugosidade",
"appearance.surface_response": "Resposta da superfície",
"browser.body_name": "Corpo{number}",
+ "browser.capture_many": "{count} componentes foram movidos, mas suas posições não foram capturadas.",
+ "browser.capture_note": "Capturar posição mantém a nova posição; Reverter posição restaura a anterior.",
+ "browser.capture_one": "Um componente foi movido, mas sua posição não foi capturada.",
"browser.component_name": "Componente{number}",
+ "browser.move_title": "Mover: {name}",
"browser.parameters": "Parâmetros ({count})",
"browser.precision": "Precisão: {precision}",
"browser.sketch_name": "Esboço{number}",
@@ -644,6 +684,8 @@
"cmd.view_rename": "Renomear vista nomeada",
"cmd.view_save": "Nova vista nomeada",
"command name": "nome do comando",
+ "contact.components_count": "{count} componentes",
+ "contact.enabled_label": "ativado",
"coupling.gear_1": "Engrenagem 1",
"coupling.gear_1_pick": "Engrenagem 1 (opcional)",
"coupling.gear_2": "Engrenagem 2",
@@ -663,8 +705,11 @@
"crash.detected_time": "Detectado em {time} UTC",
"crash.previous_session": "Uma sessão anterior do SolidCraft terminou inesperadamente ou teve um erro interno. Encerramentos sem confirmação são detectados ao iniciar o aplicativo. Consulte Ajuda > Relatórios de falha… para ver os detalhes.",
"crash.unclean_explanation": "Detectado em uma inicialização posterior; o horário exato do encerramento não foi registrado. Um desligamento do sistema ou uma parada forçada também pode causar um encerramento sem confirmação.",
+ "delete.and_more": "… e mais {count}",
"dialog.computing": "Calculando… {seconds} s",
"dialog.custom_axis": "↖ Eixo personalizado",
+ "dialog.dimension_insert_hint": "Clique duas vezes em outra cota de controle para inserir seu nome",
+ "dialog.dimension_name": "Cota: {name}",
"dialog.edit_title": "EDITAR {title}",
"dialog.select": "↖ Selecionar",
"dialog.selected_count": "↖ {count} selecionados",
@@ -679,6 +724,15 @@
"expression, e.g. 25 mm": "expressão, p. ex. 25 mm",
"fits the face, e.g. M8": "se ajusta à face, p. ex. M8",
"from the rule": "da regra",
+ "help.apache": "Licença Apache 2.0",
+ "help.attributions": "Atribuições (ATTRIBUTION.md)",
+ "help.build": "Versão {version} · commit {commit} · compilada em {date}",
+ "help.font_details": "A interface usa as fontes integradas do egui (Ubuntu Light e Hack, sob as licenças Ubuntu Font Licence e MIT/Bitstream Vera; Noto Emoji e a fonte de ícones emoji, sob OFL e MIT). O texto dos esboços usa Liberation Sans (SIL OFL 1.1). O pacote opcional de fontes da The Crafting Apps, craft-fonts (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1), não está incluído nas compilações do SolidCraft.",
+ "help.fonts": "Fontes",
+ "help.licences": "Licenças",
+ "help.mit": "Licença MIT",
+ "help.notice": "NOTICE",
+ "help.third_party": "Licenças de terceiros",
"home.documentation": "Documentação",
"home.in_this_browser": "neste navegador",
"home.missing": "ausente",
@@ -707,6 +761,26 @@
"joint.from_bodies_hint": "Cada corpo selecionado vai para um novo componente próprio e permanece onde está.",
"joint.one_body": "As duas seleções estão em {body}. Selecione a segunda em outra peça.",
"joint.one_component": "Estas peças são corpos de um mesmo componente: {bodies}. Uma junta move um componente em relação a outro, então cada peça precisa de seu próprio componente.",
+ "keymap.command_id": "ID do comando",
+ "keymap.empty": "Nenhum comando correspondente",
+ "keymap.use_anyway": "Usar {key} aqui mesmo assim",
+ "manage.appearance_hint": "Escolha uma aparência para a seleção ou arraste uma amostra para um corpo ou uma face.",
+ "manage.assign_hint": "Selecione corpos e escolha sua regra de projeto de peças plásticas.",
+ "manage.config_hint": "Edite as linhas, colunas e regras de configuração e depois ative uma linha ou visualize sua prévia.",
+ "manage.empty": "Nenhuma linha correspondente.",
+ "manage.material_hint": "Selecione corpos e escolha seu material físico.",
+ "manage.parameters_hint": "Edite expressões e unidades. As alterações são aplicadas ao pressionar Enter ou sair de um campo.",
+ "manage.rules_hint": "Escolha uma regra para editar ou crie uma nova. Confirme para salvar a regra.",
+ "measure.at": "Em",
+ "measure.item": "Item {number}",
+ "motion.delete_key": "Excluir quadro-chave",
+ "motion.key_here": "Inserir quadro-chave aqui",
+ "motion.key_here_hint": "Adicionar um quadro-chave neste passo com o valor atual da junta",
+ "motion.step_back": "Passo anterior",
+ "motion.step_forward": "Próximo passo",
+ "motion.to_end": "Para o fim",
+ "motion.to_start": "Para o início",
+ "motion.track_name": "Trilha {number}",
"nav.touchpad.help": "Segure Shift e mova o ponteiro para deslocar; segure Alt/Option e mova para orbitar. Não é preciso botão do mouse. A rolagem vertical aplica zoom.",
"nav.touchpad.label": "Touchpad",
"nav.touchpad.orbit": "Orbitar (segure Alt/Option e mova; sem botão do mouse)",
@@ -720,6 +794,8 @@
"no interference": "sem interferência",
"no joint that moves yet": "ainda não há junta que se mova",
"no picture": "sem imagem",
+ "none": "nenhum",
+ "parts.automatic_name": "automático",
"pattern.alignment_2": "Alinhamento 2",
"pattern.alignment_hint": "As contagens incluem o original. Centralizar equilibra as cópias; Inverter escolhe o lado extra para totais pares.",
"pattern.direction_1": "Direção 1",
@@ -727,6 +803,9 @@
"pattern.flip_direction": "Inverter direção",
"pick a hole to seat it, or OK places it at the origin": "selecione um furo para assentá-la, ou OK a coloca na origem",
"pick one or two vertices, edges or faces": "selecione um ou dois vértices, arestas ou faces",
+ "prefs.cpu": "CPU (software)",
+ "prefs.minutes_suffix": " min",
+ "properties.title": "Propriedades: {name}",
"render.background": "Fundo da cena",
"render.fit": "Enquadrar produto",
"render.image_cancel": "Cancelar renderização",
@@ -789,6 +868,10 @@
"settings.reset_intro": "Estas configurações não funcionam neste computador e impediriam o SolidCraft de iniciar, por isso foram alteradas:",
"settings.reset_title": "As configurações foram alteradas",
"settings.supersampling_note": "Desenha a vista em resolução maior e a filtra para baixo: arestas, linhas e grade mais suaves em telas abaixo de 4K. Custa tempo de GPU: cerca de 2,25× os pixels em 1,5× e 4× em 2×.",
+ "shortcut.json_error": "os parâmetros devem estar no formato JSON: {error}",
+ "shortcut.no_command": "o comando `{id}` não existe; o texto antes do JSON deve ser um ID de comando",
+ "shortcut.pin": "Fixar no topo da caixa S",
+ "shortcut.unpin": "Desafixar",
"sketch.degrees_of_freedom": "{count} graus de liberdade",
"sketch.dof_left": "{count} graus de liberdade restantes",
"sketch.dof_left_one": "{count} grau de liberdade restante",
@@ -822,6 +905,7 @@
"timeline.reorder_many": "Reordenar recursos",
"timeline.ungroup": "Remover pastas de recursos",
"to the next face": "até a próxima face",
+ "toolbar.customize_note": "Aba {tab}. Marque um comando para adicionar seu botão à barra de ferramentas. Você também pode arrastar uma linha do menu suspenso de um painel para a barra, arrastar um botão para fora da barra para removê-lo ou usar o alfinete de uma linha do menu suspenso.",
"toolbar.image": "IMAGEM",
"toolbar.render": "RENDERIZAR",
"toolbar.render_scene": "CENA",
@@ -875,6 +959,7 @@
"ui.agent_chat_new": "Novo chat",
"ui.agent_chat_new_confirm": "Começar um novo chat? O atual será apagado.",
"ui.agent_chat_new_yes": "Novo chat",
+ "ui.agent_chat_next_picture": "Próxima imagem",
"ui.agent_chat_no_cli": "O solidcraft-cli não foi encontrado junto ao aplicativo, então o agente não consegue acessar o projeto.",
"ui.agent_chat_no_control": "O endpoint do chat com agente não iniciou, então o agente não consegue acessar o projeto.",
"ui.agent_chat_no_images": "Este agente não aceita imagens",
@@ -886,6 +971,7 @@
"ui.agent_chat_pick": "Agente",
"ui.agent_chat_placeholder": "Peça ao agente para alterar o projeto…",
"ui.agent_chat_placeholder_busy": "Enfileirar uma mensagem para quando o agente terminar (Ctrl+Enter: enviar agora)",
+ "ui.agent_chat_previous_picture": "Imagem anterior",
"ui.agent_chat_privacy": "Nada vai para lugar algum além do agente que você executa, na sua própria conta.",
"ui.agent_chat_privacy_note": "O SolidCraft não envia nada a lugar nenhum: o agente que você executa fala com o próprio serviço, na sua própria conta. O SolidCraft nunca vê nem guarda chaves ou senhas.",
"ui.agent_chat_queue": "Fila",
@@ -939,6 +1025,7 @@
"ui.ai_bad_url": "Digite uma URL que comece com http:// ou https://",
"ui.ai_base_url": "URL base",
"ui.ai_button": "IA",
+ "ui.ai_command_hint": "my-agent --acp",
"ui.ai_copy_suffix": "cópia",
"ui.ai_custom_url": "URL personalizada",
"ui.ai_default": "Padrão",
@@ -959,8 +1046,10 @@
"ui.ai_mode_edits_note": "Comandos de modelagem rodam sem perguntar; salvar, abrir, exportar e outras ações com arquivos ou destrutivas ainda perguntam.",
"ui.ai_mode_global": "Como definido acima",
"ui.ai_model": "Modelo",
+ "ui.ai_model_hint": "qwen3:14b",
"ui.ai_modes_scope": "Estas configurações valem para as ferramentas do SolidCraft. As ferramentas do próprio agente (shell, edição de arquivos) seguem o modo do agente, que você escolhe no cabeçalho do painel de chat quando o agente tem modos.",
"ui.ai_name": "Nome",
+ "ui.ai_name_hint": "Meu agente",
"ui.ai_need_command": "Digite o comando que inicia o agente",
"ui.ai_need_model": "Digite o nome do modelo",
"ui.ai_no_answer": "O agente não respondeu a tempo",
@@ -991,6 +1080,7 @@
"ui.ai_toolbar_button": "Mostrar botão na barra de ferramentas",
"ui.ai_toolbar_button_note": "O botão de IA no fim direito da barra de ferramentas. Ctrl+Shift+A e o menu Exibir ainda abrem o painel.",
"ui.ai_undo_tip": "Desfazer tudo o que o agente alterou nesta mensagem, em um passo",
+ "ui.ai_url_hint": "https://example.com/v1",
"ui.all": "Tudo",
"ui.analysis": "Análise",
"ui.angle": "Ângulo",
@@ -1551,5 +1641,6 @@
"update.title": "Atualização disponível",
"update.up_to_date": "O SolidCraft está atualizado.",
"update.update_now": "Atualizar agora",
- "update.you_have": "Você tem a {version}."
+ "update.you_have": "Você tem a {version}.",
+ "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ escolher · Enter / Tab completar · Esc fechar"
}
diff --git a/assets/locales/ru.json b/assets/locales/ru.json
index 3a7d82f0f3..ad7cb798ad 100644
--- a/assets/locales/ru.json
+++ b/assets/locales/ru.json
@@ -5,6 +5,7 @@
"ARRANGE": "РАСПОЛОЖЕНИЕ",
"About SolidCraft": "О SolidCraft",
"Acceleration": "Ускорение",
+ "Actions": "Действия",
"Active": "Активный",
"Active rule": "Активное правило",
"Add": "Добавить",
@@ -12,6 +13,7 @@
"Add Mid Radius": "Добавить средний радиус",
"Add Row": "Добавить строку",
"Add condition": "Добавить условие",
+ "Add or edit rule": "Добавить или изменить правило",
"Against": "Против",
"Alignment": "Выравнивание",
"All Sketch Points": "Все точки эскиза",
@@ -25,6 +27,7 @@
"Applied Radius": "Применённый радиус",
"Apply To": "Применить к",
"Apply to selection": "Применить к выделению",
+ "Apply your appearance first. Exports assigned appearances and materials created in this design.": "Сначала примените внешний вид. Экспортирует назначенные внешние виды и материалы, созданные в этом дизайне.",
"Area": "Площадь",
"Attachment": "Привязка",
"BROWSER": "БРАУЗЕР",
@@ -52,9 +55,11 @@
"Check collisions": "Проверить столкновения",
"Checked": "Включено",
"Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "Выберите новую плоскость. Геометрия и размеры эскиза останутся неизменными в её двумерных координатах.",
+ "Choose…": "Выбрать…",
"Close draft": "Закрыть анализ уклонов",
"Collisions": "Столкновения",
"Colour": "Цвет",
+ "Comment": "Комментарий",
"Component1": "Компонент1",
"Configuration": "Конфигурация",
"Configuration rules": "Правила конфигурации",
@@ -77,6 +82,7 @@
"Curvature (G2)": "Кривизна (G2)",
"Curvature change (G3)": "Изменение кривизны (G3)",
"Customize Toolbar": "Настроить панель инструментов",
+ "Delete": "Удалить",
"Delete all": "Удалить все",
"Delete rule": "Удалить правило",
"Delete the row": "Удалить строку",
@@ -92,11 +98,15 @@
"Drive Joint": "Привод сопряжения",
"Duration": "Длительность",
"Edges": "Рёбра",
+ "Edit": "Изменить",
"Edit Profile Sketch": "Редактировать эскиз профиля",
"Enable rule": "Включить правило",
"Enabled": "Включено",
"Explode": "Разобрать",
"Export Animation…": "Экспортировать анимацию…",
+ "Export CSV…": "Экспорт CSV…",
+ "Export JSON…": "Экспорт JSON…",
+ "Expression": "Выражение",
"Extend to meet": "Продлить до пересечения",
"Extents": "Пределы",
"FILES": "ФАЙЛЫ",
@@ -104,7 +114,9 @@
"Face attachment lost": "Привязка к грани потеряна",
"Faces": "Грани",
"Faces / edges / vertices": "Грани / рёбра / вершины",
+ "Favorites": "Избранное",
"Favourite": "Избранное",
+ "Feature": "Операция",
"Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "Файлы многих CAD-программ ориентированы Y вверх, поэтому здесь они открываются лёжа на спине (Z вверх).",
"Filter": "Фильтр",
"Find in Browser": "Найти в браузере",
@@ -120,6 +132,7 @@
"Height": "Высота",
"Home view": "Главный вид",
"IMAGES": "ИЗОБРАЖЕНИЯ",
+ "Import…": "Импорт…",
"In This Design": "В этом дизайне",
"In plane": "В плоскости",
"Interferes": "Пересекается",
@@ -138,7 +151,9 @@
"Length units": "Единицы длины",
"Letter Spacing": "Межбуквенный интервал",
"Library": "Библиотека",
+ "Library file": "Файл библиотеки",
"Line Spacing": "Межстрочный интервал",
+ "Local library": "Локальная библиотека",
"Loop": "Контур",
"MANAGE": "УПРАВЛЕНИЕ",
"MATERIALS": "МАТЕРИАЛЫ",
@@ -146,18 +161,25 @@
"MOTION": "ДВИЖЕНИЕ",
"Margin": "Отступ",
"Mass": "Масса",
+ "Matched restrictions check the final values.": "Ограничения, условия которых выполнены, проверяют итоговые значения.",
"Material": "Материал",
"Mid Radius": "Средний радиус",
"Middle double-click": "Двойной щелчок средней кнопкой",
+ "Model Parameters": "Параметры модели",
"Modeled": "Смоделировано",
"More toolbar panels": "Другие панели инструментов",
"Motion": "Движение",
"Move Type": "Тип перемещения",
+ "Move down": "Переместить вниз",
"Move earlier": "Сдвинуть раньше",
"Move later": "Сдвинуть позже",
+ "Move up": "Переместить вверх",
"Name": "Имя",
+ "New": "Создать",
+ "New rule…": "Новое правило…",
"New study": "Новое исследование",
"No crash reports.": "Нет отчётов о сбоях.",
+ "No matching appearance presets.": "Нет подходящих наборов внешнего вида.",
"No matching appearances": "Нет подходящих внешних видов",
"Normal to sketch": "По нормали к эскизу",
"Not available yet": "Пока недоступно",
@@ -165,9 +187,12 @@
"OUTPUT": "ВЫВОД",
"Opacity": "Непрозрачность",
"Open GitHub draft": "Открыть черновик на GitHub",
+ "Open local libraries in the desktop app. You can export this design's library here.": "Открывайте локальные библиотеки в настольном приложении. Здесь можно экспортировать библиотеку этого дизайна.",
"Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "Открытая параметрическая 3D CAD на Rust. Лицензия MIT OR Apache-2.0.",
+ "Operator": "Оператор",
"Other side": "Другая сторона",
"Other surface (mutual trim)": "Другая поверхность (взаимная обрезка)",
+ "Parameter": "Параметр",
"Parameter values": "Значения параметров",
"Pass through": "Через точки",
"Path": "Траектория",
@@ -216,6 +241,8 @@
"Roll History Marker Here": "Переместить маркер истории сюда",
"Round": "Круглая",
"Rule": "Правило",
+ "Rule name": "Имя правила",
+ "Rules run from top to bottom. Matched drives change effective values.": "Правила выполняются сверху вниз. Управляющие правила, условия которых выполнены, изменяют действующие значения.",
"SECTION": "СЕЧЕНИЕ",
"SURFACE QUALITY": "КАЧЕСТВО ПОВЕРХНОСТИ",
"Save Rule": "Сохранить правило",
@@ -224,6 +251,7 @@
"Scale factor": "Коэффициент масштаба",
"Search": "Поиск",
"Search commands": "Поиск команд",
+ "Search this library": "Поиск в этой библиотеке",
"Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Выбрать другое: удерживайте левую кнопку на модели (или правый щелчок › Выбрать другое…), чтобы увидеть всё под курсором; повторный щелчок в том же месте выбирает следующий объект. Двойной щелчок средней кнопкой — «Главная» (Настройки › Навигация).",
"Select bodies (a face picks its body)": "Выберите тела (выбор грани выбирает её тело)",
"Select bodies or faces instead": "Вместо этого выберите тела или грани",
@@ -272,11 +300,13 @@
"Tolerance": "Допуск",
"Trimming tool (plane, face or curves)": "Инструмент обрезки (плоскость, грань или кривые)",
"Type": "Тип",
+ "Unit": "Единица",
"Updating the preview": "Обновление предпросмотра",
"Use active author placement": "Использовать активное исходное положение",
"Use fixed plane": "Использовать фиксированную плоскость",
"Use saved fixed plane": "Использовать сохранённую фиксированную плоскость",
"Use selected face as fixed plane": "Использовать выбранную грань как фиксированную плоскость",
+ "User Parameters": "Пользовательские параметры",
"VIEW": "ВИД",
"VIEWS": "ВИДЫ",
"Value": "Значение",
@@ -288,6 +318,12 @@
"When": "Когда",
"Width": "Ширина",
"Will fail": "Завершится с ошибкой",
+ "X angle": "Угол X",
+ "X distance": "Расстояние X",
+ "Y angle": "Угол Y",
+ "Y distance": "Расстояние Y",
+ "Z angle": "Угол Z",
+ "Z distance": "Расстояние Z",
"angle, height": "угол, высота",
"appearance.dielectric_ior": "Показатель преломления диэлектрика",
"appearance.metallic": "Металличность",
@@ -296,7 +332,11 @@
"appearance.roughness": "Шероховатость",
"appearance.surface_response": "Поведение поверхности",
"browser.body_name": "Тело{number}",
+ "browser.capture_many": "Компоненты ({count}) перемещены, но их положения не зафиксированы.",
+ "browser.capture_note": "«Зафиксировать положение» сохраняет новое положение; «Вернуть положение» восстанавливает прежнее.",
+ "browser.capture_one": "Компонент перемещён, но его положение не зафиксировано.",
"browser.component_name": "Компонент{number}",
+ "browser.move_title": "Переместить: {name}",
"browser.parameters": "Параметры ({count})",
"browser.precision": "Точность: {precision}",
"browser.sketch_name": "Эскиз{number}",
@@ -615,6 +655,8 @@
"cmd.view_rename": "Переименовать именованный вид",
"cmd.view_save": "Новый именованный вид",
"command name": "имя команды",
+ "contact.components_count": "Компонентов: {count}",
+ "contact.enabled_label": "включено",
"coupling.gear_1": "Шестерня 1",
"coupling.gear_1_pick": "Шестерня 1 (необязательно)",
"coupling.gear_2": "Шестерня 2",
@@ -631,7 +673,10 @@
"coupling.rack": "Рейка",
"coupling.radius_1": "Радиус 1",
"coupling.radius_2": "Радиус 2",
+ "delete.and_more": "… и ещё {count}",
"dialog.custom_axis": "↖ Своя ось",
+ "dialog.dimension_insert_hint": "Дважды щёлкните другой управляющий размер, чтобы вставить его имя",
+ "dialog.dimension_name": "Размер: {name}",
"dialog.edit_title": "ИЗМЕНИТЬ: {title}",
"dialog.select": "↖ Выбрать",
"dialog.selected_count": "↖ Выбрано: {count}",
@@ -646,6 +691,15 @@
"expression, e.g. 25 mm": "выражение, напр. 25 мм",
"fits the face, e.g. M8": "подходит грани, напр. M8",
"from the rule": "из правила",
+ "help.apache": "Лицензия Apache 2.0",
+ "help.attributions": "Сведения об авторстве (ATTRIBUTION.md)",
+ "help.build": "Версия {version} · коммит {commit} · сборка от {date}",
+ "help.font_details": "Интерфейс использует встроенные шрифты egui (Ubuntu Light и Hack под лицензиями Ubuntu Font Licence и MIT/Bitstream Vera; Noto Emoji и шрифт значков эмодзи под лицензиями OFL и MIT). Для текста эскизов используется Liberation Sans (SIL OFL 1.1). Необязательный пакет шрифтов The Crafting Apps, craft-fonts (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1), не входит в сборки SolidCraft.",
+ "help.fonts": "Шрифты",
+ "help.licences": "Лицензии",
+ "help.mit": "Лицензия MIT",
+ "help.notice": "NOTICE",
+ "help.third_party": "Лицензии сторонних компонентов",
"home.documentation": "Документация",
"home.in_this_browser": "в этом браузере",
"home.missing": "отсутствует",
@@ -674,10 +728,30 @@
"joint.from_bodies_hint": "Каждое выбранное тело переходит в свой новый компонент и остаётся на месте.",
"joint.one_body": "Оба выбора на {body}. Выберите второй на другой детали.",
"joint.one_component": "Эти детали - тела одного компонента: {bodies}. Сопряжение двигает один компонент относительно другого, поэтому каждой детали нужен свой компонент.",
+ "keymap.command_id": "ID команды",
+ "keymap.empty": "Нет подходящих команд",
+ "keymap.use_anyway": "Всё равно использовать здесь {key}",
+ "manage.appearance_hint": "Выберите внешний вид для выделенных объектов или перетащите образец на тело или грань.",
+ "manage.assign_hint": "Выберите тела и правило проектирования пластиковых деталей для них.",
+ "manage.config_hint": "Измените строки, столбцы и правила конфигурации, затем активируйте строку или просмотрите её.",
+ "manage.empty": "Нет подходящих строк.",
+ "manage.material_hint": "Выберите тела и их физический материал.",
+ "manage.parameters_hint": "Измените выражения и единицы. Изменения применяются по нажатию Enter или при выходе из поля.",
+ "manage.rules_hint": "Выберите правило для редактирования или создайте новое. Подтвердите, чтобы сохранить правило.",
+ "measure.at": "В точке",
+ "measure.item": "Элемент {number}",
"motion.checked_to": "Проверено только до шага {step}: проверка исчерпала свой бюджет работы",
"motion.collision": "{a} · {b}: шаги {steps}",
+ "motion.delete_key": "Удалить ключевой кадр",
"motion.duration_hint": "секунды (пусто: на шаг)",
+ "motion.key_here": "Вставить ключевой кадр здесь",
+ "motion.key_here_hint": "Добавить ключевой кадр на этом шаге с текущим значением сопряжения",
"motion.no_collisions": "За всё исследование столкновений нет",
+ "motion.step_back": "Шаг назад",
+ "motion.step_forward": "Шаг вперёд",
+ "motion.to_end": "В конец",
+ "motion.to_start": "В начало",
+ "motion.track_name": "Дорожка {number}",
"needs two joints": "нужны два сопряжения",
"new configuration": "новая конфигурация",
"new name": "новое имя",
@@ -685,6 +759,8 @@
"no interference": "нет интерференции",
"no joint that moves yet": "пока нет подвижных сопряжений",
"no picture": "нет картинки",
+ "none": "нет",
+ "parts.automatic_name": "автоматически",
"pattern.alignment_2": "Выравнивание 2",
"pattern.alignment_hint": "Количество включает оригинал. Центрирование распределяет копии по обе стороны; при чётном количестве смена направления выбирает сторону с дополнительной копией.",
"pattern.direction_1": "Направление 1",
@@ -692,6 +768,9 @@
"pattern.flip_direction": "Изменить направление",
"pick a hole to seat it, or OK places it at the origin": "выберите отверстие для установки, или OK разместит в начале координат",
"pick one or two vertices, edges or faces": "выберите одну-две вершины, ребра или грани",
+ "prefs.cpu": "ЦП (программный)",
+ "prefs.minutes_suffix": " min",
+ "properties.title": "Свойства: {name}",
"render.background": "Фон сцены",
"render.fit": "Вписать модель",
"render.image_cancel": "Отменить рендеринг",
@@ -751,6 +830,10 @@
"settings.msaa_unsupported": "Не поддерживается этим графическим устройством",
"settings.reset_intro": "Эти настройки не работают на этом компьютере и могли бы помешать запуску SolidCraft, поэтому они были изменены:",
"settings.reset_title": "Настройки были изменены",
+ "shortcut.json_error": "параметры должны быть в формате JSON: {error}",
+ "shortcut.no_command": "команда `{id}` не найдена; текст перед JSON должен быть ID команды",
+ "shortcut.pin": "Закрепить вверху поля S",
+ "shortcut.unpin": "Открепить",
"sketch.degrees_of_freedom": "Степеней свободы: {count}",
"sketch.dof_left": "Осталось степеней свободы: {count}",
"sketch.dof_left_one": "Осталась {count} степень свободы",
@@ -784,6 +867,7 @@
"timeline.reorder_many": "Изменить порядок операций",
"timeline.ungroup": "Убрать папки операций",
"to the next face": "до следующей грани",
+ "toolbar.customize_note": "Вкладка {tab}. Отметьте команду, чтобы добавить её кнопку на панель инструментов. Можно также перетащить строку из выпадающего меню панели на панель инструментов, перетащить кнопку за пределы панели для удаления или использовать значок закрепления в строке выпадающего меню.",
"toolbar.image": "ИЗОБРАЖЕНИЕ",
"toolbar.render": "РЕНДЕРИНГ",
"toolbar.render_scene": "СЦЕНА",
@@ -797,8 +881,14 @@
"ui.about": "О программе",
"ui.activate": "Активировать",
"ui.active_component": "Активный компонент",
+ "ui.agent_chat_next_picture": "Следующее изображение",
+ "ui.agent_chat_previous_picture": "Предыдущее изображение",
"ui.agent_cursor": "Курсор агента",
"ui.agent_cursor_speed": "Скорость курсора агента",
+ "ui.ai_command_hint": "my-agent --acp",
+ "ui.ai_model_hint": "qwen3:14b",
+ "ui.ai_name_hint": "Мой агент",
+ "ui.ai_url_hint": "https://example.com/v1",
"ui.all": "Все",
"ui.ambient_occlusion": "Окружающее затенение",
"ui.ambient_occlusion_help": "Мягкое затенение в местах соприкосновения непрозрачных поверхностей. Требуется видовой экран GPU.",
@@ -1318,5 +1408,6 @@
"ui.z_up": "Z вверх",
"ui.zoom": "Масштаб",
"ui.zoom_to_cursor_tip": "Колесо масштабирует к точке под курсором (выкл.: к центру вида)",
- "ui.zoom_to_the_cursor": "Масштаб к курсору"
+ "ui.zoom_to_the_cursor": "Масштаб к курсору",
+ "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ выбрать · Enter / Tab дополнить · Esc закрыть"
}
diff --git a/assets/locales/tr.json b/assets/locales/tr.json
index 84aba852cd..a92a060adb 100644
--- a/assets/locales/tr.json
+++ b/assets/locales/tr.json
@@ -10,6 +10,7 @@
"ARRANGE": "DÜZENLE",
"About SolidCraft": "SolidCraft hakkında",
"Acceleration": "İvme",
+ "Actions": "Eylemler",
"Active": "Etkin",
"Active rule": "Etkin kural",
"Add": "Ekle",
@@ -17,6 +18,7 @@
"Add Mid Radius": "Ara yarıçap ekle",
"Add Row": "Satır ekle",
"Add condition": "Koşul ekle",
+ "Add or edit rule": "Kural ekle veya düzenle",
"Against": "Karşı",
"Alignment": "Hizalama",
"All Sketch Points": "Tüm eskiz noktaları",
@@ -30,6 +32,7 @@
"Applied Radius": "Uygulanan yarıçap",
"Apply To": "Uygulama hedefi",
"Apply to selection": "Seçime uygula",
+ "Apply your appearance first. Exports assigned appearances and materials created in this design.": "Önce görünümünüzü uygulayın. Atanan görünümleri ve bu tasarımda oluşturulan malzemeleri dışa aktarır.",
"Arc length": "Yay uzunluğu",
"Area": "Alan",
"Attachment": "Bağlama",
@@ -58,10 +61,12 @@
"Check collisions": "Çarpışmaları kontrol et",
"Checked": "Kontrol edildi",
"Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "Yeni bir düzlem seçin. Eskiz geometrisi ve ölçüler, iki boyutlu koordinatlarında değişmeden kalır.",
+ "Choose…": "Seç…",
"Circumference": "Çevre",
"Close draft": "Taslağı kapat",
"Collisions": "Çarpışmalar",
"Colour": "Renk",
+ "Comment": "Yorum",
"Component1": "Bileşen1",
"Configuration": "Konfigürasyon",
"Configuration rules": "Konfigürasyon kuralları",
@@ -81,6 +86,7 @@
"Cube": "Küp",
"Curvature change (G3)": "Eğrilik değişimi (G3)",
"Customize Toolbar": "Araç çubuğunu özelleştir",
+ "Delete": "Sil",
"Delete all": "Tümünü sil",
"Delete rule": "Kuralı sil",
"Delete the row": "Satırı sil",
@@ -96,11 +102,15 @@
"Drive Joint": "Bağlantıyı tahrik et",
"Duration": "Süre",
"Edges": "Kenarlar",
+ "Edit": "Düzenle",
"Edit Profile Sketch": "Profil eskizini düzenle",
"Enable rule": "Kuralı etkinleştir",
"Enabled": "Etkin",
"Explode": "Patlat",
"Export Animation…": "Animasyonu dışa aktar…",
+ "Export CSV…": "CSV dışa aktar…",
+ "Export JSON…": "JSON dışa aktar…",
+ "Expression": "İfade",
"Extend to meet": "Buluşana kadar uzat",
"Extents": "Kapsamlar",
"FILES": "DOSYALAR",
@@ -109,7 +119,9 @@
"Face attachment lost": "Yüze bağlama kayboldu",
"Faces": "Yüzler",
"Faces / edges / vertices": "Yüzler / kenarlar / köşe noktaları",
+ "Favorites": "Sık kullanılanlar",
"Favourite": "Favori",
+ "Feature": "Özellik",
"Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "Birçok CAD programının dosyalarında Y yukarıyı gösterir; bu yüzden burada (Z yukarı) sırtüstü yatar hâlde açılırlar.",
"Filter": "Filtre",
"Find in Browser": "Tarayıcıda bul",
@@ -127,6 +139,7 @@
"Holes (edges on them)": "Delikler (kenarları)",
"Home view": "Başlangıç görünümü",
"IMAGES": "GÖRSELLER",
+ "Import…": "İçe aktar…",
"In This Design": "Bu tasarımda",
"In place (surfaces)": "Yerinde (yüzeyler)",
"In plane": "Düzlemde",
@@ -147,7 +160,9 @@
"Length units": "Uzunluk birimleri",
"Letter Spacing": "Harf aralığı",
"Library": "Kitaplık",
+ "Library file": "Kitaplık dosyası",
"Line Spacing": "Satır aralığı",
+ "Local library": "Yerel kitaplık",
"Loop": "Döngü",
"MANAGE": "YÖNET",
"MATERIALS": "MALZEMELER",
@@ -155,21 +170,28 @@
"MOTION": "HAREKET",
"Margin": "Kenar boşluğu",
"Mass": "Kütle",
+ "Matched restrictions check the final values.": "Koşulları sağlanan kısıtlamalar son değerleri denetler.",
"Material": "Malzeme",
"Max": "Maks",
"Mid Radius": "Ara yarıçap",
"Middle double-click": "Orta tuşla çift tıklama",
"Min": "Min",
"Mitre": "Gönye",
+ "Model Parameters": "Model parametreleri",
"Modeled": "Modellenmiş",
"More toolbar panels": "Diğer araç çubuğu panelleri",
"Motion": "Hareket",
"Move Type": "Taşıma türü",
+ "Move down": "Aşağı taşı",
"Move earlier": "Öne al",
"Move later": "Sonraya al",
+ "Move up": "Yukarı taşı",
"Name": "Ad",
+ "New": "Yeni",
+ "New rule…": "Yeni kural…",
"New study": "Yeni etüt",
"No crash reports.": "Çökme raporu yok.",
+ "No matching appearance presets.": "Eşleşen görünüm ön ayarı yok.",
"No matching appearances": "Eşleşen görünüm yok",
"None": "Hiçbiri",
"Normal to sketch": "Eskize dik",
@@ -177,11 +199,14 @@
"OUTPUT": "ÇIKTI",
"Opacity": "Opaklık",
"Open GitHub draft": "GitHub taslağını aç",
+ "Open local libraries in the desktop app. You can export this design's library here.": "Yerel kitaplıkları masaüstü uygulamasında açın. Bu tasarımın kitaplığını buradan dışa aktarabilirsiniz.",
"Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "Rust ile yazılmış açık kaynaklı parametrik 3D CAD. Lisans: MIT OR Apache-2.0.",
+ "Operator": "İşleç",
"Other side": "Diğer taraf",
"Other surface (mutual trim)": "Diğer yüzey (karşılıklı kırpma)",
"Outside": "Dış",
"Overall length": "Toplam uzunluk",
+ "Parameter": "Parametre",
"Parameter values": "Parametre değerleri",
"Path": "Yol",
"Per Edge": "Kenar başına",
@@ -232,6 +257,8 @@
"Roll History Marker Here": "Geçmiş işaretçisini buraya taşı",
"Round": "Yuvarlak",
"Rule": "Kural",
+ "Rule name": "Kural adı",
+ "Rules run from top to bottom. Matched drives change effective values.": "Kurallar yukarıdan aşağıya çalışır. Koşulları sağlanan sürücü kurallar etkin değerleri değiştirir.",
"SECTION": "KESİT",
"SURFACE QUALITY": "YÜZEY KALİTESİ",
"Save Rule": "Kuralı kaydet",
@@ -240,6 +267,7 @@
"Scale factor": "Ölçek faktörü",
"Search": "Ara",
"Search commands": "Komutlarda ara",
+ "Search this library": "Bu kitaplıkta ara",
"Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Diğerini seç: İmlecin altındaki her şeyi listelemek için sol tuşu model üzerinde hareket ettirmeden basılı tutun (veya sağ tık › Diğerini seç…); oradaki bir sonraki öğeyi seçmek için aynı noktaya tekrar tıklayın. Başlangıç görünümüne dönmek için orta tuşla çift tıklayın (Ayarlar › Gezinme).",
"Select bodies (a face picks its body)": "Gövdeleri seçin (bir yüz kendi gövdesini seçer)",
"Select bodies or faces instead": "Bunun yerine gövde veya yüz seçin",
@@ -292,11 +320,13 @@
"Trimming tool (plane, face or curves)": "Kırpma aracı (düzlem, yüz veya eğriler)",
"Type": "Tür",
"UNTRIM": "KIRPMAYI KALDIR",
+ "Unit": "Birim",
"Updating the preview": "Önizleme güncelleniyor",
"Use active author placement": "Etkin kaynak yerleşimini kullan",
"Use fixed plane": "Sabit düzlem kullan",
"Use saved fixed plane": "Kaydedilmiş sabit düzlemi kullan",
"Use selected face as fixed plane": "Seçili yüzü sabit düzlem olarak kullan",
+ "User Parameters": "Kullanıcı parametreleri",
"VIEW": "GÖRÜNÜM",
"VIEWS": "GÖRÜNÜMLER",
"Value": "Değer",
@@ -310,6 +340,12 @@
"When": "Eğer",
"Width": "Genişlik",
"Will fail": "Başarısız olacak",
+ "X angle": "X açısı",
+ "X distance": "X mesafesi",
+ "Y angle": "Y açısı",
+ "Y distance": "Y mesafesi",
+ "Z angle": "Z açısı",
+ "Z distance": "Z mesafesi",
"angle, height": "açı, yükseklik",
"appearance.dielectric_ior": "Dielektrik kırılma indisi",
"appearance.metallic": "Metaliklik",
@@ -318,7 +354,11 @@
"appearance.roughness": "Pürüzlülük",
"appearance.surface_response": "Yüzey davranışı",
"browser.body_name": "Gövde {number}",
+ "browser.capture_many": "{count} bileşen taşındı ancak konumları yakalanmadı.",
+ "browser.capture_note": "Konumu yakala yeni konumu korur; Konumu geri al önceki konuma döndürür.",
+ "browser.capture_one": "Bir bileşen taşındı ancak konumu yakalanmadı.",
"browser.component_name": "Bileşen {number}",
+ "browser.move_title": "Taşı: {name}",
"browser.parameters": "Parametreler ({count})",
"browser.precision": "Hassasiyet: {precision}",
"browser.sketch_name": "Eskiz {number}",
@@ -627,8 +667,13 @@
"cmd.view_rename": "Adlandırılmış görünümü yeniden adlandır",
"cmd.view_save": "Yeni adlandırılmış görünüm",
"command name": "komut adı",
+ "contact.components_count": "{count} bileşen",
+ "contact.enabled_label": "etkin",
+ "delete.and_more": "… ve {count} tane daha",
"dialog.computing": "Hesaplanıyor… {seconds} sn",
"dialog.custom_axis": "↖ Özel eksen",
+ "dialog.dimension_insert_hint": "Adını eklemek için başka bir sürücü ölçüye çift tıklayın",
+ "dialog.dimension_name": "Ölçü: {name}",
"dialog.edit_title": "{title} düzenleniyor",
"dialog.select": "↖ Seç",
"dialog.selected_count": "↖ {count} seçildi",
@@ -643,6 +688,15 @@
"expression, e.g. 25 mm": "ifade, ör. 25 mm",
"fits the face, e.g. M8": "yüze uyar, ör. M8",
"from the rule": "kuraldan",
+ "help.apache": "Apache lisansı 2.0",
+ "help.attributions": "Atıflar (ATTRIBUTION.md)",
+ "help.build": "Sürüm {version} · commit {commit} · derleme tarihi {date}",
+ "help.font_details": "Arayüz, egui'nin yerleşik yazı tiplerini kullanır (Ubuntu Font Licence ve MIT/Bitstream Vera lisansları altında Ubuntu Light ve Hack; OFL ve MIT altında Noto Emoji ve emoji simge yazı tipi). Eskiz metni Liberation Sans (SIL OFL 1.1) kullanır. The Crafting Apps'in isteğe bağlı yazı tipi paketi craft-fonts (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1), SolidCraft derlemelerine dahil değildir.",
+ "help.fonts": "Yazı tipleri",
+ "help.licences": "Lisanslar",
+ "help.mit": "MIT lisansı",
+ "help.notice": "NOTICE",
+ "help.third_party": "Üçüncü taraf lisansları",
"home.documentation": "Belgeler",
"home.in_this_browser": "bu tarayıcıda",
"home.missing": "eksik",
@@ -671,10 +725,30 @@
"joint.from_bodies_hint": "Seçilen her gövde kendi yeni bileşenine konur ve bulunduğu yerde kalır.",
"joint.one_body": "Her iki seçim de {body} üzerinde. İkincisini başka bir parçada seçin.",
"joint.one_component": "Bu parçalar tek bir bileşenin gövdeleridir: {bodies}. Bir bağlantı bir bileşeni diğerine göre hareket ettirir, bu nedenle her parçanın kendi bileşeni olması gerekir.",
+ "keymap.command_id": "Komut kimliği",
+ "keymap.empty": "Eşleşen komut yok",
+ "keymap.use_anyway": "Yine de burada {key} kullan",
+ "manage.appearance_hint": "Seçim için bir görünüm seçin veya bir örneği gövde ya da yüz üzerine sürükleyin.",
+ "manage.assign_hint": "Gövdeleri seçin ve plastik tasarım kurallarını belirleyin.",
+ "manage.config_hint": "Yapılandırma satırlarını, sütunlarını ve kurallarını düzenleyin, ardından bir satırı etkinleştirin veya önizleyin.",
+ "manage.empty": "Eşleşen satır yok.",
+ "manage.material_hint": "Gövdeleri seçin ve fiziksel malzemelerini belirleyin.",
+ "manage.parameters_hint": "İfadeleri ve birimleri düzenleyin. Değişiklikler Enter'a basıldığında veya alandan çıkıldığında uygulanır.",
+ "manage.rules_hint": "Düzenlemek için bir kural seçin veya yeni bir kural oluşturun. Kuralı kaydetmek için onaylayın.",
+ "measure.at": "Konum",
+ "measure.item": "Öğe {number}",
"motion.checked_to": "Yalnızca {step}. adıma kadar denetlendi: denetim iş bütçesini tüketti",
"motion.collision": "{a} · {b}: adımlar {steps}",
+ "motion.delete_key": "Anahtar kareyi sil",
"motion.duration_hint": "saniye (boş: adım başına)",
+ "motion.key_here": "Buraya anahtar kare ekle",
+ "motion.key_here_hint": "Bu adıma bağlantının mevcut değeriyle bir anahtar kare ekle",
"motion.no_collisions": "Etüt boyunca çarpışma yok",
+ "motion.step_back": "Bir adım geri",
+ "motion.step_forward": "Bir adım ileri",
+ "motion.to_end": "Sona git",
+ "motion.to_start": "Başa git",
+ "motion.track_name": "İz {number}",
"nav.touchpad.help": "Kaydırmak için Shift tuşunu basılı tutun ve imleci hareket ettirin; Alt/Option ile döndürün. Fare tuşu gerekmez. Dikey kaydırma yakınlaştırır.",
"nav.touchpad.label": "Dokunmatik yüzey",
"nav.touchpad.orbit": "Döndür (Alt/Option tuşunu basılı tutup hareket ettirin; fare tuşu olmadan)",
@@ -688,6 +762,8 @@
"no interference": "girişim yok",
"no joint that moves yet": "henüz hareket eden bir bağlantı yok",
"no picture": "resim yok",
+ "none": "yok",
+ "parts.automatic_name": "otomatik",
"pattern.alignment_2": "Hizalama 2",
"pattern.alignment_hint": "Adet, orijinali içerir. Ortala, kopyaları iki yana dağıtır; çift adetlerde yönü ters çevirme, fazladan kopyanın hangi tarafta olacağını belirler.",
"pattern.direction_1": "Yön 1",
@@ -695,6 +771,9 @@
"pattern.flip_direction": "Yönü ters çevir",
"pick a hole to seat it, or OK places it at the origin": "yerleştirmek için bir delik seçin veya OK ile orijine yerleştirin",
"pick one or two vertices, edges or faces": "bir veya iki köşe noktası, kenar ya da yüz seçin",
+ "prefs.cpu": "CPU (yazılım)",
+ "prefs.minutes_suffix": " min",
+ "properties.title": "Özellikler: {name}",
"render.background": "Sahne arka planı",
"render.fit": "Ürünü sığdır",
"render.image_cancel": "Render'ı iptal et",
@@ -754,6 +833,10 @@
"settings.reset_intro": "Bu ayarlar bu bilgisayarda çalışmadığı ve SolidCraft'ın başlamasını engelleyeceği için değiştirildi:",
"settings.reset_title": "Ayarlar değiştirildi",
"settings.supersampling_note": "Görünümü daha yüksek çözünürlükte çizer ve küçültür: 4K altındaki ekranlarda kenarlar, çizgiler ve ızgaralar daha pürüzsüz görünür. GPU süresi gerektirir: 1,5× ayarında yaklaşık 2,25 kat, 2× ayarında 4 kat daha fazla piksel işlenir.",
+ "shortcut.json_error": "parametreler JSON biçiminde olmalıdır: {error}",
+ "shortcut.no_command": "`{id}` komutu yok; JSON'dan önceki metin bir komut kimliği olmalıdır",
+ "shortcut.pin": "S kutusunun üstüne sabitle",
+ "shortcut.unpin": "Sabitlemeyi kaldır",
"sketch.degrees_of_freedom": "{count} serbestlik derecesi",
"sketch.dof_left": "Kalan serbestlik derecesi: {count}",
"sketch.dof_left_one": "Kalan serbestlik derecesi: {count}",
@@ -787,6 +870,7 @@
"timeline.reorder_many": "Özellikleri yeniden sırala",
"timeline.ungroup": "Özellik klasörünü kaldır",
"to the next face": "sonraki yüze kadar",
+ "toolbar.customize_note": "{tab} sekmesi. Bir komuta araç çubuğu düğmesi eklemek için komutu işaretleyin. Ayrıca panelin açılır menüsündeki bir satırı araç çubuğuna sürükleyebilir, bir düğmeyi kaldırmak için araç çubuğunun dışına sürükleyebilir veya açılır menü satırındaki raptiyeyi kullanabilirsiniz.",
"toolbar.image": "RESİM",
"toolbar.render": "RENDER",
"toolbar.render_scene": "SAHNE",
@@ -832,6 +916,7 @@
"ui.agent_chat_left": "Sol",
"ui.agent_chat_limit": "Ajan, bir mesaj için {limit} değişiklik sınırına ulaştı. Devam etmesi için başka bir mesaj gönderin.",
"ui.agent_chat_minimize": "Bir çubuğa küçült",
+ "ui.agent_chat_next_picture": "Sonraki resim",
"ui.agent_chat_no_cli": "solidcraft-cli uygulamanın yanında bulunamadı, bu yüzden ajan tasarıma erişemiyor.",
"ui.agent_chat_no_control": "Ajan sohbetinin uç noktası başlatılmadı, bu yüzden ajan tasarıma erişemiyor.",
"ui.agent_chat_no_images": "Bu ajan resim kabul etmiyor",
@@ -842,6 +927,7 @@
"ui.agent_chat_permission": "Ajan şunu çalıştırmak istiyor: {title}",
"ui.agent_chat_pick": "Ajan",
"ui.agent_chat_placeholder": "Ajandan tasarımı değiştirmesini isteyin…",
+ "ui.agent_chat_previous_picture": "Önceki resim",
"ui.agent_chat_privacy": "Kendi hesabınızla çalıştırdığınız ajan dışında hiçbir yere bir şey gitmez.",
"ui.agent_chat_privacy_note": "SolidCraft hiçbir yere bir şey göndermez: Başlattığınız ajan, sizin hesabınızla kendi hizmetine bağlanır. SolidCraft hiçbir anahtarı veya parolayı görmez ve kaydetmez.",
"ui.agent_chat_refresh": "Yenile",
@@ -886,6 +972,7 @@
"ui.ai_bad_url": "http:// veya https:// ile başlayan bir URL girin",
"ui.ai_base_url": "Temel URL",
"ui.ai_button": "AI",
+ "ui.ai_command_hint": "my-agent --acp",
"ui.ai_copy_suffix": "Kopya",
"ui.ai_custom_url": "Özel URL",
"ui.ai_default": "Varsayılan",
@@ -906,8 +993,10 @@
"ui.ai_mode_edits_note": "Modelleme komutları onay istemeden çalışır; kaydetme, açma, dışa aktarma ve diğer dosya ya da yıkıcı işlemler için yine onay istenir.",
"ui.ai_mode_global": "Yukarıda ayarlandığı gibi",
"ui.ai_model": "Model",
+ "ui.ai_model_hint": "qwen3:14b",
"ui.ai_modes_scope": "Bu ayarlar SolidCraft araçları için geçerlidir. Bir ajanın kendi araçları (kabuğu, dosya değişiklikleri), ajanın modları varsa sohbet panelinin başlığında seçtiğiniz kendi modunu izler.",
"ui.ai_name": "Ad",
+ "ui.ai_name_hint": "Ajanım",
"ui.ai_need_command": "Ajanı başlatan komutu girin",
"ui.ai_need_model": "Model adını girin",
"ui.ai_no_answer": "Ajan zamanında yanıt vermedi",
@@ -938,6 +1027,7 @@
"ui.ai_toolbar_button": "Araç çubuğunda düğmeyi göster",
"ui.ai_toolbar_button_note": "Araç çubuğunun sağ ucundaki AI düğmesi. Ctrl+Shift+A ve Görünüm menüsü paneli açmaya devam eder.",
"ui.ai_undo_tip": "Ajanın bu mesaj için değiştirdiği her şeyi tek adımda geri al",
+ "ui.ai_url_hint": "https://example.com/v1",
"ui.all": "Tümü",
"ui.analysis": "Analiz",
"ui.angle": "Açı",
@@ -1495,5 +1585,6 @@
"update.title": "Güncelleme mevcut",
"update.up_to_date": "SolidCraft güncel.",
"update.update_now": "Şimdi güncelle",
- "update.you_have": "Yüklü sürüm: {version}."
+ "update.you_have": "Yüklü sürüm: {version}.",
+ "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ seç · Enter / Tab tamamla · Esc kapat"
}
diff --git a/assets/locales/uk.json b/assets/locales/uk.json
index 4b76a43024..139432659c 100644
--- a/assets/locales/uk.json
+++ b/assets/locales/uk.json
@@ -10,6 +10,7 @@
"ARRANGE": "РОЗТАШУВАННЯ",
"About SolidCraft": "Про SolidCraft",
"Acceleration": "Прискорення",
+ "Actions": "Дії",
"Active": "Активна",
"Active rule": "Активне правило",
"Add": "Додати",
@@ -17,6 +18,7 @@
"Add Mid Radius": "Додати середній радіус",
"Add Row": "Додати рядок",
"Add condition": "Додати умову",
+ "Add or edit rule": "Додати або змінити правило",
"Against": "Проти",
"Alignment": "Вирівнювання",
"All Sketch Points": "Усі точки ескізу",
@@ -30,6 +32,7 @@
"Applied Radius": "Застосований радіус",
"Apply To": "Застосувати до",
"Apply to selection": "Застосувати до виділення",
+ "Apply your appearance first. Exports assigned appearances and materials created in this design.": "Спочатку застосуйте вигляд. Експортує призначені вигляди та матеріали, створені в цьому проєкті.",
"Arc length": "Довжина дуги",
"Area": "Площа",
"Attachment": "Прив'язка",
@@ -60,10 +63,12 @@
"Check collisions": "Перевіряти зіткнення",
"Checked": "Перевірено",
"Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "Виберіть нову площину. Геометрія та розміри ескізу залишаються незмінними у своїх двовимірних координатах.",
+ "Choose…": "Вибрати…",
"Circumference": "Довжина кола",
"Close draft": "Закрити чернетку",
"Collisions": "Зіткнення",
"Colour": "Колір",
+ "Comment": "Коментар",
"Component1": "Компонент1",
"Configuration": "Конфігурація",
"Configuration rules": "Правила конфігурації",
@@ -89,6 +94,7 @@
"Curvature (G2)": "Кривина (G2)",
"Curvature change (G3)": "Зміна кривини (G3)",
"Customize Toolbar": "Налаштувати панель інструментів",
+ "Delete": "Видалити",
"Delete all": "Видалити все",
"Delete rule": "Видалити правило",
"Delete the row": "Видалити рядок",
@@ -106,16 +112,20 @@
"Drive Joint": "Керувати з'єднанням",
"Duration": "Тривалість",
"Edges": "Ребра",
+ "Edit": "Змінити",
"Edit Profile Sketch": "Редагувати ескіз профілю",
"Enable rule": "Увімкнути правило",
"Enabled": "Увімкнено",
"Explode": "Рознести",
"Explode Text": "Розібрати текст",
"Export Animation…": "Експортувати анімацію…",
+ "Export CSV…": "Експорт CSV…",
"Export Current View as DXF": "Експортувати поточний вид як DXF",
"Export Current View as DXF…": "Експортувати поточний вид як DXF…",
"Export DXF…": "Експорт DXF…",
+ "Export JSON…": "Експорт JSON…",
"Export hidden edges as dashed lines": "Експортувати приховані ребра як штрихові лінії",
+ "Expression": "Вираз",
"Extend to meet": "Подовжити до перетину",
"Extents": "Межі",
"FILES": "ФАЙЛИ",
@@ -124,7 +134,9 @@
"Face attachment lost": "Втрачено прив'язку до грані",
"Faces": "Грані",
"Faces / edges / vertices": "Грані / ребра / вершини",
+ "Favorites": "Обране",
"Favourite": "Обране",
+ "Feature": "Операція",
"Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "Файли з багатьох CAD-програм мають напрямок Y вгору, тому тут вони відкриваються лежачи на спині (Z вгору).",
"Filter": "Фільтр",
"Find in Browser": "Знайти в браузері",
@@ -143,6 +155,7 @@
"Holes (edges on them)": "Отвори (ребра на них)",
"Home view": "Головний вид",
"IMAGES": "ЗОБРАЖЕННЯ",
+ "Import…": "Імпорт…",
"In This Design": "У цьому проєкті",
"In place (surfaces)": "На місці (поверхні)",
"In plane": "У площині",
@@ -163,7 +176,9 @@
"Length units": "Одиниці довжини",
"Letter Spacing": "Міжлітерний інтервал",
"Library": "Бібліотека",
+ "Library file": "Файл бібліотеки",
"Line Spacing": "Міжрядковий інтервал",
+ "Local library": "Локальна бібліотека",
"Loop": "Контур",
"MANAGE": "КЕРУВАННЯ",
"MATERIALS": "МАТЕРІАЛИ",
@@ -171,22 +186,29 @@
"MOTION": "РУХ",
"Margin": "Відступ",
"Mass": "Маса",
+ "Matched restrictions check the final values.": "Обмеження, умови яких виконано, перевіряють кінцеві значення.",
"Material": "Матеріал",
"Max": "Макс.",
"Mid Radius": "Середній радіус",
"Middle double-click": "Подвійне клацання середньою кнопкою",
"Min": "Мін.",
"Mitre": "Скіс",
+ "Model Parameters": "Параметри моделі",
"Modeled": "Змодельовано",
"More toolbar panels": "Більше панелей інструментів",
"Motion": "Рух",
"Move Type": "Тип переміщення",
+ "Move down": "Перемістити вниз",
"Move earlier": "Перемістити раніше",
"Move later": "Перемістити пізніше",
+ "Move up": "Перемістити вгору",
"Name": "Назва",
"Nearest": "Найближчі",
+ "New": "Створити",
+ "New rule…": "Нове правило…",
"New study": "Нове дослідження",
"No crash reports.": "Немає звітів про збої.",
+ "No matching appearance presets.": "Немає відповідних наборів вигляду.",
"No matching appearances": "Немає відповідних виглядів",
"No visible bodies to export.": "Немає видимих тіл для експорту.",
"None": "Немає",
@@ -196,11 +218,14 @@
"OUTPUT": "ВИВЕДЕННЯ",
"Opacity": "Непрозорість",
"Open GitHub draft": "Відкрити чернетку GitHub",
+ "Open local libraries in the desktop app. You can export this design's library here.": "Відкривайте локальні бібліотеки в настільному застосунку. Тут можна експортувати бібліотеку цього проєкту.",
"Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "Параметричний 3D-CAD з відкритим вихідним кодом на Rust. Ліцензовано за MIT OR Apache-2.0.",
+ "Operator": "Оператор",
"Other side": "Інший бік",
"Other surface (mutual trim)": "Інша поверхня (взаємне обрізання)",
"Outside": "Назовні",
"Overall length": "Загальна довжина",
+ "Parameter": "Параметр",
"Parameter values": "Значення параметрів",
"Pass through": "Через точки",
"Path": "Траєкторія",
@@ -256,6 +281,8 @@
"Roll History Marker Here": "Перемістити маркер історії сюди",
"Round": "Круглий",
"Rule": "Правило",
+ "Rule name": "Назва правила",
+ "Rules run from top to bottom. Matched drives change effective values.": "Правила виконуються згори вниз. Керівні правила, умови яких виконано, змінюють дійсні значення.",
"SECTION": "ПЕРЕРІЗ",
"SURFACE QUALITY": "ЯКІСТЬ ПОВЕРХНІ",
"Save Rule": "Зберегти правило",
@@ -264,6 +291,7 @@
"Scale factor": "Коефіцієнт масштабу",
"Search": "Пошук",
"Search commands": "Пошук команд",
+ "Search this library": "Пошук у цій бібліотеці",
"Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Вибір іншого: утримуйте ліву кнопку нерухомо на моделі (або клацніть правою › Вибрати інше…), щоб побачити список усього під курсором; клацніть ще раз у тому ж місці, щоб вибрати наступний об'єкт там. Двічі клацніть середньою кнопкою, щоб перейти до головного виду (Налаштування › Навігація).",
"Select bodies (a face picks its body)": "Виділяти тіла (грань виділяє своє тіло)",
"Select bodies or faces instead": "Натомість виділіть тіла або грані",
@@ -320,11 +348,13 @@
"Turn off section analysis before exporting the view.": "Вимкніть аналіз перерізу перед експортом виду.",
"Type": "Тип",
"UNTRIM": "ЗНЯТИ ОБРІЗАННЯ",
+ "Unit": "Одиниця",
"Updating the preview": "Оновлення попереднього перегляду",
"Use active author placement": "Використати активне вихідне розміщення",
"Use fixed plane": "Використати фіксовану площину",
"Use saved fixed plane": "Використати збережену фіксовану площину",
"Use selected face as fixed plane": "Використати вибрану грань як фіксовану площину",
+ "User Parameters": "Параметри користувача",
"VIEW": "ВИД",
"VIEWS": "ВИГЛЯДИ",
"Value": "Значення",
@@ -339,6 +369,12 @@
"When": "Коли",
"Width": "Ширина",
"Will fail": "Зазнає невдачі",
+ "X angle": "Кут X",
+ "X distance": "Відстань X",
+ "Y angle": "Кут Y",
+ "Y distance": "Відстань Y",
+ "Z angle": "Кут Z",
+ "Z distance": "Відстань Z",
"angle, height": "кут, висота",
"appearance.dielectric_ior": "Діелектричний IOR",
"appearance.metallic": "Металевість",
@@ -347,7 +383,11 @@
"appearance.roughness": "Шорсткість",
"appearance.surface_response": "Відгук поверхні",
"browser.body_name": "Тіло{number}",
+ "browser.capture_many": "Компоненти ({count}) переміщено, але їхні положення не зафіксовано.",
+ "browser.capture_note": "«Зафіксувати положення» зберігає нове положення; «Відновити положення» повертає попереднє.",
+ "browser.capture_one": "Компонент переміщено, але його положення не зафіксовано.",
"browser.component_name": "Компонент{number}",
+ "browser.move_title": "Перемістити: {name}",
"browser.parameters": "Параметри ({count})",
"browser.precision": "Точність: {precision}",
"browser.sketch_name": "Ескіз{number}",
@@ -679,6 +719,8 @@
"cmd.view_rename": "Перейменувати іменований вид",
"cmd.view_save": "Новий іменований вид",
"command name": "назва команди",
+ "contact.components_count": "Компонентів: {count}",
+ "contact.enabled_label": "увімкнено",
"coupling.gear_1": "Шестерня 1",
"coupling.gear_1_pick": "Шестерня 1 (необов'язково)",
"coupling.gear_2": "Шестерня 2",
@@ -695,6 +737,7 @@
"coupling.rack": "Рейка",
"coupling.radius_1": "Радіус 1",
"coupling.radius_2": "Радіус 2",
+ "delete.and_more": "… і ще {count}",
"dialog.bodies_count": "Тіл: {count}",
"dialog.clearance_invalid": "зазор має бути довжиною 0 або більше",
"dialog.compute": "Обчислити",
@@ -702,6 +745,8 @@
"dialog.computing": "Обчислення… {seconds} с",
"dialog.could_not_be_checked": "не вдалося перевірити",
"dialog.custom_axis": "↖ Власна вісь",
+ "dialog.dimension_insert_hint": "Двічі клацніть інший керівний розмір, щоб вставити його назву",
+ "dialog.dimension_name": "Розмір: {name}",
"dialog.edit_title": "РЕДАГУВАННЯ {title}",
"dialog.select": "↖ Вибрати",
"dialog.selected_count": "↖ Вибрано: {count}",
@@ -728,6 +773,15 @@
"expression, e.g. 25 mm": "вираз, напр. 25 mm",
"fits the face, e.g. M8": "відповідає грані, напр. M8",
"from the rule": "з правила",
+ "help.apache": "Ліцензія Apache 2.0",
+ "help.attributions": "Відомості про авторство (ATTRIBUTION.md)",
+ "help.build": "Версія {version} · коміт {commit} · зібрано {date}",
+ "help.font_details": "Інтерфейс використовує вбудовані шрифти egui (Ubuntu Light і Hack під ліцензіями Ubuntu Font Licence та MIT/Bitstream Vera; Noto Emoji та шрифт піктограм емодзі під ліцензіями OFL і MIT). Для тексту ескізів використовується Liberation Sans (SIL OFL 1.1). Необов’язковий пакет шрифтів The Crafting Apps, craft-fonts (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1), не входить до збірок SolidCraft.",
+ "help.fonts": "Шрифти",
+ "help.licences": "Ліцензії",
+ "help.mit": "Ліцензія MIT",
+ "help.notice": "NOTICE",
+ "help.third_party": "Ліцензії сторонніх компонентів",
"home.documentation": "Документація",
"home.in_this_browser": "у цьому браузері",
"home.missing": "відсутній",
@@ -756,10 +810,30 @@
"joint.from_bodies_hint": "Кожне вибране тіло переходить у власний новий компонент і лишається на місці.",
"joint.one_body": "Обидва вибори на {body}. Виберіть другий на іншій деталі.",
"joint.one_component": "Ці деталі - тіла одного компонента: {bodies}. З'єднання рухає один компонент відносно іншого, тому кожній деталі потрібен власний компонент.",
+ "keymap.command_id": "ID команди",
+ "keymap.empty": "Немає відповідних команд",
+ "keymap.use_anyway": "Усе одно використовувати тут {key}",
+ "manage.appearance_hint": "Виберіть вигляд для виділених об’єктів або перетягніть зразок на тіло чи грань.",
+ "manage.assign_hint": "Виберіть тіла та їхнє правило проєктування пластикових деталей.",
+ "manage.config_hint": "Змініть рядки, стовпці та правила конфігурації, а потім активуйте рядок або перегляньте його.",
+ "manage.empty": "Немає відповідних рядків.",
+ "manage.material_hint": "Виберіть тіла та їхній фізичний матеріал.",
+ "manage.parameters_hint": "Змініть вирази й одиниці. Зміни застосовуються після натискання Enter або виходу з поля.",
+ "manage.rules_hint": "Виберіть правило для редагування або створіть нове. Підтвердьте, щоб зберегти правило.",
+ "measure.at": "У точці",
+ "measure.item": "Елемент {number}",
"motion.checked_to": "Перевірено лише до кроку {step}: перевірка вичерпала свій бюджет роботи",
"motion.collision": "{a} · {b}: кроки {steps}",
+ "motion.delete_key": "Видалити ключовий кадр",
"motion.duration_hint": "секунди (порожньо: на крок)",
+ "motion.key_here": "Вставити ключовий кадр тут",
+ "motion.key_here_hint": "Додати ключовий кадр на цьому кроці з поточним значенням з’єднання",
"motion.no_collisions": "За все дослідження зіткнень немає",
+ "motion.step_back": "Крок назад",
+ "motion.step_forward": "Крок уперед",
+ "motion.to_end": "У кінець",
+ "motion.to_start": "На початок",
+ "motion.track_name": "Доріжка {number}",
"nav.touchpad.help": "Утримуйте Shift і рухайте вказівник, щоб панорамувати; утримуйте Alt/Option і рухайте, щоб обертати. Кнопка миші не потрібна. Вертикальна прокрутка масштабує.",
"nav.touchpad.label": "Трекпад",
"nav.touchpad.orbit": "Обертання (утримуйте Alt/Option і рухайте; без кнопки миші)",
@@ -775,6 +849,7 @@
"no joint that moves yet": "ще немає рухомого з'єднання",
"no picture": "немає зображення",
"none": "немає",
+ "parts.automatic_name": "автоматично",
"pattern.alignment_2": "Вирівнювання 2",
"pattern.alignment_hint": "Кількість включає оригінал. Центрування розподіляє копії з обох боків; за парної кількості зміна напрямку визначає бік із додатковою копією.",
"pattern.direction_1": "Напрямок 1",
@@ -782,6 +857,9 @@
"pattern.flip_direction": "Змінити напрямок",
"pick a hole to seat it, or OK places it at the origin": "виберіть отвір для посадки, або OK розмістить його в початку координат",
"pick one or two vertices, edges or faces": "виберіть одну-дві вершини, ребра або грані",
+ "prefs.cpu": "ЦП (програмний)",
+ "prefs.minutes_suffix": " min",
+ "properties.title": "Властивості: {name}",
"render.background": "Фон сцени",
"render.fit": "Вписати виріб",
"render.image_cancel": "Скасувати рендеринг",
@@ -844,6 +922,10 @@
"settings.reset_intro": "Ці налаштування не працюють на цьому комп'ютері й не давали б SolidCraft запуститися, тому їх змінено:",
"settings.reset_title": "Налаштування було змінено",
"settings.supersampling_note": "Малює вид у вищій роздільності й потім зменшує його: плавніші ребра, лінії та сітка на екранах до 4K. Це коштує часу GPU: приблизно 2,25× пікселів за 1,5× і 4× за 2×.",
+ "shortcut.json_error": "параметри мають бути у форматі JSON: {error}",
+ "shortcut.no_command": "команду `{id}` не знайдено; текст перед JSON має бути ID команди",
+ "shortcut.pin": "Закріпити вгорі поля S",
+ "shortcut.unpin": "Відкріпити",
"sketch.degrees_of_freedom": "{count} ступенів вільності",
"sketch.dof_left": "Залишилося ступенів свободи: {count}",
"sketch.dof_left_one": "Залишився {count} ступінь свободи",
@@ -885,6 +967,7 @@
"timeline.ungroup": "Прибрати теки операцій",
"to the face": "до грані",
"to the next face": "до наступної грані",
+ "toolbar.customize_note": "Вкладка {tab}. Позначте команду, щоб додати її кнопку на панель інструментів. Також можна перетягнути рядок зі спадного меню панелі на панель інструментів, перетягнути кнопку за межі панелі для видалення або скористатися значком закріплення в рядку спадного меню.",
"toolbar.image": "ЗОБРАЖЕННЯ",
"toolbar.render": "РЕНДЕР",
"toolbar.render_scene": "СЦЕНА",
@@ -962,6 +1045,7 @@
"ui.agent_chat_new": "Новий чат",
"ui.agent_chat_new_confirm": "Почати новий чат? Поточний буде очищено.",
"ui.agent_chat_new_yes": "Новий чат",
+ "ui.agent_chat_next_picture": "Наступне зображення",
"ui.agent_chat_no_cli": "solidcraft-cli не знайдено поруч із програмою, тож агент не може дістатися до проєкту.",
"ui.agent_chat_no_control": "Кінцева точка чату з агентом не запустилася, тож агент не може дістатися до проєкту.",
"ui.agent_chat_no_images": "Цей агент не приймає зображень",
@@ -977,6 +1061,7 @@
"ui.agent_chat_placeholder": "Попросіть агента змінити проєкт…",
"ui.agent_chat_placeholder_busy": "Поставте повідомлення в чергу, доки агент завершить (Ctrl+Enter: надіслати зараз)",
"ui.agent_chat_pop_out": "Відкрити у власному вікні, яке можна перемістити на інший екран",
+ "ui.agent_chat_previous_picture": "Попереднє зображення",
"ui.agent_chat_privacy": "Нічого нікуди не надсилається, крім агента, який ви запускаєте, під вашим власним обліковим записом.",
"ui.agent_chat_privacy_note": "SolidCraft нічого нікуди не надсилає: агент, який ви запускаєте, спілкується з власним сервісом під вашим обліковим записом. SolidCraft ніколи не бачить і не зберігає ключ чи пароль.",
"ui.agent_chat_queue": "У чергу",
@@ -1032,6 +1117,7 @@
"ui.ai_bad_url": "Введіть URL-адресу, що починається з http:// або https://",
"ui.ai_base_url": "Базова URL-адреса",
"ui.ai_button": "ШІ",
+ "ui.ai_command_hint": "my-agent --acp",
"ui.ai_copy_suffix": "копія",
"ui.ai_custom_url": "Власна URL-адреса",
"ui.ai_default": "Типовий",
@@ -1052,8 +1138,10 @@
"ui.ai_mode_edits_note": "Команди моделювання виконуються без запиту; збереження, відкриття, експорт та інші файлові чи руйнівні дії все ще запитують.",
"ui.ai_mode_global": "Як задано вище",
"ui.ai_model": "Модель",
+ "ui.ai_model_hint": "qwen3:14b",
"ui.ai_modes_scope": "Ці налаштування стосуються інструментів SolidCraft. Власні інструменти агента (його оболонка, його редагування файлів) підкоряються власному режиму агента, який ви вибираєте в заголовку панелі чату, коли агент має режими.",
"ui.ai_name": "Назва",
+ "ui.ai_name_hint": "Мій агент",
"ui.ai_need_command": "Введіть команду, що запускає агента",
"ui.ai_need_model": "Введіть назву моделі",
"ui.ai_no_answer": "Агент не відповів вчасно",
@@ -1084,6 +1172,7 @@
"ui.ai_toolbar_button": "Показувати кнопку на панелі інструментів",
"ui.ai_toolbar_button_note": "Кнопка ШІ в правому кінці панелі інструментів. Ctrl+Shift+A і меню «Вид» усе одно відкривають панель.",
"ui.ai_undo_tip": "Скасувати все, що агент змінив для цього повідомлення, одним кроком",
+ "ui.ai_url_hint": "https://example.com/v1",
"ui.all": "Усі",
"ui.ambient_occlusion": "Окружне затінення",
"ui.ambient_occlusion_help": "М'яке затінення в місцях, де стикаються непрозорі поверхні. Потребує вікна перегляду на GPU.",
@@ -1668,5 +1757,6 @@
"update.title": "Доступне оновлення",
"update.up_to_date": "SolidCraft оновлено.",
"update.update_now": "Оновити зараз",
- "update.you_have": "У вас версія {version}."
+ "update.you_have": "У вас версія {version}.",
+ "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ вибрати · Enter / Tab доповнити · Esc закрити"
}
diff --git a/assets/locales/zh.json b/assets/locales/zh.json
index c6d893c26e..671335734c 100644
--- a/assets/locales/zh.json
+++ b/assets/locales/zh.json
@@ -11,6 +11,7 @@
"About SolidCraft": "关于 SolidCraft",
"Acceleration": "加速度",
"Access": "可达性",
+ "Actions": "操作",
"Active": "活动",
"Active rule": "活动规则",
"Add": "添加",
@@ -18,6 +19,7 @@
"Add Mid Radius": "添加中间半径",
"Add Row": "添加行",
"Add condition": "添加条件",
+ "Add or edit rule": "添加或编辑规则",
"Against": "对照",
"Alignment": "对齐",
"All Sketch Points": "所有草图点",
@@ -31,6 +33,7 @@
"Applied Radius": "应用半径",
"Apply To": "应用于",
"Apply to selection": "应用到选择",
+ "Apply your appearance first. Exports assigned appearances and materials created in this design.": "请先应用外观。导出已指定的外观和在此设计中创建的材质。",
"Arc length": "弧长",
"Area": "面积",
"As-Built": "现有位置",
@@ -67,11 +70,13 @@
"Check collisions": "检查碰撞",
"Checked": "已检查",
"Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "选择一个新平面。草图几何和尺寸在其二维坐标中保持不变。",
+ "Choose…": "选择…",
"Circular": "圆周",
"Circumference": "周长",
"Close draft": "关闭草稿",
"Collisions": "碰撞",
"Colour": "颜色",
+ "Comment": "注释",
"Component1": "组件1",
"Config Table": "配置表",
"Configuration": "配置",
@@ -100,6 +105,7 @@
"Curvature (G2)": "曲率 (G2)",
"Curvature change (G3)": "曲率变化 (G3)",
"Customize Toolbar": "自定义工具栏",
+ "Delete": "删除",
"Delete all": "全部删除",
"Delete rule": "删除规则",
"Delete the row": "删除此行",
@@ -118,6 +124,7 @@
"Drive Joint": "驱动接头",
"Duration": "时长",
"Edges": "边",
+ "Edit": "编辑",
"Edit Profile Sketch": "编辑轮廓草图",
"Enable rule": "启用规则",
"Enabled": "已启用",
@@ -126,11 +133,14 @@
"Explode": "爆炸",
"Explode Text": "分解文字",
"Export Animation…": "导出动画…",
+ "Export CSV…": "导出 CSV…",
"Export Current View as DXF": "将当前视图导出为DXF",
"Export Current View as DXF…": "将当前视图导出为DXF…",
"Export DXF": "导出DXF",
"Export DXF…": "导出DXF…",
+ "Export JSON…": "导出 JSON…",
"Export hidden edges as dashed lines": "以虚线导出隐藏线",
+ "Expression": "表达式",
"Extend to meet": "延伸至相交",
"Extents": "范围",
"FILES": "文件",
@@ -140,7 +150,9 @@
"Faces": "面",
"Faces / edges / vertices": "面 / 边 / 顶点",
"Fastener": "紧固件",
+ "Favorites": "收藏",
"Favourite": "收藏",
+ "Feature": "特征",
"Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "许多 CAD 程序的文件以 Y 为上轴,因此在此处打开时会平躺(Z 朝上)。",
"Filter": "筛选",
"Find in Browser": "在浏览器中查找",
@@ -164,6 +176,7 @@
"Home view": "主视图",
"Horiz./Vert.": "水平 / 垂直",
"IMAGES": "图像",
+ "Import…": "导入…",
"In This Design": "在此设计中",
"In place (surfaces)": "原位(曲面)",
"In plane": "在平面内",
@@ -185,7 +198,9 @@
"Length units": "长度单位",
"Letter Spacing": "字间距",
"Library": "零件库",
+ "Library file": "库文件",
"Line Spacing": "行间距",
+ "Local library": "本地库",
"Loop": "循环",
"MANAGE": "管理",
"MATERIALS": "材料",
@@ -194,25 +209,32 @@
"Margin": "余量",
"Mass": "质量",
"Mass Center": "质心",
+ "Matched restrictions check the final values.": "满足条件的限制规则检查最终值。",
"Material": "材质",
"Max": "最大",
"Mid Radius": "中间半径",
"Middle double-click": "中键双击",
"Min": "最小",
"Mitre": "斜接",
+ "Model Parameters": "模型参数",
"Modeled": "已建模",
"More toolbar panels": "更多工具栏面板",
"Motion": "运动",
"Move / Copy": "移动 / 复制",
"Move Type": "移动类型",
+ "Move down": "下移",
"Move earlier": "向前移动",
"Move later": "向后移动",
+ "Move up": "上移",
"Name": "名称",
"Nearest": "最近",
+ "New": "新建",
"New Comp.": "新建组件",
"New Sketch": "新建草图",
+ "New rule…": "新建规则…",
"New study": "新建研究",
"No crash reports.": "没有崩溃报告。",
+ "No matching appearance presets.": "没有匹配的外观预设。",
"No matching appearances": "没有匹配的外观",
"No visible bodies to export.": "没有可导出的可见实体。",
"None": "无",
@@ -222,12 +244,15 @@
"OUTPUT": "输出",
"Opacity": "不透明度",
"Open GitHub draft": "打开 GitHub 草稿",
+ "Open local libraries in the desktop app. You can export this design's library here.": "请在桌面应用中打开本地库。您可以在此导出当前设计的库。",
"Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "使用 Rust 编写的开源参数化 3D CAD。基于 MIT OR Apache-2.0 许可。",
+ "Operator": "运算符",
"Other side": "另一侧",
"Other surface (mutual trim)": "另一曲面(相互修剪)",
"Outside": "外侧",
"Overall length": "总长",
"Param. Graph": "参数图",
+ "Parameter": "参数",
"Parameter values": "参数值",
"Parts": "零件",
"Pass through": "通过点",
@@ -289,6 +314,8 @@
"Roll History Marker Here": "将历史标记滚动到此处",
"Round": "圆角",
"Rule": "规则",
+ "Rule name": "规则名称",
+ "Rules run from top to bottom. Matched drives change effective values.": "规则从上到下依次运行。满足条件的驱动规则更改有效值。",
"SECTION": "剖面",
"SURFACE QUALITY": "曲面质量",
"Save Rule": "保存规则",
@@ -299,6 +326,7 @@
"Scene": "场景",
"Search": "搜索",
"Search commands": "搜索命令",
+ "Search this library": "搜索此库",
"Section": "剖面",
"Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "“选择其他”:在模型上按住左键(或右键单击 › 选择其他…)列出光标下的所有对象;在同一位置再次单击可选择该处的下一个对象。双击中键转到主视图(首选项 › 导航)。",
"Select bodies (a face picks its body)": "选择实体(单击面即选择其所属实体)",
@@ -360,11 +388,13 @@
"Turn off section analysis before exporting the view.": "请关闭截面分析后再导出视图。",
"Type": "类型",
"UNTRIM": "取消修剪",
+ "Unit": "单位",
"Updating the preview": "正在更新预览",
"Use active author placement": "使用活动作者放置",
"Use fixed plane": "使用固定平面",
"Use saved fixed plane": "使用已保存的固定平面",
"Use selected face as fixed plane": "使用所选面作为固定平面",
+ "User Parameters": "用户参数",
"VIEW": "视图",
"VIEWS": "视图",
"Value": "值",
@@ -379,6 +409,12 @@
"When": "条件",
"Width": "宽度",
"Will fail": "将失败",
+ "X angle": "X 角度",
+ "X distance": "X 距离",
+ "Y angle": "Y 角度",
+ "Y distance": "Y 距离",
+ "Z angle": "Z 角度",
+ "Z distance": "Z 距离",
"Zebra": "斑马纹",
"angle, height": "角度、高度",
"appearance.dielectric_ior": "电介质折射率",
@@ -388,7 +424,13 @@
"appearance.roughness": "粗糙度",
"appearance.surface_response": "表面响应",
"browser.body_name": "实体{number}",
+ "browser.calibrate_title": "校准:{name}",
+ "browser.capture_many": "{count} 个组件已移动,但尚未捕获其位置。",
+ "browser.capture_note": "“捕获位置”保留新位置;“恢复位置”还原原先的位置。",
+ "browser.capture_one": "一个组件已移动,但尚未捕获其位置。",
"browser.component_name": "组件{number}",
+ "browser.edit_canvas_title": "编辑画布:{name}",
+ "browser.move_title": "移动:{name}",
"browser.parameters": "参数 ({count})",
"browser.precision": "精度: {precision}",
"browser.sketch_name": "草图{number}",
@@ -727,6 +769,8 @@
"cmd.view_rename": "重命名命名视图",
"cmd.view_save": "新建命名视图",
"command name": "命令名称",
+ "contact.components_count": "{count} 个组件",
+ "contact.enabled_label": "已启用",
"coupling.gear_1": "齿轮 1",
"coupling.gear_1_pick": "齿轮 1(可选)",
"coupling.gear_2": "齿轮 2",
@@ -746,6 +790,18 @@
"crash.detected_time": "检测时间:{time} UTC",
"crash.previous_session": "较早的 SolidCraft 会话意外结束或发生了内部错误。未正常结束的会话会在启动时被检测到。详情请参阅 帮助 > 崩溃报告…。",
"crash.unclean_explanation": "在后续启动时检测到;未记录确切的退出时间。系统关机或强制停止也可能导致会话未正常结束。",
+ "crash.announce": "SolidCraft 上次意外关闭或发生了内部错误。崩溃报告已保存(帮助 > 崩溃报告…)。",
+ "crash.copy_folder": "复制文件夹路径",
+ "crash.copy_path": "复制路径",
+ "crash.deleted": "已删除 {count} 份报告。",
+ "crash.intro": "崩溃报告保存在此计算机上,不会发送到任何地方。“报告…”会打开草稿,供您在分享前检查。",
+ "crash.kind_command": "命令内部错误",
+ "crash.kind_internal": "内部错误",
+ "crash.kind_kernel": "内核错误(已恢复)",
+ "crash.kind_unclean": "意外关闭",
+ "crash.replayable": "可重放",
+ "crash.report": "报告…",
+ "delete.and_more": "…以及另外 {count} 项",
"dialog.bodies_count": "{count} 个实体",
"dialog.clearance_invalid": "间隙必须是 0 或更大的长度",
"dialog.compute": "计算",
@@ -753,6 +809,8 @@
"dialog.computing": "正在计算… {seconds} 秒",
"dialog.could_not_be_checked": "无法检查",
"dialog.custom_axis": "↖ 自定义轴",
+ "dialog.dimension_insert_hint": "双击其他驱动尺寸以插入其名称",
+ "dialog.dimension_name": "尺寸:{name}",
"dialog.edit_title": "编辑 {title}",
"dialog.select": "↖ 选择",
"dialog.selected_count": "↖ 已选择 {count} 个",
@@ -777,8 +835,30 @@
"dxf.tolerance": "曲线公差",
"dxf.tolerance_help": "仅导出可见实体。曲线使用直线段近似。公差越小,曲线越精细,但需要更多时间和内存。",
"expression, e.g. 25 mm": "表达式,例如 25 mm",
+ "file_load.built": "已构建:{built}/{total} 个特征。",
+ "file_load.converting": "正在转换实体 {done}/{total}",
+ "file_load.inserting": "正在插入几何体",
+ "file_load.opening": "正在打开设计",
+ "file_load.preparing_thumbnail": "正在准备缩略图...",
+ "file_load.preparing_view": "正在准备视图...",
+ "file_load.preview_note": "这是已保存的预览。正在检查几何体,完成后即可编辑。",
+ "file_load.reading": "正在读取文件...",
+ "file_load.reading_percent": "正在读取文件... {percent}%",
+ "file_load.rebuilding": "正在重建特征 {done}/{total}",
+ "file_load.recovering": "正在恢复设计",
+ "file_load.stopping": "正在等待上一次操作停止...",
+ "file_load.waiting": "正在等待文件操作",
"fits the face, e.g. M8": "适配该面,例如 M8",
"from the rule": "来自规则",
+ "help.apache": "Apache 许可证 2.0",
+ "help.attributions": "署名信息 (ATTRIBUTION.md)",
+ "help.build": "版本 {version} · 提交 {commit} · 构建日期 {date}",
+ "help.font_details": "界面使用 egui 的内置字体(Ubuntu Light 和 Hack,采用 Ubuntu Font Licence 和 MIT/Bitstream Vera 许可证;Noto Emoji 和表情图标字体,采用 OFL 和 MIT 许可证)。草图文本使用 Liberation Sans(SIL OFL 1.1)。The Crafting Apps 的可选字体包 craft-fonts(BIZ UDPGothic、Shippori Mincho、BIZ UDMincho、Noto Sans CJK SC、Noto Sans Arabic;SIL OFL 1.1)未随 SolidCraft 构建版本捆绑提供。",
+ "help.fonts": "字体",
+ "help.licences": "许可证",
+ "help.mit": "MIT 许可证",
+ "help.notice": "NOTICE",
+ "help.third_party": "第三方许可证",
"home.documentation": "文档",
"home.in_this_browser": "在此浏览器中",
"home.missing": "文件不存在",
@@ -804,9 +884,30 @@
"install.menu": "安装应用…",
"install.steps_intro": "Safari 通过自身的菜单安装网页应用:",
"install.title": "安装 SolidCraft",
+ "issue.body_label": "报告正文",
+ "issue.note_image_copied": "请将图片粘贴到 GitHub 草稿中。如果无法复制图片,请保存 PNG。",
+ "issue.note_opened": "请检查 GitHub 草稿并附上截图。点击 GitHub 的 Submit new issue 按钮即可发布。",
+ "issue.note_opened_copied": "报告已复制。请粘贴到 GitHub 草稿中,附上截图,然后在 GitHub 上点击 Submit new issue。",
+ "issue.note_removed": "已从此草稿中移除截图。",
+ "issue.note_report_copied": "报告已复制。如有需要,请将其粘贴到 GitHub 草稿中。",
+ "issue.note_save_failed": "无法保存截图:{error}",
+ "issue.note_saved": "截图已保存。请在 GitHub 草稿中附上 PNG。",
+ "issue.save_screenshot": "保存截图…",
"joint.from_bodies_hint": "每个所选实体移入各自的新组件,位置保持不变。",
"joint.one_body": "两次选择都在 {body} 上。请在另一个零件上选择第二个。",
"joint.one_component": "这些零件是同一组件的实体:{bodies}。接头使一个组件相对另一个组件运动,因此每个零件都需要自己的组件。",
+ "keymap.command_id": "命令 ID",
+ "keymap.empty": "没有匹配的命令",
+ "keymap.use_anyway": "仍在此处使用 {key}",
+ "manage.appearance_hint": "为所选对象选择外观,或将色样拖到实体或面上。",
+ "manage.assign_hint": "选择实体并指定其塑料设计规则。",
+ "manage.config_hint": "编辑配置行、列和规则,然后激活或预览某一行。",
+ "manage.empty": "没有匹配的行。",
+ "manage.material_hint": "选择实体并指定其物理材质。",
+ "manage.parameters_hint": "编辑表达式和单位。按 Enter 或离开字段时应用更改。",
+ "manage.rules_hint": "选择要编辑的规则,或创建新规则。确认以保存规则。",
+ "measure.at": "位置",
+ "measure.item": "项目 {number}",
"messages.ago_h": "{n} 小时前",
"messages.ago_min": "{n} 分钟前",
"messages.ago_s": "{n} 秒前",
@@ -818,8 +919,16 @@
"messages.title": "消息",
"motion.checked_to": "仅检查到第 {step} 步:检查已用完其工作量上限",
"motion.collision": "{a} · {b}:第 {steps} 步",
+ "motion.delete_key": "删除关键帧",
"motion.duration_hint": "秒(留空:按步)",
+ "motion.key_here": "在此添加关键帧",
+ "motion.key_here_hint": "在此步骤添加关键帧,使用关节的当前值",
"motion.no_collisions": "整个研究中没有碰撞",
+ "motion.step_back": "上一步",
+ "motion.step_forward": "下一步",
+ "motion.to_end": "到结尾",
+ "motion.to_start": "到开头",
+ "motion.track_name": "轨道 {number}",
"nav.touchpad.help": "按住 Shift 并移动指针可平移;按住 Alt/Option 并移动可旋转。无需按鼠标按钮。垂直滚动可缩放。",
"nav.touchpad.label": "触控板",
"nav.touchpad.orbit": "旋转(按住 Alt/Option 并移动,无需鼠标按钮)",
@@ -835,6 +944,7 @@
"no joint that moves yet": "尚无运动接头",
"no picture": "无图片",
"none": "无",
+ "parts.automatic_name": "自动",
"pattern.alignment_2": "对齐 2",
"pattern.alignment_hint": "数量包含原始图形。居中时副本分布在两侧;数量为偶数时,反转可切换多一个副本的一侧。",
"pattern.direction_1": "方向 1",
@@ -842,6 +952,15 @@
"pattern.flip_direction": "反转方向",
"pick a hole to seat it, or OK places it at the origin": "选择一个孔放置,或单击确定放置在原点",
"pick one or two vertices, edges or faces": "选择一个或两个顶点、边或面",
+ "prefs.cpu": "CPU(软件)",
+ "prefs.minutes_suffix": " min",
+ "properties.title": "属性:{name}",
+ "recovery.days_ago": "{count} 天前",
+ "recovery.detail": "{file} · {features} 个特征 · 自动保存于 {when}",
+ "recovery.hours_ago": "{count} 小时前",
+ "recovery.just_now": "刚刚",
+ "recovery.min_ago": "{count} 分钟前",
+ "recovery.never_saved": "从未保存",
"render.background": "场景背景",
"render.fit": "适配产品视图",
"render.image_cancel": "取消渲染",
@@ -904,6 +1023,10 @@
"settings.reset_intro": "这些设置在此计算机上无法正常工作,会导致 SolidCraft 无法启动,因此已更改:",
"settings.reset_title": "设置已更改",
"settings.supersampling_note": "以更高分辨率绘制视图再缩小:在低于 4K 的屏幕上边、线和网格更平滑。会消耗 GPU 时间:1.5× 时约 2.25 倍像素,2× 时 4 倍。",
+ "shortcut.json_error": "参数必须采用 JSON 格式:{error}",
+ "shortcut.no_command": "没有命令 `{id}`;JSON 前的文本必须是命令 ID",
+ "shortcut.pin": "固定到 S 框顶部",
+ "shortcut.unpin": "取消固定",
"sketch.degrees_of_freedom": "{count} 个自由度",
"sketch.dof_left": "剩余 {count} 个自由度",
"sketch.dof_left_one": "剩余 {count} 个自由度",
@@ -945,6 +1068,7 @@
"timeline.ungroup": "移除特征文件夹",
"to the face": "到面",
"to the next face": "到下一个面",
+ "toolbar.customize_note": "{tab} 选项卡。勾选命令可将其按钮添加到工具栏。您也可以将面板下拉菜单中的某一行拖到工具栏,将按钮拖出工具栏以移除,或使用下拉菜单行中的固定图标。",
"toolbar.image": "图像",
"toolbar.render": "渲染",
"toolbar.render_scene": "场景",
@@ -999,6 +1123,7 @@
"ui.agent_chat_file_error": "{name}:{error}",
"ui.agent_chat_file_heic": "{name}:这里无法读取 HEIC 图片;请先导出为 JPEG 或 PNG",
"ui.agent_chat_file_importing": "正在导入设计…",
+ "ui.agent_chat_file_kinds": "{name}:可以附加图片(PNG、JPEG、GIF、WebP、BMP、TIFF)、文本文件(包括 SVG)和 CAD 文件(STEP、IGES、FreeCAD、Rhino、STL、3MF、OBJ、glTF)",
"ui.agent_chat_file_loading": "正在读取文件…",
"ui.agent_chat_file_not_a_file": "{name}:不是文件",
"ui.agent_chat_file_not_a_picture": "{name}:不是图片",
@@ -1022,6 +1147,7 @@
"ui.agent_chat_new": "新对话",
"ui.agent_chat_new_confirm": "开始新对话?当前对话将被清除。",
"ui.agent_chat_new_yes": "新对话",
+ "ui.agent_chat_next_picture": "下一张图片",
"ui.agent_chat_no_cli": "在应用旁边未找到 solidcraft-cli,因此智能体无法访问设计。",
"ui.agent_chat_no_control": "智能体聊天的端点未能启动,因此智能体无法访问设计。",
"ui.agent_chat_no_images": "该智能体不接收图片",
@@ -1037,6 +1163,7 @@
"ui.agent_chat_placeholder": "让智能体修改设计…",
"ui.agent_chat_placeholder_busy": "输入消息,待智能体完成后发送(Ctrl+Enter:立即发送)",
"ui.agent_chat_pop_out": "在独立窗口中打开(可移到另一个屏幕)",
+ "ui.agent_chat_previous_picture": "上一张图片",
"ui.agent_chat_privacy": "除了你以自己的账户运行的智能体之外,不会向任何地方发送任何内容。",
"ui.agent_chat_privacy_note": "SolidCraft 不向任何地方发送任何内容:你运行的智能体以你自己的账户与它自己的服务通信。SolidCraft 从不查看或保存任何密钥或密码。",
"ui.agent_chat_queue": "加入队列",
@@ -1092,6 +1219,7 @@
"ui.ai_bad_url": "请输入以 http:// 或 https:// 开头的 URL",
"ui.ai_base_url": "基础 URL",
"ui.ai_button": "AI",
+ "ui.ai_command_hint": "my-agent --acp",
"ui.ai_copy_suffix": "副本",
"ui.ai_custom_url": "自定义 URL",
"ui.ai_default": "默认",
@@ -1112,8 +1240,10 @@
"ui.ai_mode_edits_note": "建模命令无需询问即可运行;保存、打开、导出等文件操作或破坏性操作仍会询问。",
"ui.ai_mode_global": "按上方设置",
"ui.ai_model": "模型",
+ "ui.ai_model_hint": "qwen3:14b",
"ui.ai_modes_scope": "这些设置适用于 SolidCraft 的工具。智能体自己的工具(它的 shell、文件编辑)遵循智能体自己的模式;如果智能体提供模式,可在聊天面板标题栏中选择。",
"ui.ai_name": "名称",
+ "ui.ai_name_hint": "我的智能体",
"ui.ai_need_command": "请输入启动智能体的命令",
"ui.ai_need_model": "请输入模型名称",
"ui.ai_no_answer": "智能体未及时响应",
@@ -1144,6 +1274,7 @@
"ui.ai_toolbar_button": "在工具栏显示按钮",
"ui.ai_toolbar_button_note": "工具栏右端的 AI 按钮。Ctrl+Shift+A 和视图菜单仍可打开面板。",
"ui.ai_undo_tip": "将智能体为此消息所做的全部更改一步撤销",
+ "ui.ai_url_hint": "https://example.com/v1",
"ui.all": "全部",
"ui.ambient_occlusion": "环境光遮蔽",
"ui.ambient_occlusion_help": "在不透明表面相接处添加柔和阴影。需要 GPU 视口。",
@@ -1765,5 +1896,6 @@
"update.title": "有可用更新",
"update.up_to_date": "SolidCraft 已是最新版本。",
"update.update_now": "立即更新",
- "update.you_have": "当前版本为 {version}。"
+ "update.you_have": "当前版本为 {version}。",
+ "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ 选择 · Enter / Tab 补全 · Esc 关闭"
}
diff --git a/crates/ui-egui/src/agent_chat/panel.rs b/crates/ui-egui/src/agent_chat/panel.rs
index f4aa88c762..1003f2885b 100644
--- a/crates/ui-egui/src/agent_chat/panel.rs
+++ b/crates/ui-egui/src/agent_chat/panel.rs
@@ -7,6 +7,7 @@ use egui::{Align, Align2, Color32, Id, Layout, Rect, RichText, Sense, Stroke, po
use super::*;
use crate::theme::Tokens;
+use crate::ui_kit;
pub const MIN_WIDTH: f32 = 280.0;
pub const MAX_WIDTH: f32 = 760.0;
@@ -110,7 +111,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
.size_range(MIN_WIDTH..=MAX_WIDTH)
.resizable(true)
.frame(egui::Frame::NONE.fill(t.panel).inner_margin(egui::Margin::symmetric(8, 6)))
- .show(ui, |ui| body(app, ui, left));
+ .show(ui, |ui| ui_kit::scope(ui, |ui| body(app, ui, left)));
crate::scenario::publish_rect("agent_chat:panel", r.response.rect);
app.agent_chat.panel_rect = Some(r.response.rect);
#[cfg(not(target_arch = "wasm32"))]
@@ -185,9 +186,9 @@ fn gallery_window(app: &mut SolveApp, ctx: &egui::Context) {
let modal = egui::Modal::new(Id::new("sc_agent_chat_gallery")).show(ctx, |ui| {
ui.set_max_width(max.x);
ui.horizontal(|ui| {
- let prev = ui.add_enabled(count > 1, egui::Button::new("‹"));
+ let prev = ui_kit::enabled_button(ui, tr("ui.agent_chat_previous_picture"), count > 1);
crate::scenario::publish_handle("agent_chat:gallery_prev", prev.rect.center());
- let next = ui.add_enabled(count > 1, egui::Button::new("›"));
+ let next = ui_kit::enabled_button(ui, tr("ui.agent_chat_next_picture"), count > 1);
crate::scenario::publish_handle("agent_chat:gallery_next", next.rect.center());
if prev.clicked() {
step = -1;
@@ -302,7 +303,7 @@ fn window(app: &mut SolveApp, ctx: &egui::Context) {
ctx.show_viewport_immediate(egui::ViewportId::from_hash_of("sc_agent_chat_window"), builder, |ui, class| {
let t = Tokens::get();
let frame = egui::Frame::NONE.fill(t.panel).inner_margin(egui::Margin::symmetric(8, 6));
- let r = egui::CentralPanel::default().frame(frame).show(ui, |ui| body(app, ui, false));
+ let r = egui::CentralPanel::default().frame(frame).show(ui, |ui| ui_kit::scope(ui, |ui| body(app, ui, false)));
// The picture viewer opens over this window, where the click was, not over the main one.
gallery_window(app, ui.ctx());
if class == egui::ViewportClass::EmbeddedWindow {
@@ -504,9 +505,9 @@ fn header(app: &mut SolveApp, ui: &mut egui::Ui, left: bool) {
#[cfg(not(target_arch = "wasm32"))]
{
let b = if state.running() {
- ui.button(tr("ui.agent_chat_stop")).on_hover_text(tr("ui.agent_chat_stop_tip"))
+ ui_kit::secondary_button(ui, tr("ui.agent_chat_stop")).on_hover_text(tr("ui.agent_chat_stop_tip"))
} else {
- ui.button(tr("ui.agent_chat_connect"))
+ ui_kit::secondary_button(ui, tr("ui.agent_chat_connect"))
};
crate::scenario::publish_handle("agent_chat:connect", b.rect.center());
if b.clicked() {
@@ -579,17 +580,16 @@ fn desktop_body(app: &mut SolveApp, ui: &mut egui::Ui) {
}
let state = app.agent_chat.state();
if app.agent_chat.confirm_new {
- let t = Tokens::get();
- egui::Frame::NONE.fill(t.accent_soft).corner_radius(6.0).inner_margin(egui::Margin::same(6)).show(ui, |ui| {
+ ui_kit::scope(ui, |ui| {
ui.set_width(ui.available_width());
- ui.label(tr("ui.agent_chat_new_confirm"));
+ ui_kit::text_block(ui, "new_chat", tr("ui.agent_chat_new_confirm"), false);
ui.horizontal(|ui| {
- let yes = ui.button(tr("ui.agent_chat_new_yes"));
+ let yes = ui_kit::secondary_button(ui, tr("ui.agent_chat_new_yes"));
crate::scenario::publish_handle("agent_chat:new_confirm", yes.rect.center());
if yes.clicked() {
new_chat(app);
}
- if ui.button(tr("ui.agent_chat_cancel")).clicked() {
+ if ui_kit::secondary_button(ui, tr("ui.agent_chat_cancel")).clicked() {
app.agent_chat.confirm_new = false;
}
});
@@ -624,16 +624,18 @@ fn desktop_body(app: &mut SolveApp, ui: &mut egui::Ui) {
if focused {
super::paste::handle(app, ui);
}
- let edit = egui::TextEdit::multiline(&mut app.agent_chat.input)
- .hint_text(tr(if busy { "ui.agent_chat_placeholder_busy" } else { "ui.agent_chat_placeholder" }))
- .desired_rows(2)
- .desired_width(f32::INFINITY)
- .id_salt("sc_agent_chat_input");
let r = egui::ScrollArea::vertical()
.id_salt("sc_agent_chat_input_scroll")
.max_height(edit_max)
.auto_shrink([false, true])
- .show(ui, |ui| ui.add(edit))
+ .show(ui, |ui| {
+ ui_kit::message_field(
+ ui,
+ Id::new("sc_agent_chat_input"),
+ &mut app.agent_chat.input,
+ tr(if busy { "ui.agent_chat_placeholder_busy" } else { "ui.agent_chat_placeholder" }),
+ )
+ })
.inner;
crate::scenario::publish_rect("agent_chat:input", r.rect);
// macOS shows a window's cursors only while it is the active window: over the text box of a
@@ -649,8 +651,7 @@ fn desktop_body(app: &mut SolveApp, ui: &mut egui::Ui) {
add_menu(app, ui);
// A message waits for files still being read.
let reading = !app.agent_chat.loading.is_empty();
- let send_b = ui
- .add_enabled(!reading, egui::Button::new(tr(if busy { "ui.agent_chat_queue" } else { "ui.agent_chat_send" })))
+ let send_b = ui_kit::enabled_button(ui, tr(if busy { "ui.agent_chat_queue" } else { "ui.agent_chat_send" }), !reading)
.on_disabled_hover_text(tr("ui.agent_chat_files_loading"));
crate::scenario::publish_handle("agent_chat:send", send_b.rect.center());
send_clicked = send_b.clicked();
@@ -658,7 +659,8 @@ fn desktop_body(app: &mut SolveApp, ui: &mut egui::Ui) {
// A picture of the view goes with the message to agents that take pictures.
let images = app.agent_chat.images || !state.running();
let attach = ui
- .add_enabled(images, egui::Checkbox::new(&mut app.agent_chat.attach_view, tr("ui.agent_chat_attach_view")))
+ .add_enabled_ui(images, |ui| ui_kit::checkbox(ui, tr("ui.agent_chat_attach_view"), &mut app.agent_chat.attach_view))
+ .inner
.on_hover_text(tr("ui.agent_chat_attach_view_tip"))
.on_disabled_hover_text(tr("ui.agent_chat_no_images"));
crate::scenario::publish_handle("agent_chat:attach", attach.rect.center());
@@ -706,28 +708,6 @@ pub(super) fn login_chip(ui: &mut egui::Ui, login: &str) {
});
}
-/// A small mark for an agent's kind: a terminal prompt for a program, a cloud for an endpoint.
-pub(super) fn kind_icon(ui: &mut egui::Ui, kind: agents::Kind) {
- let t = Tokens::get();
- let (r, _) = ui.allocate_exact_size(vec2(16.0, 14.0), Sense::hover());
- let p = ui.painter();
- let s = Stroke::new(1.3, t.text_dim);
- match kind {
- agents::Kind::Acp => {
- p.rect_stroke(r.shrink(1.0), 2.0, s, egui::StrokeKind::Inside);
- p.line_segment([r.left_top() + vec2(4.0, 4.0), r.left_top() + vec2(7.0, 7.0)], s);
- p.line_segment([r.left_top() + vec2(7.0, 7.0), r.left_top() + vec2(4.0, 10.0)], s);
- p.line_segment([r.left_top() + vec2(8.5, 10.0), r.left_top() + vec2(12.0, 10.0)], s);
- }
- agents::Kind::Api => {
- let c = r.center();
- p.circle_stroke(c + vec2(-3.0, 1.5), 3.2, s);
- p.circle_stroke(c + vec2(1.0, -1.0), 4.2, s);
- p.circle_stroke(c + vec2(4.0, 2.0), 2.8, s);
- }
- }
-}
-
/// The header's second row: the agent this conversation uses (a compact switcher), the agent's
/// own mode when it has modes, and the state of its login.
#[cfg(not(target_arch = "wasm32"))]
@@ -745,34 +725,29 @@ fn switcher(app: &mut SolveApp, ui: &mut egui::Ui) {
(ui.available_width() - if app.agent_chat.modes.is_empty() { 4.0 } else { 116.0 } - if models { 146.0 } else { 0.0 }).clamp(90.0, 260.0);
let mut picked: Option<String> = None;
let mut add = false;
- let combo = egui::ComboBox::from_id_salt("sc_agent_switch")
- .width(w)
- .selected_text(RichText::new(label).semibold().color(crate::theme::Tokens::get().text))
- .show_ui(ui, |ui| {
- for e in &all {
- let sel = current.as_ref().is_some_and(|c| c.id == e.id);
- let r = ui.horizontal(|ui| {
- kind_icon(ui, e.kind);
- let r = ui.selectable_label(sel, &e.name);
- ui.label(RichText::new(e.detail()).color(t.text_dim).size(crate::theme::Tokens::get().font_small));
- login_chip(ui, e.login);
- r
- });
- crate::scenario::publish_handle(&format!("agent_chat:agent:{}", e.id), r.inner.rect.center());
- if r.inner.clicked() {
- picked = Some(e.id.clone());
+ let combo = ui
+ .allocate_ui(vec2(w, t.control_height), |ui| {
+ ui_kit::dropdown_menu(ui, "sc_agent_switch", &label, |ui| {
+ for e in &all {
+ let sel = current.as_ref().is_some_and(|c| c.id == e.id);
+ let r = ui_kit::list_picker(ui, &e.id, &e.name, sel).on_hover_text(format!("{} {}", e.detail(), e.login));
+ crate::scenario::publish_handle(&format!("agent_chat:agent:{}", e.id), r.rect.center());
+ if r.clicked() {
+ picked = Some(e.id.clone());
+ }
}
- }
- ui.separator();
- if ui.selectable_label(false, tr("ui.ai_add_agent")).clicked() {
- add = true;
- }
- if ui.selectable_label(false, tr("ui.ai_settings")).clicked() {
- crate::prefs::open_at(app, crate::prefs::PAGE_AI);
- }
- });
- crate::scenario::publish_handle("agent_chat:switcher", combo.response.rect.center());
- combo.response.on_hover_text(tr("ui.ai_switch_tip"));
+ ui.separator();
+ if ui_kit::list_picker(ui, "add", tr("ui.ai_add_agent"), false).clicked() {
+ add = true;
+ }
+ if ui_kit::list_picker(ui, "settings", tr("ui.ai_settings"), false).clicked() {
+ crate::prefs::open_at(app, crate::prefs::PAGE_AI);
+ }
+ })
+ })
+ .inner;
+ crate::scenario::publish_handle("agent_chat:switcher", combo.rect.center());
+ combo.on_hover_text(tr("ui.ai_switch_tip"));
if add {
super::settings::open_add(app);
}
@@ -787,15 +762,19 @@ fn switcher(app: &mut SolveApp, ui: &mut egui::Ui) {
let modes = app.agent_chat.modes.clone();
let cur = modes.iter().find(|(id, _)| *id == app.agent_chat.mode).map_or_else(|| app.agent_chat.mode.clone(), |(_, n)| n.clone());
let mut pick: Option<String> = None;
- let r = egui::ComboBox::from_id_salt("sc_agent_mode").width(100.0).selected_text(cur).show_ui(ui, |ui| {
- for (id, name) in &modes {
- if ui.selectable_label(*id == app.agent_chat.mode, name).clicked() {
- pick = Some(id.clone());
- }
- }
- });
- crate::scenario::publish_handle("agent_chat:mode", r.response.rect.center());
- r.response.on_hover_text(tr("ui.ai_agent_mode_tip"));
+ let r = ui
+ .allocate_ui(vec2(t.form_label_width, t.control_height), |ui| {
+ ui_kit::dropdown_menu(ui, "sc_agent_mode", &cur, |ui| {
+ for (id, name) in &modes {
+ if ui_kit::list_picker(ui, id, name, *id == app.agent_chat.mode).clicked() {
+ pick = Some(id.clone());
+ }
+ }
+ })
+ })
+ .inner;
+ crate::scenario::publish_handle("agent_chat:mode", r.rect.center());
+ r.on_hover_text(tr("ui.ai_agent_mode_tip"));
if let Some(m) = pick {
set_mode(app, &m);
}
@@ -805,18 +784,22 @@ fn switcher(app: &mut SolveApp, ui: &mut egui::Ui) {
let list = app.agent_chat.models.clone();
let cur = list.iter().find(|m| m.id == app.agent_chat.model).map_or_else(|| app.agent_chat.model.clone(), |m| m.name.clone());
let mut pick: Option<String> = None;
- let r = egui::ComboBox::from_id_salt("sc_agent_model").width(140.0).truncate().selected_text(cur).show_ui(ui, |ui| {
- for m in &list {
- let row = ui.selectable_label(m.id == app.agent_chat.model, &m.name);
- let row = if m.description.is_empty() { row } else { row.on_hover_text(&m.description) };
- crate::scenario::publish_handle(&format!("agent_chat:model:{}", m.id), row.rect.center());
- if row.clicked() {
- pick = Some(m.id.clone());
- }
- }
- });
- crate::scenario::publish_handle("agent_chat:model", r.response.rect.center());
- r.response.on_hover_text(tr("ui.agent_chat_model_tip"));
+ let r = ui
+ .allocate_ui(vec2(t.form_label_width, t.control_height), |ui| {
+ ui_kit::dropdown_menu(ui, "sc_agent_model", &cur, |ui| {
+ for m in &list {
+ let row = ui_kit::list_picker(ui, &m.id, &m.name, m.id == app.agent_chat.model);
+ let row = if m.description.is_empty() { row } else { row.on_hover_text(&m.description) };
+ crate::scenario::publish_handle(&format!("agent_chat:model:{}", m.id), row.rect.center());
+ if row.clicked() {
+ pick = Some(m.id.clone());
+ }
+ }
+ })
+ })
+ .inner;
+ crate::scenario::publish_handle("agent_chat:model", r.rect.center());
+ r.on_hover_text(tr("ui.agent_chat_model_tip"));
if let Some(m) = pick {
set_model(app, &m);
}
@@ -830,7 +813,6 @@ fn switcher(app: &mut SolveApp, ui: &mut egui::Ui) {
/// Before the first connection: what's installed, how to install the rest, and Add agent.
#[cfg(not(target_arch = "wasm32"))]
fn picker(app: &mut SolveApp, ui: &mut egui::Ui) {
- let t = Tokens::get();
let open = app.agent_chat.picking.unwrap_or(!app.agent_chat.state().running() && app.agent_chat.items.is_empty());
if !open {
return;
@@ -838,33 +820,23 @@ fn picker(app: &mut SolveApp, ui: &mut egui::Ui) {
let all = agents::entries(app);
let current = agents::current(app);
ui.horizontal(|ui| {
- ui.label(RichText::new(tr("ui.agent_chat_pick")).semibold().color(crate::theme::Tokens::get().text));
+ ui_kit::inline_text(ui, tr("ui.agent_chat_pick"));
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
let refreshing = app.agent_chat.detecting.is_some();
- if ui.add_enabled(!refreshing, egui::Button::new(tr("ui.agent_chat_refresh")).small()).clicked() {
+ if ui_kit::enabled_button(ui, tr("ui.agent_chat_refresh"), !refreshing).clicked() {
refresh(app, ui.ctx());
}
- if ui.small_button(tr("ui.ai_add_agent")).clicked() {
+ if ui_kit::small_button(ui, tr("ui.ai_add_agent")).clicked() {
super::settings::open_add(app);
}
});
});
if app.agent_chat.detecting.is_some() {
- ui.label(RichText::new(tr("ui.agent_chat_detecting")).color(t.text_dim));
+ ui_kit::note(ui, "detecting", tr("ui.agent_chat_detecting"));
}
for e in &all {
let selected = current.as_ref().is_some_and(|c| c.id == e.id);
- let fill = if selected { t.accent_soft } else { Color32::TRANSPARENT };
- let r = egui::Frame::NONE.fill(fill).corner_radius(5.0).inner_margin(egui::Margin::symmetric(6, 3)).show(ui, |ui| {
- ui.set_width(ui.available_width());
- ui.horizontal(|ui| {
- kind_icon(ui, e.kind);
- ui.label(RichText::new(&e.name).semibold().color(t.text));
- ui.label(RichText::new(e.detail()).color(t.text_dim).size(crate::theme::Tokens::get().font_small));
- ui.with_layout(Layout::right_to_left(Align::Center), |ui| login_chip(ui, e.login));
- });
- });
- let resp = ui.interact(r.response.rect, Id::new(("sc_agent_pick", &e.id)), Sense::click());
+ let resp = ui_kit::list_picker(ui, &e.id, &e.name, selected).on_hover_text(format!("{} {}", e.detail(), e.login));
crate::scenario::publish_handle(&format!("agent_chat:pick:{}", e.id), resp.rect.center());
if resp.clicked() {
app.agent_chat.agent_id = Some(e.id.clone());
@@ -873,78 +845,59 @@ fn picker(app: &mut SolveApp, ui: &mut egui::Ui) {
let missing: Vec<discover::Missing> = app.agent_chat.detection.as_ref().map(|d| d.missing.clone()).unwrap_or_default();
if !missing.is_empty() {
let heading = if all.is_empty() { tr("ui.agent_chat_none_found") } else { tr("ui.agent_chat_not_installed") };
- egui::CollapsingHeader::new(RichText::new(heading).color(t.text_dim)).id_salt("sc_agent_missing").default_open(all.is_empty()).show(
- ui,
- |ui| {
- for m in missing {
- ui.horizontal(|ui| {
- ui.label(RichText::new(m.name).semibold().color(crate::theme::Tokens::get().text));
- if ui.small_button(tr("ui.agent_chat_copy")).on_hover_text(m.install).clicked() {
- ui.ctx().copy_text(m.install.to_string());
- }
- });
- ui.add(
- egui::Label::new(RichText::new(m.install).monospace().size(crate::theme::Tokens::get().font_small).color(t.text_dim))
- .selectable(true)
- .wrap(),
- );
- }
- },
- );
+ ui_kit::section(ui, "sc_agent_missing", heading, all.is_empty(), |ui| {
+ for m in missing {
+ ui.horizontal(|ui| {
+ ui_kit::inline_text(ui, m.name);
+ if ui_kit::small_button(ui, tr("ui.agent_chat_copy")).on_hover_text(m.install).clicked() {
+ ui.ctx().copy_text(m.install.to_string());
+ }
+ });
+ ui_kit::text_block(ui, m.name, m.install, false);
+ }
+ });
}
}
#[cfg(not(target_arch = "wasm32"))]
fn auth_box(app: &mut SolveApp, ui: &mut egui::Ui) {
- let t = Tokens::get();
- egui::Frame::group(ui.style()).stroke(Stroke::new(1.0, t.warning)).show(ui, |ui| {
+ ui_kit::section(ui, "authentication", tr("ui.agent_chat_auth_title"), true, |ui| {
ui.set_width(ui.available_width());
- ui.label(RichText::new(tr("ui.agent_chat_auth_title")).semibold().color(crate::theme::Tokens::get().text));
- ui.label(RichText::new(tr("ui.agent_chat_auth_needed")).color(t.text_dim));
+ ui_kit::note(ui, "auth_needed", tr("ui.agent_chat_auth_needed"));
let methods = app.agent_chat.auth.clone();
let base = app.agent_chat.argv.iter().map(|a| quote(a)).collect::<Vec<_>>().join(" ");
if methods.is_empty() {
- ui.label(tr("ui.agent_chat_auth_none"));
+ ui_kit::note(ui, "auth_none", tr("ui.agent_chat_auth_none"));
}
for m in methods {
- ui.add_space(4.0);
+ ui.add_space(crate::theme::Tokens::get().space_4);
let desc = m.description.trim();
- ui.label(
- RichText::new(if desc.is_empty() || desc == m.name { m.name.clone() } else { format!("{} — {desc}", m.name) })
- .semibold()
- .color(crate::theme::Tokens::get().text),
- );
+ ui_kit::text_block(ui, &m.id, &if desc.is_empty() || desc == m.name { m.name.clone() } else { format!("{} — {desc}", m.name) }, false);
match &m.kind {
acp::AuthKind::Terminal { args, .. } => {
- ui.label(tr("ui.agent_chat_auth_terminal"));
+ ui_kit::note(ui, "terminal", tr("ui.agent_chat_auth_terminal"));
let cmd = format!("{base} {}", args.iter().map(|a| quote(a)).collect::<Vec<_>>().join(" "));
ui.horizontal_wrapped(|ui| {
- egui::Frame::NONE.fill(t.toolbar).corner_radius(4.0).inner_margin(egui::Margin::symmetric(6, 3)).show(ui, |ui| {
- ui.add(
- egui::Label::new(RichText::new(&cmd).monospace().size(crate::theme::Tokens::get().font_small))
- .selectable(true)
- .wrap(),
- );
- });
- if ui.small_button(tr("ui.agent_chat_copy")).clicked() {
+ ui_kit::text_block(ui, "auth_command", &cmd, false);
+ if ui_kit::small_button(ui, tr("ui.agent_chat_copy")).clicked() {
ui.ctx().copy_text(cmd.clone());
}
});
}
acp::AuthKind::Agent => {
- let b = ui.button(trf("ui.agent_chat_auth_agent", &[("name", &m.name)]));
+ let b = ui_kit::secondary_button(ui, trf("ui.agent_chat_auth_agent", &[("name", &m.name)]));
crate::scenario::publish_handle(&format!("agent_chat:auth:{}", m.id), b.rect.center());
if b.clicked() {
app.agent_chat.authenticate(&m.id);
}
}
acp::AuthKind::EnvVar { vars } => {
- ui.label(trf("ui.agent_chat_auth_env", &[("vars", &vars.join(", "))]));
+ ui_kit::text_block(ui, "auth_environment", &trf("ui.agent_chat_auth_env", &[("vars", &vars.join(", "))]), false);
}
}
}
- ui.add_space(4.0);
- if ui.button(tr("ui.agent_chat_auth_retry")).clicked() {
+ ui.add_space(crate::theme::Tokens::get().space_4);
+ if ui_kit::secondary_button(ui, tr("ui.agent_chat_auth_retry")).clicked() {
connect(app, ui.ctx());
}
});
@@ -1013,9 +966,11 @@ fn conversation(app: &mut SolveApp, ui: &mut egui::Ui) {
None => {
ui.horizontal_wrapped(|ui| {
for o in options {
- let b = egui::Button::new(&o.name);
- let b = if o.kind.starts_with("allow") { b.fill(t.accent_soft) } else { b };
- let r = ui.add(b);
+ let r = if o.kind.starts_with("allow") {
+ ui_kit::primary_button(ui, &o.name)
+ } else {
+ ui_kit::secondary_button(ui, &o.name)
+ };
crate::scenario::publish_handle(&format!("agent_chat:permission:{}", o.id), r.rect.center());
if r.clicked() {
answer = Some((n, Some(o.id.clone())));
@@ -1040,9 +995,10 @@ fn conversation(app: &mut SolveApp, ui: &mut egui::Ui) {
}
None => {
ui.horizontal(|ui| {
- let allow = ui.add(egui::Button::new(tr("ui.agent_chat_allow")).fill(t.accent_soft));
- let always = ui.button(tr("ui.ai_always_allow")).on_hover_text(trf("ui.ai_always_allow_tip", &[("tool", tool)]));
- let deny = ui.button(tr("ui.agent_chat_deny"));
+ let allow = ui_kit::primary_button(ui, tr("ui.agent_chat_allow"));
+ let always = ui_kit::secondary_button(ui, tr("ui.ai_always_allow"))
+ .on_hover_text(trf("ui.ai_always_allow_tip", &[("tool", tool)]));
+ let deny = ui_kit::secondary_button(ui, tr("ui.agent_chat_deny"));
crate::scenario::publish_handle("agent_chat:allow", allow.rect.center());
crate::scenario::publish_handle("agent_chat:always", always.rect.center());
crate::scenario::publish_handle("agent_chat:deny", deny.rect.center());
@@ -1067,7 +1023,7 @@ fn conversation(app: &mut SolveApp, ui: &mut egui::Ui) {
if *undone {
ui.label(RichText::new(tr("ui.agent_chat_undone")).color(t.text_dim).size(crate::theme::Tokens::get().font_caption));
} else if Arc::ptr_eq(doc, &current_doc) {
- let b = ui.button(tr("ui.agent_chat_undo_changes")).on_hover_text(tr("ui.ai_undo_tip"));
+ let b = ui_kit::secondary_button(ui, tr("ui.agent_chat_undo_changes")).on_hover_text(tr("ui.ai_undo_tip"));
crate::scenario::publish_handle("agent_chat:undo", b.rect.center());
if b.clicked() {
undo = Some(n);
@@ -1097,17 +1053,13 @@ fn conversation(app: &mut SolveApp, ui: &mut egui::Ui) {
let tag = if stopped && !busy { "ui.agent_chat_queued_stopped" } else { "ui.agent_chat_queued" };
ui.label(RichText::new(tr(tag)).color(t.accent).semibold().size(crate::theme::Tokens::get().font_small));
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
- let x = ui
- .add(egui::Button::new(RichText::new("×").size(crate::theme::Tokens::get().font_heading)).frame(false))
- .on_hover_text(tr("ui.agent_chat_remove"));
+ let x = ui_kit::small_button(ui, "×").on_hover_text(tr("ui.agent_chat_remove"));
crate::scenario::publish_handle(&format!("agent_chat:pending_remove:{n}"), x.rect.center());
if x.clicked() {
remove = Some(n);
}
if editing.as_ref().is_none_or(|(i, _)| *i != n) {
- let e = ui.add(
- egui::Button::new(RichText::new(tr("ui.agent_chat_edit")).size(crate::theme::Tokens::get().font_caption)).frame(false),
- );
+ let e = ui_kit::small_button(ui, tr("ui.agent_chat_edit"));
crate::scenario::publish_handle(&format!("agent_chat:pending_edit:{n}"), e.rect.center());
if e.clicked() {
start_edit = Some((n, p.text.clone()));
@@ -1117,13 +1069,13 @@ fn conversation(app: &mut SolveApp, ui: &mut egui::Ui) {
});
match (&editing, edit_buf.as_mut()) {
(Some((i, _)), Some(buf)) if *i == n => {
- let te = ui.add(egui::TextEdit::multiline(buf).desired_rows(2).desired_width(f32::INFINITY));
+ let te = ui_kit::message_field(ui, Id::new(("sc_agent_pending_input", n)), buf, "");
crate::scenario::publish_rect("agent_chat:pending_input", te.rect);
ui.horizontal(|ui| {
- if ui.button(tr("ui.agent_chat_save")).clicked() {
+ if ui_kit::secondary_button(ui, tr("ui.agent_chat_save")).clicked() {
edit_done = Some((n, Some(buf.clone())));
}
- if ui.button(tr("ui.agent_chat_cancel")).clicked() {
+ if ui_kit::secondary_button(ui, tr("ui.agent_chat_cancel")).clicked() {
edit_done = Some((n, None));
}
});
@@ -1143,11 +1095,11 @@ fn conversation(app: &mut SolveApp, ui: &mut egui::Ui) {
if !app.agent_chat.pending.is_empty() && editing.is_none() {
ui.horizontal(|ui| {
if busy {
- let b = ui.button(tr("ui.agent_chat_send_now")).on_hover_text(tr("ui.agent_chat_send_now_tip"));
+ let b = ui_kit::secondary_button(ui, tr("ui.agent_chat_send_now")).on_hover_text(tr("ui.agent_chat_send_now_tip"));
crate::scenario::publish_handle("agent_chat:send_now", b.rect.center());
send_now_clicked = b.clicked();
} else {
- let b = ui.add(egui::Button::new(tr("ui.agent_chat_send")).fill(t.accent_soft));
+ let b = ui_kit::primary_button(ui, tr("ui.agent_chat_send"));
crate::scenario::publish_handle("agent_chat:send_queue", b.rect.center());
send_queue_clicked = b.clicked();
}
@@ -1359,12 +1311,11 @@ fn chip(ui: &mut egui::Ui, thumbs: &mut std::collections::HashMap<u64, egui::Tex
/// the clipboard's picture.
#[cfg(not(target_arch = "wasm32"))]
fn add_menu(app: &mut SolveApp, ui: &mut egui::Ui) {
- let t = Tokens::get();
let (mut choose, mut paste) = (false, false);
- let r = ui.menu_button(RichText::new("+").semibold().size(t.font_heading), |ui| {
- let a = ui.button(tr("ui.agent_chat_add_file"));
+ let r = ui_kit::action_menu(ui, "+", |ui| {
+ let a = ui_kit::secondary_button(ui, tr("ui.agent_chat_add_file"));
crate::scenario::publish_handle("agent_chat:add_file", a.rect.center());
- let b = ui.button(tr("ui.agent_chat_paste_picture"));
+ let b = ui_kit::secondary_button(ui, tr("ui.agent_chat_paste_picture"));
crate::scenario::publish_handle("agent_chat:paste_picture", b.rect.center());
if a.clicked() {
choose = true;
diff --git a/crates/ui-egui/src/agent_chat/settings.rs b/crates/ui-egui/src/agent_chat/settings.rs
index b9d3463361..5e79c96cf3 100644
--- a/crates/ui-egui/src/agent_chat/settings.rs
+++ b/crates/ui-egui/src/agent_chat/settings.rs
@@ -3,12 +3,9 @@
//! and the panel. Plus the Add agent dialog: an installed ACP agent, a custom command, or an
//! OpenAI-compatible endpoint (whose key goes to the system keychain).
-use crate::fonts::RichTextExt as _;
-use egui::{RichText, Stroke};
-
use super::agents::{self, AgentConfig, Kind, Mode};
use super::*;
-use crate::theme::Tokens;
+use crate::ui_kit;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum AddKind {
@@ -89,52 +86,36 @@ fn start_test(app: &SolveApp, e: &agents::Entry, key: Option<String>) -> Test {
Test::Running(rx)
}
-fn test_line(ui: &mut egui::Ui, t: &Option<&Test>) {
- let tk = Tokens::get();
- match t {
+fn test_line(ui: &mut egui::Ui, test: &Option<&Test>) {
+ match test {
Some(Test::Running(_)) => {
- ui.label(RichText::new(tr("ui.ai_testing")).color(tk.text_dim).size(crate::theme::Tokens::get().font_small));
+ ui_kit::note(ui, "testing", tr("ui.ai_testing"));
}
- Some(Test::Done(Ok(m))) => {
- ui.label(RichText::new(m.clone()).color(tk.accent).size(crate::theme::Tokens::get().font_small));
+ Some(Test::Done(Ok(message))) => {
+ ui_kit::text_block(ui, "test_ok", message, false);
}
- Some(Test::Done(Err(e))) => {
- ui.add(egui::Label::new(RichText::new(e).color(tk.error).size(crate::theme::Tokens::get().font_small)).wrap());
+ Some(Test::Done(Err(error))) => {
+ ui_kit::text_block(ui, "test_error", error, true);
}
None => {}
}
}
-fn section(ui: &mut egui::Ui, title: &str) {
- ui.add_space(10.0);
- ui.label(RichText::new(title).semibold().color(crate::theme::Tokens::get().text).size(crate::theme::Tokens::get().font_button));
- ui.separator();
-}
-
-fn note(ui: &mut egui::Ui, text: &str) {
- let t = Tokens::get();
- ui.add(egui::Label::new(RichText::new(text).size(crate::theme::Tokens::get().font_small).color(t.text_dim)).wrap());
-}
-
/// The AI page of Settings.
pub fn page(app: &mut SolveApp, ui: &mut egui::Ui) {
- let t = Tokens::get();
- let r =
- ui.checkbox(&mut app.preferences.ai_features, RichText::new(tr("ui.ai_show_features")).semibold().color(crate::theme::Tokens::get().text));
+ let r = ui_kit::checkbox(ui, tr("ui.ai_show_features"), &mut app.preferences.ai_features);
crate::scenario::publish_handle("prefs:ai_features", r.rect.center());
- note(ui, tr("ui.ai_show_features_note"));
+ ui_kit::note(ui, "features", tr("ui.ai_show_features_note"));
if cfg!(target_arch = "wasm32") {
- note(ui, tr("ui.agent_chat_desktop_only"));
+ ui_kit::note(ui, "desktop", tr("ui.agent_chat_desktop_only"));
return;
}
if !app.preferences.ai_features {
return;
}
- ui.add_enabled_ui(true, |ui| {
- let r = ui.checkbox(&mut app.preferences.ai_toolbar_button, tr("ui.ai_toolbar_button"));
- crate::scenario::publish_handle("prefs:ai_toolbar_button", r.rect.center());
- });
- note(ui, tr("ui.ai_toolbar_button_note"));
+ let r = ui_kit::checkbox(ui, tr("ui.ai_toolbar_button"), &mut app.preferences.ai_toolbar_button);
+ crate::scenario::publish_handle("prefs:ai_toolbar_button", r.rect.center());
+ ui_kit::note(ui, "toolbar", tr("ui.ai_toolbar_button_note"));
#[cfg(not(target_arch = "wasm32"))]
{
if app.agent_chat.detection.is_none() && app.agent_chat.detecting.is_none() {
@@ -142,153 +123,139 @@ pub fn page(app: &mut SolveApp, ui: &mut egui::Ui) {
}
agents_section(app, ui);
}
- section(ui, tr("ui.ai_permissions"));
- for m in Mode::ALL {
- let r = ui.radio_value(&mut app.preferences.ai_permissions, m, m.label());
- crate::scenario::publish_handle(&format!("prefs:ai_mode:{}", m.id()), r.rect.center());
- note(
- ui,
- tr(match m {
- Mode::Ask => "ui.ai_mode_ask_note",
- Mode::Edits => "ui.ai_mode_edits_note",
- Mode::All => "ui.ai_mode_all_note",
- }),
- );
- }
- if app.preferences.ai_permissions == Mode::All {
- egui::Frame::NONE.stroke(Stroke::new(1.0, t.warning)).corner_radius(4.0).inner_margin(egui::Margin::same(6)).show(ui, |ui| {
- ui.add(egui::Label::new(RichText::new(tr("ui.ai_mode_all_warning")).color(t.warning)).wrap());
- });
- }
- note(ui, tr("ui.ai_modes_scope"));
- // "Always allow" answers.
- let remembered: Vec<(String, Vec<String>)> =
- app.preferences.agent_always_allow.iter().filter(|(_, v)| !v.is_empty()).map(|(k, v)| (k.clone(), v.clone())).collect();
- ui.add_space(4.0);
- ui.label(RichText::new(tr("ui.ai_always_allowed")).semibold().color(crate::theme::Tokens::get().text));
- if remembered.is_empty() {
- note(ui, tr("ui.ai_always_allowed_none"));
- }
- let names: std::collections::HashMap<String, String> = agents::entries(app).into_iter().map(|e| (e.id, e.name)).collect();
- for (agent, tools) in remembered {
- ui.horizontal_wrapped(|ui| {
- ui.label(names.get(&agent).cloned().unwrap_or_else(|| agent.clone()));
- for tool in &tools {
- ui.label(RichText::new(tool).monospace().size(crate::theme::Tokens::get().font_small).color(t.text_dim));
+ ui_kit::section(ui, "permissions", tr("ui.ai_permissions"), true, |ui| {
+ for mode in Mode::ALL {
+ let r = ui_kit::list_picker(ui, mode.id(), mode.label(), app.preferences.ai_permissions == mode);
+ crate::scenario::publish_handle(&format!("prefs:ai_mode:{}", mode.id()), r.rect.center());
+ if r.clicked() {
+ app.preferences.ai_permissions = mode;
}
- if ui.small_button(tr("ui.ai_reset")).clicked() {
- app.preferences.agent_always_allow.remove(&agent);
+ ui_kit::note(
+ ui,
+ mode.id(),
+ tr(match mode {
+ Mode::Ask => "ui.ai_mode_ask_note",
+ Mode::Edits => "ui.ai_mode_edits_note",
+ Mode::All => "ui.ai_mode_all_note",
+ }),
+ );
+ }
+ if app.preferences.ai_permissions == Mode::All {
+ ui_kit::text_block(ui, "permissions_warning", tr("ui.ai_mode_all_warning"), true);
+ }
+ ui_kit::note(ui, "scope", tr("ui.ai_modes_scope"));
+ ui_kit::section(ui, "always_allowed", tr("ui.ai_always_allowed"), true, |ui| {
+ let remembered: Vec<_> =
+ app.preferences.agent_always_allow.iter().filter(|(_, v)| !v.is_empty()).map(|(k, v)| (k.clone(), v.clone())).collect();
+ if remembered.is_empty() {
+ ui_kit::note(ui, "none", tr("ui.ai_always_allowed_none"));
+ }
+ let names: std::collections::HashMap<_, _> = agents::entries(app).into_iter().map(|e| (e.id, e.name)).collect();
+ for (agent, tools) in remembered {
+ ui_kit::label_actions(ui, names.get(&agent).unwrap_or(&agent), |ui| {
+ if ui_kit::small_button(ui, tr("ui.ai_reset")).clicked() {
+ app.preferences.agent_always_allow.remove(&agent);
+ }
+ });
+ ui_kit::text_block(ui, &agent, &tools.join(", "), false);
}
});
- }
- section(ui, tr("ui.ai_panel"));
- egui::Grid::new("sc_ai_panel_grid").num_columns(2).spacing([16.0, 6.0]).show(ui, |ui| {
- ui.label(tr("ui.agent_chat_side"));
- ui.horizontal(|ui| {
+ });
+ ui_kit::section(ui, "panel", tr("ui.ai_panel"), true, |ui| {
+ ui_kit::row(ui, tr("ui.agent_chat_side"), |ui| {
let p = &mut app.preferences;
- let (left, popped) = (p.agent_chat_side == "left", p.agent_chat_popped);
- if ui.radio(left && !popped, tr("ui.agent_chat_left")).clicked() {
- p.agent_chat_side = "left".into();
- p.agent_chat_popped = false;
- }
- if ui.radio(!left && !popped, tr("ui.agent_chat_right")).clicked() {
- p.agent_chat_side = "right".into();
- p.agent_chat_popped = false;
- }
- #[cfg(not(target_arch = "wasm32"))]
- if ui.radio(popped, tr("ui.agent_chat_own_window")).on_hover_text(tr("ui.agent_chat_pop_out")).clicked() {
- p.agent_chat_popped = true;
+ let mut selected = if p.agent_chat_popped { 2 } else { usize::from(p.agent_chat_side != "left") };
+ let options = [tr("ui.agent_chat_left"), tr("ui.agent_chat_right"), tr("ui.agent_chat_own_window")];
+ if ui_kit::segmented(ui, &mut selected, &options) {
+ p.agent_chat_popped = selected == 2;
+ if selected < 2 {
+ p.agent_chat_side = if selected == 0 { "left" } else { "right" }.into();
+ }
}
});
- ui.end_row();
- ui.label(tr("ui.agent_chat_turn_limit"));
- ui.add(egui::DragValue::new(&mut app.preferences.agent_chat_turn_limit).range(1..=200));
- ui.end_row();
+ ui_kit::row(ui, tr("ui.agent_chat_turn_limit"), |ui| {
+ ui_kit::number_field(ui, &mut app.preferences.agent_chat_turn_limit, 1..=200, 1.0, "");
+ });
+ ui_kit::note(ui, "privacy", tr("ui.agent_chat_privacy_note"));
});
- ui.add_space(6.0);
- note(ui, tr("ui.agent_chat_privacy_note"));
}
/// The agents: found and added, with Test, Default, a permission override and Remove.
#[cfg(not(target_arch = "wasm32"))]
fn agents_section(app: &mut SolveApp, ui: &mut egui::Ui) {
- let t = Tokens::get();
- section(ui, tr("ui.ai_agents"));
for test in app.agent_chat.settings.tests.values_mut() {
test.poll();
}
let all = agents::entries(app);
let d = &app.preferences.agent_default;
let default = if all.iter().any(|e| &e.id == d) { Some(d.clone()) } else { all.first().map(|e| e.id.clone()) };
- if app.agent_chat.detecting.is_some() {
- ui.label(RichText::new(tr("ui.agent_chat_detecting")).color(t.text_dim));
- } else if all.is_empty() {
- note(ui, tr("ui.agent_chat_none_found"));
- }
let mut remove: Option<String> = None;
let mut test: Option<agents::Entry> = None;
- for e in &all {
- egui::Frame::NONE.stroke(Stroke::new(1.0, t.border)).corner_radius(5.0).inner_margin(egui::Margin::symmetric(8, 5)).show(ui, |ui| {
- ui.set_width(ui.available_width());
- ui.horizontal(|ui| {
- super::panel::kind_icon(ui, e.kind);
- ui.label(RichText::new(&e.name).semibold().color(crate::theme::Tokens::get().text));
- ui.label(RichText::new(e.detail()).color(t.text_dim).size(crate::theme::Tokens::get().font_small));
+ ui_kit::section(ui, "agents", tr("ui.ai_agents"), true, |ui| {
+ if app.agent_chat.detecting.is_some() {
+ ui_kit::note(ui, "detecting", tr("ui.agent_chat_detecting"));
+ } else if all.is_empty() {
+ ui_kit::note(ui, "none", tr("ui.agent_chat_none_found"));
+ }
+ for e in &all {
+ ui_kit::section(ui, &e.id, &e.name, true, |ui| {
+ ui_kit::text_block(ui, "detail", &e.detail(), false);
super::panel::login_chip(ui, e.login);
if !e.found {
- ui.label(RichText::new(tr("ui.ai_added")).color(t.text_dim).size(crate::theme::Tokens::get().font_small));
- }
- });
- ui.horizontal(|ui| {
- let is_default = default.as_deref() == Some(e.id.as_str());
- if ui.radio(is_default, tr("ui.ai_default")).clicked() {
- app.preferences.agent_default = e.id.clone();
- }
- let b = ui.small_button(tr("ui.ai_test"));
- crate::scenario::publish_handle(&format!("prefs:ai_test:{}", e.id), b.rect.center());
- if b.on_hover_text(tr(if e.kind == Kind::Acp { "ui.ai_test_acp_tip" } else { "ui.ai_test_api_tip" })).clicked() {
- test = Some(e.clone());
+ ui_kit::note(ui, "added", tr("ui.ai_added"));
}
- // Its own permission mode, or the global one.
- let cur = app.preferences.agent_permissions.get(&e.id).copied();
- let shown = cur.map_or_else(|| tr("ui.ai_mode_global").to_string(), |m| m.label().to_string());
- let mut pick: Option<Option<Mode>> = None;
- egui::ComboBox::from_id_salt(("sc_ai_mode", &e.id)).width(150.0).selected_text(shown).show_ui(ui, |ui| {
- if ui.selectable_label(cur.is_none(), tr("ui.ai_mode_global")).clicked() {
- pick = Some(None);
+ ui.horizontal_wrapped(|ui| {
+ if ui_kit::list_picker(ui, &e.id, tr("ui.ai_default"), default.as_deref() == Some(e.id.as_str())).clicked() {
+ app.preferences.agent_default = e.id.clone();
}
- for m in Mode::ALL {
- if ui.selectable_label(cur == Some(m), m.label()).clicked() {
- pick = Some(Some(m));
+ });
+ ui_kit::row(ui, tr("ui.ai_permissions"), |ui| {
+ let cur = app.preferences.agent_permissions.get(&e.id).copied();
+ let shown = cur.map_or_else(|| tr("ui.ai_mode_global").to_string(), |m| m.label().to_string());
+ let mut pick: Option<Option<Mode>> = None;
+ ui_kit::dropdown_menu(ui, ("sc_ai_mode", &e.id), &shown, |ui| {
+ if ui_kit::list_picker(ui, "global", tr("ui.ai_mode_global"), cur.is_none()).clicked() {
+ pick = Some(None);
+ }
+ for m in Mode::ALL {
+ if ui_kit::list_picker(ui, m.id(), m.label(), cur == Some(m)).clicked() {
+ pick = Some(Some(m));
+ }
+ }
+ });
+ match pick {
+ Some(Some(m)) => {
+ app.preferences.agent_permissions.insert(e.id.clone(), m);
}
+ Some(None) => {
+ app.preferences.agent_permissions.remove(&e.id);
+ }
+ None => {}
}
});
- match pick {
- Some(Some(m)) => {
- app.preferences.agent_permissions.insert(e.id.clone(), m);
+ ui.horizontal_wrapped(|ui| {
+ let b = ui_kit::secondary_button(ui, tr("ui.ai_test"));
+ crate::scenario::publish_handle(&format!("prefs:ai_test:{}", e.id), b.rect.center());
+ if b.on_hover_text(tr(if e.kind == Kind::Acp { "ui.ai_test_acp_tip" } else { "ui.ai_test_api_tip" })).clicked() {
+ test = Some(e.clone());
}
- Some(None) => {
- app.preferences.agent_permissions.remove(&e.id);
+ if !e.found && ui_kit::secondary_button(ui, tr("ui.ai_remove")).clicked() {
+ remove = Some(e.id.clone());
}
- None => {}
- }
- if !e.found && ui.small_button(tr("ui.ai_remove")).clicked() {
- remove = Some(e.id.clone());
- }
+ });
+ test_line(ui, &app.agent_chat.settings.tests.get(&e.id));
});
- test_line(ui, &app.agent_chat.settings.tests.get(&e.id));
- });
- ui.add_space(3.0);
- }
- ui.horizontal(|ui| {
- let b = ui.button(tr("ui.ai_add_agent"));
- crate::scenario::publish_handle("prefs:ai_add", b.rect.center());
- if b.clicked() {
- open_add(app);
- }
- if ui.add_enabled(app.agent_chat.detecting.is_none(), egui::Button::new(tr("ui.agent_chat_refresh"))).clicked() {
- refresh(app, &ui.ctx().clone());
}
+ ui.horizontal_wrapped(|ui| {
+ let b = ui_kit::secondary_button(ui, tr("ui.ai_add_agent"));
+ crate::scenario::publish_handle("prefs:ai_add", b.rect.center());
+ if b.clicked() {
+ open_add(app);
+ }
+ if ui_kit::enabled_button(ui, tr("ui.agent_chat_refresh"), app.agent_chat.detecting.is_none()).clicked() {
+ refresh(app, &ui.ctx().clone());
+ }
+ });
});
if let Some(e) = test {
let key = if e.key { app.services.secrets.as_ref().and_then(|s| s.get(&e.id).ok().flatten()) } else { None };
@@ -324,155 +291,122 @@ pub fn dialog(app: &mut SolveApp, ctx: &egui::Context) {
let mut open = true;
let mut add = false;
let mut test = false;
- let t = Tokens::get();
- egui::Window::new(tr("ui.ai_add_agent_title"))
- .id(egui::Id::new("sc_ai_add"))
- .collapsible(false)
- .resizable(false)
- .default_width(460.0)
- .pivot(egui::Align2::CENTER_CENTER)
- .default_pos(ctx.content_rect().center())
- .open(&mut open)
- .order(egui::Order::Foreground)
- .show(ctx, |ui| {
+ let (closed, action) = ui_kit::Prompt::new(egui::Id::new("sc_ai_add"), "settings", tr("ui.ai_add_agent_title"))
+ .cards(2.0)
+ .fields()
+ .actions(tr("ui.ai_add"), "Cancel", None)
+ .show(ctx, true, |ui| {
let Some(s) = app.agent_chat.settings.add.as_mut() else { return };
if let Some(test) = s.test.as_mut() {
test.poll();
}
- ui.horizontal(|ui| {
- for (k, label) in
- [(AddKind::Installed, "ui.ai_add_installed"), (AddKind::Custom, "ui.ai_add_custom"), (AddKind::Api, "ui.ai_add_api")]
+ let kinds = [(AddKind::Installed, "ui.ai_add_installed"), (AddKind::Custom, "ui.ai_add_custom"), (AddKind::Api, "ui.ai_add_api")];
+ ui_kit::row(ui, tr("ui.ai_preset"), |ui| {
+ let mut selected = kinds.iter().position(|(k, _)| *k == s.kind).unwrap_or(0);
+ let labels = kinds.map(|(_, key)| tr(key));
+ if ui_kit::segmented_compact(ui, &mut selected, &labels)
+ && let Some((kind, _)) = kinds.get(selected)
{
- let r = ui.selectable_value(&mut s.kind, k, tr(label));
- crate::scenario::publish_handle(&format!("ai_add:{label}"), r.rect.center());
- if r.clicked() {
- s.error = None;
- s.test = None;
- s.command.clear();
- s.name.clear();
- if k == AddKind::Api
- && let Some((name, url, _)) = agents::API_PRESETS.get(s.preset)
- {
- s.name = name.to_string();
- s.base_url = url.to_string();
- }
+ s.kind = *kind;
+ s.error = None;
+ s.test = None;
+ }
+ for (_, key) in kinds {
+ if let Some(at) = crate::scenario::handle_at(&format!("dialog:{}:{}", tr("ui.ai_preset"), tr(key))) {
+ crate::scenario::publish_handle(&format!("ai_add:{key}"), at);
}
}
});
- ui.separator();
- egui::Grid::new("sc_ai_add_grid").num_columns(2).spacing([12.0, 8.0]).show(ui, |ui| match s.kind {
+ match s.kind {
AddKind::Installed => {
- ui.label(tr("ui.agent_chat_pick"));
- if found.is_empty() {
- ui.label(RichText::new(tr("ui.agent_chat_none_found_short")).color(t.text_dim));
- } else {
- let sel = found.get(s.installed).map(|e| e.name.clone()).unwrap_or_default();
- egui::ComboBox::from_id_salt("sc_ai_add_installed").width(260.0).selected_text(sel).show_ui(ui, |ui| {
- for (i, e) in found.iter().enumerate() {
- if ui.selectable_value(&mut s.installed, i, format!("{} {}", e.name, e.detail())).clicked() {
- s.command = e.argv.iter().map(|a| super::panel::quote(a)).collect::<Vec<_>>().join(" ");
- s.name = format!("{} ({})", e.name, tr("ui.ai_copy_suffix"));
+ ui_kit::row(ui, tr("ui.agent_chat_pick"), |ui| {
+ if found.is_empty() {
+ ui_kit::inline_text(ui, tr("ui.agent_chat_none_found_short"));
+ } else {
+ let sel = found.get(s.installed).map(|e| e.name.clone()).unwrap_or_default();
+ ui_kit::dropdown_menu(ui, "sc_ai_add_installed", &sel, |ui| {
+ for (i, e) in found.iter().enumerate() {
+ if ui_kit::list_picker(ui, &e.id, &format!("{} {}", e.name, e.detail()), s.installed == i).clicked() {
+ s.installed = i;
+ s.command = e.argv.iter().map(|a| super::panel::quote(a)).collect::<Vec<_>>().join(" ");
+ s.name = format!("{} ({})", e.name, tr("ui.ai_copy_suffix"));
+ }
}
- }
- });
- }
- ui.end_row();
+ });
+ }
+ });
if s.command.is_empty()
&& let Some(e) = found.get(s.installed)
{
s.command = e.argv.iter().map(|a| super::panel::quote(a)).collect::<Vec<_>>().join(" ");
s.name = format!("{} ({})", e.name, tr("ui.ai_copy_suffix"));
}
- ui.label(tr("ui.ai_name"));
- ui.add(egui::TextEdit::singleline(&mut s.name).desired_width(300.0));
- ui.end_row();
- ui.label(tr("ui.agent_chat_command"));
- ui.add(egui::TextEdit::singleline(&mut s.command).desired_width(300.0));
- ui.end_row();
- ui.label("");
- ui.add(
- egui::Label::new(
- RichText::new(tr("ui.ai_add_installed_note")).size(crate::theme::Tokens::get().font_small).color(t.text_dim),
- )
- .wrap(),
- );
- ui.end_row();
+ ui_kit::row(ui, tr("ui.ai_name"), |ui| {
+ ui_kit::text_field(ui, &mut s.name, "");
+ });
+ ui_kit::row(ui, tr("ui.agent_chat_command"), |ui| {
+ ui_kit::text_field(ui, &mut s.command, "");
+ });
+ ui_kit::note(ui, "installed", tr("ui.ai_add_installed_note"));
}
AddKind::Custom => {
- ui.label(tr("ui.ai_name"));
- ui.add(egui::TextEdit::singleline(&mut s.name).hint_text("My agent").desired_width(300.0));
- ui.end_row();
- ui.label(tr("ui.agent_chat_command"));
- ui.add(egui::TextEdit::singleline(&mut s.command).hint_text("my-agent --acp").desired_width(300.0));
- ui.end_row();
- ui.label("");
- ui.add(
- egui::Label::new(
- RichText::new(tr("ui.agent_chat_custom_hint")).size(crate::theme::Tokens::get().font_small).color(t.text_dim),
- )
- .wrap(),
- );
- ui.end_row();
+ ui_kit::row(ui, tr("ui.ai_name"), |ui| {
+ ui_kit::text_field(ui, &mut s.name, tr("ui.ai_name_hint"));
+ });
+ ui_kit::row(ui, tr("ui.agent_chat_command"), |ui| {
+ ui_kit::text_field(ui, &mut s.command, tr("ui.ai_command_hint"));
+ });
+ ui_kit::note(ui, "custom", tr("ui.agent_chat_custom_hint"));
}
AddKind::Api => {
- ui.label(tr("ui.ai_preset"));
- let presets: Vec<String> =
- agents::API_PRESETS.iter().map(|p| p.0.to_string()).chain(std::iter::once(tr("ui.ai_custom_url").to_string())).collect();
- let sel = presets.get(s.preset).cloned().unwrap_or_default();
- egui::ComboBox::from_id_salt("sc_ai_add_preset").width(200.0).selected_text(sel).show_ui(ui, |ui| {
- for (i, p) in presets.iter().enumerate() {
- if ui.selectable_value(&mut s.preset, i, p).clicked() {
- if let Some((name, url, _)) = agents::API_PRESETS.get(i) {
- s.base_url = url.to_string();
- s.name = name.to_string();
- } else {
- s.base_url.clear();
+ let presets: Vec<_> = agents::API_PRESETS.iter().map(|p| p.0).chain(std::iter::once(tr("ui.ai_custom_url"))).collect();
+ ui_kit::row(ui, tr("ui.ai_preset"), |ui| {
+ ui_kit::dropdown_menu(ui, "sc_ai_add_preset", presets.get(s.preset).copied().unwrap_or_default(), |ui| {
+ for (index, preset) in presets.iter().enumerate() {
+ if ui_kit::list_picker(ui, preset, preset, s.preset == index).clicked() {
+ s.preset = index;
+ if let Some((name, url, _)) = agents::API_PRESETS.get(index) {
+ s.base_url = url.to_string();
+ s.name = name.to_string();
+ } else {
+ s.base_url.clear();
+ }
}
}
- }
+ });
});
- ui.end_row();
- ui.label(tr("ui.ai_name"));
- ui.add(egui::TextEdit::singleline(&mut s.name).desired_width(300.0));
- ui.end_row();
- ui.label(tr("ui.ai_base_url"));
- ui.add(egui::TextEdit::singleline(&mut s.base_url).hint_text("https://example.com/v1").desired_width(300.0));
- ui.end_row();
- ui.label(tr("ui.ai_model"));
- ui.add(egui::TextEdit::singleline(&mut s.model).hint_text("qwen3:14b").desired_width(300.0));
- ui.end_row();
- ui.label(tr("ui.ai_key"));
- ui.add_enabled(
- has_keychain,
- egui::TextEdit::singleline(&mut s.key).password(true).hint_text(tr("ui.ai_key_hint")).desired_width(300.0),
- );
- ui.end_row();
- ui.label("");
- let note = if has_keychain { tr("ui.ai_key_note") } else { tr("ui.ai_no_keychain") };
- ui.add(egui::Label::new(RichText::new(note).size(crate::theme::Tokens::get().font_small).color(t.text_dim)).wrap());
- ui.end_row();
- ui.label("");
- ui.horizontal(|ui| {
- if ui.button(tr("ui.ai_test")).clicked() {
- test = true;
- }
- test_line(ui, &s.test.as_ref());
+ ui_kit::row(ui, tr("ui.ai_name"), |ui| {
+ ui_kit::text_field(ui, &mut s.name, "");
+ });
+ ui_kit::row(ui, tr("ui.ai_base_url"), |ui| {
+ ui_kit::text_field(ui, &mut s.base_url, tr("ui.ai_url_hint"));
});
- ui.end_row();
+ ui_kit::row(ui, tr("ui.ai_model"), |ui| {
+ ui_kit::text_field(ui, &mut s.model, tr("ui.ai_model_hint"));
+ });
+ ui_kit::row(ui, tr("ui.ai_key"), |ui| {
+ ui.add_enabled_ui(has_keychain, |ui| {
+ let r = ui_kit::password_field(ui, egui::Id::new("sc_ai_add_key"), &mut s.key, tr("ui.ai_key_hint"));
+ crate::scenario::publish_rect("ai_add:key", r.rect);
+ crate::scenario::publish_handle("ai_add:key", r.rect.center());
+ });
+ });
+ ui_kit::note(ui, "keychain", tr(if has_keychain { "ui.ai_key_note" } else { "ui.ai_no_keychain" }));
+ if ui_kit::secondary_button(ui, tr("ui.ai_test")).clicked() {
+ test = true;
+ }
+ test_line(ui, &s.test.as_ref());
}
- });
+ }
if let Some(e) = &s.error {
- ui.label(RichText::new(e).color(t.error));
+ ui_kit::text_block(ui, "add_error", e, true);
}
- ui.separator();
- ui.horizontal(|ui| {
- let b = ui.add(egui::Button::new(tr("ui.ai_add")).fill(t.accent_soft));
- crate::scenario::publish_handle("ai_add:add", b.rect.center());
- if b.clicked() {
- add = true;
- }
- });
});
+ if let Some(rect) = crate::scenario::rect_of("dialog:ok") {
+ crate::scenario::publish_handle("ai_add:add", rect.center());
+ }
+ add |= action == ui_kit::Action::Ok;
+ open &= !closed && action != ui_kit::Action::Cancel;
if test {
#[cfg(not(target_arch = "wasm32"))]
if let Some(s) = app.agent_chat.settings.add.as_ref() {
@@ -558,3 +492,38 @@ fn add_agent(app: &mut SolveApp) -> Result<(), String> {
app.preferences.agents.push(c);
Ok(())
}
+
+#[cfg(all(test, not(target_arch = "wasm32")))]
+mod card_tests {
+ use super::*;
+ use crate::scenario::{self, Harness};
+ use serde_json::json;
+
+ #[test]
+ fn add_agent_card_retains_kind_handles_draft_and_validation() {
+ let mut h = Harness::new();
+ h.app.home.open = false;
+ h.app.preferences.ai_features = true;
+ h.app.agent_chat.detection = Some(Default::default());
+ open_add(&mut h.app);
+ h.frames(4);
+ h.step(&json!({"click":{"handle":"ai_add:ui.ai_add_custom"}})).unwrap();
+ assert_eq!(h.app.agent_chat.settings.add.as_ref().unwrap().kind, AddKind::Custom);
+ h.step(&json!({"click":{"handle":"ai_add:add"}})).unwrap();
+ assert!(h.app.agent_chat.settings.add.as_ref().unwrap().error.is_some());
+ let add = h.app.agent_chat.settings.add.as_mut().unwrap();
+ add.name = "Local fixture".into();
+ add.command = "solidcraft-fixture-agent --acp".into();
+ h.frames(3);
+ h.step(&json!({"click":{"handle":"ai_add:add"}})).unwrap();
+ assert!(h.app.agent_chat.settings.add.is_none());
+ assert!(h.app.preferences.agents.iter().any(|e| e.name == "Local fixture"));
+ open_add(&mut h.app);
+ h.frames(3);
+ h.step(&json!({"click":{"handle":"ai_add:ui.ai_add_api"}})).unwrap();
+ assert!(scenario::handle_at("ai_add:key").is_some());
+ assert!(h.app.services.secrets.is_none(), "this fixture has no keychain");
+ h.step(&json!({"key":"Escape"})).unwrap();
+ assert!(h.app.agent_chat.settings.add.is_none());
+ }
+}
diff --git a/crates/ui-egui/src/agent_cursor.rs b/crates/ui-egui/src/agent_cursor.rs
index 530f285d6e..11f08fd35c 100644
--- a/crates/ui-egui/src/agent_cursor.rs
+++ b/crates/ui-egui/src/agent_cursor.rs
@@ -101,9 +101,9 @@ pub fn speed_slider(ui: &mut egui::Ui, speed: &mut Speed) -> egui::Response {
Speed::Times(x) => x.clamp(1.0, 5.0),
Speed::Instant => 5.5,
};
- let r = ui.add(
- egui::Slider::new(&mut v, 1.0..=5.5).step_by(0.5).custom_formatter(|v, _| if v > 5.25 { "Instant".into() } else { Speed::Times(v).label() }),
- );
+ let r = crate::ui_kit::formatted_slider(ui, &mut v, 1.0..=5.5, 0.5, |v| {
+ if v > 5.25 { crate::i18n::tr_label("Instant").into() } else { Speed::Times(v).label() }
+ });
if r.changed() {
*speed = if v > 5.25 { Speed::Instant } else { Speed::Times(v) };
}
diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rs
index f083115b9a..25fb224d0d 100644
--- a/crates/ui-egui/src/browser.rs
+++ b/crates/ui-egui/src/browser.rs
@@ -927,9 +927,9 @@ fn finish_browser(app: &mut SolveApp, ui: &mut egui::Ui, acts: Actions) {
if let Some((at, target)) = acts.menu {
crate::context_menu::open_for(app, at, target);
}
- occurrence_panel(app, ui);
- capture_prompt(app, ui.ctx());
- canvas_panel(app, ui.ctx());
+ crate::browser_prompts::occurrence_panel(app, ui);
+ crate::browser_prompts::capture_prompt(app, ui.ctx());
+ crate::browser_canvas::panel(app, ui.ctx());
crate::sketch_attachment_ui::panel(app, ui.ctx());
}
@@ -1529,7 +1529,7 @@ pub struct CanvasPanel {
pub canvas: u64,
pub calibrate: bool,
/// Undo depth when the panel opened.
- depth: usize,
+ pub(crate) depth: usize,
pub a: [f64; 2],
pub b: [f64; 2],
pub distance: f64,
@@ -1550,86 +1550,6 @@ impl CanvasPanel {
}
}
-fn canvas_panel(app: &mut SolveApp, ctx: &egui::Context) {
- let Some(mut m) = app.tree.canvas_panel.clone() else { return };
- let Some(c) = app.session.doc.canvases.iter().find(|c| c.id == m.canvas).cloned() else {
- app.tree.canvas_panel = None;
- return;
- };
- let mut open = true;
- let mut edit: Option<Value> = None;
- let mut done = false;
- let title = if m.calibrate { format!("Calibrate: {}", c.name) } else { format!("Edit Canvas: {}", c.name) };
- crate::frame::window(ctx, title, crate::frame::Width::Normal)
- .id(egui::Id::new("sc_canvas_panel"))
- .pivot(egui::Align2::LEFT_TOP)
- .default_pos(panel_pos(app))
- .open(&mut open)
- .resizable(false)
- .collapsible(false)
- .show(ctx, |ui| {
- egui::Grid::new("sc_canvas_grid").num_columns(2).spacing([12.0, 6.0]).show(ui, |ui| {
- if m.calibrate {
- for (label, p) in [("Point A", &mut m.a), ("Point B", &mut m.b)] {
- ui.label(label);
- ui.horizontal(|ui| {
- ui.add(crate::prefs::length_drag(&mut p[0], &app.session.doc.units, app.preferences.length_decimals));
- ui.add(crate::prefs::length_drag(&mut p[1], &app.session.doc.units, app.preferences.length_decimals));
- });
- ui.end_row();
- }
- ui.label(crate::i18n::tr_label("Distance"));
- ui.add(crate::prefs::length_drag(&mut m.distance, &app.session.doc.units, app.preferences.length_decimals).range(0.001..=1e6));
- ui.end_row();
- } else {
- let (mut x, mut y, mut w, mut ang, mut op, mut flip) = (c.center.x, c.center.y, c.width, c.angle.to_degrees(), c.opacity, c.flip);
- ui.label(crate::i18n::tr_label("Center X"));
- let r1 = ui.add(crate::prefs::length_drag(&mut x, &app.session.doc.units, app.preferences.length_decimals));
- ui.end_row();
- ui.label(crate::i18n::tr_label("Center Y"));
- let r2 = ui.add(crate::prefs::length_drag(&mut y, &app.session.doc.units, app.preferences.length_decimals));
- ui.end_row();
- ui.label(crate::i18n::tr_label("Width"));
- let r3 = ui.add(crate::prefs::length_drag(&mut w, &app.session.doc.units, app.preferences.length_decimals).range(0.01..=1e6));
- ui.end_row();
- ui.label(crate::i18n::tr_label("Angle"));
- let r4 = ui.add(egui::DragValue::new(&mut ang).speed(1.0).suffix(" deg").custom_parser(crate::prefs::parse_number));
- ui.end_row();
- ui.label(crate::i18n::tr_label("Opacity"));
- let r5 = ui.add(egui::Slider::new(&mut op, 0.0..=1.0));
- ui.end_row();
- ui.label(crate::i18n::tr_label("Flip"));
- let r6 = ui.checkbox(&mut flip, "");
- ui.end_row();
- if [r1, r2, r3, r4, r5, r6].iter().any(|r| r.changed()) {
- edit = Some(json!({ "canvas": c.id, "center": [x, y], "width": w, "angle": ang, "opacity": op, "flip": flip }));
- }
- }
- });
- ui.add_space(6.0);
- if ui.button(if m.calibrate { "Calibrate" } else { "OK" }).clicked() {
- done = true;
- }
- });
- if let Some(p) = edit
- && app.run("canvas.edit", p).is_ok()
- {
- // One undo step for the whole edit.
- if app.session.undo.len() > m.depth + 1 {
- let keep = app.session.undo.get(m.depth).cloned();
- app.session.undo.truncate(m.depth);
- app.session.undo.extend(keep);
- }
- }
- if done && m.calibrate {
- if app.run("canvas.calibrate", json!({ "canvas": c.id, "a": m.a, "b": m.b, "distance": m.distance })).is_ok() {
- app.tree.canvas_panel = None;
- }
- return;
- }
- app.tree.canvas_panel = if done || !open { None } else { Some(m) };
-}
-
/// A browser click on a plane or axis: it goes to the open dialog's input if that takes it,
/// otherwise it becomes the selection.
fn pick_from_browser(app: &mut SolveApp, x: Sel) {
@@ -2131,96 +2051,6 @@ fn apply_drop(app: &mut SolveApp, d: DropAction) {
// Panels opened from the menus
// ---------------------------------------------------------------------------------------------
-/// Move/Copy of an occurrence: offsets and a rotation about Z, pending until Capture Position.
-fn occurrence_panel(app: &mut SolveApp, ui: &mut egui::Ui) {
- let Some(mut m) = app.tree.occurrence_move.clone() else { return };
- if !m.path.is_empty()
- && let Err(error) = app.session.occurrence_placement(&m.path)
- {
- app.tree.occurrence_move = None;
- app.set_status(error.to_string(), true);
- return;
- }
- if m.baseline.is_none() {
- m.had_pending = app.session.pending_moves.contains_key(&m.occurrence);
- m.baseline = app
- .session
- .pending_moves
- .get(&m.occurrence)
- .copied()
- .or_else(|| app.session.doc.occurrences.iter().find(|o| o.id == m.occurrence).map(|o| o.transform));
- }
- let ctx = ui.ctx().clone();
- if m.pivot.is_none() {
- m.pivot = if m.path.is_empty() {
- occurrence_origin(app, m.occurrence)
- } else {
- app.session.occurrence_placement(&m.path).ok().map(|p| solidcraft_engine::doc::apply_point(&p.world, solidcraft_engine::geom::Vec3::ZERO))
- };
- }
- let name = app.session.doc.occurrences.iter().find(|o| o.id == m.occurrence).map(|o| o.name.clone()).unwrap_or_default();
- let mut open = true;
- let mut action: Option<&str> = None;
- let before = (m.translate, m.angles);
- crate::frame::window(&ctx, format!("Move: {name}"), crate::frame::Width::Normal)
- .id(egui::Id::new("sc_occ_move"))
- .pivot(egui::Align2::LEFT_TOP)
- .default_pos(panel_pos(app))
- .open(&mut open)
- .resizable(false)
- .collapsible(false)
- .show(&ctx, |ui| {
- if !m.path.is_empty() && app.session.occurrence_scope_count(&m.path).is_ok_and(|n| n > 1) {
- ui.label(crate::i18n::tr_label("This child is shared. Position changes apply to every copy of its parent."));
- }
- egui::Grid::new("sc_occ_grid").num_columns(2).spacing([12.0, 6.0]).show(ui, |ui| {
- for (k, axis) in ["X distance", "Y distance", "Z distance"].iter().enumerate() {
- ui.label(*axis);
- if let Some(v) = m.translate.get_mut(k) {
- let response = ui.add(crate::prefs::length_drag(v, &app.session.doc.units, app.preferences.length_decimals));
- crate::scenario::publish_handle(&format!("occurrence-move:distance:{k}"), response.rect.center());
- }
- ui.end_row();
- }
- for (k, axis) in ["X angle", "Y angle", "Z angle"].iter().enumerate() {
- ui.label(*axis);
- if let Some(v) = m.angles.get_mut(k) {
- let response = ui.add(egui::DragValue::new(v).speed(1.0).suffix(" deg").custom_parser(crate::prefs::parse_number));
- crate::scenario::publish_handle(&format!("occurrence-move:angle:{k}"), response.rect.center());
- }
- ui.end_row();
- }
- });
- ui.add_space(6.0);
- ui.horizontal(|ui| {
- if ui.button(crate::i18n::tr_label("Capture All Positions")).clicked() {
- action = Some("capture");
- }
- if ui.button(crate::i18n::tr_label("Revert All Positions")).clicked() {
- action = Some("revert");
- }
- });
- });
- if (m.translate, m.angles) != before {
- apply_occurrence_move(app, &m);
- }
- match action {
- Some("capture") => {
- let _ = app.run("component.capture_position", json!({}));
- app.tree.occurrence_move = None;
- }
- Some(_) => {
- let _ = app.run("component.revert_position", json!({}));
- app.tree.occurrence_move = None;
- }
- None if !open => {
- revert_occurrence_dialog(app, &m);
- app.tree.occurrence_move = None;
- }
- None => app.tree.occurrence_move = Some(m),
- }
-}
-
pub(crate) fn revert_occurrence_dialog(app: &mut SolveApp, m: &OccMove) {
if m.had_pending {
let _ = app.run("occurrence.move", json!({"occurrence":m.occurrence,"base_transform":m.baseline,"capture":false}));
@@ -2349,7 +2179,7 @@ pub fn dims_overlay(app: &SolveApp, ctx: &egui::Context) {
}
/// Keep browser panels beside the browser and below the ribbon, including the floating shell.
-fn panel_pos(app: &SolveApp) -> Pos2 {
+pub(crate) fn panel_pos(app: &SolveApp) -> Pos2 {
app.viewport
.rect
.map(|r| crate::shell::content_rect(app, r).left_top() + vec2(Tokens::get().space_16, Tokens::get().space_16))
@@ -2391,47 +2221,8 @@ pub fn answer_capture(app: &mut SolveApp, action: &str) -> Result<(), String> {
Ok(())
}
-fn capture_prompt(app: &mut SolveApp, ctx: &egui::Context) {
- if app.tree.capture_prompt.is_none() {
- return;
- }
- let n = app.session.pending_moves.len();
- let mut answer: Option<&str> = None;
- crate::frame::window(ctx, crate::i18n::tr_label("Capture Position"), crate::frame::Width::Normal)
- .id(egui::Id::new("sc_capture_prompt"))
- .collapsible(false)
- .resizable(false)
- .anchor(egui::Align2::CENTER_CENTER, vec2(0.0, -80.0))
- .show(ctx, |ui| {
- ui.label(if n == 1 {
- "A component was moved but its position isn't captured.".to_string()
- } else {
- format!("{n} components were moved but their positions aren't captured.")
- });
- ui.label(RichText::new("Capture keeps the new position; Revert puts it back.").color(Tokens::get().text_dim));
- ui.add_space(6.0);
- ui.horizontal(|ui| {
- if ui.button(crate::i18n::tr_label("Capture Position")).clicked() {
- answer = Some("capture");
- }
- if ui.button(crate::i18n::tr_label("Revert")).clicked() {
- answer = Some("revert");
- }
- if ui.button("Cancel").clicked() {
- answer = Some("cancel");
- }
- });
- if ui.input(|i| i.key_pressed(egui::Key::Escape)) {
- answer = Some("cancel");
- }
- });
- if let Some(a) = answer {
- let _ = answer_capture(app, a);
- }
-}
-
/// Where an occurrence's origin is now (with its pending move).
-fn occurrence_origin(app: &SolveApp, occurrence: u64) -> Option<solidcraft_engine::geom::Vec3> {
+pub(crate) fn occurrence_origin(app: &SolveApp, occurrence: u64) -> Option<solidcraft_engine::geom::Vec3> {
let o = app.session.doc.occurrences.iter().find(|o| o.id == occurrence)?;
let parent = app.session.doc.component_transform(o.parent);
let own = app.session.pending_moves.get(&occurrence).copied().unwrap_or(o.transform);
diff --git a/crates/ui-egui/src/browser_canvas.rs b/crates/ui-egui/src/browser_canvas.rs
new file mode 100644
index 0000000000..5894db17f9
--- /dev/null
+++ b/crates/ui-egui/src/browser_canvas.rs
@@ -0,0 +1,128 @@
+//! The Edit Canvas / Calibrate card the Browser opens for a reference image: position, size,
+//! angle, opacity and flip (live, one undo step per opening), or two points on the image and
+//! their true distance.
+
+use serde_json::{Value, json};
+
+use crate::SolveApp;
+use crate::browser::panel_pos;
+use crate::ui_kit;
+
+pub(crate) fn panel(app: &mut SolveApp, ctx: &egui::Context) {
+ let Some(mut m) = app.tree.canvas_panel.clone() else { return };
+ let Some(c) = app.session.doc.canvases.iter().find(|c| c.id == m.canvas).cloned() else {
+ app.tree.canvas_panel = None;
+ return;
+ };
+ let mut edit: Option<Value> = None;
+ let (units, decimals) = (app.session.doc.units.clone(), app.preferences.length_decimals);
+ let title = crate::i18n::format(if m.calibrate { "browser.calibrate_title" } else { "browser.edit_canvas_title" }, &[("name", &c.name)]);
+ let at = panel_pos(app);
+ let (calibrate, name) = (m.calibrate, c.id);
+ let (ok, cancel) = if calibrate { (crate::i18n::tr_label("Calibrate"), crate::i18n::tr("ui.cancel")) } else { ("", crate::i18n::tr("ui.close")) };
+ let (closed, action) = ui_kit::Prompt::new(egui::Id::new("sc_canvas_panel"), "canvas", &title)
+ .placed(egui::Align2::LEFT_TOP, at)
+ .fields()
+ .actions(ok, cancel, None)
+ .show(ctx, true, |ui| {
+ if calibrate {
+ for (label, p) in [("Point A", &mut m.a), ("Point B", &mut m.b)] {
+ ui_kit::row(ui, crate::i18n::tr_label(label), |ui| {
+ let [x, y] = p;
+ ui.horizontal(|ui| {
+ ui_kit::length_field(ui, x, &units, decimals);
+ ui_kit::length_field(ui, y, &units, decimals);
+ });
+ });
+ }
+ ui_kit::row(ui, crate::i18n::tr_label("Distance"), |ui| ui_kit::length_field(ui, &mut m.distance, &units, decimals));
+ m.distance = m.distance.clamp(0.001, 1e6);
+ } else {
+ let (mut x, mut y, mut w, mut ang, mut op, mut flip) = (c.center.x, c.center.y, c.width, c.angle.to_degrees(), c.opacity, c.flip);
+ let mut changed = false;
+ changed |= ui_kit::row(ui, crate::i18n::tr_label("Center X"), |ui| ui_kit::length_field(ui, &mut x, &units, decimals)).changed();
+ changed |= ui_kit::row(ui, crate::i18n::tr_label("Center Y"), |ui| ui_kit::length_field(ui, &mut y, &units, decimals)).changed();
+ changed |= ui_kit::row(ui, crate::i18n::tr_label("Width"), |ui| ui_kit::length_field(ui, &mut w, &units, decimals)).changed();
+ changed |= ui_kit::row(ui, crate::i18n::tr_label("Angle"), |ui| ui_kit::angle_field(ui, &mut ang)).changed();
+ changed |= ui_kit::row(ui, crate::i18n::tr_label("Opacity"), |ui| ui_kit::slider(ui, &mut op, 0.0..=1.0)).changed();
+ if ui_kit::checkbox_row(ui, "flip", crate::i18n::tr_label("Flip"), flip) {
+ flip = !flip;
+ changed = true;
+ }
+ if changed {
+ edit = Some(json!({ "canvas": name, "center": [x, y], "width": w.clamp(0.01, 1e6), "angle": ang, "opacity": op, "flip": flip }));
+ }
+ }
+ });
+ if let Some(p) = edit
+ && app.run("canvas.edit", p).is_ok()
+ {
+ // One undo step for the whole edit.
+ if app.session.undo.len() > m.depth + 1 {
+ let keep = app.session.undo.get(m.depth).cloned();
+ app.session.undo.truncate(m.depth);
+ app.session.undo.extend(keep);
+ }
+ }
+ if action == ui_kit::Action::Ok {
+ if app.run("canvas.calibrate", json!({ "canvas": c.id, "a": m.a, "b": m.b, "distance": m.distance })).is_ok() {
+ app.tree.canvas_panel = None;
+ }
+ return;
+ }
+ app.tree.canvas_panel = if closed || action == ui_kit::Action::Cancel { None } else { Some(m) };
+}
+
+#[cfg(test)]
+mod tests {
+ use serde_json::json;
+
+ fn canvas(h: &mut crate::scenario::Harness) -> u64 {
+ let mut png = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR".to_vec();
+ png.extend(400u32.to_be_bytes());
+ png.extend(200u32.to_be_bytes());
+ png.extend([8, 6, 0, 0, 0, 0, 0, 0, 0]);
+ let data = solidcraft_engine::doc::canvas::base64_encode(&png);
+ h.app.run("canvas.insert", json!({"data": data, "plane": "XY", "width": 80})).unwrap()["canvas"].as_u64().unwrap()
+ }
+
+ #[test]
+ fn edit_canvas_is_a_card_whose_close_keeps_the_live_edits() {
+ let mut h = crate::scenario::Harness::new();
+ h.app.home.open = false;
+ let id = canvas(&mut h);
+ h.app.tree.canvas_panel = Some(crate::browser::CanvasPanel::new(&h.app, id, false));
+ h.frames(4);
+ assert!(crate::scenario::handle_at("dialog:close").is_some() && h.widget("Close").is_some());
+ assert!(h.widget("Calibrate").is_none(), "editing has no Calibrate action");
+ for row in ["dialog:length:Center X", "dialog:angle:Angle", "dialog:slider:Opacity"] {
+ assert!(crate::scenario::handle_at(row).is_some(), "{row}");
+ }
+ h.step(&json!({"widget": "Close"})).unwrap();
+ h.frames(2);
+ assert!(h.app.tree.canvas_panel.is_none());
+ assert_eq!(h.app.session.doc.canvases.len(), 1);
+ }
+
+ #[test]
+ fn calibrate_runs_the_command_and_cancel_leaves_the_canvas_alone() {
+ let mut h = crate::scenario::Harness::new();
+ h.app.home.open = false;
+ let id = canvas(&mut h);
+ let width = |h: &crate::scenario::Harness| h.app.session.doc.canvases[0].width;
+ h.app.tree.canvas_panel = Some(crate::browser::CanvasPanel::new(&h.app, id, true));
+ h.frames(4);
+ h.step(&json!({"widget": "Cancel"})).unwrap();
+ h.frames(2);
+ assert!(h.app.tree.canvas_panel.is_none());
+ assert!((width(&h) - 80.0).abs() < 1e-9);
+ let mut panel = crate::browser::CanvasPanel::new(&h.app, id, true);
+ panel.distance = 40.0;
+ h.app.tree.canvas_panel = Some(panel);
+ h.frames(4);
+ h.step(&json!({"widget": "Calibrate"})).unwrap();
+ h.frames(2);
+ assert!(h.app.tree.canvas_panel.is_none());
+ assert!((width(&h) - 40.0).abs() < 1e-6, "calibrating to half the distance halves the image: {}", width(&h));
+ }
+}
diff --git a/crates/ui-egui/src/browser_prompts.rs b/crates/ui-egui/src/browser_prompts.rs
new file mode 100644
index 0000000000..d5bad960d0
--- /dev/null
+++ b/crates/ui-egui/src/browser_prompts.rs
@@ -0,0 +1,118 @@
+//! The two prompts the Browser opens over the viewport: Move/Copy of an occurrence (offsets and
+//! turns, pending until Capture Position) and the Capture Position question asked before a
+//! command or a save while components are moved but not captured.
+
+use serde_json::json;
+
+use crate::SolveApp;
+use crate::browser::{answer_capture, apply_occurrence_move, occurrence_origin, panel_pos, revert_occurrence_dialog};
+use crate::ui_kit;
+
+/// Move/Copy of an occurrence: offsets and a rotation about Z, pending until Capture Position.
+pub(crate) fn occurrence_panel(app: &mut SolveApp, ui: &mut egui::Ui) {
+ let Some(mut m) = app.tree.occurrence_move.clone() else { return };
+ if !m.path.is_empty()
+ && let Err(error) = app.session.occurrence_placement(&m.path)
+ {
+ app.tree.occurrence_move = None;
+ app.set_status(error.to_string(), true);
+ return;
+ }
+ if m.baseline.is_none() {
+ m.had_pending = app.session.pending_moves.contains_key(&m.occurrence);
+ m.baseline = app
+ .session
+ .pending_moves
+ .get(&m.occurrence)
+ .copied()
+ .or_else(|| app.session.doc.occurrences.iter().find(|o| o.id == m.occurrence).map(|o| o.transform));
+ }
+ let ctx = ui.ctx().clone();
+ if m.pivot.is_none() {
+ m.pivot = if m.path.is_empty() {
+ occurrence_origin(app, m.occurrence)
+ } else {
+ app.session.occurrence_placement(&m.path).ok().map(|p| solidcraft_engine::doc::apply_point(&p.world, solidcraft_engine::geom::Vec3::ZERO))
+ };
+ }
+ let name = app.session.doc.occurrences.iter().find(|o| o.id == m.occurrence).map(|o| o.name.clone()).unwrap_or_default();
+ let before = (m.translate, m.angles);
+ let shared = !m.path.is_empty() && app.session.occurrence_scope_count(&m.path).is_ok_and(|n| n > 1);
+ let title = crate::i18n::format("browser.move_title", &[("name", &name)]);
+ let at = panel_pos(app);
+ let (units, decimals) = (app.session.doc.units.clone(), app.preferences.length_decimals);
+ let (closed, action) = ui_kit::Prompt::new(egui::Id::new("sc_occ_move"), "move", &title)
+ .placed(egui::Align2::LEFT_TOP, at)
+ .fields()
+ .cards(2.0)
+ .actions("Capture All Positions", "Cancel", Some("Revert All Positions"))
+ .show(&ctx, true, |ui| {
+ if shared {
+ ui_kit::note(ui, "shared", crate::i18n::tr_label("This child is shared. Position changes apply to every copy of its parent."));
+ }
+ for (k, axis) in ["X distance", "Y distance", "Z distance"].into_iter().enumerate() {
+ if let Some(v) = m.translate.get_mut(k) {
+ let response = ui_kit::row(ui, crate::i18n::tr_label(axis), |ui| ui_kit::length_field(ui, v, &units, decimals));
+ crate::scenario::publish_handle(&format!("occurrence-move:distance:{k}"), response.rect.center());
+ }
+ }
+ for (k, axis) in ["X angle", "Y angle", "Z angle"].into_iter().enumerate() {
+ if let Some(v) = m.angles.get_mut(k) {
+ let response = ui_kit::row(ui, crate::i18n::tr_label(axis), |ui| ui_kit::angle_field(ui, v));
+ crate::scenario::publish_handle(&format!("occurrence-move:angle:{k}"), response.rect.center());
+ }
+ }
+ });
+ if (m.translate, m.angles) != before {
+ apply_occurrence_move(app, &m);
+ }
+ match action {
+ ui_kit::Action::Ok => {
+ let _ = app.run("component.capture_position", json!({}));
+ app.tree.occurrence_move = None;
+ }
+ ui_kit::Action::Apply => {
+ let _ = app.run("component.revert_position", json!({}));
+ app.tree.occurrence_move = None;
+ }
+ ui_kit::Action::Cancel => {
+ revert_occurrence_dialog(app, &m);
+ app.tree.occurrence_move = None;
+ }
+ ui_kit::Action::None if closed => {
+ revert_occurrence_dialog(app, &m);
+ app.tree.occurrence_move = None;
+ }
+ ui_kit::Action::None => app.tree.occurrence_move = Some(m),
+ }
+}
+
+/// The Capture Position question: capture, revert or cancel the waiting command (or save).
+pub(crate) fn capture_prompt(app: &mut SolveApp, ctx: &egui::Context) {
+ if app.tree.capture_prompt.is_none() {
+ return;
+ }
+ let n = app.session.pending_moves.len();
+ let (closed, action) = ui_kit::Prompt::new(egui::Id::new("sc_capture_prompt"), "capture", crate::i18n::tr_label("Capture Position"))
+ .anchor(egui::Align2::CENTER_CENTER, egui::vec2(0.0, -80.0))
+ .actions("Capture Position", "Cancel", Some("Revert"))
+ .show(ctx, true, |ui| {
+ let question = if n == 1 {
+ crate::i18n::tr("browser.capture_one").to_string()
+ } else {
+ crate::i18n::format("browser.capture_many", &[("count", &n.to_string())])
+ };
+ ui_kit::text_block(ui, "question", &question, false);
+ ui_kit::note(ui, "capture", crate::i18n::tr("browser.capture_note"));
+ });
+ let answer = match action {
+ ui_kit::Action::Ok => Some("capture"),
+ ui_kit::Action::Apply => Some("revert"),
+ ui_kit::Action::Cancel => Some("cancel"),
+ ui_kit::Action::None if closed => Some("cancel"),
+ ui_kit::Action::None => None,
+ };
+ if let Some(answer) = answer {
+ let _ = answer_capture(app, answer);
+ }
+}
diff --git a/crates/ui-egui/src/configuration_rules_ui.rs b/crates/ui-egui/src/configuration_rules_ui.rs
index f3c1361221..dc91476b9a 100644
--- a/crates/ui-egui/src/configuration_rules_ui.rs
+++ b/crates/ui-egui/src/configuration_rules_ui.rs
@@ -1,7 +1,7 @@
//! Structured configuration rule editing and non-mutating row preview.
use crate::SolveApp;
-use crate::fonts::RichTextExt as _;
-use egui::{RichText, Ui};
+use crate::ui_kit;
+use egui::Ui;
use serde_json::{Value, json};
use solidcraft_engine::doc::config::{Column, ConfigRule, RuleCondition, RuleEffect, RuleOperator};
@@ -36,15 +36,30 @@ impl Default for Editor {
}
}
fn choose(ui: &mut Ui, id: &str, value: &mut String, options: &[String]) {
- egui::ComboBox::from_id_salt(id).selected_text(if value.is_empty() { "Choose…" } else { value.as_str() }).width(130.0).show_ui(ui, |ui| {
- for option in options {
- ui.selectable_value(value, option.clone(), option);
- }
- });
+ let mut labels = vec![crate::i18n::tr_label("Choose…")];
+ labels.extend(options.iter().map(String::as_str));
+ let mut selected = options.iter().position(|o| o == value).map_or(0, |i| i + 1);
+ let before = selected;
+ let label = match id {
+ "rule_length_units" => "Length units",
+ "rule_effect_kind" => "Then",
+ "condition_kind" => "When",
+ "effect_parameter" | "range_parameter" | "allowed_parameter" | "condition_parameter" => "Parameter",
+ "effect_feature" | "condition_feature" => "Feature",
+ "preview_configuration" => "Configuration",
+ _ => id,
+ };
+ ui_kit::row(ui, label, |ui| ui_kit::dropdown(ui, id, &mut selected, &labels));
+ if before != selected
+ && let Some(choice) = selected.checked_sub(1).and_then(|i| options.get(i))
+ {
+ *value = choice.clone();
+ }
}
fn expression(ui: &mut Ui, label: &str, value: &mut String) {
- ui.label(label);
- ui.add(egui::TextEdit::singleline(value).desired_width(160.0));
+ ui_kit::row(ui, label, |ui| {
+ ui_kit::text_field(ui, value, label);
+ });
}
pub(super) fn show(ui: &mut Ui, app: &mut SolveApp, error: &mut Option<String>, editor: &mut Editor) {
@@ -58,60 +73,60 @@ pub(super) fn show(ui: &mut Ui, app: &mut SolveApp, error: &mut Option<String>,
let features: Vec<(u64, String)> = app.session.doc.features.iter().map(|f| (f.id, f.name.clone())).collect();
let suppression_features: Vec<(u64, String)> =
features.iter().filter(|(id, _)| app.session.doc.configs.columns.contains(&Column::Suppress(*id))).cloned().collect();
- ui.separator();
- ui.label(RichText::new(crate::i18n::tr_label("Configuration rules")).semibold().color(crate::theme::Tokens::get().text));
- ui.add(egui::Label::new("Rules run from top to bottom. Matched drives change effective values.").wrap());
- ui.add(egui::Label::new("Matched restrictions check the final values.").wrap());
+ ui_kit::divider(ui, "configuration_rules");
+ ui_kit::text_block(ui, "rules_heading", crate::i18n::tr_label("Configuration rules"), false);
+ ui_kit::note(ui, "rules_drives", crate::i18n::tr_label("Rules run from top to bottom. Matched drives change effective values."));
+ ui_kit::note(ui, "rules_restrictions", crate::i18n::tr_label("Matched restrictions check the final values."));
for (index, rule) in rules.iter().enumerate() {
ui.push_id(&rule.id, |ui| {
- ui.horizontal(|ui| {
+ ui.horizontal_wrapped(|ui| {
let mut enabled = rule.enabled;
- if ui.checkbox(&mut enabled, "").on_hover_text(crate::i18n::tr_label("Enable rule")).changed() {
+ if ui_kit::checkbox(ui, "", &mut enabled).on_hover_text(crate::i18n::tr_label("Enable rule")).changed() {
let mut r = rule.clone();
r.enabled = enabled;
*error = app.run("config.rule", json!({"rule":r})).err();
}
- ui.add(egui::Label::new(&rule.name).truncate());
- if ui.small_button("Edit").clicked() {
+ ui_kit::inline_text(ui, &rule.name);
+ if ui_kit::small_button(ui, crate::i18n::tr_label("Edit")).clicked() {
editor.rule = rule.clone();
}
- if ui.add_enabled(index > 0, egui::Button::new("↑").small()).on_hover_text(crate::i18n::tr_label("Move earlier")).clicked() {
+ let up = ui_kit::enabled_button(ui, "↑", index > 0).on_hover_text(crate::i18n::tr_label("Move earlier"));
+ crate::scenario::publish_handle(&format!("config:rule:{}:up", rule.id), up.rect.center());
+ if up.clicked() {
*error = app.run("config.rule", json!({"id":rule.id,"index":index-1})).err();
}
- if ui
- .add_enabled(index + 1 < rules.len(), egui::Button::new("↓").small())
- .on_hover_text(crate::i18n::tr_label("Move later"))
- .clicked()
- {
+ if ui_kit::enabled_button(ui, "↓", index + 1 < rules.len()).on_hover_text(crate::i18n::tr_label("Move later")).clicked() {
*error = app.run("config.rule", json!({"id":rule.id,"index":index+1})).err();
}
- if ui.small_button("Delete").clicked() {
+ if ui_kit::small_button(ui, crate::i18n::tr_label("Delete")).clicked() {
*error = app.run("config.rule", json!({"id":rule.id,"delete":true})).err();
}
});
- ui.label(match &rule.effect {
- RuleEffect::DriveParameter { parameter, expression } => format!("Drives {parameter} = {expression}"),
- RuleEffect::DriveSuppression { feature, value } => format!(
- "Drives suppression {} = {value}",
- features.iter().find(|f| f.0 == *feature).map(|f| f.1.as_str()).unwrap_or("missing feature")
- ),
- RuleEffect::ParameterRange { parameter, minimum, maximum } => format!("Restricts {parameter}: {minimum} through {maximum}"),
- RuleEffect::AllowParameterValues { parameter, expressions } => format!("Restricts {parameter}: {}", expressions.join(", ")),
- });
+ report(
+ ui,
+ match &rule.effect {
+ RuleEffect::DriveParameter { parameter, expression } => format!("Drives {parameter} = {expression}"),
+ RuleEffect::DriveSuppression { feature, value } => format!(
+ "Drives suppression {} = {value}",
+ features.iter().find(|f| f.0 == *feature).map(|f| f.1.as_str()).unwrap_or("missing feature")
+ ),
+ RuleEffect::ParameterRange { parameter, minimum, maximum } => format!("Restricts {parameter}: {minimum} through {maximum}"),
+ RuleEffect::AllowParameterValues { parameter, expressions } => format!("Restricts {parameter}: {}", expressions.join(", ")),
+ },
+ );
});
}
- ui.collapsing("Add or edit rule", |ui| {
- ui.horizontal(|ui| {
+ ui_kit::section(ui, "rule_editor", "Add or edit rule", false, |ui| {
+ ui.vertical(|ui| {
expression(ui, "Rule name", &mut editor.rule.name);
- ui.checkbox(&mut editor.rule.enabled, crate::i18n::tr_label("Enabled"));
- if ui.small_button("New").clicked() {
+ ui_kit::checkbox(ui, crate::i18n::tr_label("Enabled"), &mut editor.rule.enabled);
+ if ui_kit::small_button(ui, crate::i18n::tr_label("New")).clicked() {
editor.rule = Editor::default().rule;
}
});
let mut length_unit = editor.rule.length_unit.clone().unwrap_or_else(|| app.session.doc.units.clone());
let old_unit = length_unit.clone();
- ui.horizontal(|ui| {
- ui.label(crate::i18n::tr_label("Length units"));
+ ui.vertical(|ui| {
choose(ui, "rule_length_units", &mut length_unit, &["mm".into(), "cm".into(), "m".into(), "in".into(), "ft".into()]);
});
if length_unit != old_unit {
@@ -126,8 +141,7 @@ pub(super) fn show(ui: &mut Ui, app: &mut SolveApp, error: &mut Option<String>,
}
.to_string();
let prior = effect_kind.clone();
- ui.horizontal(|ui| {
- ui.label(crate::i18n::tr_label("Then"));
+ ui.vertical(|ui| {
choose(
ui,
"rule_effect_kind",
@@ -146,36 +160,37 @@ pub(super) fn show(ui: &mut Ui, app: &mut SolveApp, error: &mut Option<String>,
}
match &mut editor.rule.effect {
RuleEffect::DriveParameter { parameter, expression: value } => {
- ui.horizontal(|ui| {
+ ui.vertical(|ui| {
choose(ui, "effect_parameter", parameter, &parameters);
expression(ui, "Value", value);
});
}
RuleEffect::DriveSuppression { feature, value } => {
- ui.horizontal(|ui| {
+ ui.vertical(|ui| {
feature_choice(ui, "effect_feature", feature, &suppression_features);
- ui.checkbox(value, crate::i18n::tr_label("Suppressed"));
+ ui_kit::checkbox(ui, crate::i18n::tr_label("Suppressed"), value);
});
}
RuleEffect::ParameterRange { parameter, minimum, maximum } => {
choose(ui, "range_parameter", parameter, &parameters);
- ui.horizontal(|ui| {
+ ui.vertical(|ui| {
expression(ui, "Minimum", minimum);
});
- ui.horizontal(|ui| {
+ ui.vertical(|ui| {
expression(ui, "Maximum", maximum);
});
}
RuleEffect::AllowParameterValues { parameter, expressions } => {
choose(ui, "allowed_parameter", parameter, &parameters);
let mut text = expressions.join("; ");
- ui.label(crate::i18n::tr_label("Allowed expressions, separated by semicolons"));
- if ui.add(egui::TextEdit::singleline(&mut text).desired_width(300.0)).changed() {
+ if ui_kit::row(ui, "Allowed expressions, separated by semicolons", |ui| ui_kit::text_field(ui, &mut text, "").1) {
*expressions = text.split(';').map(|s| s.trim().to_string()).collect();
}
}
}
- if ui.add_enabled(!app.session.doc.configs.rows.is_empty(), egui::Button::new(crate::i18n::tr_label("Save Rule"))).clicked() {
+ let save = ui_kit::enabled_button(ui, "Save Rule", !app.session.doc.configs.rows.is_empty());
+ crate::scenario::publish_handle("config:save_rule", save.rect.center());
+ if save.clicked() {
let result = (|| -> Result<(), String> {
let mut rule = editor.rule.clone();
if rule.id.is_empty() {
@@ -193,9 +208,11 @@ pub(super) fn show(ui: &mut Ui, app: &mut SolveApp, error: &mut Option<String>,
editor.row = app.session.doc.configs.active.clone().or_else(|| rows.first().cloned()).unwrap_or_default();
}
let previous_row = editor.row.clone();
- ui.horizontal(|ui| {
+ ui.vertical(|ui| {
choose(ui, "preview_configuration", &mut editor.row, &rows);
- if ui.add_enabled(!editor.row.is_empty(), egui::Button::new(crate::i18n::tr_label("Preview Row"))).clicked() {
+ let preview = ui_kit::enabled_button(ui, "Preview Row", !editor.row.is_empty());
+ crate::scenario::publish_handle("config:preview_row", preview.rect.center());
+ if preview.clicked() {
match app.session.execute("config.preview", &json!({"row":editor.row})) {
Ok(result) => {
editor.preview = Some(result);
@@ -213,44 +230,50 @@ pub(super) fn show(ui: &mut Ui, app: &mut SolveApp, error: &mut Option<String>,
editor.preview = None;
}
if let Some(preview) = &editor.preview {
- ui.collapsing(format!("Preview: {}", preview["active"].as_str().unwrap_or("row")), |ui| {
- ui.label(crate::i18n::tr_label("Preview leaves the current design unchanged."));
+ ui_kit::section(ui, "rule_preview", &format!("Preview: {}", preview["active"].as_str().unwrap_or("row")), false, |ui| {
+ report(ui, crate::i18n::tr_label("Preview leaves the current design unchanged."));
if let Some(styles) = preview["styles"].as_array() {
for style in styles {
- ui.add(
- egui::Label::new(format!(
+ report(
+ ui,
+ format!(
"{}: {} (shared definition)",
style["target"].as_str().unwrap_or("Appearance"),
if style["dormant"].as_bool() == Some(true) { "dormant" } else { "resolved" }
- ))
- .wrap(),
+ ),
);
}
}
if let Some(trace) = preview["trace"].as_array() {
for entry in trace {
- ui.label(format!(
- "{} — {}",
- entry["name"].as_str().unwrap_or("rule"),
- if entry["matched"].as_bool() == Some(true) { "matched" } else { "skipped" }
- ));
+ report(
+ ui,
+ format!(
+ "{} — {}",
+ entry["name"].as_str().unwrap_or("rule"),
+ if entry["matched"].as_bool() == Some(true) { "matched" } else { "skipped" }
+ ),
+ );
if entry["matched"].as_bool() == Some(true)
&& let Ok(effect) = serde_json::from_value::<RuleEffect>(entry["effect"].clone())
{
- ui.label(match effect {
- RuleEffect::DriveParameter { parameter, expression } => format!("Driven: {parameter} = {expression}"),
- RuleEffect::DriveSuppression { feature, value } => format!(
- "Driven: {} is {}",
- features.iter().find(|f| f.0 == feature).map(|f| f.1.as_str()).unwrap_or("feature"),
- if value { "suppressed" } else { "unsuppressed" }
- ),
- RuleEffect::ParameterRange { parameter, minimum, maximum } => {
- format!("Restricted: {parameter}, {minimum} through {maximum}")
- }
- RuleEffect::AllowParameterValues { parameter, expressions } => {
- format!("Restricted: {parameter}, {}", expressions.join("; "))
- }
- });
+ report(
+ ui,
+ match effect {
+ RuleEffect::DriveParameter { parameter, expression } => format!("Driven: {parameter} = {expression}"),
+ RuleEffect::DriveSuppression { feature, value } => format!(
+ "Driven: {} is {}",
+ features.iter().find(|f| f.0 == feature).map(|f| f.1.as_str()).unwrap_or("feature"),
+ if value { "suppressed" } else { "unsuppressed" }
+ ),
+ RuleEffect::ParameterRange { parameter, minimum, maximum } => {
+ format!("Restricted: {parameter}, {minimum} through {maximum}")
+ }
+ RuleEffect::AllowParameterValues { parameter, expressions } => {
+ format!("Restricted: {parameter}, {}", expressions.join("; "))
+ }
+ },
+ );
}
}
}
@@ -259,21 +282,30 @@ pub(super) fn show(ui: &mut Ui, app: &mut SolveApp, error: &mut Option<String>,
if let Some(name) = parameter["name"].as_str()
&& all_parameters.iter().any(|p| p == name)
{
- ui.label(format!("{name} = {}", parameter["expression"].as_str().unwrap_or("")));
+ let response = ui_kit::text_block(
+ ui,
+ "preview_parameter",
+ &format!("{name} = {}", parameter["expression"].as_str().unwrap_or("")),
+ false,
+ );
+ crate::scenario::publish_handle(&format!("config:preview:param:{name}"), response.rect.center());
}
}
}
});
}
}
+fn report(ui: &mut Ui, text: impl AsRef<str>) {
+ ui_kit::text_block(ui, "rule_report", crate::i18n::tr_label(text.as_ref()), false);
+}
+
fn feature_choice(ui: &mut Ui, id: &str, feature: &mut u64, features: &[(u64, String)]) {
- egui::ComboBox::from_id_salt(id)
- .selected_text(features.iter().find(|f| f.0 == *feature).map(|f| f.1.as_str()).unwrap_or("Choose feature…"))
- .show_ui(ui, |ui| {
- for (id, name) in features {
- ui.selectable_value(feature, *id, name);
- }
- });
+ let options: Vec<_> = features.iter().map(|(_, name)| name.clone()).collect();
+ let mut selected = features.iter().find(|f| f.0 == *feature).map(|f| f.1.clone()).unwrap_or_default();
+ choose(ui, id, &mut selected, &options);
+ if let Some((id, _)) = features.iter().find(|(_, name)| *name == selected) {
+ *feature = *id;
+ }
}
fn condition_editor(ui: &mut Ui, condition: &mut RuleCondition, parameters: &[String], features: &[(u64, String)], depth: usize) {
@@ -291,8 +323,7 @@ fn condition_editor(ui: &mut Ui, condition: &mut RuleCondition, parameters: &[St
if depth < 8 {
choices.extend(["All".into(), "Any".into(), "Not".into()]);
}
- ui.horizontal(|ui| {
- ui.label(crate::i18n::tr_label("When"));
+ ui.vertical(|ui| {
choose(ui, "condition_kind", &mut kind, &choices);
});
if previous != kind {
@@ -311,37 +342,29 @@ fn condition_editor(ui: &mut Ui, condition: &mut RuleCondition, parameters: &[St
}
match condition {
RuleCondition::Parameter { parameter, operator, expression } => {
- ui.horizontal(|ui| {
+ ui.vertical(|ui| {
choose(ui, "condition_parameter", parameter, parameters);
- egui::ComboBox::from_id_salt("condition_operator")
- .width(45.0)
- .selected_text(match operator {
- RuleOperator::Eq => "=",
- RuleOperator::Ne => "≠",
- RuleOperator::Lt => "<",
- RuleOperator::Le => "≤",
- RuleOperator::Gt => ">",
- RuleOperator::Ge => "≥",
- })
- .show_ui(ui, |ui| {
- for (label, op) in [
- ("=", RuleOperator::Eq),
- ("≠", RuleOperator::Ne),
- ("<", RuleOperator::Lt),
- ("≤", RuleOperator::Le),
- (">", RuleOperator::Gt),
- ("≥", RuleOperator::Ge),
- ] {
- ui.selectable_value(operator, op, label);
- }
- });
- ui.add(egui::TextEdit::singleline(expression).desired_width(110.0));
+ let operators = [
+ ("=", RuleOperator::Eq),
+ ("≠", RuleOperator::Ne),
+ ("<", RuleOperator::Lt),
+ ("≤", RuleOperator::Le),
+ (">", RuleOperator::Gt),
+ ("≥", RuleOperator::Ge),
+ ];
+ let mut index = operators.iter().position(|(_, op)| op == operator).unwrap_or(0);
+ let labels: Vec<_> = operators.iter().map(|(label, _)| *label).collect();
+ ui_kit::row(ui, "Operator", |ui| ui_kit::dropdown(ui, "condition_operator", &mut index, &labels));
+ if let Some((_, op)) = operators.get(index) {
+ *operator = *op;
+ }
+ ui_kit::row(ui, "Expression", |ui| ui_kit::field(ui, expression));
});
}
RuleCondition::Suppression { feature, value } => {
- ui.horizontal(|ui| {
+ ui.vertical(|ui| {
feature_choice(ui, "condition_feature", feature, features);
- ui.checkbox(value, crate::i18n::tr_label("Suppressed"));
+ ui_kit::checkbox(ui, crate::i18n::tr_label("Suppressed"), value);
});
}
RuleCondition::All { conditions } | RuleCondition::Any { conditions } => {
@@ -350,7 +373,7 @@ fn condition_editor(ui: &mut Ui, condition: &mut RuleCondition, parameters: &[St
ui.push_id(index, |ui| {
ui.indent("condition_group", |ui| {
condition_editor(ui, child, parameters, features, depth + 1);
- if ui.small_button("Remove condition").clicked() {
+ if ui_kit::small_button(ui, crate::i18n::tr_label("Remove condition")).clicked() {
remove = Some(index);
}
});
@@ -359,7 +382,7 @@ fn condition_editor(ui: &mut Ui, condition: &mut RuleCondition, parameters: &[St
if let Some(index) = remove {
conditions.remove(index);
}
- if ui.add_enabled(conditions.len() < 32, egui::Button::new(crate::i18n::tr_label("Add condition")).small()).clicked() {
+ if ui_kit::enabled_button(ui, "Add condition", conditions.len() < 32).clicked() {
conditions.push(RuleCondition::Always);
}
}
diff --git a/crates/ui-egui/src/configurations_ui.rs b/crates/ui-egui/src/configurations_ui.rs
new file mode 100644
index 0000000000..0de609c1ed
--- /dev/null
+++ b/crates/ui-egui/src/configurations_ui.rs
@@ -0,0 +1,328 @@
+//! Manage configuration table. Commands and cell decoding remain in dialogs_motion.
+use super::{cell_value, column_parts, configuration_rules_ui, table, unit_of};
+use crate::{SolveApp, ui_kit};
+use serde_json::{Value, json};
+/// The Configurations table, its rules and errors.
+pub(super) fn configurations_rows(
+ app: &mut SolveApp,
+ ui: &mut egui::Ui,
+ new_row: &mut String,
+ error: &mut Option<String>,
+ rule_editor: &mut configuration_rules_ui::Editor,
+) {
+ // Physical materials for the configuration table's Library: the library's, then the design's own.
+ let material_names = app.session.doc.material_names();
+ let revision = app.session.revision;
+ let v = rule_editor.table.as_ref().filter(|(r, _)| *r == revision).map(|(_, v)| v.clone()).unwrap_or_else(|| {
+ let value = app.session.execute("config.table", &json!({})).unwrap_or(Value::Null);
+ rule_editor.table = Some((revision, value.clone()));
+ value
+ });
+ let mut tb = table(&v);
+ // Bare numbers show with their parameter's unit ("40" is 40 mm), as Fusion shows them.
+ let kinds = app.session.doc.all_param_exprs();
+ for (_, vals) in &mut tb.rows {
+ for (c, val) in tb.columns.iter().zip(vals.iter_mut()) {
+ let (kind, n) = column_parts(c);
+ if kind == "param"
+ && val.trim().parse::<f64>().is_ok()
+ && let Some(unit) = app.session.doc.param(n).map(|parameter| parameter.unit.clone()).or_else(|| {
+ kinds.iter().find(|x| x.0 == n).and_then(|x| {
+ unit_of(x.2).map(|unit| {
+ if x.2 == solidcraft_engine::doc::expr::Kind::Length { app.session.doc.units.clone() } else { unit.to_string() }
+ })
+ })
+ })
+ {
+ *val = format!("{} {unit}", val.trim());
+ }
+ }
+ }
+ let run = |app: &mut SolveApp, error: &mut Option<String>, id: &str, p: Value| {
+ *error = app.run(id, p).err();
+ };
+ let labels: Vec<_> = std::iter::once(crate::i18n::tr_label("Configuration").to_owned())
+ .chain(tb.columns.iter().map(|c| {
+ let (kind, name) = column_parts(c);
+ v["targets"]
+ .as_array()
+ .and_then(|targets| targets.iter().find(|target| target["key"].as_str() == Some(c)))
+ .and_then(|target| target["label"].as_str())
+ .filter(|_| matches!(kind, "component_appearance" | "face_appearance"))
+ .map(str::to_string)
+ .unwrap_or_else(|| match kind {
+ "material" => format!("{}: {name}", crate::i18n::tr_label("Material")),
+ "appearance" => format!("{}: {name}", crate::i18n::tr_label("Appearance")),
+ "suppress" => format!("{}: {name}", crate::i18n::tr_label("Suppress")),
+ _ => name.to_owned(),
+ })
+ }))
+ .chain(std::iter::once(crate::i18n::tr_label("Actions").to_owned()))
+ .collect();
+ let columns: Vec<_> = labels.iter().map(|label| ui_kit::Column { label, width: 2.0 }).collect();
+ ui_kit::table(ui, "configuration_table", &columns, crate::i18n::tr("manage.empty"), |ui, table| {
+ // Column actions are ordinary cells, so they share the header's exact widths.
+ if !tb.columns.is_empty() {
+ table.row(ui, "columns", false, |row| {
+ row.cell(|_| {});
+ for c in &tb.columns {
+ row.cell(|ui| {
+ let (kind, name) = column_parts(c);
+ if ui_kit::small_button(ui, "×").on_hover_text(crate::i18n::tr_label("Remove the column")).clicked() {
+ let key = if kind == "suppress" { "feature" } else { kind };
+ run(app, error, "config.column", json!({key:if kind == "face_appearance" {c.as_str()} else {name},"delete":true}));
+ }
+ });
+ }
+ row.cell(|_| {});
+ });
+ }
+ for (name, values) in &tb.rows {
+ let active = tb.active.as_deref() == Some(name.as_str());
+ table.row(ui, name, active, |row| {
+ row.cell(|ui| {
+ // Reserve space for Activate/Apply even when the row name is long.
+ ui_kit::label_actions(ui, name, |ui| {
+ if active {
+ ui_kit::inline_text(ui, crate::i18n::tr_label("Active"));
+ if v.get("matches").and_then(Value::as_bool) == Some(false) {
+ let apply = ui_kit::small_button(ui, crate::i18n::tr_label("Apply"));
+ crate::scenario::publish_handle(&format!("config:activate:{name}"), apply.rect.center());
+ if apply.clicked() {
+ run(app, error, "config.activate", json!({"row":name}));
+ }
+ }
+ } else {
+ let activate = ui_kit::small_button(ui, crate::i18n::tr_label("Activate"));
+ crate::scenario::publish_handle(&format!("config:activate:{name}"), activate.rect.center());
+ if activate.clicked() {
+ run(app, error, "config.activate", json!({"row":name}));
+ }
+ }
+ });
+ });
+ for (column, value) in tb.columns.iter().zip(values) {
+ row.cell(|ui| {
+ let (kind, _) = column_parts(column);
+ let appearance = matches!(kind, "appearance" | "component_appearance" | "face_appearance");
+ let shown = if appearance {
+ solidcraft_engine::doc::config::appearance_cell(value)
+ .ok()
+ .flatten()
+ .filter(|look| solidcraft_engine::doc::appearance::library(&look.name).as_ref() == Some(look))
+ .map(|look| look.name)
+ .unwrap_or_else(|| value.clone())
+ } else {
+ value.clone()
+ };
+ if kind == "material" || appearance {
+ let mut choice = None;
+ ui_kit::action_menu(ui, "Library", |ui| {
+ let follow = if kind == "appearance" {
+ "Follow material"
+ } else if appearance {
+ "Follow inherited appearance"
+ } else {
+ "Default material"
+ };
+ if ui_kit::secondary_button(ui, crate::i18n::tr_label(follow)).clicked() {
+ choice = Some("Default".to_owned());
+ ui.close();
+ }
+ let choices: Vec<_> = if kind == "material" {
+ material_names.iter().filter(|n| *n != "Default").map(String::as_str).collect()
+ } else {
+ solidcraft_engine::doc::appearance::LIBRARY.iter().map(|(name, _, _)| *name).collect()
+ };
+ for name in choices {
+ if ui_kit::secondary_button(ui, name).clicked() {
+ choice = Some(name.to_owned());
+ ui.close();
+ }
+ }
+ });
+ if let Some(choice) = choice {
+ run(app, error, "config.row", json!({"name":name,"values":{column:choice}}));
+ }
+ }
+ let key = (name.clone(), column.clone());
+ let mut text = rule_editor.drafts.get(&key).cloned().unwrap_or_else(|| shown.clone());
+ let id = ui.make_persistent_id(&key);
+ let response = ui_kit::cell_editor(ui, id, &mut text, "", false);
+ crate::scenario::publish_handle(&format!("config:cell:{name}:{column}"), response.rect.center());
+ let focused = response.has_focus();
+ let completed = crate::params_dialog::complete(ui, &response, &mut text);
+ if response.changed() || completed {
+ rule_editor.drafts.insert(key.clone(), text.clone());
+ }
+ let enter = !completed && focused && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter));
+ if response.lost_focus() || enter {
+ rule_editor.drafts.remove(&key);
+ if text != shown {
+ run(app, error, "config.row", json!({"name":name,"values":{column:cell_value(column,&text)}}));
+ }
+ }
+ });
+ }
+ row.cell(|ui| {
+ if ui_kit::small_button(ui, "×").on_hover_text(crate::i18n::tr_label("Delete the row")).clicked() {
+ run(app, error, "config.row", json!({"name":name,"delete":true}));
+ }
+ });
+ });
+ }
+ });
+ // New row (a copy of the active one) and new column.
+ ui_kit::row(ui, "Configuration", |ui| {
+ let id = ui.make_persistent_id("new_configuration");
+ ui_kit::cell_editor(ui, id, new_row, "new configuration", false);
+ });
+ ui.horizontal_wrapped(|ui| {
+ ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend);
+
+ if ui_kit::secondary_button(ui, crate::i18n::tr_label("Add Row"))
+ .on_hover_text(crate::i18n::tr_label("A new configuration, a copy of the active one"))
+ .clicked()
+ {
+ let name = if new_row.trim().is_empty() {
+ (tb.rows.len() + 1..).map(|k| format!("Configuration{k}")).find(|n| !tb.rows.iter().any(|r| &r.0 == n)).unwrap_or_default()
+ } else {
+ new_row.trim().to_string()
+ };
+ let mut p = json!({ "name": name });
+ if let Some(a) = &tb.active {
+ p["from"] = json!(a);
+ }
+ run(app, error, "config.row", p);
+ new_row.clear();
+ }
+ // A column: a parameter's value or a feature's suppression.
+ let mut options: Vec<(String, Value)> = Vec::new();
+ for p in app.session.doc.all_param_exprs() {
+ if !tb.columns.contains(&format!("param:{}", p.0)) {
+ options.push((format!("{} (parameter)", p.0), json!({ "param": p.0 })));
+ }
+ }
+ for f in &app.session.doc.features {
+ if !tb.columns.contains(&format!("suppress:{}", f.name)) {
+ options.push((format!("Suppress {}", f.name), json!({ "feature": f.name })));
+ }
+ }
+ for body in &app.session.model.state().bodies {
+ for kind in ["material", "appearance"] {
+ if !tb.columns.contains(&format!("{kind}:{}", body.name)) {
+ options.push((format!("{} ({kind})", body.name), json!({kind: body.name})));
+ }
+ }
+ }
+ for component in &app.session.doc.components {
+ if component.id != 0 && !tb.columns.contains(&format!("component_appearance:{}", component.id)) {
+ options.push((format!("{} (component appearance)", component.name), json!({"component_appearance":component.id})));
+ }
+ }
+ for selected in &app.session.selection {
+ if let solidcraft_engine::Sel::Face { body, point, .. } = selected {
+ options.push((format!("Selected face on {body} (shared appearance)"), json!({"face_appearance":{"body":body,"point":point}})));
+ }
+ }
+ let mut pick: Option<Value> = None;
+ ui_kit::action_menu(ui, "Add Column", |ui| {
+ egui::ScrollArea::vertical().max_height(ui_kit::row_height() * 12.0).show(ui, |ui| {
+ for (label, p) in &options {
+ if ui_kit::secondary_button(ui, label.as_str()).clicked() {
+ pick = Some(p.clone());
+ ui.close();
+ }
+ }
+ ui_kit::action_menu(ui, "Face Appearance", |ui| {
+ ui_kit::note(ui, "semantic_faces", crate::i18n::tr_label("Semantic faces share their appearance across instances."));
+ let state = app.session.model.state();
+ for body in &state.bodies {
+ if body.body.is_mesh() {
+ continue;
+ }
+ ui_kit::action_menu(ui, &format!("Faces on {}", body.name), |ui| {
+ if let Ok(faces) = body.body.faces((body.body.size() * 2e-3).max(1e-3)) {
+ let mut seen = std::collections::BTreeSet::new();
+ let mesh = body.mesh();
+ let mut points = std::collections::BTreeMap::new();
+ for (triangle, index) in mesh.triangles.iter().zip(&mesh.tri_face) {
+ if let std::collections::btree_map::Entry::Vacant(entry) = points.entry(*index as usize)
+ && let Some([a, b, c]) = mesh.tri(triangle)
+ {
+ entry.insert((a + b + c) * (1. / 3.));
+ }
+ }
+ for face in faces {
+ // A curved face centroid can lie on another surface.
+ // Pick an interior triangle point on this actual face.
+ let Some(point) = points.get(&face.index).copied() else { continue };
+ let Ok(target) = app.session.doc.configuration_face_target(body, face.index, point) else { continue };
+ let supported = if target.certificate.is_some() {
+ // Capture read this exact face's current source certificate.
+ // Enumerate its pieces once in the command, not per menu face.
+ app.session.doc.certify_config_face(&target).is_ok()
+ } else {
+ app.session.doc.configuration_face_indices(body, &target).is_ok()
+ };
+ if !supported || !seen.insert(target.name.clone()) {
+ continue;
+ }
+ let Some((_, role)) = target.name.split_once(':') else { continue };
+ if ui_kit::secondary_button(ui, role).clicked() {
+ pick = Some(json!({"face_appearance":{"target":target}}));
+ ui.close();
+ }
+ }
+ }
+ });
+ }
+ });
+ });
+ });
+ if let Some(p) = pick {
+ // The first column starts the table (with a Default row of the current values).
+ let (id, p) = if tb.columns.is_empty() {
+ (
+ "config.configure",
+ if let Some(n) = p.get("param") {
+ json!({ "params": [n] })
+ } else if let Some(n) = p.get("feature") {
+ json!({ "features": [n] })
+ } else if let Some(n) = p.get("material") {
+ json!({ "materials": [n] })
+ } else if let Some(n) = p.get("component_appearance") {
+ json!({ "component_appearances": [n] })
+ } else if let Some(n) = p.get("face_appearance") {
+ json!({ "face_appearances": [n] })
+ } else {
+ json!({ "appearances": [p.get("appearance")] })
+ },
+ )
+ } else {
+ ("config.column", p)
+ };
+ run(app, error, id, p);
+ }
+ });
+ configuration_rules_ui::show(ui, app, error, rule_editor);
+ if let Some(styles) = v["style_status"].as_array() {
+ for style in styles.iter().filter(|style| style["dormant"].as_bool() == Some(true)) {
+ ui_kit::text_block(
+ ui,
+ "dormant",
+ &format!("{}: appearance dormant while its feature is suppressed", style["target"].as_str().unwrap_or("Face")),
+ false,
+ );
+ }
+ }
+ if let Some(message) = v["style_error"].as_str() {
+ ui_kit::text_block(ui, "style_error", message, true);
+ }
+ if let Some(message) = error {
+ ui_kit::text_block(ui, "config_error", message, true);
+ }
+ // Table cells and rule editors own Enter. As in the legacy wide manager, it
+ // commits an edited cell without also submitting the enclosing card.
+ ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Enter));
+}
diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs
index 702889563b..014d68a057 100644
--- a/crates/ui-egui/src/context_menu.rs
+++ b/crates/ui-egui/src/context_menu.rs
@@ -1674,7 +1674,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
crate::browser::dims_overlay(app, ctx);
track_hold(app, ctx);
show_rename(app, ctx);
- show_props(app, ctx);
+ crate::design_properties::show_object(app, ctx);
let Some(at) = app.viewport.context_menu else { return };
let t = Tokens::get();
let screen = ctx.content_rect();
@@ -2060,66 +2060,6 @@ pub fn finish_rename(app: &mut SolveApp, text: Option<&str>, commit: bool) -> bo
true
}
-fn show_props(app: &mut SolveApp, ctx: &egui::Context) {
- let Some((title, v)) = app.menu.props.clone() else { return };
- let mut open = true;
- let f = |x: &Value, k: &str| x.get(k).and_then(Value::as_f64).unwrap_or(f64::NAN);
- crate::frame::window(ctx, format!("Properties: {title}"), crate::frame::Width::Normal)
- .id(egui::Id::new("sc_props"))
- .open(&mut open)
- .resizable(false)
- .collapsible(false)
- .show(ctx, |ui| {
- egui::Grid::new("sc_props_grid").num_columns(2).spacing([16.0, 4.0]).show(ui, |ui| {
- let total = &v["total"];
- let bodies = v["bodies"].as_array().cloned().unwrap_or_default();
- if let [b] = bodies.as_slice() {
- ui.label(crate::i18n::tr_label("Material"));
- ui.label(b["material"].as_str().unwrap_or("Default"));
- ui.end_row();
- ui.label(crate::i18n::tr_label("Density"));
- ui.label(format!("{:.3} g/cm³", f(b, "density_g_cm3")));
- ui.end_row();
- }
- ui.label(crate::i18n::tr_label("Mass"));
- ui.label(format!("{:.3} g", f(total, "mass_g")));
- ui.end_row();
- ui.label(crate::i18n::tr_label("Volume"));
- ui.label(crate::prefs::show_mm(app, f(total, "volume_mm3"), 3));
- ui.end_row();
- ui.label(crate::i18n::tr_label("Area"));
- ui.label(crate::prefs::show_mm(app, f(total, "area_mm2"), 2));
- ui.end_row();
- let geometry = if total.get("center_of_mass").is_some() { Some(total) } else { bodies.first().filter(|_| bodies.len() == 1) };
- if let Some(b) = geometry {
- if let Some(c) = b["center_of_mass"].as_array() {
- let c: Vec<String> = c.iter().map(|x| crate::prefs::show_mm_bare(app, x.as_f64().unwrap_or(f64::NAN))).collect();
- ui.label(crate::i18n::tr_label("Center of mass"));
- ui.label(format!("({}) {}", c.join(", "), crate::prefs::unit_scale(&app.session.doc.units).1));
- ui.end_row();
- }
- let (mn, mx) = (&b["bbox"]["min"], &b["bbox"]["max"]);
- if let (Some(a), Some(z)) = (mn.as_array(), mx.as_array()) {
- let d: Vec<String> = a
- .iter()
- .zip(z)
- .map(|(a, z)| crate::prefs::show_mm_bare(app, z.as_f64().unwrap_or(0.0) - a.as_f64().unwrap_or(0.0)))
- .collect();
- ui.label(crate::i18n::tr_label("Bounding box"));
- ui.label(format!("{} {}", d.join(" × "), crate::prefs::unit_scale(&app.session.doc.units).1));
- ui.end_row();
- }
- }
- ui.label(crate::i18n::tr_label("Faces / edges / vertices"));
- ui.label(format!("{} / {} / {}", total["faces"], total["edges"], total["vertices"]));
- ui.end_row();
- });
- });
- if !open {
- app.menu.props = None;
- }
-}
-
#[cfg(test)]
mod tests {
use super::*;
diff --git a/crates/ui-egui/src/crash_ui.rs b/crates/ui-egui/src/crash_ui.rs
index 75412fefde..a94cd41b9e 100644
--- a/crates/ui-egui/src/crash_ui.rs
+++ b/crates/ui-egui/src/crash_ui.rs
@@ -1,12 +1,10 @@
//! The Crash Reports window (Help > Crash Reports…): the reports `solidcraft_engine::crash`
//! keeps on this computer, each with a reviewed issue draft. It opens by itself after a crash.
-use crate::fonts::RichTextExt as _;
-use egui::{RichText, vec2};
use solidcraft_engine::crash::{self, Summary};
use crate::SolveApp;
-use crate::theme::Tokens;
+use crate::ui_kit;
#[derive(Default)]
pub struct CrashUi {
@@ -34,12 +32,12 @@ impl CrashUi {
}
fn kind_label(kind: &str) -> &'static str {
- match kind {
- "command_panic" => "Internal error in a command",
- "kernel_panic_recovered" => "Kernel error (recovered)",
- "unclean_exit" => "Closed unexpectedly",
- _ => "Internal error",
- }
+ crate::i18n::tr(match kind {
+ "command_panic" => "crash.kind_command",
+ "kernel_panic_recovered" => "crash.kind_kernel",
+ "unclean_exit" => "crash.kind_unclean",
+ _ => "crash.kind_internal",
+ })
}
fn report_heading(r: &Summary) -> String {
@@ -67,73 +65,62 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
if !app.crashes.open {
return;
}
- let t = Tokens::get();
- let mut open = true;
let mut report: Option<String> = None;
let mut delete: Option<Option<String>> = None;
- crate::frame::window(ctx, crate::i18n::tr_label("Crash Reports"), crate::frame::Width::Wide)
- .id(egui::Id::new("sc_crash_reports"))
- .open(&mut open)
- .default_size(vec2(620.0, 420.0))
- .show(ctx, |ui| {
- ui.label(
- RichText::new(
- "Crash reports stay on this computer and are never sent anywhere. Report… opens a draft you review before anything is shared.",
- )
- .color(t.text_dim),
- );
+ let (closed, action) = ui_kit::Prompt::new(egui::Id::new("sc_crash_reports"), "bug_report", crate::i18n::tr_label("Crash Reports"))
+ .cards(2.0)
+ .actions("", crate::i18n::tr("ui.close"), None)
+ .show(ctx, true, |ui| {
+ ui_kit::note(ui, "intro", crate::i18n::tr("crash.intro"));
if let Some(d) = app.crashes.dir.clone() {
- // A long path is cut short (hover shows it all): it must not widen the window
- // past its title bar.
- ui.horizontal(|ui| {
- if ui.small_button("Copy folder path").clicked() {
+ // A long path is cut short (hover shows it all): it must not widen the card.
+ ui_kit::label_actions(ui, &d, |ui| {
+ if ui_kit::small_button(ui, crate::i18n::tr("crash.copy_folder")).clicked() {
ctx.copy_text(d.clone());
}
- ui.add(egui::Label::new(RichText::new(&d).monospace().size(crate::theme::Tokens::get().font_small)).truncate()).on_hover_text(&d);
});
}
- ui.separator();
+ ui_kit::divider(ui, "reports");
if app.crashes.reports.is_empty() {
- ui.label(crate::i18n::tr_label("No crash reports."));
+ ui_kit::note(ui, "none", crate::i18n::tr_label("No crash reports."));
}
egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| {
for r in &app.crashes.reports {
- ui.horizontal(|ui| {
- ui.label(RichText::new(report_heading(r)).semibold().color(crate::theme::Tokens::get().text));
- if let Some(c) = &r.command {
- ui.label(RichText::new(c).monospace().size(crate::theme::Tokens::get().font_small).color(t.text_dim));
- }
- });
- ui.label(RichText::new(&r.message).size(t.font_body));
- if r.kind == "unclean_exit" {
- ui.label(RichText::new(crate::i18n::tr("crash.unclean_explanation")).size(t.font_body).color(t.text_dim));
- }
- ui.horizontal(|ui| {
- if ui.small_button("Report…").clicked() {
+ let title = report_heading(r);
+ ui_kit::label_actions(ui, &title, |ui| {
+ if ui_kit::small_button(ui, crate::i18n::tr("crash.report")).clicked() {
report = Some(r.id.clone());
}
- if ui.small_button("Copy path").clicked() {
+ if ui_kit::small_button(ui, crate::i18n::tr("crash.copy_path")).clicked() {
ctx.copy_text(r.path.clone());
}
- if ui.small_button("Delete").clicked() {
+ if ui_kit::small_button(ui, crate::i18n::tr("ui.delete")).clicked() {
delete = Some(Some(r.id.clone()));
}
- if r.replayable {
- ui.label(RichText::new("replayable").size(crate::theme::Tokens::get().font_small).color(t.text_dim));
- }
});
- ui.add_space(6.0);
+ let mut detail = r.command.clone().unwrap_or_default();
+ if r.replayable {
+ let sep = if detail.is_empty() { "" } else { " · " };
+ detail = format!("{detail}{sep}{}", crate::i18n::tr("crash.replayable"));
+ }
+ if !detail.is_empty() {
+ ui_kit::note(ui, &format!("detail:{}", r.id), &detail);
+ }
+ ui_kit::text_block(ui, &format!("message:{}", r.id), &r.message, false);
+ if r.kind == "unclean_exit" {
+ ui_kit::note(ui, &format!("unclean:{}", r.id), crate::i18n::tr("crash.unclean_explanation"));
+ }
+ ui_kit::divider(ui, &format!("end:{}", r.id));
}
});
if !app.crashes.note.is_empty() {
- ui.label(RichText::new(&app.crashes.note).color(t.text_dim));
+ ui_kit::note(ui, "note", &app.crashes.note);
}
- ui.separator();
- if !app.crashes.reports.is_empty() && ui.button(crate::i18n::tr_label("Delete all")).clicked() {
+ if ui_kit::enabled_button(ui, "Delete all", !app.crashes.reports.is_empty()).clicked() {
delete = Some(None);
}
});
- app.crashes.open = open;
+ app.crashes.open = !(closed || action == ui_kit::Action::Cancel);
if let Some(id) = report
&& let Some(dir) = app.crashes.dir_path()
{
@@ -146,7 +133,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
&& let Some(dir) = app.crashes.dir_path()
{
let n = crash::clear(&dir, which.as_deref());
- app.crashes.note = format!("Deleted {n} report(s).");
+ app.crashes.note = crate::i18n::format("crash.deleted", &[("count", &n.to_string())]);
app.crashes.refresh();
}
}
diff --git a/crates/ui-egui/src/delete.rs b/crates/ui-egui/src/delete.rs
index 571e75ceac..f12389f149 100644
--- a/crates/ui-egui/src/delete.rs
+++ b/crates/ui-egui/src/delete.rs
@@ -2,11 +2,14 @@
//! the viewport or the browser goes in one undoable step through `selection.delete`. When it
//! takes other features with it or makes some fail, a confirmation lists them first.
-use egui::{RichText, vec2};
+use egui::vec2;
use serde_json::{Value, json};
use crate::SolveApp;
-use crate::theme::Tokens;
+use crate::ui_kit;
+
+/// Longest list of names the confirmation shows before "and n more".
+const MAX_LISTED: usize = 20;
/// A delete waiting for confirmation: its parameters and the dry run's report.
#[derive(Clone, Debug)]
@@ -110,55 +113,46 @@ pub fn confirm(app: &mut SolveApp, accept: bool) -> bool {
true
}
-/// The confirmation window.
+/// The confirmation card.
pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
let Some(p) = app.menu.confirm.clone() else { return };
- let t = Tokens::get();
let list = |k: &str| -> Vec<String> {
p.report[k].as_array().map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or_default()
};
let (deleted, fails) = (list("deleted"), list("would_fail"));
- let mut answer: Option<bool> = None;
- crate::frame::window(ctx, crate::i18n::tr_label("Delete"), crate::frame::Width::Normal)
- .id(egui::Id::new("sc_delete_confirm"))
- .collapsible(false)
- .resizable(false)
+ let shared = shared_occurrences(app, &p.params);
+ let (closed, action) = ui_kit::Prompt::new(egui::Id::new("sc_delete_confirm"), "delete", crate::i18n::tr_label("Delete"))
.anchor(egui::Align2::CENTER_CENTER, vec2(0.0, -60.0))
- .show(ctx, |ui| {
- ui.set_max_width(360.0);
- if shared_occurrences(app, &p.params) {
- ui.label(crate::i18n::tr_label("This child is shared. Deleting it removes it from every copy of its parent."));
+ .actions("Delete", "Cancel", None)
+ .show(ctx, true, |ui| {
+ if shared {
+ ui_kit::text_block(
+ ui,
+ "shared",
+ crate::i18n::tr_label("This child is shared. Deleting it removes it from every copy of its parent."),
+ false,
+ );
}
- if !deleted.is_empty() {
- ui.label(crate::i18n::tr_label("These features will be deleted:"));
- for d in deleted.iter().take(20) {
- ui.label(RichText::new(format!(" • {d}")).color(t.text));
- }
- if deleted.len() > 20 {
- ui.label(format!(" … and {} more", deleted.len() - 20));
+ for (key, heading, names, error) in
+ [("deleted", "These features will be deleted:", &deleted, false), ("fails", "These features will fail:", &fails, true)]
+ {
+ if names.is_empty() {
+ continue;
}
- }
- if !fails.is_empty() {
- ui.add_space(6.0);
- ui.label(RichText::new(crate::i18n::tr_label("These features will fail:")).color(t.warning));
- for f in fails.iter().take(20) {
- ui.label(RichText::new(format!(" • {f}")).color(t.warning));
- }
- }
- ui.add_space(8.0);
- ui.horizontal(|ui| {
- if ui.button("Delete").clicked() {
- answer = Some(true);
+ ui_kit::text_block(ui, key, crate::i18n::tr_label(heading), error);
+ for name in names.iter().take(MAX_LISTED) {
+ ui_kit::text_block(ui, &format!("{key}:{name}"), &format!(" • {name}"), error);
}
- if ui.button("Cancel").clicked() {
- answer = Some(false);
+ if names.len() > MAX_LISTED {
+ let more = (names.len() - MAX_LISTED).to_string();
+ ui_kit::text_block(ui, &format!("{key}:more"), &crate::i18n::format("delete.and_more", &[("count", &more)]), error);
}
- });
- if ui.input(|i| i.key_pressed(egui::Key::Escape)) {
- answer = Some(false);
}
});
- if let Some(a) = answer {
- confirm(app, a);
+ match action {
+ ui_kit::Action::Ok => drop(confirm(app, true)),
+ ui_kit::Action::Cancel => drop(confirm(app, false)),
+ _ if closed => drop(confirm(app, false)),
+ _ => {}
}
}
diff --git a/crates/ui-egui/src/design_properties.rs b/crates/ui-egui/src/design_properties.rs
index 1a20dacf6c..53d21b828a 100644
--- a/crates/ui-egui/src/design_properties.rs
+++ b/crates/ui-egui/src/design_properties.rs
@@ -3,18 +3,20 @@
//! the design. OK applies the edited fields through one `document.metadata.set` (one undo step);
//! Cancel and the close button change nothing. File → Design Properties…, the Browser's
//! Document Settings, the root component's menu and `ui.start` of `document.metadata` or
-//! `document.metadata.set` open it.
+//! `document.metadata.set` open it. [`show_object`] draws the Properties card (mass, volume, area,
+//! centre of mass, bounding box, counts) of the body or component a menu asked about; both are
+//! `ui_kit::Prompt` cards.
-use crate::fonts::RichTextExt as _;
-use egui::RichText;
use serde_json::{Map, Value};
use solidcraft_engine::doc::metadata::{DESCRIPTION, WELL_KNOWN};
use crate::SolveApp;
-use crate::theme::Tokens;
+use crate::ui_kit;
/// Longest preview of another tool's value in the list.
const PREVIEW_CHARS: usize = 80;
+/// Rows of other tools' data shown before the list scrolls.
+const OTHERS_ROWS: f32 = 6.0;
/// What is being typed; the properties themselves live in the document.
pub struct DesignProperties {
@@ -86,71 +88,86 @@ fn preview(v: &Value) -> String {
/// Draw the window when it is open. Called once per frame.
pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
let Some(mut d) = app.design_properties.take() else { return };
- let t = Tokens::get();
- let mut open = true;
- let (mut ok, mut cancel) = (false, false);
let metadata = app.session.doc.metadata.clone();
- let title = RichText::new(crate::i18n::tr_label("Design Properties"))
- .semibold()
- .color(crate::theme::Tokens::get().text)
- .size(crate::theme::Tokens::get().font_button);
- crate::frame::window(ctx, title, crate::frame::Width::Normal)
- .id(egui::Id::new("sc_design_properties"))
- .open(&mut open)
- .resizable(false)
- .min_width(420.0)
- .show(ctx, |ui| {
- egui::Grid::new("sc_design_properties_grid").num_columns(2).spacing([12.0, 6.0]).show(ui, |ui| {
- for (i, key) in WELL_KNOWN.iter().enumerate() {
- ui.label(label(key));
- let Some(field) = d.fields.get_mut(i) else { continue };
- ui.vertical(|ui| {
- let edit =
- if *key == DESCRIPTION { egui::TextEdit::multiline(field).desired_rows(3) } else { egui::TextEdit::singleline(field) };
- ui.add(edit.desired_width(280.0));
- // Saved by another tool as something other than text: kept unless typed over.
- if metadata.get(key).is_some() && metadata.text(key).is_none() && d.opened.get(i).is_some_and(String::is_empty) {
- ui.label(RichText::new(crate::i18n::tr("ui.design_properties.not_text")).small().color(t.text_dim));
- }
- });
- ui.end_row();
- }
- });
- ui.add_space(4.0);
- ui.label(RichText::new(crate::i18n::tr("ui.design_properties.exports")).small().color(t.text_dim));
- let others: Vec<(&String, &Value)> = metadata.others().collect();
- if !others.is_empty() {
- ui.add_space(4.0);
- egui::CollapsingHeader::new(format!("{} ({})", crate::i18n::tr("ui.design_properties.others"), others.len()))
- .id_salt("sc_design_properties_others")
- .show(ui, |ui| {
- ui.label(RichText::new(crate::i18n::tr("ui.design_properties.others_note")).small().color(t.text_dim));
- egui::ScrollArea::vertical().max_height(160.0).show(ui, |ui| {
- for (k, v) in others {
- ui.label(RichText::new(k).monospace().size(crate::theme::Tokens::get().font_body).color(t.text));
- ui.label(RichText::new(preview(v)).monospace().small().color(t.text_dim));
- }
- });
- });
+ let title = crate::i18n::tr_label("Design Properties");
+ let (closed, action) = ui_kit::Prompt::new(egui::Id::new("sc_design_properties"), "settings", title).fields().show(ctx, true, |ui| {
+ for (i, key) in WELL_KNOWN.iter().enumerate() {
+ let label = label(key);
+ let Some(field) = d.fields.get_mut(i) else { continue };
+ if *key == DESCRIPTION {
+ ui_kit::multiline_text_field(ui, label, egui::Id::new(("sc_design_properties", key)), field);
+ } else {
+ ui_kit::row(ui, label, |ui| ui_kit::text_field(ui, field, ""));
}
- if let Some(e) = &d.error {
- ui.label(RichText::new(e).color(t.error));
+ // Saved by another tool as something other than text: kept unless typed over.
+ if metadata.get(key).is_some() && metadata.text(key).is_none() && d.opened.get(i).is_some_and(String::is_empty) {
+ ui_kit::caption(ui, label, crate::i18n::tr("ui.design_properties.not_text"));
}
- ui.separator();
- // OK and Cancel flush right, as in every dialog.
- ui.horizontal(|ui| {
- ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
- cancel = ui.button(crate::i18n::tr("ui.cancel")).clicked();
- ok = ui.button(crate::i18n::tr("ui.heading_ok")).clicked();
+ }
+ ui_kit::note(ui, "exports", crate::i18n::tr("ui.design_properties.exports"));
+ let others: Vec<(&String, &Value)> = metadata.others().collect();
+ if !others.is_empty() {
+ let heading = format!("{} ({})", crate::i18n::tr("ui.design_properties.others"), others.len());
+ ui_kit::section(ui, "sc_design_properties_others", &heading, false, |ui| {
+ ui_kit::note(ui, "others", crate::i18n::tr("ui.design_properties.others_note"));
+ egui::ScrollArea::vertical().max_height(ui_kit::row_height() * OTHERS_ROWS).show(ui, |ui| {
+ for (key, value) in others {
+ ui_kit::row(ui, key, |ui| ui_kit::cell_text(ui, &preview(value)));
+ }
});
});
- });
- if !open || cancel || (ok && apply(app, &mut d)) {
+ }
+ if let Some(error) = &d.error {
+ ui_kit::text_block(ui, "error", error, true);
+ }
+ });
+ if closed || action == ui_kit::Action::Cancel || (action == ui_kit::Action::Ok && apply(app, &mut d)) {
return;
}
app.design_properties = Some(d);
}
+/// Draw the Properties window of the body or component the menu asked about (mass, volume,
+/// area, centre of mass, bounding box and counts), when it is open. Close dismisses it.
+pub fn show_object(app: &mut SolveApp, ctx: &egui::Context) {
+ let Some((title, v)) = app.menu.props.clone() else { return };
+ let number = |x: &Value, k: &str| x.get(k).and_then(Value::as_f64).unwrap_or(f64::NAN);
+ let mut rows: Vec<(&str, String)> = Vec::new();
+ let total = &v["total"];
+ let bodies = v["bodies"].as_array().cloned().unwrap_or_default();
+ if let [b] = bodies.as_slice() {
+ rows.push(("Material", b["material"].as_str().unwrap_or("Default").to_string()));
+ rows.push(("Density", format!("{:.3} g/cm³", number(b, "density_g_cm3"))));
+ }
+ rows.push(("Mass", format!("{:.3} g", number(total, "mass_g"))));
+ rows.push(("Volume", crate::prefs::show_mm(app, number(total, "volume_mm3"), 3)));
+ rows.push(("Area", crate::prefs::show_mm(app, number(total, "area_mm2"), 2)));
+ let geometry = if total.get("center_of_mass").is_some() { Some(total) } else { bodies.first().filter(|_| bodies.len() == 1) };
+ if let Some(b) = geometry {
+ let unit = crate::prefs::unit_scale(&app.session.doc.units).1;
+ if let Some(c) = b["center_of_mass"].as_array() {
+ let c: Vec<String> = c.iter().map(|x| crate::prefs::show_mm_bare(app, x.as_f64().unwrap_or(f64::NAN))).collect();
+ rows.push(("Center of mass", format!("({}) {unit}", c.join(", "))));
+ }
+ let (mn, mx) = (&b["bbox"]["min"], &b["bbox"]["max"]);
+ if let (Some(a), Some(z)) = (mn.as_array(), mx.as_array()) {
+ let d: Vec<String> =
+ a.iter().zip(z).map(|(a, z)| crate::prefs::show_mm_bare(app, z.as_f64().unwrap_or(0.0) - a.as_f64().unwrap_or(0.0))).collect();
+ rows.push(("Bounding box", format!("{} {unit}", d.join(" × "))));
+ }
+ }
+ rows.push(("Faces / edges / vertices", format!("{} / {} / {}", total["faces"], total["edges"], total["vertices"])));
+ let heading = crate::i18n::format("properties.title", &[("name", &title)]);
+ let (closed, action) = ui_kit::Prompt::new(egui::Id::new("sc_props"), "settings", &heading).actions("", "Close", None).show(ctx, true, |ui| {
+ for (label, value) in &rows {
+ ui_kit::row(ui, crate::i18n::tr_label(label), |ui| ui_kit::cell_text(ui, value));
+ }
+ });
+ if closed || action == ui_kit::Action::Cancel {
+ app.menu.props = None;
+ }
+}
+
#[cfg(test)]
mod tests {
use serde_json::json;
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index 2b5ce075bf..fbe47fa5ee 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -2,10 +2,9 @@
//! inputs (geometry picked in the viewport, never typed), then runs its command; it never
//! changes the design itself. Things selected before the command starts become its input.
-use crate::fonts::RichTextExt as _;
use std::hash::{Hash, Hasher};
-use egui::{Color32, RichText, Stroke, vec2};
+use egui::{RichText, vec2};
use serde_json::{Value, json};
use solidcraft_engine::Sel;
use solidcraft_engine::Session;
@@ -319,10 +318,6 @@ pub enum Kind {
operation: usize,
keep_tools: bool,
},
- Params {
- new_name: String,
- new_expr: String,
- },
EditParam {
name: String,
expr: String,
@@ -737,7 +732,6 @@ impl Dialog {
Kind::Combine { operation: 1, keep_tools: false },
vec![SelInput::new("Target Body", BODIES, false), SelInput::new("Tool Bodies", BODIES, true)],
),
- "parameters.change" => Dialog::new(Kind::Params { new_name: String::new(), new_expr: String::new() }, vec![]),
_ => {
let (kind, inputs) = crate::dialogs_assembly::start(app, id)
.or_else(|| crate::dialogs_sheet::start(app, id))
@@ -972,8 +966,7 @@ impl Dialog {
/// Dialogs holding a table get the wide limit.
pub fn is_wide(&self) -> bool {
- matches!(self.kind, Kind::Params { .. })
- || (matches!(self.kind, Kind::PatternRect { .. }) && self.inputs.first().is_some_and(|i| i.accept == selection::FEATURES))
+ (matches!(self.kind, Kind::PatternRect { .. }) && self.inputs.first().is_some_and(|i| i.accept == selection::FEATURES))
|| matches!(&self.kind, Kind::Motion(k) if k.wide())
}
@@ -1552,37 +1545,16 @@ fn plane_value(s: &Session, sel: Option<&Sel>) -> Option<Value> {
/// A value field; true when Enter was pressed in it.
pub(crate) fn field(ui: &mut egui::Ui, s: &mut String) -> bool {
- if crate::ui_kit::contains(ui) {
- return crate::ui_kit::field(ui, s);
- }
- let r = ui.text_edit_singleline(s);
- crate::theme::TabAccent::number_focus(ui, &r);
- publish_row(&r);
- crate::params_dialog::complete(ui, &r, s);
- r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter))
+ crate::ui_kit::field(ui, s)
}
-/// A checkbox row. Its row handle (`dialog:<row label>`) lets a scenario click it by the label
-/// beside it, the way `field` already publishes one for a value field.
pub(crate) fn check(ui: &mut egui::Ui, on: &mut bool) {
- let r = if crate::ui_kit::contains(ui) { crate::ui_kit::checkbox(ui, "", on) } else { ui.checkbox(on, "") };
+ let r = crate::ui_kit::checkbox(ui, "", on);
publish_check(ui, &r, *on);
}
pub(crate) fn combo(ui: &mut egui::Ui, id: &str, labels: &[&str], sel: &mut usize) {
- if crate::ui_kit::contains(ui) {
- crate::ui_kit::dropdown(ui, id, sel, labels);
- return;
- }
- let row = ROW.with(|r| r.borrow().clone());
- let selected = labels.get(*sel).copied().map(tr).unwrap_or("");
- let r = egui::ComboBox::from_id_salt(id).selected_text(selected).width(FIELD_W).show_ui(ui, |ui| {
- for (i, l) in labels.iter().enumerate() {
- let item = ui.selectable_value(sel, i, tr(l));
- crate::scenario::publish_handle(&format!("dialog:{row}:{l}"), item.rect.center());
- }
- });
- publish_row(&r.response);
+ crate::ui_kit::dropdown(ui, id, sel, labels);
}
thread_local! {
@@ -1654,7 +1626,6 @@ fn title(k: &Kind) -> &'static str {
_ => "TORUS",
},
Kind::Combine { .. } => "COMBINE",
- Kind::Params { .. } => "PARAMETERS",
Kind::EditParam { .. } => "EDIT DIMENSION",
Kind::Rename { .. } => "RENAME",
Kind::ConfirmDelete { .. } => "DELETE FEATURE",
@@ -1695,33 +1666,9 @@ fn hint(inp: &SelInput) -> &'static str {
}
}
-/// Width of the label column; longer labels are cut with "…".
-const LABEL_W: f32 = 92.0;
-/// The label column grows to fit its labels up to this, then long labels wrap.
-const LABEL_MAX_W: f32 = 150.0;
-
pub(crate) fn form_row<R>(ui: &mut egui::Ui, label: &str, add: impl FnOnce(&mut egui::Ui) -> R) -> R {
ROW.with(|row| *row.borrow_mut() = label.to_string());
- if crate::ui_kit::contains(ui) {
- crate::ui_kit::row(ui, label, add)
- } else {
- row_label(ui, label);
- let result = add(ui);
- ui.end_row();
- result
- }
-}
-
-/// A row label in the dialog's label column (the grid sizes the column to its widest label).
-pub(crate) fn row_label(ui: &mut egui::Ui, text: &str) {
- ROW.with(|r| *r.borrow_mut() = text.to_string());
- let display_text = tr(text);
- let full = egui::WidgetText::from(display_text).into_galley(ui, Some(egui::TextWrapMode::Extend), f32::INFINITY, egui::TextStyle::Body).size().x;
- let w = full.clamp(LABEL_W, LABEL_MAX_W);
- ui.allocate_ui_with_layout(vec2(w, 22.0), egui::Layout::left_to_right(egui::Align::Center), |ui| {
- ui.set_width(w);
- ui.add(egui::Label::new(display_text).wrap());
- });
+ crate::ui_kit::row(ui, label, add)
}
thread_local! {
@@ -1953,22 +1900,9 @@ fn input_rows_range(d: &mut Dialog, ui: &mut egui::Ui, s: &Session, range: std::
} else {
RichText::new(crate::i18n::tr("dialog.select")).color(t.text)
};
- let stroke = if active { Stroke::new(1.5, t.accent) } else { Stroke::new(1.0, t.dialog_border.gamma_multiply(1.6)) };
- // Not in the Tab order: Tab moves between values.
- let b = egui::Button::new(text.clone())
- .wrap_mode(egui::TextWrapMode::Wrap)
- .fill(if filled { t.chip } else { Color32::TRANSPARENT })
- .stroke(stroke)
- .min_size(vec2(0.0, 22.0))
- .sense(egui::Sense::CLICK);
- let chip = if crate::ui_kit::contains(ui) {
- // The dense field replaces the legacy arrow chip with a filled surface.
- let selected_text = text.text().strip_prefix("↖ ").unwrap_or_else(|| text.text());
- let prompt = if !filled && inp.label == "Edges" { tr("Select edges") } else { selected_text };
- crate::ui_kit::selection_field_state(ui, prompt, active, filled)
- } else {
- crate::frame::add_outlined(ui, b, stroke.width)
- };
+ let selected_text = text.text().strip_prefix("↖ ").unwrap_or_else(|| text.text());
+ let prompt = if !filled && inp.label == "Edges" { tr("Select edges") } else { selected_text };
+ let chip = crate::ui_kit::selection_field_state(ui, prompt, active, filled);
let chip_rect = chip.rect;
publish_row(&chip);
let tooltip = if let Some(reference) = stored_reference {
@@ -1990,15 +1924,11 @@ fn input_rows_range(d: &mut Dialog, ui: &mut egui::Ui, s: &Session, range: std::
activate = Some(i);
}
if !inp.items.is_empty() || stored_reference.is_some() {
- let button = if crate::ui_kit::contains(ui) {
- let rect = egui::Rect::from_center_size(
- egui::pos2(chip_rect.right() - t.space_24 / 2.0, chip_rect.center().y),
- vec2(t.space_24, t.space_24),
- );
- crate::ui_kit::icon_button_at(ui, rect, "close", "Clear the selection")
- } else {
- ui.small_button("×").on_hover_text(tr("Clear the selection"))
- };
+ let rect = egui::Rect::from_center_size(
+ egui::pos2(chip_rect.right() - t.space_24 / 2.0, chip_rect.center().y),
+ vec2(t.space_24, t.space_24),
+ );
+ let button = crate::ui_kit::icon_button_at(ui, rect, "close", "Clear the selection");
crate::scenario::publish_handle(&format!("dialog:clear:{}", inp.label), button.rect.center());
if button.clicked() {
clear = Some(i);
@@ -2070,7 +2000,7 @@ fn awaiting_selection(error: &str) -> bool {
error.get(..7).is_some_and(|start| start.eq_ignore_ascii_case("select "))
}
-fn error_rows(app: &mut SolveApp, ctx: &egui::Context, d: &mut Dialog, ui: &mut egui::Ui, full_width: bool) {
+fn error_rows(app: &mut SolveApp, ctx: &egui::Context, d: &mut Dialog, ui: &mut egui::Ui) {
if matches!(d.kind, Kind::SketchModify(_))
&& d.previews()
&& let Err(error) = apply_commands(app, d)
@@ -2088,26 +2018,17 @@ fn error_rows(app: &mut SolveApp, ctx: &egui::Context, d: &mut Dialog, ui: &mut
if matches!(d.kind, Kind::SketchModify(_)) && awaiting_selection(&error) {
return;
}
- if !full_width {
- row_label(ui, "");
- }
ui.vertical(|ui| {
- ui.add(egui::Label::new(RichText::new(error.as_str()).color(Tokens::get().error)).wrap());
+ crate::ui_kit::text_block(ui, "error", &error, true);
let response = crate::ui_kit::secondary_button(ui, "Create Issue…");
crate::scenario::publish_handle("dialog:create_issue", response.rect.center());
if response.clicked() {
crate::issue_report::begin(app, ctx, Some(d), Some(&error));
}
});
- ui.end_row();
}
}
-/// Width limits of a docked dialog: shrink-wrapped to its content within these.
-use crate::frame::{DIALOG_MAX_W, DIALOG_MIN_W, DIALOG_WIDE_MAX_W};
-/// Width of value fields and choice boxes in a dialog.
-pub(crate) const FIELD_W: f32 = 124.0;
-
/// Find the Boundary Fill cells again when the tool bodies changed (keeping the choices of
/// cells that are still there).
fn update_fill_cells(app: &SolveApp, d: &mut Dialog) {
@@ -2180,10 +2101,6 @@ fn update_measure(app: &SolveApp, d: &mut Dialog) {
}
}
-fn fmt_mm(app: &SolveApp, v: &Value) -> String {
- v.as_f64().map(|x| crate::prefs::show_mm(app, x, 1)).unwrap_or_default()
-}
-
/// Which distance of a pair the Measure panel shows (and the canvas draws).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Shown {
@@ -2215,94 +2132,6 @@ pub(crate) fn shown_distance(r: &Value, show: Option<Shown>) -> Option<(Shown, f
show.and_then(get).or_else(|| get(default)).or_else(|| get(Shown::Min))
}
-/// The measurement in the dialog.
-fn measure_rows(app: &SolveApp, ui: &mut egui::Ui, r: Option<&Value>, show: &mut Option<Shown>) {
- let t = Tokens::get();
- let Some(r) = r else {
- ui.label("");
- ui.label(RichText::new(tr("pick one or two vertices, edges or faces")).color(t.text_dim));
- ui.end_row();
- return;
- };
- if let Some(e) = r.get("error").and_then(Value::as_str) {
- ui.label("");
- ui.label(RichText::new(e).color(t.error));
- ui.end_row();
- return;
- }
- let mm = |v: &Value| fmt_mm(app, v);
- for (i, it) in r["items"].as_array().into_iter().flatten().enumerate() {
- // Round items: Ø first, then R, then the length (circumference, or the arc's length
- // and angle).
- let mut lines: Vec<String> = Vec::new();
- if it.get("diameter").is_some() {
- lines.push(format!("Ø {}", mm(&it["diameter"])));
- lines.push(format!("R {}", mm(&it["radius"])));
- if it.get("circumference").is_some() {
- lines.push(format!("{} {}", tr("Circumference"), mm(&it["circumference"])));
- } else if let Some(a) = it["angle_deg"].as_f64() {
- lines.push(format!("{} {}", tr("Arc length"), mm(&it["arc_length"])));
- lines.push(format!("{} {a:.2}°", crate::i18n::tr_label("Angle")));
- }
- }
- if let Some(sl) = it.get("slot") {
- lines.push(format!("{} {}", tr("Slot width"), mm(&sl["width"])));
- lines.push(format!("{} {}", tr("Centre to centre"), mm(&sl["center_distance"])));
- lines.push(format!("{} {}", tr("Overall length"), mm(&sl["overall_length"])));
- }
- let round = it.get("diameter").is_some();
- match it["type"].as_str() {
- Some("edge" | "sketch_curve") if !round => lines.push(format!("{} {}", tr("Length"), mm(&it["length_mm"]))),
- Some("face" | "profile") => {
- lines.push(format!("{} {}", tr("Area"), crate::prefs::show_mm(app, it["area_mm2"].as_f64().unwrap_or(0.0), 2)))
- }
- Some("vertex" | "sketch_point") => {
- let p = &it["position"];
- lines.push(format!("At {}, {}, {}", mm(&p[0]), mm(&p[1]), mm(&p[2])));
- }
- _ => {}
- }
- for (k, line) in lines.into_iter().enumerate() {
- ui.label(if k == 0 { format!("Item {}", i + 1) } else { String::new() });
- ui.label(line);
- ui.end_row();
- }
- }
- if let Some((now, d, a, b)) = shown_distance(r, *show) {
- if r.get("center_distance").is_some() {
- // Centre, min and max all listed; the chosen one is drawn and broken into ΔX/Y/Z.
- for (which, label, key) in
- [(Shown::Centre, "Centre to centre", "center_distance"), (Shown::Min, "Min", "distance_mm"), (Shown::Max, "Max", "max")]
- {
- let Some(v) = r.get(key).filter(|v| v.is_number()) else { continue };
- if ui.radio(now == which, tr(label)).clicked() {
- *show = Some(which);
- }
- let text = RichText::new(mm(v));
- ui.label(if now == which { text.semibold().color(crate::theme::Tokens::get().text) } else { text });
- ui.end_row();
- }
- } else {
- ui.label(RichText::new(crate::i18n::tr_label("Distance")).semibold().color(crate::theme::Tokens::get().text));
- ui.label(RichText::new(crate::prefs::show_mm(app, d, 1)).semibold().color(crate::theme::Tokens::get().text));
- ui.end_row();
- }
- let delta = b - a;
- for (l, v) in [("ΔX", delta.x), ("ΔY", delta.y), ("ΔZ", delta.z)] {
- ui.label(l);
- ui.label(crate::prefs::show_mm(app, v.abs(), 1));
- ui.end_row();
- }
- }
- if let Some(a) = r["angle_deg"].as_f64()
- && r["items"].as_array().is_some_and(|v| v.len() == 2)
- {
- ui.label(RichText::new(crate::i18n::tr_label("Angle")).semibold().color(crate::theme::Tokens::get().text));
- ui.label(RichText::new(format!("{a:.3}°")).semibold().color(crate::theme::Tokens::get().text));
- ui.end_row();
- }
-}
-
/// Smart Extrude (#1257, see [`crate::smart_extrude`]): a new pick sets the direction from the
/// side it was picked from, and the automatic operation follows the geometry, latched per side.
fn auto_operation(app: &SolveApp, d: &mut Dialog) {
@@ -2401,7 +2230,6 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
}
}
// Physical materials: the library's, then the design's own (material.create).
- let material_names = app.session.doc.material_names();
let t = Tokens::get();
let vp = crate::shell::content_rect(app, app.viewport.rect.unwrap_or_else(|| ctx.content_rect()));
// The Sketch Palette owns the right edge for as long as a sketch is being edited. A dialog
@@ -2411,10 +2239,9 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
} else {
crate::frame::Side::Right
};
- let dense_form = dense::command(&d.kind).is_some();
let top = crate::shell::panel_top(app, vp, vp.bottom(), side);
// Empty/hostile viewport geometry cannot provide a safe window rectangle.
- if dense_form && (!vp.is_finite() || !vp.is_positive()) {
+ if !vp.is_finite() || !vp.is_positive() {
app.dialog = Some(d);
return;
}
@@ -2429,16 +2256,13 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
let mut apply_again = app.applying.is_some() && d.repeat_after_apply;
let mut cancel = false;
let mut enter = false;
- let wide = d.is_wide();
+ let wide = matches!(&d.kind, Kind::Motion(k) if k.wide());
let raw_title = title(&d.kind);
let heading = if d.editing.is_some() { crate::i18n::format("dialog.edit_title", &[("title", tr(raw_title))]) } else { tr(raw_title).to_string() };
- let frame = if dense_form { crate::ui_kit::Panel::feature_frame(ctx, app.ui.layout, side) } else { crate::frame::dock_frame(ctx, side) };
- // The area includes the border as well as the inner margins; reserve all of it so a
- // horizontally scrolling table cannot push a wide dialog two pixels past its limit.
- let horizontal_frame = frame.inner_margin.leftf() + frame.inner_margin.rightf() + 2.0 * frame.stroke.width;
+ let frame = crate::ui_kit::Panel::feature_frame(ctx, app.ui.layout, side);
// OK is offered once the inputs make a feature.
- let has_ok = !matches!(d.kind, Kind::Sketch | Kind::Params { .. } | Kind::Measure { .. });
+ let has_ok = !matches!(d.kind, Kind::Sketch | Kind::Measure { .. });
let valid = match &d.kind {
Kind::Sketch => false,
Kind::SaveMesh(_) => crate::dialogs_save_mesh::ready(&d.inputs),
@@ -2449,302 +2273,88 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
}
_ => !has_ok || !d.previews() || (built.unwrap_or_else(|| apply_commands(app, &d).is_ok()) && app.preview.error.is_none()),
};
- let width = if wide { crate::frame::Width::Wide } else { crate::frame::Width::Normal };
- let wkey = egui::Id::new(("sc_dialog_w", wide));
- let panel = crate::ui_kit::Panel::new(&heading, egui::Id::new(("sc_dialog", title(&d.kind))), anchor, vp, side, frame);
- let window = if dense_form {
- panel.window()
+ // Measure only closes; a deletion's primary action says what it does.
+ let (ok_label, close_label) = match &d.kind {
+ Kind::Measure { .. } => ("", "Close"),
+ Kind::ConfirmDelete { .. } => ("Delete", "Cancel"),
+ Kind::SaveMesh(k) => (crate::dialogs_save_mesh::button(k), "Cancel"),
+ Kind::ViewDxf { .. } => ("Export DXF…", "Cancel"),
+ _ => ("OK", "Cancel"),
+ };
+ let panel =
+ crate::ui_kit::Panel::new(&heading, egui::Id::new(("sc_dialog", title(&d.kind))), anchor, vp, side, frame).actions(ok_label, close_label);
+ let panel = if wide {
+ let panel = panel.wide();
+ if side == crate::frame::Side::Left {
+ let available = app.viewport.palette_rect.map_or(vp.width(), |r| (r.left() - vp.left() - t.space_8).max(0.0));
+ panel.width((t.form_card_width * 3.0).min(available))
+ } else {
+ panel
+ }
} else {
- crate::frame::docked_on(
- RichText::new(heading.clone()).semibold().color(crate::theme::Tokens::get().text).size(crate::theme::Tokens::get().font_button),
- egui::Id::new(("sc_dialog", title(&d.kind))),
- anchor,
- vp.bottom() - anchor.y - 8.0,
- width,
- side,
- )
+ panel
};
+ let window = panel.window();
let repeatable =
matches!(&d.kind, Kind::SketchModify(k) if crate::sketch_modify_ui::repeatable(k)) && d.editing.is_none() && !d.extra.contains_key("pattern");
let response = window.frame(frame).open(&mut keep).show(ctx, |ui| {
- if dense_form {
- let spec = dense::command(&d.kind).and_then(solidcraft_engine::find_command);
- let icon = spec.as_ref().map_or("", |s| s.icon);
- let label = spec.as_ref().map_or(heading.as_str(), |s| tr(s.label));
- let label = if d.editing.is_some() { heading.as_str() } else { label };
- let (closed, action) = panel.feature(
- ui,
- crate::ui_kit::FeatureOptions {
- icon,
- title: label,
- drag_key: title(&d.kind),
- moved,
- docked,
- apply_label: repeatable.then_some("Apply"),
- },
- app.applying.is_some(),
- valid,
- |ui| {
- enter |= dense::rows(app, ctx, &mut d, ui);
- let text = app.applying.as_ref().map(|job| {
- let seconds = ((crate::now_ms() - job.started) / 1000.0).floor().max(0.0);
- crate::i18n::format("dialog.computing", &[("seconds", &format!("{seconds:.0}"))])
- });
- crate::ui_kit::ComputeStatus { text, busy: app.applying.is_some() || app.preview.busy, applying: app.applying.is_some() }
- },
- );
- cancel |= closed;
- if app.issue_report.draft.is_none() {
- match action {
- crate::ui_kit::Action::Ok => {
- ok = true;
- apply_again = false;
- }
- crate::ui_kit::Action::Cancel => {
- if !app.esc_handled || !ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
- cancel = true;
- }
- }
- crate::ui_kit::Action::Apply => {
- ok = true;
- apply_again = true;
- }
- crate::ui_kit::Action::None => {}
- }
- }
- return;
+ let spec = dense::command(&d.kind).and_then(solidcraft_engine::find_command);
+ let icon = spec.as_ref().map_or("", |s| s.icon);
+ let label = spec.as_ref().map_or(heading.as_str(), |s| tr(s.label));
+ let label = if d.editing.is_some() { heading.as_str() } else { label };
+ let heading =
+ crate::ui_kit::FeatureOptions { icon, title: label, drag_key: title(&d.kind), moved, docked, apply_label: repeatable.then_some("Apply") };
+ let applying = app.applying.is_some();
+ let mut collapsed = d.collapsed;
+ let manager = matches!(
+ d.kind,
+ Kind::Material { .. }
+ | Kind::Appearance(_)
+ | Kind::Motion(crate::dialogs_motion::Mo::Configurations { .. })
+ | Kind::Sheet(crate::dialogs_sheet::Sm::Rules { .. })
+ | Kind::Plastic(crate::dialogs_plastic::Pl::Rules { .. })
+ );
+ // A study/configuration owns Enter for its cells, including when folded.
+ let cell_enter = matches!(&d.kind, Kind::Motion(k) if k.wide());
+ if cell_enter && collapsed {
+ ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter));
}
- ui.spacing_mut().text_edit_width = FIELD_W;
- // Long texts (errors, notes) wrap instead of widening the dialog.
- ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Wrap);
- let margin = horizontal_frame;
- let min_w = if wide { 480.0 } else { DIALOG_MIN_W } - margin;
- ui.set_min_width(min_w);
- ui.set_max_width(if wide { DIALOG_WIDE_MAX_W } else { DIALOG_MAX_W } - margin);
- // Rows that end at the right edge line up with last frame's content width.
- let total = crate::frame::content_width(ui, wkey, min_w);
- // Header: "−" folds the dialog, the command name, "»" at the right, on the title band,
- // which also moves the dialog.
- let band_top = ui.cursor().min;
- let band = egui::Rect::from_min_size(band_top, vec2(total, ui.spacing().interact_size.y + 2.0));
- crate::frame::drag_dock(ui, band, title(&d.kind), moved, anchor - docked);
- crate::frame::heading(ui, crate::frame::Level::Title, total, |ui| {
- let total = total - 2.0 * crate::frame::HEADING_MARGIN;
- let fold = if d.collapsed { "+" } else { "−" };
- if ui
- .add(egui::Button::new(RichText::new(fold).size(crate::theme::Tokens::get().font_heading)).frame(false))
- .on_hover_text(if d.collapsed { "Expand" } else { "Collapse" })
- .clicked()
- {
- d.collapsed = !d.collapsed;
- }
- // Not selectable: a drag on the title moves the dialog.
- ui.add(
- egui::Label::new(
- RichText::new(heading.as_str()).semibold().color(crate::theme::Tokens::get().text).size(crate::theme::Tokens::get().font_label),
- )
- .selectable(false),
- );
- let chevron_width = ui.spacing().interact_size.x;
- crate::frame::right_aligned(ui, total, chevron_width, |ui| {
- let chevron = if d.collapsed { "«" } else { "»" };
- if ui
- .add(egui::Button::new(RichText::new(chevron).color(t.text_dim)).frame(false).min_size(vec2(chevron_width, 0.0)))
- .on_hover_text(if d.collapsed { "Expand" } else { "Collapse" })
- .clicked()
- {
- d.collapsed = !d.collapsed;
- }
+ let body = |ui: &mut egui::Ui| {
+ enter |= dense::rows(app, ctx, &mut d, ui);
+ if cell_enter {
+ ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter));
+ }
+ let text = app.applying.as_ref().map(|job| {
+ let seconds = ((crate::now_ms() - job.started) / 1000.0).floor().max(0.0);
+ crate::i18n::format("dialog.computing", &[("seconds", &format!("{seconds:.0}"))])
});
- });
- if d.collapsed {
- return;
- }
- ui.add_space(2.0);
- // A sizing pass initially offers almost no height to an auto-sized window.
- // Give only the fields a viewport-derived scroll budget; header and actions
- // stay visible, while short forms still shrink to their natural height.
- let vertical_frame = frame.inner_margin.topf() + frame.inner_margin.bottomf() + 2.0 * frame.stroke.width;
- let footer_height = ui.spacing().interact_size.y.max(24.0) + 6.0 + ui.spacing().item_spacing.y;
- let fields_height = (vp.bottom() - anchor.y - 8.0 - vertical_frame - ui.min_rect().height() - footer_height).max(1.0);
- egui::ScrollArea::vertical().id_salt("feature_fields").min_scrolled_height(fields_height).max_height(fields_height).show(ui, |ui| {
- // While OK computes, its inputs hold: what is applied is what was asked.
- if app.applying.is_some() {
- ui.disable();
- }
- // Configuration tables own their column widths and scrolling; the two-column form
- // grid would squeeze their row names and action buttons into a label-sized cell.
- if let Kind::Motion(k @ crate::dialogs_motion::Mo::Configurations { .. }) = &mut d.kind {
- enter |= crate::dialogs_motion::rows(app, ui, k, &mut d.inputs);
- }
- egui::Grid::new("sc_dialog_grid").num_columns(2).spacing(vec2(10.0, 8.0)).show(ui, |ui| {
- if matches!(&d.kind, Kind::Motion(crate::dialogs_motion::Mo::Configurations { .. })) {
- return;
- }
- placement_row(&mut d, ui);
- if matches!(&d.kind, Kind::SketchModify(k) if k.previews())
- || matches!(d.kind, Kind::Mirror | Kind::PatternRect { .. } | Kind::PatternCirc { .. } | Kind::PathPattern { .. })
- {
- row_label(ui, "dialog.step");
- let label = d.active_input().map(|input| tr(input.label)).unwrap_or_else(|| tr("Objects"));
- ui.label(crate::i18n::format(
- "dialog.selection_step",
- &[("step", &(d.active + 1).to_string()), ("total", &d.inputs.len().to_string()), ("input", label)],
- ));
- ui.end_row();
- row_label(ui, "");
- ui.label(tr("dialog.selection_guidance"));
- ui.end_row();
+ crate::ui_kit::ComputeStatus { text, busy: app.applying.is_some() || app.preview.busy, applying: app.applying.is_some() }
+ };
+ let (closed, action) = if manager {
+ panel.feature_collapsible(ui, heading, applying, valid, &mut collapsed, body)
+ } else {
+ panel.feature(ui, heading, applying, valid, body)
+ };
+ d.collapsed = collapsed;
+ cancel |= closed;
+ if app.issue_report.draft.is_none() {
+ match action {
+ crate::ui_kit::Action::Ok => {
+ ok = true;
+ apply_again = false;
}
- d.sync_fillet_chain(&app.session);
- input_rows(&mut d, ui, &app.session);
- match &mut d.kind {
- // These forms are drawn by dense::rows before entering this legacy grid.
- Kind::Extrude { .. } | Kind::Fillet { .. } | Kind::PatternRect { .. } | Kind::PatternCirc { .. } | Kind::Hole { .. } => {}
-
- Kind::Sketch | Kind::SketchModify(_) | Kind::Text(_) | Kind::TextMove(_) | Kind::EditParam { .. } => {}
-
- Kind::Revolve { .. }
- | Kind::Shell { .. }
- | Kind::Draft { .. }
- | Kind::Mirror
- | Kind::OffsetPlane { .. }
- | Kind::AnglePlane { .. }
- | Kind::PathPlane { .. }
- | Kind::Split
- | Kind::DeleteFaces
- | Kind::ReplaceFace
- | Kind::Remove
- | Kind::Midplane
- | Kind::MeshConvert { .. }
- | Kind::Construct { .. }
- | Kind::Rib { .. }
- | Kind::Emboss { .. }
- | Kind::Align { .. }
- | Kind::BoundaryFill { .. }
- | Kind::PathPattern { .. }
- | Kind::Pipe { .. }
- | Kind::Stock { .. }
- | Kind::Scale { .. }
- | Kind::OffsetFaces { .. }
- | Kind::Thread { .. }
- | Kind::Loft { .. }
- | Kind::Sweep { .. }
- | Kind::Move { .. }
- | Kind::Primitive { .. }
- | Kind::Combine { .. } => {}
- Kind::Measure { result, show, .. } => measure_rows(app, ui, result.as_ref(), show),
- Kind::Material { index } => {
- let names: Vec<&str> = material_names.iter().map(String::as_str).collect();
- row_label(ui, "Material");
- combo(ui, "mat", &names, index);
- ui.end_row();
- }
- Kind::Section { offset, flip } => {
- row_label(ui, "Distance");
- enter |= field(ui, offset);
- ui.end_row();
- row_label(ui, "Flip");
- ui.checkbox(flip, "");
- ui.end_row();
- }
-
- Kind::Params { new_name, new_expr } => params_table(app, ui, new_name, new_expr),
- Kind::Rename { name, .. } => {
- row_label(ui, "Name");
- let r = ui.text_edit_singleline(name);
- if r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {
- ok = true;
- }
- r.request_focus();
- ui.end_row();
- }
- Kind::Assembly(k) => enter |= crate::dialogs_assembly::rows(app, ui, k, &mut d.inputs, &mut d.active),
- Kind::Sheet(k) => enter |= crate::dialogs_sheet::rows(app, ui, k, &mut d.inputs),
- Kind::Surface(k) => enter |= crate::dialogs_surface::rows(ui, k),
- Kind::SaveMesh(k) => enter |= crate::dialogs_save_mesh::rows(app, ui, k),
- Kind::ViewDxf { dashed, tolerance } => crate::dialogs_view_dxf::rows(app, ui, dashed, tolerance),
- Kind::Plastic(k) => enter |= crate::dialogs_plastic::rows(app, ui, k, &d.inputs),
- Kind::Appearance(k) => enter |= crate::dialogs_appearance::rows(app, ui, k, &mut d.inputs),
- Kind::Motion(k) => enter |= crate::dialogs_motion::rows(app, ui, k, &mut d.inputs),
- Kind::Part(k) => enter |= crate::dialogs_parts::rows(app, ui, k, &d.inputs),
- Kind::PartSize(k) => enter |= crate::dialogs_part_size::rows(app, ui, k),
- Kind::ConfirmDelete { with, fail, .. } => {
- if !with.is_empty() {
- row_label(ui, "Also deletes");
- ui.label(with.join(", "));
- ui.end_row();
- }
- if !fail.is_empty() {
- row_label(ui, "Will fail");
- ui.label(RichText::new(fail.join(", ")).color(t.warning));
- ui.end_row();
- }
+ crate::ui_kit::Action::Cancel => {
+ if !app.esc_handled || !ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
+ cancel = true;
}
}
- d.sync_fillet_chain(&app.session);
- error_rows(app, ctx, &mut d, ui, false);
- });
- });
- ui.add_space(6.0);
- // Footer: an info glyph at the left, OK and Cancel at the right.
- ui.horizontal(|ui| {
- let (r, resp) = ui.allocate_exact_size(vec2(16.0, 16.0), egui::Sense::hover());
- ui.painter().circle_stroke(r.center(), 7.0, Stroke::new(1.2, t.text_dim));
- ui.painter().text(
- r.center(),
- egui::Align2::CENTER_CENTER,
- "i",
- egui::FontId::proportional(crate::theme::Tokens::get().font_small),
- t.text_dim,
- );
- resp.on_hover_text(heading.as_str());
- // The spinner's place is always taken: a widget that comes and goes would shift
- // the automatic ids of OK and Cancel, and a click pressed in one frame and
- // released in the next would be lost (an animating preview toggles it often).
- let (sr, sresp) = ui.allocate_exact_size(vec2(14.0, 14.0), egui::Sense::hover());
- if let Some(job) = &app.applying {
- egui::Spinner::new().size(14.0).paint_at(ui, sr);
- let seconds = ((crate::now_ms() - job.started) / 1000.0).floor().max(0.0);
- ui.label(RichText::new(crate::i18n::format("dialog.computing", &[("seconds", &format!("{seconds:.0}"))])).color(t.text_dim));
- ctx.request_repaint_after(std::time::Duration::from_millis(100));
- } else if app.preview.busy {
- egui::Spinner::new().size(14.0).paint_at(ui, sr);
- sresp.on_hover_text(tr("Updating the preview"));
- }
- let raw_label = match &d.kind {
- Kind::ConfirmDelete { .. } => "Delete",
- Kind::SaveMesh(k) => crate::dialogs_save_mesh::button(k),
- Kind::ViewDxf { .. } => "Export DXF…",
- _ => "OK",
- };
- let label = tr(raw_label);
- let raw_close = if matches!(d.kind, Kind::Params { .. } | Kind::Measure { .. }) { "Close" } else { "Cancel" };
- let close = tr(raw_close);
- let button_width = |text: &str| {
- let galley = egui::WidgetText::from(text).into_galley(ui, Some(egui::TextWrapMode::Extend), f32::INFINITY, egui::TextStyle::Button);
- (galley.size().x + 2.0 * ui.spacing().button_padding.x).max(64.0)
- };
- let (ok_width, close_width) = (button_width(label), button_width(close));
- let buttons = close_width + if has_ok { ok_width + ui.spacing().item_spacing.x } else { 0.0 };
- crate::frame::right_aligned(ui, total, buttons, |ui| {
- if has_ok {
- let b = egui::Button::new(RichText::new(label).color(if valid { t.on_accent } else { t.text_dim }))
- .fill(if valid { t.accent } else { Color32::TRANSPARENT })
- .wrap_mode(egui::TextWrapMode::Extend)
- .min_size(vec2(ok_width, 24.0));
- let r = ui.add_enabled(valid && app.applying.is_none(), b);
- crate::scenario::publish_handle(&format!("dialog:{raw_label}"), r.rect.center());
- if r.clicked() {
- ok = true;
- }
- }
- if ui.add(egui::Button::new(close).wrap_mode(egui::TextWrapMode::Extend).min_size(vec2(close_width, 24.0))).clicked() {
- cancel = true;
+ crate::ui_kit::Action::Apply => {
+ ok = true;
+ apply_again = true;
}
- });
- });
- crate::frame::remember_width(ui, wkey);
+ crate::ui_kit::Action::None => {}
+ }
+ }
});
app.viewport.dialog_rect = response.map(|r| r.response.rect);
if let Some(r) = app.viewport.dialog_rect {
@@ -2757,8 +2367,8 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
let nothing_focused = ctx.memory(|m| m.focused().is_none());
let canvas_enter = enter_free && ctx.memory(|m| m.had_focus_last_frame(egui::Id::new("sc_canvas_value")));
// Tables (configurations, a study's keys) take Enter for their cells.
- let enter_applies = !matches!(d.kind, Kind::Sketch | Kind::Params { .. } | Kind::Measure { .. } | Kind::ConfirmDelete { .. })
- && !matches!(&d.kind, Kind::Motion(k) if k.wide());
+ let enter_applies =
+ !matches!(d.kind, Kind::Sketch | Kind::Measure { .. } | Kind::ConfirmDelete { .. }) && !matches!(&d.kind, Kind::Motion(k) if k.wide());
let report_active = app.issue_report.draft.is_some();
if !report_active && enter_applies && app.applying.is_none() && (enter || canvas_enter || (enter_free && nothing_focused)) {
ok = true;
@@ -2985,7 +2595,7 @@ fn extra_choice(ui: &mut egui::Ui, extra: &mut serde_json::Map<String, Value>, i
/// A checkbox stored in the dialog's extra parameters.
fn extra_check(ui: &mut egui::Ui, extra: &mut serde_json::Map<String, Value>, key: &str) {
let mut on = extra.get(key).and_then(Value::as_bool).unwrap_or(false);
- let r = if crate::ui_kit::contains(ui) { crate::ui_kit::checkbox(ui, "", &mut on) } else { ui.checkbox(&mut on, "") };
+ let r = crate::ui_kit::checkbox(ui, "", &mut on);
if r.changed() {
extra.insert(key.into(), json!(on));
}
@@ -3094,72 +2704,6 @@ fn hole_defaults() -> Kind {
}
}
-fn params_table(app: &mut SolveApp, ui: &mut egui::Ui, new_name: &mut String, new_expr: &mut String) {
- let t = Tokens::get();
- ui.label(RichText::new(tr("Name")).semibold().color(crate::theme::Tokens::get().text));
- ui.label(RichText::new(tr("Expression · value")).semibold().color(crate::theme::Tokens::get().text));
- ui.end_row();
- let (vals, errs) = app.session.doc.param_values();
- let params = app.session.doc.params.clone();
- for p in params {
- ui.label(if p.model { RichText::new(&p.name).color(t.text_dim) } else { RichText::new(&p.name) });
- ui.horizontal(|ui| {
- let id = egui::Id::new(("pexpr", &p.name));
- let mut e = ui.data(|dd| dd.get_temp::<String>(id)).unwrap_or_else(|| p.expr.clone());
- let r = ui.add(egui::TextEdit::singleline(&mut e).desired_width(160.0));
- let refused_id = egui::Id::new(("prefused", &p.name));
- if r.changed() {
- // Typing again clears the reason a previous change was refused.
- ui.data_mut(|dd| {
- dd.insert_temp(id, e.clone());
- dd.remove::<String>(refused_id);
- });
- }
- if r.lost_focus() && e != p.expr {
- match change_param(app, &p.name, &e) {
- Ok(()) => ui.data_mut(|dd| {
- dd.remove::<String>(id);
- dd.remove::<String>(refused_id);
- }),
- // Refused (it would leave a sketch unsolved, say): the typed expression
- // stays in the field with the reason beside it, nothing silently reverts.
- Err(why) => ui.data_mut(|dd| {
- dd.insert_temp(refused_id, why);
- }),
- }
- }
- let refused = ui.data(|dd| dd.get_temp::<String>(refused_id));
- let v = vals.get(&p.name).map(|v| if p.unit == "deg" { format!("{:.3}°", v.v.to_degrees()) } else { format!("{:.4} {}", v.v, p.unit) });
- match (v, errs.get(&p.name).or(refused.as_ref())) {
- (_, Some(e)) => ui.label(RichText::new(e).color(t.error)),
- (Some(v), None) => ui.label(RichText::new(v).color(t.text_dim)),
- _ => ui.label(""),
- };
- });
- ui.end_row();
- }
- ui.add(egui::TextEdit::singleline(new_name).hint_text(tr("new name")).desired_width(110.0));
- ui.horizontal(|ui| {
- ui.add(egui::TextEdit::singleline(new_expr).hint_text(tr("expression, e.g. 25 mm")).desired_width(160.0));
- if ui.button(tr("Add")).clicked()
- && !new_name.is_empty()
- && app.run("parameters.change", json!({"name": new_name, "expression": new_expr})).is_ok()
- {
- new_name.clear();
- new_expr.clear();
- }
- });
- ui.end_row();
-}
-
-/// Set a parameter's expression from the parameters table: `Err` with the message to show
-/// beside the field when the change is refused (the document keeps its values).
-pub(crate) fn change_param(app: &mut SolveApp, name: &str, expression: &str) -> Result<(), String> {
- app.run("parameters.change", json!({"name": name, "expression": expression}))
- .map(|_| ())
- .map_err(|e| crate::friendly_error("parameters.change", &e))
-}
-
/// Start a sketch on a picked plane or planar face and turn the view to face it.
pub fn start_sketch(app: &mut SolveApp, sel: &Sel) -> Result<(), String> {
let mut params = match sel {
@@ -4054,7 +3598,7 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result<Vec<(String, Value)>, S
Kind::EditParam { name, expr } => ("parameters.change", json!({"name": name, "expression": expr})),
Kind::Rename { feature, name } => ("timeline.rename", json!({"feature": feature, "name": name})),
Kind::ConfirmDelete { features, .. } => ("timeline.delete", json!({ "features": features })),
- Kind::Sketch | Kind::Params { .. } | Kind::Measure { .. } => return Ok(Vec::new()),
+ Kind::Sketch | Kind::Measure { .. } => return Ok(Vec::new()),
Kind::Assembly(k) => return crate::dialogs_assembly::commands(app, k, &d.inputs),
Kind::Sheet(k) => return crate::dialogs_sheet::commands(app, k, &d.inputs, &d.extra),
Kind::Surface(k) => return crate::dialogs_surface::commands(app, k, &d.inputs, &d.extra),
@@ -5217,11 +4761,11 @@ mod param_refusal_tests {
let name = s.doc.params.iter().find(|p| p.model).map(|p| p.name.clone()).unwrap();
let before = s.doc.param(&name).map(|p| p.expr.clone());
let mut app = SolveApp::new(s, Default::default());
- let why = change_param(&mut app, &name, "500 mm").unwrap_err();
+ let why = app.run("parameters.change", json!({"name":name,"expression":"500 mm"})).unwrap_err();
assert!(why.contains("Tri") && why.contains("conflict"), "{why}");
assert_eq!(app.session.doc.param(&name).map(|p| p.expr.clone()), before);
assert!(app.status.as_ref().is_some_and(|(m, _, error)| *error && m.contains("Tri")), "{:?}", app.status);
- assert!(change_param(&mut app, &name, "41 mm").is_ok());
+ assert!(app.run("parameters.change", json!({"name":name,"expression":"41 mm"})).is_ok());
}
}
diff --git a/crates/ui-egui/src/dialogs_all_tests.rs b/crates/ui-egui/src/dialogs_all_tests.rs
index fc72f68f8f..82de552260 100644
--- a/crates/ui-egui/src/dialogs_all_tests.rs
+++ b/crates/ui-egui/src/dialogs_all_tests.rs
@@ -134,7 +134,7 @@ fn check_form(command: &str, labels: &[&str]) {
}
let checks: &[&str] = match command {
"solid.shell" => &["Tangent Chain"],
- "solid.rib" | "solid.web" | "solid.align" | "sheet.flange" | "sheet.hem" | "sheet.fold" | "joint.create" => &["Flip"],
+ "solid.rib" | "solid.web" | "solid.align" | "inspect.section" | "sheet.flange" | "sheet.hem" | "sheet.fold" | "joint.create" => &["Flip"],
"solid.move" => &["Create Copy"],
"solid.combine" => &["Keep Tools", "New Component"],
"solid.thread" => &["Modeled", "Full Length", "Automatic size"],
@@ -222,6 +222,7 @@ form_case!(path_plane, "construct.plane.along_path", ["Position (0 to 1)"]);
form_case!(split, "solid.split_body", []);
form_case!(scale, "solid.scale", ["Scale factor"]);
form_case!(offset_faces, "solid.offset_face", ["Distance"]);
+form_case!(section, "inspect.section", ["Distance"]);
form_case!(move_copy, "solid.move", ["Move Type", "X Distance", "Y Distance", "Z Distance", "X Angle", "Y Angle", "Z Angle"]);
form_case!(rib, "solid.rib", ["Direction", "Thickness", "Depth"]);
form_case!(web, "solid.web", ["Direction", "Thickness", "Depth"]);
@@ -283,24 +284,7 @@ fn registry_dialog_inventory_has_no_unclassified_feature_forms() {
let h = fixture();
for spec in solidcraft_engine::command_specs() {
let Some(d) = Dialog::for_command(&h.app, spec.id) else { continue };
- let excluded = matches!(
- d.kind,
- Kind::Params { .. }
- | Kind::Rename { .. }
- | Kind::ConfirmDelete { .. }
- | Kind::Measure { .. }
- | Kind::Material { .. }
- | Kind::Section { .. }
- | Kind::SaveMesh(_)
- | Kind::ViewDxf { .. }
- | Kind::Appearance(_)
- | Kind::Motion(_)
- | Kind::Part(_)
- | Kind::Sheet(crate::dialogs_sheet::Sm::Rules { .. } | crate::dialogs_sheet::Sm::FlatPattern { .. })
- | Kind::Plastic(crate::dialogs_plastic::Pl::Rules { .. })
- | Kind::Assembly(crate::dialogs_assembly::Asm::Drive { .. } | crate::dialogs_assembly::Asm::Interference { .. })
- );
- assert_eq!(super::command(&d.kind).is_some(), !excluded, "{}: {:?}", spec.id, d.kind);
+ assert!(super::command(&d.kind).is_some(), "{}: {:?}", spec.id, d.kind);
}
}
@@ -320,3 +304,35 @@ fn new_cards_settle_before_the_first_click_in_both_layouts() {
}
}
}
+
+#[test]
+fn remaining_dialogs_keep_kit_chrome_and_cancel_restores_preview() {
+ for command in [
+ "contact.create",
+ "motion.study",
+ "explode.create",
+ "parts.insert",
+ "joint.drive",
+ "inspect.interference",
+ "file.save_mesh",
+ "file.export_view_dxf",
+ "sheet.flat_pattern",
+ ] {
+ let mut h = fixture();
+ h.call("ui.resize", json!({"width":1600,"height":1200}));
+ let design = h.app.session.doc.to_json();
+ let moves = h.app.session.pending_moves.clone();
+ h.app.start(command);
+ h.frames(4);
+ for key in ["dialog:header", "dialog:footer", "dialog:outer"] {
+ let rect = scenario::rect_of(key).unwrap_or_else(|| panic!("{command}: missing {key}"));
+ assert!(rect.is_finite() && rect.is_positive() && h.ctx.content_rect().contains_rect(rect), "{command}: {key} {rect:?}");
+ }
+ let footer = scenario::rect_of("dialog:footer").unwrap();
+ assert!(footer.contains(scenario::handle_at("dialog:cancel").unwrap()), "{command}: cancel remains in the pinned footer");
+ h.step(&json!({"click":{"handle":"dialog:cancel"}})).unwrap();
+ assert!(h.app.dialog.is_none(), "{command}");
+ assert_eq!(h.app.session.doc.to_json(), design, "{command}: opening/cancelling keeps the design");
+ assert_eq!(h.app.session.pending_moves, moves, "{command}: cancel restores display-only moves");
+ }
+}
diff --git a/crates/ui-egui/src/dialogs_appearance.rs b/crates/ui-egui/src/dialogs_appearance.rs
index 765e3329d6..ddcadcc576 100644
--- a/crates/ui-egui/src/dialogs_appearance.rs
+++ b/crates/ui-egui/src/dialogs_appearance.rs
@@ -3,15 +3,15 @@
//! body or face in the viewport, or onto a body's row in the Browser, applies at once; Apply
//! (and OK) gives the picked objects the current look.
-use egui::{Color32, RichText, Sense, Stroke, vec2};
+use egui::Color32;
use serde_json::{Value, json};
use solidcraft_engine::Sel;
use solidcraft_engine::doc::pbr_appearance::PbrParameters;
use crate::SolveApp;
-use crate::dialogs::{Kind, combo, row_label};
+use crate::dialogs::{Kind, combo};
use crate::selection::{BODIES, FACES, SelInput};
-use crate::theme::Tokens;
+use crate::ui_kit;
use crate::viewport::Hit;
/// A named look: colour and opacity.
@@ -278,99 +278,48 @@ fn c32(c: [u8; 3], opacity: f64) -> Color32 {
/// A swatch: a rounded square of the look; returns its response (click, drag).
fn swatch(ui: &mut egui::Ui, id: egui::Id, color: [u8; 3], opacity: f64, picked: bool, tip: &str, payload: Look) -> egui::Response {
- let t = Tokens::get();
- let r = ui
- .dnd_drag_source(id, payload, |ui| {
- let (rect, _) = ui.allocate_exact_size(vec2(30.0, 30.0), Sense::hover());
- // A checker behind see-through looks.
- if opacity < 0.999 {
- let h = rect.width() / 2.0;
- for (dx, dy) in [(0.0, 0.0), (h, h)] {
- ui.painter().rect_filled(egui::Rect::from_min_size(rect.min + vec2(dx, dy), vec2(h, h)), 0.0, t.hover);
- }
- }
- ui.painter().rect(
- rect,
- 5.0,
- c32(color, opacity),
- Stroke::new(if picked { 2.0 } else { 1.0 }, if picked { t.accent } else { t.border }),
- egui::StrokeKind::Inside,
- );
- })
- .response;
- let r = ui.interact(r.rect, id.with("click"), Sense::click()).on_hover_text(tip);
- if r.hovered() {
- ui.ctx().set_cursor_icon(egui::CursorIcon::Grab);
- }
- r
+ ui_kit::color_swatch(ui, id, c32(color, opacity), picked, tip, payload)
}
-/// Swatches six to a row.
-fn swatch_rows<T>(ui: &mut egui::Ui, items: &[T], mut each: impl FnMut(&mut egui::Ui, &T)) {
- ui.vertical(|ui| {
- ui.spacing_mut().item_spacing = vec2(4.0, 4.0);
- for row in items.chunks(6) {
- ui.horizontal(|ui| {
- for x in row {
- each(ui, x);
- }
- });
- }
- });
+fn swatch_rows<T>(ui: &mut egui::Ui, items: &[T], each: impl FnMut(&mut egui::Ui, &T)) {
+ ui_kit::swatch_grid(ui, items, each);
}
/// The dialog's rows (after the Objects input); applies drops and Apply at once.
pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Ap, inputs: &mut [SelInput]) -> bool {
- let t = Tokens::get();
// Apply To: bodies or faces (the input follows).
- row_label(ui, "Apply To");
if let Some(component) = &k.component {
- ui.label(format!("Component: {component}"));
- ui.end_row();
- row_label(ui, "");
- if ui.button(crate::i18n::tr_label("Select bodies or faces instead")).clicked() {
+ ui_kit::row(ui, "Apply To", |ui| ui_kit::cell_text(ui, &format!("Component: {component}")));
+ if ui_kit::secondary_button(ui, crate::i18n::tr_label("Select bodies or faces instead")).clicked() {
k.component = None;
}
- ui.end_row();
} else {
let mut mode = usize::from(k.faces);
- combo(ui, "ap_mode", &["Bodies", "Faces"], &mut mode);
- ui.end_row();
+ ui_kit::row(ui, "Apply To", |ui| combo(ui, "ap_mode", &["Bodies", "Faces"], &mut mode));
if (mode == 1) != k.faces {
k.faces = mode == 1;
- if let Some(i) = inputs.first_mut() {
- *i = SelInput::new("Objects", if k.faces { FACES } else { BODIES }, true);
+ if let Some(input) = inputs.first_mut() {
+ *input = SelInput::new("Objects", if k.faces { FACES } else { BODIES }, true);
}
}
}
- // The current look: colour and opacity.
- row_label(ui, "Colour");
- ui.horizontal(|ui| {
+ ui_kit::row(ui, "Colour", |ui| {
let mut rgb = k.color;
- if ui.color_edit_button_srgb(&mut rgb).changed() {
+ if ui_kit::color_field(ui, &mut rgb).changed() {
k.color = rgb;
k.look = None;
k.remove_override = false;
}
- ui.label(RichText::new(k.look.clone().unwrap_or_else(|| hex(k.color))).color(t.text_dim));
+ ui_kit::cell_text(ui, &k.look.clone().unwrap_or_else(|| hex(k.color)));
+ });
+ ui_kit::row(ui, "Opacity", |ui| {
+ if ui.add_enabled_ui(k.pbr.is_none(), |ui| ui_kit::slider(ui, &mut k.opacity, 0.0..=1.0)).inner.changed() {
+ k.remove_override = false;
+ }
});
- ui.end_row();
- row_label(ui, "Opacity");
- ui.spacing_mut().slider_width = 110.0;
- // Decimal formatting must not round a saved look merely by drawing its editor.
- if ui
- .add_enabled(
- k.pbr.is_none(),
- egui::Slider::new(&mut k.opacity, 0.0..=1.0).max_decimals_opt(None).custom_formatter(|value, _| format!("{value:.2}")),
- )
- .changed()
- {
- k.remove_override = false;
- }
- ui.end_row();
- row_label(ui, app.tr("appearance.surface_response"));
let mut enabled = k.pbr.is_some();
- let toggle = ui.checkbox(&mut enabled, app.tr("appearance.pbr_opaque")).on_hover_text(app.tr("appearance.pbr_help"));
+ let toggle = ui_kit::row(ui, app.tr("appearance.surface_response"), |ui| ui_kit::checkbox(ui, app.tr("appearance.pbr_opaque"), &mut enabled))
+ .on_hover_text(app.tr("appearance.pbr_help"));
crate::scenario::publish_handle("appearance:pbr", toggle.rect.center());
if toggle.changed() {
k.pbr = enabled.then(PbrParameters::default);
@@ -379,7 +328,6 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Ap, inputs: &mut [Sel
}
k.remove_override = false;
}
- ui.end_row();
if let Some(parameters) = k.pbr {
let mut metallic = parameters.metallic();
let mut roughness = parameters.roughness();
@@ -389,23 +337,20 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Ap, inputs: &mut [Sel
("appearance.roughness", "appearance:roughness", &mut roughness, 0.045..=1.0),
("appearance.dielectric_ior", "appearance:ior", &mut ior, 1.0..=3.0),
] {
- row_label(ui, app.tr(label));
- let response = ui.add(egui::DragValue::new(value).range(range).speed(0.01).custom_parser(crate::prefs::parse_number));
+ let response = ui_kit::row(ui, app.tr(label), |ui| ui_kit::scalar_field(ui, value, range));
crate::scenario::publish_handle(handle, response.rect.center());
if response.changed() {
k.remove_override = false;
}
- ui.end_row();
}
if let Ok(parameters) = PbrParameters::new(metallic, roughness, ior) {
k.pbr = Some(parameters);
}
}
- row_label(ui, "");
let picked: Vec<Sel> = inputs.first().map(|i| i.items.clone()).unwrap_or_default();
ui.horizontal(|ui| {
let has_target = !picked.is_empty() || k.component.is_some();
- if ui.add_enabled(has_target, egui::Button::new(crate::i18n::tr_label("Apply to selection"))).clicked()
+ if ui_kit::enabled_button(ui, "Apply to selection", has_target).clicked()
&& let Some(p) = selected_params(k, &picked)
{
k.remove_override = false;
@@ -417,8 +362,7 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Ap, inputs: &mut [Sel
Err(e) => e,
});
}
- if ui
- .add_enabled(has_target, egui::Button::new(crate::i18n::tr_label("Remove override")))
+ if ui_kit::enabled_button(ui, "Remove override", has_target)
.on_hover_text(crate::i18n::tr_label("Restore the inherited component or physical material appearance"))
.clicked()
&& let Some(p) = clear_params(k, &picked)
@@ -433,33 +377,32 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Ap, inputs: &mut [Sel
});
}
});
- ui.end_row();
crate::dialogs_library::rows(app, ui, k, inputs);
// In this design.
let used = in_design(app);
if !used.is_empty() {
- row_label(ui, "In This Design");
- let items: Vec<_> = used.iter().enumerate().collect();
- swatch_rows(ui, &items, |ui, (i, (look, n))| {
- if swatch(
- ui,
- egui::Id::new(("ap_used", *i)),
- look.color,
- look.opacity,
- k.color == look.color && k.opacity == look.opacity && k.pbr == look.pbr,
- &format!("{} · {n} item(s)", look.name),
- look.clone(),
- )
- .clicked()
- {
- k.color = look.color;
- k.opacity = look.opacity;
- k.pbr = look.pbr;
- k.look = Some(look.name.clone());
- k.remove_override = false;
- }
+ ui_kit::section(ui, "in_design", "In This Design", true, |ui| {
+ let items: Vec<_> = used.iter().enumerate().collect();
+ swatch_rows(ui, &items, |ui, (i, (look, n))| {
+ if swatch(
+ ui,
+ egui::Id::new(("ap_used", *i)),
+ look.color,
+ look.opacity,
+ k.color == look.color && k.opacity == look.opacity && k.pbr == look.pbr,
+ &format!("{} · {n} item(s)", look.name),
+ look.clone(),
+ )
+ .clicked()
+ {
+ k.color = look.color;
+ k.opacity = look.opacity;
+ k.pbr = look.pbr;
+ k.look = Some(look.name.clone());
+ k.remove_override = false;
+ }
+ });
});
- ui.end_row();
}
// The library, by category.
let lib = library(app);
@@ -470,20 +413,18 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Ap, inputs: &mut [Sel
}
}
let refs: Vec<&str> = cats.iter().map(String::as_str).collect();
- row_label(ui, "Library");
- combo(ui, "ap_cat", &refs, &mut k.category);
- ui.end_row();
- row_label(ui, "Search");
- let search = ui.add(egui::TextEdit::singleline(&mut k.search).hint_text(crate::i18n::tr_label("Appearance name")).desired_width(190.0));
+ ui_kit::row(ui, "Library", |ui| combo(ui, "ap_cat", &refs, &mut k.category));
+ let search = ui_kit::row(ui, "Search", |ui| {
+ let id = ui.make_persistent_id("ap_search");
+ ui_kit::search_field(ui, id, &mut k.search, "Appearance name")
+ });
crate::scenario::publish_handle("appearance:search", search.rect.center());
- ui.end_row();
- row_label(ui, "");
let want = cats.get(k.category).cloned().unwrap_or_default();
let query = k.search.trim().to_lowercase();
let shown: Vec<(usize, &Look)> =
lib.iter().enumerate().filter(|(_, l)| (k.category == 0 || l.category == want) && l.name.to_lowercase().contains(&query)).collect();
if shown.is_empty() {
- ui.label(RichText::new(crate::i18n::tr_label("No matching appearances")).color(t.text_dim));
+ ui_kit::note(ui, "appearances_empty", crate::i18n::tr_label("No matching appearances"));
}
swatch_rows(ui, &shown, |ui, (i, l)| {
let picked_look = k.look.as_deref() == Some(l.name.as_str()) && k.pbr == l.pbr;
@@ -497,7 +438,6 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Ap, inputs: &mut [Sel
k.remove_override = false;
}
});
- ui.end_row();
// A swatch dropped on the model or the Browser.
let released = ui.input(|i| i.pointer.any_released());
if released && let Some(look) = egui::DragAndDrop::take_payload::<Look>(ui.ctx()) {
@@ -521,9 +461,7 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Ap, inputs: &mut [Sel
}
}
if let Some(n) = &k.note {
- row_label(ui, "");
- ui.label(RichText::new(n.as_str()).color(t.text_dim));
- ui.end_row();
+ ui_kit::text_block(ui, "appearance_status", n, false);
}
false
}
diff --git a/crates/ui-egui/src/dialogs_assembly.rs b/crates/ui-egui/src/dialogs_assembly.rs
index 7255ec5978..d90b21a630 100644
--- a/crates/ui-egui/src/dialogs_assembly.rs
+++ b/crates/ui-egui/src/dialogs_assembly.rs
@@ -15,7 +15,7 @@ use solidcraft_engine::doc::joints::JointKind;
use solidcraft_engine::geom::{Aabb3, Mesh, Vec3};
use crate::SolveApp;
-use crate::dialogs::{Dialog, Kind, combo, field, form_row, row_label};
+use crate::dialogs::{Dialog, Kind, combo, field, form_row};
use crate::preview::{Built, Colors};
use crate::selection::{BODIES, EDGES, FACES, SelInput, VERTICES};
use crate::theme::Tokens;
@@ -610,18 +610,18 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Asm, inputs: &mut [Se
let s = &app.session;
let list = movable(s);
if list.is_empty() {
- row_label(ui, "");
- ui.label(RichText::new(crate::i18n::tr_label("no joint that moves yet")).color(t.text_dim));
- ui.end_row();
+ ui.vertical(|ui| {
+ ui.label(RichText::new(crate::i18n::tr_label("no joint that moves yet")).color(t.text_dim));
+ });
return false;
}
let labels: Vec<String> =
list.iter().filter_map(|i| s.doc.assembly.joints.get(*i)).map(|j| format!("{} ({:?})", j.name, j.kind)).collect();
let refs: Vec<&str> = labels.iter().map(String::as_str).collect();
let mut pos = list.iter().position(|i| i == joint).unwrap_or(0);
- row_label(ui, "Joint");
- combo(ui, "drv_joint", &refs, &mut pos);
- ui.end_row();
+ form_row(ui, "Joint", |ui| {
+ combo(ui, "drv_joint", &refs, &mut pos);
+ });
let pick = list.get(pos).copied().unwrap_or(0);
if pick != *joint || values.is_empty() {
*joint = pick;
@@ -632,25 +632,27 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Asm, inputs: &mut [Se
let angle = j.kind.is_angle(i);
let unit_kind = if angle { ValueKind::Angle } else { ValueKind::Length };
let name = j.kind.dofs().get(i).copied().unwrap_or("value");
- row_label(ui, &capital(name));
- if i == 0 {
- // Typing replaces the value at once, as in the other dialogs' value boxes.
- let id = egui::Id::new("sc_drive_value");
- let r = ui.add(egui::TextEdit::singleline(v).id(id));
- crate::params_dialog::complete(ui, &r, v);
- if std::mem::take(focus) {
- r.request_focus();
- let n = v.chars().count();
- let mut st = egui::text_edit::TextEditState::load(ui.ctx(), id).unwrap_or_default();
- st.cursor
- .set_char_range(Some(egui::text_selection::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(n))));
- st.store(ui.ctx(), id);
+ form_row(ui, &capital(name), |ui| {
+ if i == 0 {
+ // Typing replaces the value at once, as in the other dialogs' value boxes.
+ let id = egui::Id::new("sc_drive_value");
+ let r = crate::ui_kit::cell_editor(ui, id, v, "", false);
+ crate::params_dialog::complete(ui, &r, v);
+ if std::mem::take(focus) {
+ r.request_focus();
+ let n = v.chars().count();
+ let mut st = egui::text_edit::TextEditState::load(ui.ctx(), id).unwrap_or_default();
+ st.cursor.set_char_range(Some(egui::text_selection::CCursorRange::two(
+ egui::text::CCursor::new(0),
+ egui::text::CCursor::new(n),
+ )));
+ st.store(ui.ctx(), id);
+ }
+ enter |= r.lost_focus() && ui.input(|x| x.key_pressed(egui::Key::Enter));
+ } else {
+ enter |= field(ui, v);
}
- enter |= r.lost_focus() && ui.input(|x| x.key_pressed(egui::Key::Enter));
- } else {
- enter |= field(ui, v);
- }
- ui.end_row();
+ });
// A slider over the limits (or a turn, or ±100 mm).
let (lo, hi) = match j.limits.get(i).copied().flatten() {
Some((a, b)) => (a.min(b), a.max(b)),
@@ -659,34 +661,34 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Asm, inputs: &mut [Se
};
let cur = s.doc.eval(v, unit_kind).ok().filter(|x| x.is_finite()).unwrap_or(0.0);
let (mut shown, scale) = if angle { (cur.to_degrees(), 1f64.to_degrees()) } else { (cur, 1.0) };
- row_label(ui, "");
- ui.spacing_mut().slider_width = 160.0;
- let r = ui.add(egui::Slider::new(&mut shown, lo * scale..=hi * scale).show_value(false));
- crate::scenario::publish_handle(&format!("drive_slider:{i}"), r.rect.center());
- if r.changed() {
- *v = if angle { format!("{shown:.1} deg") } else { format!("{shown:.2} mm") };
- }
- ui.end_row();
+ ui.vertical(|ui| {
+ ui.spacing_mut().slider_width = 160.0;
+ let r = crate::ui_kit::timeline_slider(ui, &mut shown, lo * scale..=hi * scale, false);
+ crate::scenario::publish_handle(&format!("drive_slider:{i}"), r.rect.center());
+ if r.changed() {
+ *v = if angle { format!("{shown:.1} deg") } else { format!("{shown:.2} mm") };
+ }
+ });
// The slider's range: the joint's limits, or the default span when it has none.
let limited = j.limits.get(i).copied().flatten().is_some();
let fmt = |x: f64| {
let (x, unit) = if angle { (x.to_degrees(), "°") } else { (x, " mm") };
if x.fract().abs() < 1e-6 { format!("{x:.0}{unit}") } else { format!("{x:.1}{unit}") }
};
- row_label(ui, "");
- ui.label(
- RichText::new(format!("{} … {}{}", fmt(lo), fmt(hi), if limited { " (limits)" } else { " (no limits)" }))
- .size(crate::theme::Tokens::get().font_small)
- .color(if limited { t.text } else { t.text_dim }),
- );
- ui.end_row();
+ ui.vertical(|ui| {
+ ui.label(
+ RichText::new(format!("{} … {}{}", fmt(lo), fmt(hi), if limited { " (limits)" } else { " (no limits)" }))
+ .size(crate::theme::Tokens::get().font_small)
+ .color(if limited { t.text } else { t.text_dim }),
+ );
+ });
}
// The preview drove the joint: where it stopped short, and why (a closed loop or a
// contact set), so the values asked for are not taken for where it is.
if let Some(why) = app.preview.stopped.as_ref().and_then(drive_stop) {
- row_label(ui, "");
- ui.label(RichText::new(why).color(t.warning));
- ui.end_row();
+ ui.vertical(|ui| {
+ ui.label(RichText::new(why).color(t.warning));
+ });
}
}
Asm::MotionLink { a, b, ia, ib, ratio, offset } => {
@@ -1215,20 +1217,20 @@ fn joint_menu(
open: &mut Option<Dialog>,
run: &mut Option<(&'static str, Value)>,
) {
- if ui.button(crate::i18n::tr_label("Edit Joint")).clicked() {
+ if crate::ui_kit::secondary_button(ui, crate::i18n::tr_label("Edit Joint")).clicked() {
*open = edit_joint(app, id);
ui.close();
}
- if kind != JointKind::Rigid && ui.button(crate::i18n::tr_label("Drive Joint")).clicked() {
+ if kind != JointKind::Rigid && crate::ui_kit::secondary_button(ui, crate::i18n::tr_label("Drive Joint")).clicked() {
*open = drive_joint(app, id);
ui.close();
}
- if ui.button(if suppressed { "Unsuppress" } else { "Suppress" }).clicked() {
+ if crate::ui_kit::secondary_button(ui, crate::i18n::tr_label(if suppressed { "Unsuppress" } else { "Suppress" })).clicked() {
*run = Some(("joint.edit", json!({"joint": id, "suppressed": !suppressed})));
ui.close();
}
ui.separator();
- if ui.button("Delete").clicked() {
+ if crate::ui_kit::secondary_button(ui, crate::i18n::tr_label("Delete")).clicked() {
*run = Some(("selection.delete", json!({ "joints": [id] })));
ui.close();
}
diff --git a/crates/ui-egui/src/dialogs_dense.rs b/crates/ui-egui/src/dialogs_dense.rs
index 54d5dec070..048b5889ad 100644
--- a/crates/ui-egui/src/dialogs_dense.rs
+++ b/crates/ui-egui/src/dialogs_dense.rs
@@ -4,11 +4,27 @@ use crate::ui_kit;
pub(super) fn command(kind: &Kind) -> Option<&'static str> {
match kind {
+ Kind::Material { .. } => Some("material.assign"),
+ Kind::Appearance(_) => Some("appearance.assign"),
+ Kind::Motion(k) => Some(match k {
+ crate::dialogs_motion::Mo::ContactSet { .. } => "contact.create",
+ crate::dialogs_motion::Mo::MotionStudy { .. } => "motion.study",
+ crate::dialogs_motion::Mo::Explode { .. } => "explode.create",
+ crate::dialogs_motion::Mo::Configurations { .. } => "config.table",
+ }),
+ Kind::Part(_) => Some("parts.insert"),
+ Kind::PartSize(_) => Some("parts.resize"),
+ Kind::SaveMesh(_) => Some("file.save_mesh"),
+ Kind::ViewDxf { .. } => Some("file.export_view_dxf"),
Kind::Sketch => Some("sketch.create"),
Kind::SketchModify(k) => Some(crate::sketch_modify_ui::command(k)),
Kind::Text(_) => Some("sketch.edit_text"),
Kind::TextMove(_) => Some("sketch.move"),
Kind::EditParam { .. } => Some("parameters.change"),
+ Kind::Measure { .. } => Some("inspect.measure"),
+ Kind::Section { .. } => Some("inspect.section"),
+ Kind::Rename { .. } => Some("timeline.rename"),
+ Kind::ConfirmDelete { .. } => Some("timeline.delete"),
Kind::Extrude { .. } => Some("solid.extrude"),
Kind::Fillet { chamfer, .. } => Some(if *chamfer { "solid.chamfer" } else { "solid.fillet" }),
Kind::Hole { .. } => Some("solid.hole"),
@@ -67,7 +83,8 @@ pub(super) fn command(kind: &Kind) -> Option<&'static str> {
crate::dialogs_sheet::Sm::Fold { .. } => Some("sheet.fold"),
crate::dialogs_sheet::Sm::Unfold { refold } => Some(if *refold { "sheet.refold" } else { "sheet.unfold" }),
crate::dialogs_sheet::Sm::Convert { .. } => Some("sheet.convert"),
- _ => None,
+ crate::dialogs_sheet::Sm::Rules { .. } => Some("sheet.manage_rules"),
+ crate::dialogs_sheet::Sm::FlatPattern { .. } => Some("sheet.flat_pattern"),
},
Kind::Plastic(k) => match k {
crate::dialogs_plastic::Pl::Boss { .. } => Some("plastic.boss"),
@@ -75,7 +92,7 @@ pub(super) fn command(kind: &Kind) -> Option<&'static str> {
crate::dialogs_plastic::Pl::SnapFit { .. } => Some("plastic.snap_fit"),
crate::dialogs_plastic::Pl::Rest { .. } => Some("plastic.rest"),
crate::dialogs_plastic::Pl::Assign { .. } => Some("plastic.assign_rule"),
- _ => None,
+ crate::dialogs_plastic::Pl::Rules { .. } => Some("plastic.manage_rules"),
},
Kind::Assembly(k) => match k {
crate::dialogs_assembly::Asm::NewComponent { .. } => Some("component.create"),
@@ -86,9 +103,9 @@ pub(super) fn command(kind: &Kind) -> Option<&'static str> {
crate::dialogs_assembly::Asm::Coupling(f) => Some(f.command),
crate::dialogs_assembly::Asm::Cam(_) => Some("joint.cam"),
crate::dialogs_assembly::Asm::Trace(_) => Some("motion.trace"),
- _ => None,
+ crate::dialogs_assembly::Asm::Drive { .. } => Some("joint.drive"),
+ crate::dialogs_assembly::Asm::Interference { .. } => Some("inspect.interference"),
},
- _ => None,
}
}
@@ -152,9 +169,31 @@ pub(super) fn rows(app: &mut SolveApp, ctx: &egui::Context, d: &mut Dialog, ui:
ui_kit::hint(ui, "step", &step).on_hover_text(tr("dialog.selection_guidance"));
}
}
+ let manage_hint = match &d.kind {
+ Kind::Material { .. } => Some("manage.material_hint"),
+ Kind::Appearance(_) => Some("manage.appearance_hint"),
+ Kind::Motion(crate::dialogs_motion::Mo::Configurations { .. }) => Some("manage.config_hint"),
+ Kind::Sheet(crate::dialogs_sheet::Sm::Rules { .. }) | Kind::Plastic(crate::dialogs_plastic::Pl::Rules { .. }) => Some("manage.rules_hint"),
+ Kind::Plastic(crate::dialogs_plastic::Pl::Assign { .. }) => Some("manage.assign_hint"),
+ _ => None,
+ };
+ if let Some(key) = manage_hint {
+ ui_kit::hint(ui, "manage", tr(key));
+ }
placement_row(d, ui);
input_rows(d, ui, &app.session);
match &mut d.kind {
+ Kind::Material { index } => {
+ let names = app.session.doc.material_names();
+ let names: Vec<_> = names.iter().map(String::as_str).collect();
+ ui_kit::row(ui, "Material", |ui| ui_kit::dropdown(ui, "mat", index, &names));
+ }
+ Kind::Appearance(k) => enter |= crate::dialogs_appearance::rows(app, ui, k, &mut d.inputs),
+ Kind::Motion(k) => enter |= crate::dialogs_motion::rows(app, ui, k, &mut d.inputs),
+ Kind::Part(k) => enter |= crate::dialogs_parts::rows(app, ui, k, &d.inputs),
+ Kind::PartSize(k) => enter |= crate::dialogs_part_size::rows(app, ui, k),
+ Kind::SaveMesh(k) => enter |= crate::dialogs_save_mesh::rows(app, ui, k),
+ Kind::ViewDxf { dashed, tolerance } => crate::dialogs_view_dxf::rows(app, ui, dashed, tolerance),
Kind::Sketch => {
if d.error.is_some() && matches!(d.inputs.first().and_then(|i| i.items.first()), Some(Sel::Face { .. })) {
ui_kit::hint(
@@ -552,7 +591,7 @@ pub(super) fn rows(app: &mut SolveApp, ctx: &egui::Context, d: &mut Dialog, ui:
}
_ => enter |= additional_rows(app, d, ui),
}
- error_rows(app, ctx, d, ui, true);
+ error_rows(app, ctx, d, ui);
enter
}
@@ -844,11 +883,116 @@ fn additional_rows(app: &mut SolveApp, d: &mut Dialog, ui: &mut egui::Ui) -> boo
Kind::Sheet(k) => enter |= crate::dialogs_sheet::rows(app, ui, k, &mut d.inputs),
Kind::Plastic(k) => enter |= crate::dialogs_plastic::rows(app, ui, k, &d.inputs),
Kind::Assembly(k) => enter |= crate::dialogs_assembly::rows(app, ui, k, &mut d.inputs, &mut d.active),
+ Kind::Measure { result, show, .. } => measure_rows(app, ui, result.as_ref(), show),
+ Kind::Section { offset, flip } => {
+ form_row(ui, "Distance", |ui| {
+ enter |= ui_kit::field(ui, offset);
+ });
+ ui_kit::options(ui, "feature_options", &mut [("Flip", flip)]);
+ }
+ Kind::Rename { name, .. } => {
+ form_row(ui, "Name", |ui| {
+ enter |= ui_kit::focused_text_field(ui, name, "");
+ });
+ }
+ Kind::ConfirmDelete { with, fail, .. } => {
+ if !with.is_empty() {
+ form_row(ui, "Also deletes", |ui| {
+ ui_kit::cell_text(ui, &with.join(", "));
+ });
+ }
+ if !fail.is_empty() {
+ ui_kit::text_block(ui, "will_fail", &format!("{}: {}", tr("Will fail"), fail.join(", ")), true);
+ }
+ }
_ => {}
}
enter
}
+fn fmt_mm(app: &SolveApp, v: &Value) -> String {
+ v.as_f64().map(|x| crate::prefs::show_mm(app, x, 1)).unwrap_or_default()
+}
+
+/// The measurement in the dialog: each item's size, then the distance (a pair of round items
+/// offers centre to centre, closest and farthest), its ΔX/Y/Z and the angle between two items.
+fn measure_rows(app: &SolveApp, ui: &mut egui::Ui, r: Option<&Value>, show: &mut Option<Shown>) {
+ let Some(r) = r else {
+ ui_kit::hint(ui, "measure", tr("pick one or two vertices, edges or faces"));
+ return;
+ };
+ if let Some(e) = r.get("error").and_then(Value::as_str) {
+ ui_kit::text_block(ui, "measure_error", e, true);
+ return;
+ }
+ let mm = |v: &Value| fmt_mm(app, v);
+ let value = |ui: &mut egui::Ui, label: &str, text: &str| {
+ form_row(ui, label, |ui| {
+ ui_kit::cell_text(ui, text);
+ });
+ };
+ for (i, it) in r["items"].as_array().into_iter().flatten().enumerate() {
+ // Round items: Ø first, then R, then the length (circumference, or the arc's length
+ // and angle).
+ let mut lines: Vec<String> = Vec::new();
+ if it.get("diameter").is_some() {
+ lines.push(format!("Ø {}", mm(&it["diameter"])));
+ lines.push(format!("R {}", mm(&it["radius"])));
+ if it.get("circumference").is_some() {
+ lines.push(format!("{} {}", tr("Circumference"), mm(&it["circumference"])));
+ } else if let Some(a) = it["angle_deg"].as_f64() {
+ lines.push(format!("{} {}", tr("Arc length"), mm(&it["arc_length"])));
+ lines.push(format!("{} {a:.2}°", crate::i18n::tr_label("Angle")));
+ }
+ }
+ if let Some(sl) = it.get("slot") {
+ lines.push(format!("{} {}", tr("Slot width"), mm(&sl["width"])));
+ lines.push(format!("{} {}", tr("Centre to centre"), mm(&sl["center_distance"])));
+ lines.push(format!("{} {}", tr("Overall length"), mm(&sl["overall_length"])));
+ }
+ let round = it.get("diameter").is_some();
+ match it["type"].as_str() {
+ Some("edge" | "sketch_curve") if !round => lines.push(format!("{} {}", tr("Length"), mm(&it["length_mm"]))),
+ Some("face" | "profile") => {
+ lines.push(format!("{} {}", tr("Area"), crate::prefs::show_mm(app, it["area_mm2"].as_f64().unwrap_or(0.0), 2)))
+ }
+ Some("vertex" | "sketch_point") => {
+ let p = &it["position"];
+ lines.push(format!("{} {}, {}, {}", tr("measure.at"), mm(&p[0]), mm(&p[1]), mm(&p[2])));
+ }
+ _ => {}
+ }
+ for (k, line) in lines.into_iter().enumerate() {
+ let label = if k == 0 { crate::i18n::format("measure.item", &[("number", &(i + 1).to_string())]) } else { String::new() };
+ value(ui, &label, &line);
+ }
+ }
+ if let Some((now, d, a, b)) = shown_distance(r, *show) {
+ if r.get("center_distance").is_some() {
+ // Centre, min and max all listed; the chosen one is drawn and broken into ΔX/Y/Z.
+ for (which, label, key) in
+ [(Shown::Centre, "Centre to centre", "center_distance"), (Shown::Min, "Min", "distance_mm"), (Shown::Max, "Max", "max")]
+ {
+ let Some(v) = r.get(key).filter(|v| v.is_number()) else { continue };
+ if ui_kit::list_picker(ui, key, &format!("{} {}", tr(label), mm(v)), now == which).clicked() {
+ *show = Some(which);
+ }
+ }
+ } else {
+ value(ui, crate::i18n::tr_label("Distance"), &crate::prefs::show_mm(app, d, 1));
+ }
+ let delta = b - a;
+ for (l, v) in [("ΔX", delta.x), ("ΔY", delta.y), ("ΔZ", delta.z)] {
+ value(ui, l, &crate::prefs::show_mm(app, v.abs(), 1));
+ }
+ }
+ if let Some(a) = r["angle_deg"].as_f64()
+ && r["items"].as_array().is_some_and(|v| v.len() == 2)
+ {
+ value(ui, crate::i18n::tr_label("Angle"), &format!("{a:.3}°"));
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/crates/ui-egui/src/dialogs_library.rs b/crates/ui-egui/src/dialogs_library.rs
index 5a9e01a672..e10766a5c5 100644
--- a/crates/ui-egui/src/dialogs_library.rs
+++ b/crates/ui-egui/src/dialogs_library.rs
@@ -1,10 +1,7 @@
//! The first local appearance-library consumer, inside the existing Appearance panel.
#[cfg(not(target_arch = "wasm32"))]
use crate::dialogs_appearance::selected_params;
-#[cfg(not(target_arch = "wasm32"))]
-use crate::fonts::RichTextExt as _;
-use crate::{SolveApp, dialogs::row_label, dialogs_appearance::Ap, selection::SelInput, theme::Tokens};
-use egui::RichText;
+use crate::{SolveApp, dialogs_appearance::Ap, selection::SelInput, ui_kit};
use serde_json::json;
use solidcraft_engine::io::catalog::Catalog;
#[cfg(not(target_arch = "wasm32"))]
@@ -106,17 +103,20 @@ fn load(app: &mut SolveApp, library: &mut LocalLibrary) -> Result<String, String
}
pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Ap, inputs: &[SelInput]) {
- row_label(ui, "Local library");
- ui.vertical(|ui| {
+ ui_kit::section(ui, "local_library", "Local library", true, |ui| {
#[cfg(not(target_arch = "wasm32"))]
import_rows(app, ui, k, inputs);
#[cfg(target_arch = "wasm32")]
{
let _ = inputs;
- ui.label("Open local libraries in the desktop app. You can export this design's library here.");
+ ui_kit::note(
+ ui,
+ "library_platform",
+ crate::i18n::tr_label("Open local libraries in the desktop app. You can export this design's library here."),
+ );
}
- ui.checkbox(&mut k.local.overwrite, crate::i18n::tr_label("Replace existing library file"));
- let save = ui.button(crate::i18n::tr_label("Export design library..."));
+ ui_kit::checkbox(ui, crate::i18n::tr_label("Replace existing library file"), &mut k.local.overwrite);
+ let save = ui_kit::secondary_button(ui, crate::i18n::tr_label("Export design library..."));
crate::scenario::publish_handle("library:export", save.rect.center());
if save.clicked() {
if app.services.pick_save.is_some() {
@@ -125,28 +125,30 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Ap, inputs: &[SelInpu
export(app, k, k.local.path.clone(), k.local.overwrite);
}
}
- ui.label(
- RichText::new("Apply your appearance first. Exports assigned appearances and materials created in this design.")
- .small()
- .color(Tokens::get().text_dim),
+ ui_kit::note(
+ ui,
+ "library_export",
+ crate::i18n::tr_label("Apply your appearance first. Exports assigned appearances and materials created in this design."),
);
});
- ui.end_row();
}
#[cfg(not(target_arch = "wasm32"))]
fn import_rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Ap, inputs: &[SelInput]) {
- let path = ui.add(egui::TextEdit::singleline(&mut k.local.path).hint_text("Library file").desired_width(200.0));
+ let path = ui_kit::row(ui, "Library file", |ui| {
+ let id = ui.make_persistent_id("library_path");
+ ui_kit::cell_editor(ui, id, &mut k.local.path, "Library file", false)
+ });
crate::scenario::publish_handle("library:path", path.rect.center());
if path.changed() {
k.local.catalog = None;
k.local.selected = None;
}
ui.horizontal(|ui| {
- if ui.button(crate::i18n::tr_label("Open library...")).clicked() {
+ if ui_kit::secondary_button(ui, crate::i18n::tr_label("Open library...")).clicked() {
open_library(app, k.local.token.clone());
}
- let load_button = ui.add_enabled(!k.local.path.is_empty(), egui::Button::new(crate::i18n::tr_label("Load library")));
+ let load_button = ui_kit::enabled_button(ui, "Load library", !k.local.path.is_empty());
crate::scenario::publish_handle("library:load", load_button.rect.center());
if load_button.clicked() {
k.local.catalog = None;
@@ -155,8 +157,11 @@ fn import_rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Ap, inputs: &[SelI
}
});
if let Some(catalog) = &k.local.catalog {
- ui.label(RichText::new(&catalog.name).semibold().color(crate::theme::Tokens::get().text));
- let search = ui.add(egui::TextEdit::singleline(&mut k.local.search).hint_text("Search this library").desired_width(200.0));
+ ui_kit::text_block(ui, "library_name", &catalog.name, false);
+ let search = ui_kit::row(ui, "Search this library", |ui| {
+ let id = ui.make_persistent_id("library_search");
+ ui_kit::search_field(ui, id, &mut k.local.search, "Search this library")
+ });
crate::scenario::publish_handle("library:search", search.rect.center());
if search.changed() {
k.local.selected = None;
@@ -168,31 +173,37 @@ fn import_rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Ap, inputs: &[SelI
.filter(|entry| matches!(&entry.definition, Definition::Appearance(_)) && entry.definition.name().to_lowercase().contains(&query))
.collect();
if appearances.is_empty() {
- ui.label("No matching appearance presets.");
+ ui_kit::note(ui, "library_empty", crate::i18n::tr_label("No matching appearance presets."));
}
- let row_height = ui.spacing().interact_size.y;
- egui::ScrollArea::vertical().id_salt("local_library_entries").max_height(120.0).show_rows(ui, row_height, appearances.len(), |ui, range| {
- for index in range {
- let Some(entry) = appearances.get(index) else { continue };
- if let Definition::Appearance(look) = &entry.definition {
- ui.horizontal(|ui| {
- ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate);
- let [r, g, b] = look.color;
- ui.colored_label(egui::Color32::from_rgb(r, g, b), "■");
- let button = ui.selectable_label(k.local.selected.as_deref() == Some(entry.id.as_str()), &look.name).on_hover_text(format!(
- "Opacity {:.0}% · {} · {}",
- look.opacity * 100.0,
- entry.provenance.license,
- entry.provenance.source_url.as_deref().unwrap_or("Local definition")
- ));
- crate::scenario::publish_handle(&format!("library:entry:{index}"), button.rect.center());
- if button.clicked() {
- k.local.selected = Some(entry.id.clone());
- }
- });
+ let row_height = ui_kit::row_height();
+ egui::ScrollArea::vertical().id_salt("local_library_entries").max_height(row_height * 5.0).show_rows(
+ ui,
+ row_height,
+ appearances.len(),
+ |ui, range| {
+ for index in range {
+ let Some(entry) = appearances.get(index) else { continue };
+ if let Definition::Appearance(look) = &entry.definition {
+ ui.horizontal(|ui| {
+ ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate);
+ let [r, g, b] = look.color;
+ ui_kit::color_swatch(ui, ui.id().with((&entry.id, "sample")), egui::Color32::from_rgb(r, g, b), false, &look.name, ());
+ let button = ui_kit::list_picker(ui, &entry.id, &look.name, k.local.selected.as_deref() == Some(entry.id.as_str()))
+ .on_hover_text(format!(
+ "Opacity {:.0}% · {} · {}",
+ look.opacity * 100.0,
+ entry.provenance.license,
+ entry.provenance.source_url.as_deref().unwrap_or("Local definition")
+ ));
+ crate::scenario::publish_handle(&format!("library:entry:{index}"), button.rect.center());
+ if button.clicked() {
+ k.local.selected = Some(entry.id.clone());
+ }
+ });
+ }
}
- }
- });
+ },
+ );
}
let entry = k
.local
@@ -207,7 +218,7 @@ fn import_rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Ap, inputs: &[SelI
.cloned();
let picked = inputs.first().map(|input| input.items.as_slice()).unwrap_or(&[]);
let selected = selected_params(k, picked);
- let apply = ui.add_enabled(entry.is_some() && selected.is_some(), egui::Button::new(crate::i18n::tr_label("Apply library appearance")));
+ let apply = ui_kit::enabled_button(ui, "Apply library appearance", entry.is_some() && selected.is_some());
crate::scenario::publish_handle("library:apply", apply.rect.center());
if apply.clicked()
&& let (Some(entry), Some(selected)) = (entry, selected)
diff --git a/crates/ui-egui/src/dialogs_motion.rs b/crates/ui-egui/src/dialogs_motion.rs
index 28943fa426..e1f2e2b2b4 100644
--- a/crates/ui-egui/src/dialogs_motion.rs
+++ b/crates/ui-egui/src/dialogs_motion.rs
@@ -3,20 +3,23 @@
//! show while open (a study's pose, an explosion) is display only: pending occurrence moves,
//! computed on a scratch copy of the design and put back when the dialog closes.
-use crate::fonts::RichTextExt as _;
use std::collections::BTreeMap;
-use egui::{Color32, Pos2, RichText, Sense, Stroke, pos2, vec2};
+use egui::{Pos2, RichText, Sense, Stroke, pos2, vec2};
use serde_json::{Value, json};
use solidcraft_engine::Session;
use solidcraft_engine::doc::Mat;
use solidcraft_engine::doc::joints::JointKind;
use crate::SolveApp;
-use crate::dialogs::{Dialog, Kind, combo, field, row_label};
+use crate::dialogs::{Dialog, Kind, combo, field, form_row};
use crate::selection::{BODIES, SelInput};
use crate::theme::Tokens;
+#[path = "configurations_ui.rs"]
+mod configurations_ui;
+use configurations_ui::configurations_rows;
+
#[path = "configuration_rules_ui.rs"]
mod configuration_rules_ui;
#[path = "dialogs_motion_plot.rs"]
@@ -201,7 +204,7 @@ fn transport(ui: &mut egui::Ui, what: Transport, tip: &str) -> egui::Response {
p.add(bar(c.x + 6.0));
}
}
- resp.on_hover_text(tip)
+ resp.on_hover_text(crate::i18n::tr_label(tip))
}
/// Study `key` as the Motion Study dialog edits it: (id, name, steps, keys as tracks with values
@@ -442,71 +445,74 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Mo, inputs: &mut [Sel
let mut enter = false;
match k {
Mo::ContactSet { name, check } => {
- row_label(ui, "Name");
- ui.text_edit_singleline(name);
- ui.end_row();
+ form_row(ui, "Name", |ui| {
+ crate::ui_kit::text_field(ui, name, "");
+ });
let list = app.session.execute("contact.list", &json!({})).unwrap_or(Value::Null);
- row_label(ui, "Contact");
- let mut on = list.get("enabled").and_then(Value::as_bool).unwrap_or(false);
- if ui.checkbox(&mut on, "enabled").changed() {
- let _ = app.run("contact.enable_sets", json!({ "enabled": on }));
- }
- ui.end_row();
+ form_row(ui, "Contact", |ui| {
+ let mut on = list.get("enabled").and_then(Value::as_bool).unwrap_or(false);
+ if crate::ui_kit::checkbox(ui, "enabled", &mut on).changed() {
+ let _ = app.run("contact.enable_sets", json!({ "enabled": on }));
+ }
+ });
for s in list.get("sets").and_then(Value::as_array).cloned().unwrap_or_default() {
let n = s.get("name").and_then(Value::as_str).unwrap_or("").to_string();
let off = s.get("suppressed").and_then(Value::as_bool).unwrap_or(false);
- row_label(ui, &n);
- ui.horizontal(|ui| {
- let count = s.get("occurrences").and_then(Value::as_array).map_or(0, Vec::len);
- ui.label(RichText::new(format!("{count} components")).color(t.text_dim));
- if ui.small_button(if off { "Unsuppress" } else { "Suppress" }).clicked() {
- let _ = app.run("contact.edit", json!({"set": n, "suppressed": !off}));
- }
- if ui.small_button("×").on_hover_text(crate::i18n::tr_label("Delete the set")).clicked() {
- let _ = app.run("contact.edit", json!({"set": n, "delete": true}));
- }
+ crate::ui_kit::section(ui, format!("contact:{n}"), &n, true, |ui| {
+ ui.horizontal(|ui| {
+ let count = s.get("occurrences").and_then(Value::as_array).map_or(0, Vec::len);
+ ui.label(RichText::new(crate::i18n::format("contact.components_count", &[("count", &count.to_string())])).color(t.text_dim));
+ if crate::ui_kit::small_button(ui, crate::i18n::tr_label(if off { "Unsuppress" } else { "Suppress" })).clicked() {
+ let _ = app.run("contact.edit", json!({"set": n, "suppressed": !off}));
+ }
+ if crate::ui_kit::small_button(ui, crate::i18n::tr_label("×"))
+ .on_hover_text(crate::i18n::tr_label("Delete the set"))
+ .clicked()
+ {
+ let _ = app.run("contact.edit", json!({"set": n, "delete": true}));
+ }
+ });
});
- ui.end_row();
}
- row_label(ui, "");
- if ui.button(crate::i18n::tr_label("Check collisions")).clicked() {
- *check = Some(app.session.execute("contact.check", &json!({})).unwrap_or_else(|e| json!({"error": e.to_string()})));
- }
- ui.end_row();
+ ui.vertical(|ui| {
+ if crate::ui_kit::secondary_button(ui, crate::i18n::tr_label("Check collisions")).clicked() {
+ *check = Some(app.session.execute("contact.check", &json!({})).unwrap_or_else(|e| json!({"error": e.to_string()})));
+ }
+ });
if let Some(c) = check {
let hits = c.get("collisions").and_then(Value::as_array).cloned().unwrap_or_default();
- row_label(ui, "Collisions");
- if let Some(e) = c.get("error").and_then(Value::as_str) {
- ui.label(RichText::new(e).color(t.error));
- } else if hits.is_empty() {
- ui.label(RichText::new("none").color(t.text_dim));
- } else {
- ui.vertical(|ui| {
- for h in hits {
- ui.label(
- RichText::new(format!(
- "{} · {} {:.3} mm",
- name_of(&h["a"]),
- name_of(&h["b"]),
- h["depth_mm"].as_f64().unwrap_or(0.0)
- ))
- .color(t.error),
- );
- }
- });
- }
- ui.end_row();
+ crate::ui_kit::section(ui, "contact_collisions", "Collisions", true, |ui| {
+ if let Some(e) = c.get("error").and_then(Value::as_str) {
+ ui.label(RichText::new(e).color(t.error));
+ } else if hits.is_empty() {
+ ui.label(RichText::new("none").color(t.text_dim));
+ } else {
+ ui.vertical(|ui| {
+ for h in hits {
+ ui.label(
+ RichText::new(format!(
+ "{} · {} {:.3} mm",
+ name_of(&h["a"]),
+ name_of(&h["b"]),
+ h["depth_mm"].as_f64().unwrap_or(0.0)
+ ))
+ .color(t.error),
+ );
+ }
+ });
+ }
+ });
}
}
Mo::MotionStudy { .. } => enter = motion_study_rows(app, ui, k, inputs, t),
Mo::Explode { name, scale, shown, saved, error } => {
- row_label(ui, "Name");
- ui.text_edit_singleline(name);
- ui.end_row();
- row_label(ui, "Explode");
- ui.spacing_mut().slider_width = 160.0;
- ui.add(egui::Slider::new(scale, 0.0..=2.0).fixed_decimals(2));
- ui.end_row();
+ form_row(ui, "Name", |ui| {
+ crate::ui_kit::text_field(ui, name, "");
+ });
+ form_row(ui, "Explode", |ui| {
+ ui.spacing_mut().slider_width = 160.0;
+ crate::ui_kit::slider(ui, scale, 0.0..=2.0);
+ });
let key = ((*scale * 1000.0).round() as u64, 0);
if *shown != Some(key) {
match explode_pose(app, *scale) {
@@ -519,12 +525,12 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Mo, inputs: &mut [Sel
*shown = Some(key);
}
if let Some(e) = error {
- row_label(ui, "");
- ui.label(RichText::new(e.as_str()).color(t.error));
- ui.end_row();
+ ui.vertical(|ui| {
+ ui.label(RichText::new(e.as_str()).color(t.error));
+ });
}
}
- Mo::Configurations { new_row, error, rule_editor } => configurations_rows(app, ui, new_row, error, rule_editor, t),
+ Mo::Configurations { new_row, error, rule_editor } => configurations_rows(app, ui, new_row, error, rule_editor),
}
let _ = inputs;
enter
@@ -541,9 +547,9 @@ fn motion_study_rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Mo, inputs:
let labels: Vec<&str> = std::iter::once("New study").chain(studies.iter().map(|(_, n)| n.as_str())).collect();
let was = study.as_ref().and_then(|id| studies.iter().position(|(x, _)| x == id)).map_or(0, |i| i + 1);
let mut pick = was;
- row_label(ui, "Study");
- combo(ui, "ms_study", &labels, &mut pick);
- ui.end_row();
+ form_row(ui, "Study", |ui| {
+ combo(ui, "ms_study", &labels, &mut pick);
+ });
if pick != was {
match pick.checked_sub(1).and_then(|i| studies.get(i)).map(|(id, _)| study_tracks(&app.session, id, true)) {
Some(Ok((id, n, st, t))) => (*study, *name, *steps, *tracks, *shown, *playing) = (Some(id.to_string()), n, st, t, None, false),
@@ -552,64 +558,63 @@ fn motion_study_rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Mo, inputs:
}
}
}
- row_label(ui, "Name");
- ui.text_edit_singleline(name);
- ui.end_row();
- row_label(ui, "Steps");
- enter |= field(ui, steps);
- ui.end_row();
+ form_row(ui, "Name", |ui| {
+ crate::ui_kit::text_field(ui, name, "");
+ });
+ form_row(ui, "Steps", |ui| {
+ enter |= field(ui, steps);
+ });
let total = steps.trim().parse::<u32>().unwrap_or(100).clamp(1, 100_000);
let moving = joints_moving(app);
if moving.is_empty() {
- row_label(ui, "");
- ui.label(RichText::new(crate::i18n::tr_label("no joint that moves yet")).color(t.text_dim));
- ui.end_row();
+ ui.vertical(|ui| {
+ ui.label(RichText::new(crate::i18n::tr_label("no joint that moves yet")).color(t.text_dim));
+ });
return enter;
}
// Playback: to start, step back, play/stop, step on, to end; loop and speed.
- row_label(ui, "Playback");
- ui.horizontal(|ui| {
- let last = f64::from(total);
- if transport(ui, Transport::Start, "To the start").clicked() {
- *step = 0.0;
- *playing = false;
- }
- if transport(ui, Transport::Back, "Step back").clicked() {
- *step = (step.round() - 1.0).max(0.0);
- *playing = false;
- }
- let (what, tip) = if *playing { (Transport::Stop, "Stop") } else { (Transport::Play, "Play") };
- if transport(ui, what, tip).clicked() {
- // Play from the start again when at the end.
- if !*playing && step.round() >= last {
+ crate::ui_kit::section(ui, "motion_playback", "Playback", true, |ui| {
+ ui.horizontal_wrapped(|ui| {
+ let last = f64::from(total);
+ if transport(ui, Transport::Start, "To the start").clicked() {
*step = 0.0;
+ *playing = false;
}
- *playing = !*playing;
- }
- if transport(ui, Transport::Forward, "Step on").clicked() {
- *step = (step.round() + 1.0).min(last);
- *playing = false;
- }
- if transport(ui, Transport::End, "To the end").clicked() {
- *step = last;
- *playing = false;
- }
- ui.add_space(6.0);
- ui.checkbox(looping, crate::i18n::tr_label("Loop"));
- let names: Vec<String> = SPEEDS.iter().map(|x| format!("{x}×")).collect();
- let refs: Vec<&str> = names.iter().map(String::as_str).collect();
- combo(ui, "ms_speed", &refs, speed);
+ if transport(ui, Transport::Back, "Step back").clicked() {
+ *step = (step.round() - 1.0).max(0.0);
+ *playing = false;
+ }
+ let (what, tip) = if *playing { (Transport::Stop, "Stop") } else { (Transport::Play, "Play") };
+ if transport(ui, what, tip).clicked() {
+ // Play from the start again when at the end.
+ if !*playing && step.round() >= last {
+ *step = 0.0;
+ }
+ *playing = !*playing;
+ }
+ if transport(ui, Transport::Forward, "Step on").clicked() {
+ *step = (step.round() + 1.0).min(last);
+ *playing = false;
+ }
+ if transport(ui, Transport::End, "To the end").clicked() {
+ *step = last;
+ *playing = false;
+ }
+ ui.add_space(t.space_6);
+ crate::ui_kit::checkbox(ui, "Loop", looping);
+ let names: Vec<String> = SPEEDS.iter().map(|x| format!("{x}×")).collect();
+ let refs: Vec<&str> = names.iter().map(String::as_str).collect();
+ ui.allocate_ui(vec2(t.form_label_width, t.control_height), |ui| combo(ui, "ms_speed", &refs, speed));
+ });
});
- ui.end_row();
- row_label(ui, "Step");
- ui.horizontal(|ui| {
- ui.spacing_mut().slider_width = 260.0;
- if ui.add(egui::Slider::new(step, 0.0..=f64::from(total)).integer().show_value(false)).dragged() {
- *playing = false;
- }
- ui.label(RichText::new(format!("{} / {total}", step.round() as u32)).color(t.text_dim));
+ form_row(ui, "Step", |ui| {
+ ui.horizontal(|ui| {
+ if crate::ui_kit::timeline_slider(ui, step, 0.0..=f64::from(total), true).dragged() {
+ *playing = false;
+ }
+ });
});
- ui.end_row();
+ crate::ui_kit::caption(ui, "Step", &format!("{} / {total}", step.round() as u32));
if *playing {
let dt = f64::from(ui.input(|i| i.stable_dt).min(0.1));
let fps = STEPS_PER_S * SPEEDS.get(*speed).copied().unwrap_or(1.0);
@@ -626,70 +631,74 @@ fn motion_study_rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Mo, inputs:
let labels: Vec<String> = moving.iter().map(|(_, n, _)| n.clone()).collect();
let refs: Vec<&str> = labels.iter().map(String::as_str).collect();
let mut pos = moving.iter().position(|(i, _, _)| *i == tr.joint).unwrap_or(0);
- row_label(ui, &format!("Track {}", ti + 1));
- ui.horizontal(|ui| {
- combo(ui, &format!("ms_joint{ti}"), &refs, &mut pos);
- if ui.small_button("×").on_hover_text(crate::i18n::tr_label("Remove the track")).clicked() {
- remove = Some(ti);
- }
+ form_row(ui, &crate::i18n::format("motion.track_name", &[("number", &(ti + 1).to_string())]), |ui| {
+ ui.horizontal(|ui| {
+ let width = (ui.available_width() - t.control_height - t.space_8).max(0.0);
+ ui.allocate_ui(vec2(width, t.control_height), |ui| combo(ui, &format!("ms_joint{ti}"), &refs, &mut pos));
+ if crate::ui_kit::small_button(ui, crate::i18n::tr_label("×")).on_hover_text(crate::i18n::tr_label("Remove the track")).clicked() {
+ remove = Some(ti);
+ }
+ });
});
- ui.end_row();
if let Some((ji, _, kind)) = moving.get(pos) {
tr.joint = *ji;
let dofs = kind.dofs();
if dofs.len() > 1 {
- row_label(ui, " Of");
- let caps: Vec<&str> = dofs.to_vec();
- combo(ui, &format!("ms_idx{ti}"), &caps, &mut tr.index);
- ui.end_row();
+ form_row(ui, " Of", |ui| {
+ let caps: Vec<&str> = dofs.to_vec();
+ combo(ui, &format!("ms_idx{ti}"), &caps, &mut tr.index);
+ });
} else {
tr.index = 0;
}
}
- row_label(ui, " Keys");
- key_strip(ui, tr, total, now, &t);
- ui.end_row();
+ form_row(ui, " Keys", |ui| {
+ key_strip(ui, tr, total, now, &t);
+ });
// The key at this step, if any: its value.
if let Some(p) = tr.points.iter_mut().find(|(s, _)| *s == now) {
// The key's value (Enter commits it; OK makes the study).
- row_label(ui, "Value");
- let _ = field(ui, &mut p.1);
- ui.end_row();
+ form_row(ui, "Value", |ui| {
+ let _ = field(ui, &mut p.1);
+ });
}
- row_label(ui, "");
- ui.horizontal(|ui| {
- if ui.small_button("Key here").on_hover_text("Add a key at this step with the joint's value now").clicked()
- && !tr.points.iter().any(|(s, _)| *s == now)
- {
- let unit =
- app.session.doc.assembly.joints.get(tr.joint).map(|j| if j.kind.is_angle(tr.index) { "deg" } else { "mm" }).unwrap_or("mm");
- tr.points.push((now, format!("0 {unit}")));
- tr.points.sort_by_key(|p| p.0);
- }
- if ui.small_button("Delete key").clicked() {
- tr.points.retain(|(s, _)| *s != now);
- }
+ ui.vertical(|ui| {
+ ui.horizontal(|ui| {
+ if crate::ui_kit::small_button(ui, crate::i18n::tr_label("Key here"))
+ .on_hover_text(crate::i18n::tr_label("Add a key at this step with the joint's value now"))
+ .clicked()
+ && !tr.points.iter().any(|(s, _)| *s == now)
+ {
+ let unit =
+ app.session.doc.assembly.joints.get(tr.joint).map(|j| if j.kind.is_angle(tr.index) { "deg" } else { "mm" }).unwrap_or("mm");
+ tr.points.push((now, format!("0 {unit}")));
+ tr.points.sort_by_key(|p| p.0);
+ }
+ if crate::ui_kit::small_button(ui, crate::i18n::tr_label("Delete key")).clicked() {
+ tr.points.retain(|(s, _)| *s != now);
+ }
+ });
});
- ui.end_row();
}
if let Some(i) = remove {
tracks.remove(i);
}
- row_label(ui, "");
let mut export = false;
- ui.horizontal(|ui| {
- if ui.button(crate::i18n::tr_label("Add Key")).on_hover_text(crate::i18n::tr_label("Key a joint's value at this step")).clicked()
- && let Some((ji, _, kind)) = moving.first()
- {
- let unit = if kind.is_angle(0) { "deg" } else { "mm" };
- tracks.push(Track { joint: *ji, index: 0, points: vec![(now, format!("0 {unit}"))] });
- }
- export = ui
- .button(crate::i18n::tr_label("Export Animation…"))
- .on_hover_text(crate::i18n::tr_label("Save the study as an animated GIF, seen as the viewport shows it"))
- .clicked();
+ ui.vertical(|ui| {
+ ui.horizontal(|ui| {
+ if crate::ui_kit::secondary_button(ui, crate::i18n::tr_label("Add Key"))
+ .on_hover_text(crate::i18n::tr_label("Key a joint's value at this step"))
+ .clicked()
+ && let Some((ji, _, kind)) = moving.first()
+ {
+ let unit = if kind.is_angle(0) { "deg" } else { "mm" };
+ tracks.push(Track { joint: *ji, index: 0, points: vec![(now, format!("0 {unit}"))] });
+ }
+ export = crate::ui_kit::secondary_button(ui, crate::i18n::tr_label("Export Animation…"))
+ .on_hover_text(crate::i18n::tr_label("Save the study as an animated GIF, seen as the viewport shows it"))
+ .clicked();
+ });
});
- ui.end_row();
// Show the pose at this step (again when the step or the keys change).
let params = study_params(&app.session, name, study.as_deref(), steps, tracks);
if export {
@@ -715,329 +724,11 @@ fn motion_study_rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Mo, inputs:
*shown = Some((u64::from(now), key));
}
if let Some(e) = error {
- row_label(ui, "");
- ui.label(RichText::new(e.as_str()).color(t.text_dim));
- ui.end_row();
- }
- enter
-}
-
-/// The Configurations table, its rules and errors.
-fn configurations_rows(
- app: &mut SolveApp,
- ui: &mut egui::Ui,
- new_row: &mut String,
- error: &mut Option<String>,
- rule_editor: &mut configuration_rules_ui::Editor,
- t: Tokens,
-) {
- // Physical materials for the configuration table's Library: the library's, then the design's own.
- let material_names = app.session.doc.material_names();
- let revision = app.session.revision;
- let v = rule_editor.table.as_ref().filter(|(r, _)| *r == revision).map(|(_, v)| v.clone()).unwrap_or_else(|| {
- let value = app.session.execute("config.table", &json!({})).unwrap_or(Value::Null);
- rule_editor.table = Some((revision, value.clone()));
- value
- });
- let mut tb = table(&v);
- // Bare numbers show with their parameter's unit ("40" is 40 mm).
- let kinds = app.session.doc.all_param_exprs();
- for (_, vals) in &mut tb.rows {
- for (c, val) in tb.columns.iter().zip(vals.iter_mut()) {
- let (kind, n) = column_parts(c);
- if kind == "param"
- && val.trim().parse::<f64>().is_ok()
- && let Some(unit) = app.session.doc.param(n).map(|parameter| parameter.unit.clone()).or_else(|| {
- kinds.iter().find(|x| x.0 == n).and_then(|x| {
- unit_of(x.2).map(|unit| {
- if x.2 == solidcraft_engine::doc::expr::Kind::Length { app.session.doc.units.clone() } else { unit.to_string() }
- })
- })
- })
- {
- *val = format!("{} {unit}", val.trim());
- }
- }
- }
- let run = |app: &mut SolveApp, error: &mut Option<String>, id: &str, p: Value| {
- *error = app.run(id, p).err();
- };
- egui::ScrollArea::horizontal().id_salt("configuration_columns").auto_shrink([false, true]).show(ui, |ui| {
- ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend);
- egui::Grid::new("configuration_table").num_columns(2).min_col_width(210.0).spacing(vec2(10.0, 8.0)).show(ui, |ui| {
- // Header.
- ui.label(RichText::new(crate::i18n::tr_label("Configuration")).semibold().color(crate::theme::Tokens::get().text));
- ui.horizontal(|ui| {
- for c in &tb.columns {
- ui.allocate_ui_with_layout(vec2(190.0, 22.0), egui::Layout::left_to_right(egui::Align::Center), |ui| {
- let (kind, n) = column_parts(c);
- let label = match kind {
- "material" => format!("Material: {n}"),
- "appearance" => format!("Appearance: {n}"),
- "suppress" => format!("Suppress: {n}"),
- _ => n.to_string(),
- };
- let label = v["targets"]
- .as_array()
- .and_then(|targets| targets.iter().find(|target| target["key"].as_str() == Some(c)))
- .and_then(|target| target["label"].as_str())
- .filter(|_| matches!(kind, "component_appearance" | "face_appearance"))
- .map(str::to_string)
- .unwrap_or(label);
- ui.add_sized(
- vec2(156.0, 22.0),
- egui::Label::new(RichText::new(label).semibold().color(crate::theme::Tokens::get().text)).truncate(),
- )
- .on_hover_text(c);
- if ui.small_button("×").on_hover_text(crate::i18n::tr_label("Remove the column")).clicked() {
- let key = if kind == "suppress" { "feature" } else { kind };
- run(app, error, "config.column", json!({ key: if kind == "face_appearance" {c.as_str()} else {n}, "delete": true }));
- }
- });
- }
- });
- ui.end_row();
- for (name, vals) in &tb.rows {
- let active = tb.active.as_deref() == Some(name.as_str());
- ui.horizontal(|ui| {
- ui.add_sized(
- vec2(100.0, 22.0),
- egui::Label::new(if active {
- RichText::new(name).semibold().color(crate::theme::Tokens::get().text)
- } else {
- RichText::new(name)
- })
- .truncate(),
- )
- .on_hover_text(name);
- if active {
- ui.label(RichText::new(crate::i18n::tr_label("Active")).color(t.accent));
- if v.get("matches").and_then(Value::as_bool) == Some(false) && ui.button("Apply").clicked() {
- run(app, error, "config.activate", json!({ "row": name }));
- }
- } else if ui.button(crate::i18n::tr_label("Activate")).clicked() {
- run(app, error, "config.activate", json!({ "row": name }));
- }
- });
- ui.horizontal(|ui| {
- for (c, val) in tb.columns.iter().zip(vals) {
- ui.allocate_ui_with_layout(vec2(190.0, 22.0), egui::Layout::left_to_right(egui::Align::Center), |ui| {
- let (kind, _) = column_parts(c);
- let appearance = matches!(kind, "appearance" | "component_appearance" | "face_appearance");
- let shown = if appearance {
- solidcraft_engine::doc::config::appearance_cell(val)
- .ok()
- .flatten()
- .filter(|look| solidcraft_engine::doc::appearance::library(&look.name).as_ref() == Some(look))
- .map(|look| look.name)
- .unwrap_or_else(|| val.clone())
- } else {
- val.clone()
- };
- let style = kind == "material" || appearance;
- if style {
- let mut choice = None;
- ui.menu_button("Library", |ui| {
- if ui
- .button(if kind == "appearance" {
- "Follow material"
- } else if appearance {
- "Follow inherited appearance"
- } else {
- "Default material"
- })
- .clicked()
- {
- choice = Some("Default".to_string());
- ui.close();
- }
- if kind == "material" {
- for name in material_names.iter().filter(|n| *n != "Default") {
- if ui.button(name).clicked() {
- choice = Some(name.to_string());
- ui.close();
- }
- }
- } else {
- for (name, _, _) in solidcraft_engine::doc::appearance::LIBRARY {
- if ui.button(name).clicked() {
- choice = Some(name.to_string());
- ui.close();
- }
- }
- }
- });
- if let Some(choice) = choice {
- run(app, error, "config.row", json!({"name": name, "values": { c: choice }}));
- }
- }
- let id = (name.clone(), c.clone());
- let mut text = rule_editor.drafts.get(&id).cloned().unwrap_or_else(|| shown.clone());
- let r = ui.add(egui::TextEdit::singleline(&mut text).desired_width(if style { 106.0 } else { 164.0 }));
- if r.changed() {
- rule_editor.drafts.insert(id.clone(), text.clone());
- }
- if r.lost_focus() {
- rule_editor.drafts.remove(&id);
- if text != shown {
- run(app, error, "config.row", json!({"name": name, "values": { c: cell_value(c, &text) }}));
- }
- }
- });
- }
- if ui.small_button("×").on_hover_text(crate::i18n::tr_label("Delete the row")).clicked() {
- run(app, error, "config.row", json!({"name": name, "delete": true}));
- }
- });
- ui.end_row();
- }
+ ui.vertical(|ui| {
+ ui.label(RichText::new(e.as_str()).color(t.text_dim));
});
- });
- // New row (a copy of the active one) and new column.
- ui.horizontal(|ui| {
- ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend);
- ui.add(egui::TextEdit::singleline(new_row).hint_text(crate::i18n::tr_label("new configuration")).desired_width(160.0));
- if ui.button(crate::i18n::tr_label("Add Row")).on_hover_text(crate::i18n::tr_label("A new configuration, a copy of the active one")).clicked()
- {
- let name = if new_row.trim().is_empty() {
- (tb.rows.len() + 1..).map(|k| format!("Configuration{k}")).find(|n| !tb.rows.iter().any(|r| &r.0 == n)).unwrap_or_default()
- } else {
- new_row.trim().to_string()
- };
- let mut p = json!({ "name": name });
- if let Some(a) = &tb.active {
- p["from"] = json!(a);
- }
- run(app, error, "config.row", p);
- new_row.clear();
- }
- // A column: a parameter's value or a feature's suppression.
- let mut options: Vec<(String, Value)> = Vec::new();
- for p in app.session.doc.all_param_exprs() {
- if !tb.columns.contains(&format!("param:{}", p.0)) {
- options.push((format!("{} (parameter)", p.0), json!({ "param": p.0 })));
- }
- }
- for f in &app.session.doc.features {
- if !tb.columns.contains(&format!("suppress:{}", f.name)) {
- options.push((format!("Suppress {}", f.name), json!({ "feature": f.name })));
- }
- }
- for body in &app.session.model.state().bodies {
- for kind in ["material", "appearance"] {
- if !tb.columns.contains(&format!("{kind}:{}", body.name)) {
- options.push((format!("{} ({kind})", body.name), json!({kind: body.name})));
- }
- }
- }
- for component in &app.session.doc.components {
- if component.id != 0 && !tb.columns.contains(&format!("component_appearance:{}", component.id)) {
- options.push((format!("{} (component appearance)", component.name), json!({"component_appearance":component.id})));
- }
- }
- for selected in &app.session.selection {
- if let solidcraft_engine::Sel::Face { body, point, .. } = selected {
- options.push((format!("Selected face on {body} (shared appearance)"), json!({"face_appearance":{"body":body,"point":point}})));
- }
- }
- let mut pick: Option<Value> = None;
- ui.menu_button("Add Column", |ui| {
- egui::ScrollArea::vertical().max_height(300.0).show(ui, |ui| {
- for (label, p) in &options {
- if ui.button(label.as_str()).clicked() {
- pick = Some(p.clone());
- ui.close();
- }
- }
- ui.menu_button("Face Appearance", |ui| {
- ui.label(crate::i18n::tr_label("Semantic faces share their appearance across instances."));
- let state = app.session.model.state();
- for body in &state.bodies {
- if body.body.is_mesh() {
- continue;
- }
- ui.menu_button(format!("Faces on {}", body.name), |ui| {
- if let Ok(faces) = body.body.faces((body.body.size() * 2e-3).max(1e-3)) {
- let mut seen = std::collections::BTreeSet::new();
- let mesh = body.mesh();
- let mut points = std::collections::BTreeMap::new();
- for (triangle, index) in mesh.triangles.iter().zip(&mesh.tri_face) {
- if let std::collections::btree_map::Entry::Vacant(entry) = points.entry(*index as usize)
- && let Some([a, b, c]) = mesh.tri(triangle)
- {
- entry.insert((a + b + c) * (1. / 3.));
- }
- }
- for face in faces {
- // A curved face centroid can lie on another surface.
- // Pick an interior triangle point on this actual face.
- let Some(point) = points.get(&face.index).copied() else { continue };
- let Ok(target) = app.session.doc.configuration_face_target(body, face.index, point) else { continue };
- let supported = if target.certificate.is_some() {
- // Capture read this exact face's current source certificate.
- // Enumerate its pieces once in the command, not per menu face.
- app.session.doc.certify_config_face(&target).is_ok()
- } else {
- app.session.doc.configuration_face_indices(body, &target).is_ok()
- };
- if !supported || !seen.insert(target.name.clone()) {
- continue;
- }
- let Some((_, role)) = target.name.split_once(':') else { continue };
- if ui.button(role).clicked() {
- pick = Some(json!({"face_appearance":{"target":target}}));
- ui.close();
- }
- }
- }
- });
- }
- });
- });
- });
- if let Some(p) = pick {
- // The first column starts the table (with a Default row of the current values).
- let (id, p) = if tb.columns.is_empty() {
- (
- "config.configure",
- if let Some(n) = p.get("param") {
- json!({ "params": [n] })
- } else if let Some(n) = p.get("feature") {
- json!({ "features": [n] })
- } else if let Some(n) = p.get("material") {
- json!({ "materials": [n] })
- } else if let Some(n) = p.get("component_appearance") {
- json!({ "component_appearances": [n] })
- } else if let Some(n) = p.get("face_appearance") {
- json!({ "face_appearances": [n] })
- } else {
- json!({ "appearances": [p.get("appearance")] })
- },
- )
- } else {
- ("config.column", p)
- };
- run(app, error, id, p);
- }
- });
- ui.end_row();
- configuration_rules_ui::show(ui, app, error, rule_editor);
- if let Some(styles) = v["style_status"].as_array() {
- for style in styles.iter().filter(|style| style["dormant"].as_bool() == Some(true)) {
- ui.add(
- egui::Label::new(format!("{}: appearance dormant while its feature is suppressed", style["target"].as_str().unwrap_or("Face")))
- .wrap(),
- );
- }
- }
- if let Some(message) = v["style_error"].as_str() {
- ui.add(egui::Label::new(RichText::new(message).color(t.error)).wrap());
- }
- if let Some(e) = error {
- ui.label("");
- ui.label(RichText::new(e.as_str()).color(t.error));
- ui.end_row();
}
+ enter
}
/// A JSON name or id as text.
@@ -1060,7 +751,7 @@ fn key_strip(ui: &mut egui::Ui, tr: &Track, total: u32, now: u32, t: &Tokens) {
p.add(egui::Shape::convex_polygon(
vec![q + vec2(0.0, -5.0), q + vec2(5.0, 0.0), q + vec2(0.0, 5.0), q + vec2(-5.0, 0.0)],
t.accent,
- Stroke::new(1.0, Color32::WHITE),
+ Stroke::new(1.0, t.on_accent),
));
}
let px = x(now);
@@ -1190,32 +881,87 @@ mod tests {
assert!(h.widget("Choose…").is_none(), "parameter choice should close and update the dropdown");
}
+ // Kit rows publish identities independently of translated text. Long forms scroll through
+ // the same wheel events as a person; assertions still verify the saved rules and geometry.
+ fn reveal_config_handle(h: &mut crate::scenario::Harness, handle: &str) {
+ for _ in 0..24 {
+ let at = crate::scenario::handle_at(handle).unwrap_or_else(|| panic!("missing {handle}: {:?}", h.app.dialog));
+ let header = crate::scenario::rect_of("dialog:header").unwrap();
+ let footer = crate::scenario::rect_of("dialog:footer").unwrap();
+ if at.y > header.bottom() + 8.0 && at.y < footer.top() - 8.0 {
+ return;
+ }
+ h.call(
+ "ui.scroll",
+ json!({"x":header.center().x,"y":(header.bottom()+footer.top())*0.5,"delta":if at.y > footer.top() {-160.0} else {160.0}}),
+ );
+ h.frames(6);
+ }
+ panic!("could not reveal {handle}");
+ }
+
+ fn click_config_handle(h: &mut crate::scenario::Harness, handle: &str) {
+ reveal_config_handle(h, handle);
+ h.step(&json!({"click":{"handle":handle}})).unwrap();
+ }
+
+ fn configuration_steps(h: &mut crate::scenario::Harness, steps: &Value) -> Result<(), String> {
+ for (index, step) in steps.as_array().ok_or("steps must be an array")?.iter().enumerate() {
+ let handle = match step["widget"].as_str() {
+ Some("Save Rule") => Some("config:save_rule"),
+ Some("Preview Row") => Some("config:preview_row"),
+ Some("Apply") => Some("config:activate:Default"),
+ Some("Drive parameter") => Some("dialog:Then"),
+ Some("Preview: Default") => Some("dialog:section:Preview: Default"),
+ _ => step
+ .get("click")
+ .and_then(|c| c.get("handle"))
+ .and_then(Value::as_str)
+ .filter(|h| ["dialog:Value", "dialog:Minimum", "dialog:Maximum"].contains(h)),
+ };
+ if let Some(handle) = handle {
+ click_config_handle(h, handle);
+ } else {
+ h.step(step).map_err(|error| format!("step {index}: {error}"))?;
+ }
+ }
+ Ok(())
+ }
+
#[test]
fn configuration_compound_condition_and_rule_order_are_editable_in_dialog() {
let mut h = crate::scenario::Harness::new();
h.call("ui.resize", json!({"width":1400,"height":1100}));
- h.run(&json!([
- {"call":"engine.execute","params":{"command":"parameters.change","params":{"name":"length","expression":"40 mm"}}},
- {"call":"engine.execute","params":{"command":"config.configure","params":{"params":["length"]}}},
- {"start":"config.table"},{"widget":"Add or edit rule"},
- {"widget":"Always"},{"widget":"All"},{"widget":"Always"},{"widget":"Parameter"},
- {"widget":"Choose…"}
- ]))
+ configuration_steps(
+ &mut h,
+ &json!([
+ {"call":"engine.execute","params":{"command":"parameters.change","params":{"name":"length","expression":"40 mm"}}},
+ {"call":"engine.execute","params":{"command":"config.configure","params":{"params":["length"]}}},
+ {"start":"config.table"},{"widget":"Add or edit rule"},
+ {"widget":"Always"},{"click":{"handle":"dialog:When:All"}},{"widget":"Always"},{"click":{"handle":"dialog:When:Parameter"}},
+ {"widget":"Choose…"}
+ ]),
+ )
.unwrap();
select_rule_parameter(&mut h, "length");
- h.step(&json!({"widget":"Save Rule"})).unwrap();
+ click_config_handle(&mut h, "config:save_rule");
+ assert!(!h.app.session.doc.configs.rules.is_empty(), "{:?}", h.app.dialog);
assert!(
- matches!(&h.app.session.doc.configs.rules[0].condition,solidcraft_engine::doc::config::RuleCondition::All{conditions} if matches!(&conditions[0],solidcraft_engine::doc::config::RuleCondition::Parameter{..}))
+ matches!(&h.app.session.doc.configs.rules[0].condition,solidcraft_engine::doc::config::RuleCondition::All{conditions} if matches!(&conditions[0],solidcraft_engine::doc::config::RuleCondition::Parameter{..})),
+ "{:?}",
+ h.app.dialog
);
- h.run(&json!([
+ configuration_steps(&mut h, &json!([
{"call":"engine.execute","params":{"command":"config.rule","params":{"rule":{"id":"last","name":"Last drive","condition":{"type":"always"},"effect":{"type":"drive_parameter","parameter":"length","expression":"20 mm"}}}}},
{"widget":"Preview Row"},{"widget":"Preview: Default"}
])).unwrap();
+ reveal_config_handle(&mut h, "config:preview:param:length");
assert!(h.widget("length = 20 mm").is_some());
assert_eq!(h.app.session.doc.param("length").unwrap().expr, "40 mm");
- click_rule_button(&mut h, "↑");
- h.step(&json!({"widget":"Preview Row"})).unwrap();
+ click_config_handle(&mut h, "config:rule:last:up");
+ click_config_handle(&mut h, "config:preview_row");
assert_eq!(h.app.session.doc.configs.rules[0].id, "last");
+ reveal_config_handle(&mut h, "config:preview:param:length");
assert!(h.widget("length = 10 mm").is_some());
assert_eq!(h.app.session.doc.param("length").unwrap().expr, "40 mm");
}
@@ -1224,40 +970,52 @@ mod tests {
fn configuration_rule_editor_creates_previews_edits_and_applies_driven_value() {
let mut h = crate::scenario::Harness::new();
h.call("ui.resize", json!({"width":1400,"height":1000}));
- h.run(&json!([
- {"call":"engine.execute","params":{"command":"parameters.change","params":{"name":"length","expression":"40 mm"}}},
- {"call":"engine.execute","params":{"command":"solid.box","params":{"length":"length","width":10,"height":10}}},
- {"call":"engine.execute","params":{"command":"config.configure","params":{"params":["length"]}}},
- {"start":"config.table"},
- {"widget":"Add or edit rule"},
- {"widget":"Choose…"}
- ]))
+ configuration_steps(
+ &mut h,
+ &json!([
+ {"call":"engine.execute","params":{"command":"parameters.change","params":{"name":"length","expression":"40 mm"}}},
+ {"call":"engine.execute","params":{"command":"solid.box","params":{"length":"length","width":10,"height":10}}},
+ {"call":"engine.execute","params":{"command":"config.configure","params":{"params":["length"]}}},
+ {"start":"config.table"},
+ {"widget":"Add or edit rule"},
+ {"widget":"Choose…"}
+ ]),
+ )
.unwrap();
select_rule_parameter(&mut h, "length");
- h.run(&json!([
- {"widget":"Save Rule"}
- ]))
+ configuration_steps(
+ &mut h,
+ &json!([
+ {"widget":"Save Rule"}
+ ]),
+ )
.unwrap();
assert_eq!(h.app.session.doc.configs.rules.len(), 1);
assert_eq!(h.app.session.doc.param("length").unwrap().expr, "40 mm");
let before = h.app.session.doc.clone();
- h.run(&json!([{"widget":"Preview Row"}])).unwrap();
+ configuration_steps(&mut h, &json!([{"widget":"Preview Row"}])).unwrap();
assert_eq!(h.app.session.doc, before);
- h.run(&json!([{"widget":"Apply"}])).unwrap();
+ configuration_steps(&mut h, &json!([{"widget":"Apply"}])).unwrap();
assert_eq!(h.app.session.doc.param("length").unwrap().expr, "10 mm");
assert!(h.app.session.doc.configuration_matches());
- h.run(&json!([
- {"widget":"10 mm","near":"Value"},{"key":"A","cmd":true},{"text":"20 mm"},{"widget":"Save Rule"},
- {"widget":"Apply"}
- ]))
+ configuration_steps(
+ &mut h,
+ &json!([
+ {"click":{"handle":"dialog:Value"}},{"key":"A","cmd":true},{"text":"20 mm"},{"widget":"Save Rule"},
+ {"widget":"Apply"}
+ ]),
+ )
.unwrap();
assert_eq!(h.app.session.doc.param("length").unwrap().expr, "20 mm");
assert_eq!(h.app.session.doc.configs.rows[0].cells[0], "40 mm");
let before = h.app.session.doc.clone();
- h.run(&json!([
- {"widget":"Drive parameter"},{"widget":"Range"},
- {"widget":"0 mm","near":"Minimum"},{"key":"A","cmd":true},{"text":"100 mm"},{"widget":"Save Rule"}
- ]))
+ configuration_steps(
+ &mut h,
+ &json!([
+ {"widget":"Drive parameter"},{"widget":"Range"},
+ {"click":{"handle":"dialog:Minimum"}},{"key":"A","cmd":true},{"text":"100 mm"},{"widget":"Save Rule"}
+ ]),
+ )
.unwrap();
assert_eq!(h.app.session.doc, before, "failed rule edit is atomic");
assert!(
@@ -1303,7 +1061,7 @@ mod tests {
h.run(&json!([{"widget":"Library"},{"widget":"Follow inherited appearance"},{"widget":"Apply"}])).unwrap();
assert!(h.app.session.doc.appearances.components.is_empty());
assert!(h.app.session.doc.appearances.faces.is_empty());
- crate::scenario::check(&mut h, &json!({"windows_fit":{"max_width":560}})).unwrap();
+ crate::scenario::check(&mut h, &json!({"windows_fit":{"max_width":Tokens::get().form_card_width * 3.0}})).unwrap();
}
}
@@ -1387,7 +1145,7 @@ mod tests {
for label in ["Configuration", "Active", "Apply", "Add Row", "Add Column"] {
assert_single_line(&harness, label);
}
- crate::scenario::check(&mut harness, &json!({"windows_fit":{"max_width":560}})).unwrap();
+ crate::scenario::check(&mut harness, &json!({"windows_fit":{"max_width":Tokens::get().form_card_width * 3.0}})).unwrap();
for name in ["span", "thickness", "depth", "clearance"] {
harness.call("engine.execute", json!({"command":"config.column","params":{"param":name,"delete":true}}));
}
diff --git a/crates/ui-egui/src/dialogs_motion_plot.rs b/crates/ui-egui/src/dialogs_motion_plot.rs
index 1d301f55ef..ca5e6c59a2 100644
--- a/crates/ui-egui/src/dialogs_motion_plot.rs
+++ b/crates/ui-egui/src/dialogs_motion_plot.rs
@@ -11,7 +11,7 @@ use solidcraft_engine::Session;
use solidcraft_engine::doc::joints::JointKind;
use crate::SolveApp;
-use crate::dialogs::{combo, row_label};
+use crate::dialogs::{combo, form_row};
use crate::selection::SelInput;
use crate::theme::Tokens;
@@ -267,65 +267,67 @@ fn collision_rows(
if a.collisions.as_ref().is_some_and(|(k, _)| *k != key) {
a.collisions = None;
}
- row_label(ui, "Collisions");
- ui.horizontal(|ui| {
- if sets && parts.is_empty() {
- combo(ui, "ms_among", &["All components", "Contact sets"], &mut a.among);
- }
- let button = ui.add_enabled(check.is_some(), egui::Button::new(crate::i18n::tr_label("Check collisions")));
- crate::scenario::publish_handle("motion:check", button.rect.center());
- if button.clicked()
- && let Some((st, mut p)) = check
- {
- let mut sc = app.session.scratch();
- let r = super::scratch_study(&mut sc, &st).and_then(|id| {
- p["study"] = id;
- sc.execute("motion.interference", &p).map_err(|e| e.to_string())
- });
- a.collisions = Some((key, r));
- }
+ crate::ui_kit::section(ui, "motion_collisions", "Collisions", true, |ui| {
+ ui.horizontal(|ui| {
+ if sets && parts.is_empty() {
+ ui.allocate_ui(vec2(t.form_label_width * 1.6, t.control_height), |ui| {
+ combo(ui, "ms_among", &["All components", "Contact sets"], &mut a.among)
+ });
+ }
+ let button = crate::ui_kit::enabled_button(ui, "Check collisions", check.is_some());
+ crate::scenario::publish_handle("motion:check", button.rect.center());
+ if button.clicked()
+ && let Some((st, mut p)) = check
+ {
+ let mut sc = app.session.scratch();
+ let r = super::scratch_study(&mut sc, &st).and_then(|id| {
+ p["study"] = id;
+ sc.execute("motion.interference", &p).map_err(|e| e.to_string())
+ });
+ a.collisions = Some((key, r));
+ }
+ });
});
- ui.end_row();
match a.collisions.as_ref().map(|(_, r)| r) {
Some(Ok(v)) => {
let hits = v["collisions"].as_array().cloned().unwrap_or_default();
- row_label(ui, "");
ui.vertical(|ui| {
- if hits.is_empty() {
- ui.label(RichText::new(crate::i18n::tr("motion.no_collisions")).color(t.text_dim));
- }
- for (i, c) in hits.iter().enumerate() {
- let steps: Vec<String> = c["steps"]
- .as_array()
- .into_iter()
- .flatten()
- .map(|r| {
- let (from, to) = (r[0].as_f64().unwrap_or(0.0).round(), r[1].as_f64().unwrap_or(0.0).round());
- if from == to { format!("{from}") } else { format!("{from}-{to}") }
- })
- .collect();
- let name = |k: &str| c[k].as_str().unwrap_or_default().to_string();
- let text = crate::i18n::format("motion.collision", &[("a", &name("a")), ("b", &name("b")), ("steps", &steps.join(", "))]);
- // A click shows where they first collide.
- let link = ui.link(RichText::new(text).color(t.error));
- crate::scenario::publish_handle(&format!("motion:collision:{i}"), link.rect.center());
- if link.clicked()
- && let Some(first) = c["first_step"].as_f64()
- {
- (*step, *playing) = (first, false);
+ ui.vertical(|ui| {
+ if hits.is_empty() {
+ ui.label(RichText::new(crate::i18n::tr("motion.no_collisions")).color(t.text_dim));
+ }
+ for (i, c) in hits.iter().enumerate() {
+ let steps: Vec<String> = c["steps"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .map(|r| {
+ let (from, to) = (r[0].as_f64().unwrap_or(0.0).round(), r[1].as_f64().unwrap_or(0.0).round());
+ if from == to { format!("{from}") } else { format!("{from}-{to}") }
+ })
+ .collect();
+ let name = |k: &str| c[k].as_str().unwrap_or_default().to_string();
+ let text = crate::i18n::format("motion.collision", &[("a", &name("a")), ("b", &name("b")), ("steps", &steps.join(", "))]);
+ // A click shows where they first collide.
+ let link = ui.link(RichText::new(text).color(t.error));
+ crate::scenario::publish_handle(&format!("motion:collision:{i}"), link.rect.center());
+ if link.clicked()
+ && let Some(first) = c["first_step"].as_f64()
+ {
+ (*step, *playing) = (first, false);
+ }
}
- }
- if v["truncated"] == true {
- let to = v["checked_to"].as_f64().map(|x| x.round().to_string()).unwrap_or_default();
- ui.label(RichText::new(crate::i18n::format("motion.checked_to", &[("step", &to)])).color(t.warning));
- }
+ if v["truncated"] == true {
+ let to = v["checked_to"].as_f64().map(|x| x.round().to_string()).unwrap_or_default();
+ ui.label(RichText::new(crate::i18n::format("motion.checked_to", &[("step", &to)])).color(t.warning));
+ }
+ });
});
- ui.end_row();
}
Some(Err(e)) => {
- row_label(ui, "");
- ui.add(egui::Label::new(RichText::new(e.as_str()).color(t.error)).wrap());
- ui.end_row();
+ ui.vertical(|ui| {
+ ui.add(egui::Label::new(RichText::new(e.as_str()).color(t.error)).wrap());
+ });
}
None => {}
}
@@ -356,20 +358,20 @@ fn plot_rows(
a.what = i;
}
}
- row_label(ui, "Plot");
- let labels: Vec<&str> = list.iter().map(|(l, _)| l.as_str()).collect();
- combo(ui, "ms_plot", &labels, &mut a.what);
- ui.end_row();
+ form_row(ui, "Plot", |ui| {
+ let labels: Vec<&str> = list.iter().map(|(l, _)| l.as_str()).collect();
+ combo(ui, "ms_plot", &labels, &mut a.what);
+ });
let what = list.get(a.what).map_or(Plotted::Nothing, |(_, w)| *w);
let bands = a.collisions.as_ref().and_then(|(_, r)| r.as_ref().ok()).map(collision_bands).unwrap_or_default();
if what != Plotted::Nothing {
- row_label(ui, "Quantity");
- combo(ui, "ms_quantity", &QUANTITIES, &mut a.quantity);
- ui.end_row();
- row_label(ui, "Duration");
- let r = ui.add(egui::TextEdit::singleline(&mut a.duration).hint_text(crate::i18n::tr("motion.duration_hint")));
- crate::scenario::publish_handle("dialog:Duration", r.rect.center());
- ui.end_row();
+ form_row(ui, "Quantity", |ui| {
+ combo(ui, "ms_quantity", &QUANTITIES, &mut a.quantity);
+ });
+ form_row(ui, "Duration", |ui| {
+ let r = crate::ui_kit::cell_editor(ui, ui.id().with("duration"), &mut a.duration, "motion.duration_hint", false);
+ crate::scenario::publish_handle("dialog:Duration", r.rect.center());
+ });
let params = study.clone().and_then(|st| plot_params(s, what, &st, &a.duration, inputs).map(|p| (st, p)));
let key = key_of(&params);
if a.plot.as_ref().is_none_or(|(k, _)| *k != key) {
@@ -380,8 +382,7 @@ fn plot_rows(
});
a.plot = Some((key, r));
}
- row_label(ui, "");
- match a.plot.as_ref().map(|(_, r)| r) {
+ ui.vertical(|ui| match a.plot.as_ref().map(|(_, r)| r) {
Some(Ok(v)) => {
ui.vertical(|ui| {
if let Some((xs, ys, unit)) = line(v, what, a.quantity)
@@ -398,8 +399,7 @@ fn plot_rows(
ui.add(egui::Label::new(RichText::new(e.as_str()).color(t.text_dim)).wrap());
}
None => {}
- }
- ui.end_row();
+ });
}
}
diff --git a/crates/ui-egui/src/dialogs_part_size.rs b/crates/ui-egui/src/dialogs_part_size.rs
index 9261ad1288..0a651f145b 100644
--- a/crates/ui-egui/src/dialogs_part_size.rs
+++ b/crates/ui-egui/src/dialogs_part_size.rs
@@ -2,12 +2,11 @@
use std::sync::Arc;
-use egui::RichText;
use serde_json::{Value, json};
use solidcraft_engine::{Sel, doc::Document};
use crate::SolveApp;
-use crate::dialogs::{Kind, combo, row_label};
+use crate::dialogs::{Kind, combo, form_row};
use crate::dialogs_parts::Family;
use crate::selection::SelInput;
@@ -169,30 +168,24 @@ pub fn open(app: &mut SolveApp, component: u64) {
}
pub fn rows(app: &SolveApp, ui: &mut egui::Ui, k: &mut Resize) -> bool {
- row_label(ui, "Type");
- ui.add(egui::Label::new(format!("{} ({})", k.family.name, k.family.standard)).wrap());
- ui.end_row();
- row_label(ui, "Size");
+ form_row(ui, "Type", |ui| {
+ ui.add(egui::Label::new(format!("{} ({})", k.family.name, k.family.standard)).wrap());
+ });
let sizes: Vec<&str> = k.family.sizes.iter().map(|s| s.0.as_str()).collect();
- combo(ui, "part_resize_size", &sizes, &mut k.size);
- ui.end_row();
+ form_row(ui, "Size", |ui| combo(ui, "part_resize_size", &sizes, &mut k.size));
if let Some(lengths) = k.lengths() {
let mut index = k.length.and_then(|l| lengths.iter().position(|x| *x == l)).unwrap_or(0);
let labels: Vec<String> = lengths.iter().map(|l| crate::prefs::show_mm(app, *l, 1)).collect();
let labels: Vec<&str> = labels.iter().map(String::as_str).collect();
- row_label(ui, "Length");
- combo(ui, "part_resize_length", &labels, &mut index);
- ui.end_row();
+ form_row(ui, "Length", |ui| combo(ui, "part_resize_length", &labels, &mut index));
k.length = lengths.get(index).copied();
}
if let Some((size, _)) = k.family.sizes.get(k.size) {
- row_label(ui, "Configuration");
- ui.label(configuration_name(size, k.length));
- ui.end_row();
+ form_row(ui, "Configuration", |ui| {
+ ui.label(configuration_name(size, k.length));
+ });
}
- row_label(ui, "");
- ui.add(egui::Label::new(RichText::new(crate::i18n::tr("ui.part_size_shared")).color(crate::theme::Tokens::get().text_dim)).wrap());
- ui.end_row();
+ crate::ui_kit::hint(ui, "part_size_shared", crate::i18n::tr("ui.part_size_shared"));
false
}
diff --git a/crates/ui-egui/src/dialogs_parts.rs b/crates/ui-egui/src/dialogs_parts.rs
index c86101c731..8558a73fbe 100644
--- a/crates/ui-egui/src/dialogs_parts.rs
+++ b/crates/ui-egui/src/dialogs_parts.rs
@@ -3,12 +3,12 @@
//! Picking a hole (its wall or rim) seats the part in it with a rigid joint; without one the part
//! goes at the origin. The live preview shows it placed.
-use egui::{RichText, vec2};
+use egui::vec2;
use serde_json::{Value, json};
use solidcraft_engine::{Sel, Session};
use crate::SolveApp;
-use crate::dialogs::{Kind, combo, row_label};
+use crate::dialogs::{Kind, combo, form_row};
use crate::selection::{EDGES, FACES, SelInput};
use crate::theme::Tokens;
@@ -122,40 +122,40 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Pt, inputs: &[SelInpu
}
};
if lib.is_empty() {
- row_label(ui, "");
- ui.label(RichText::new(crate::i18n::tr_label("the parts library is not available")).color(t.text_dim));
- ui.end_row();
+ ui.vertical(|ui| {
+ crate::ui_kit::note(ui, "parts_unavailable", crate::i18n::tr_label("the parts library is not available"));
+ });
return false;
}
let names: Vec<String> =
lib.iter().map(|f| if f.standard.is_empty() { f.name.clone() } else { format!("{} ({})", f.name, f.standard) }).collect();
let refs: Vec<&str> = names.iter().map(String::as_str).collect();
- row_label(ui, "Type");
let before = k.family;
- combo(ui, "pt_family", &refs, &mut k.family);
- ui.end_row();
+ form_row(ui, "Type", |ui| {
+ combo(ui, "pt_family", &refs, &mut k.family);
+ });
if k.family != before {
k.size = 0;
k.length = None;
}
let Some(f) = lib.get(k.family) else { return false };
let sizes: Vec<&str> = f.sizes.iter().map(|s| s.0.as_str()).collect();
- row_label(ui, "Size");
- combo(ui, "pt_size", &sizes, &mut k.size);
- ui.end_row();
+ form_row(ui, "Size", |ui| {
+ combo(ui, "pt_size", &sizes, &mut k.size);
+ });
if let Some(ls) = &f.lengths {
let mut labels = vec!["Default".to_string()];
labels.extend(ls.iter().map(|l| crate::prefs::show_mm(app, *l, 1)));
let refs: Vec<&str> = labels.iter().map(String::as_str).collect();
let mut i = k.length.map_or(0, |x| x + 1);
- row_label(ui, "Length");
- combo(ui, "pt_len", &refs, &mut i);
- k.length = i.checked_sub(1);
- ui.end_row();
+ form_row(ui, "Length", |ui| {
+ combo(ui, "pt_len", &refs, &mut i);
+ k.length = i.checked_sub(1);
+ });
}
- row_label(ui, "Name");
- ui.add(egui::TextEdit::singleline(&mut k.name).hint_text("automatic"));
- ui.end_row();
+ form_row(ui, "Name", |ui| {
+ crate::ui_kit::text_field(ui, &mut k.name, "automatic");
+ });
// The part, and its table values.
let key = (k.family, k.size, k.length);
let tex_id = egui::Id::new("sc_part_picture");
@@ -172,29 +172,27 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Pt, inputs: &[SelInpu
});
k.picture = Some(key);
}
- row_label(ui, "");
- match ui.data(|d| d.get_temp::<egui::TextureHandle>(tex_id)) {
+ ui.vertical(|ui| match ui.data(|d| d.get_temp::<egui::TextureHandle>(tex_id)) {
Some(tx) => {
- ui.add(egui::Image::new(&tx).fit_to_exact_size(vec2(180.0, 112.0)).corner_radius(4.0));
+ ui.add(egui::Image::new(&tx).fit_to_exact_size(vec2(180.0, 112.0)).corner_radius(t.radius_sm));
}
None => {
- ui.label(RichText::new(crate::i18n::tr_label("no picture")).color(t.text_dim));
+ crate::ui_kit::note(ui, "parts_picture", crate::i18n::tr_label("no picture"));
}
- }
- ui.end_row();
+ });
if let Some((_, row)) = f.sizes.get(k.size)
&& let Some(o) = row.as_object()
{
for (key, v) in o.iter().filter(|(key, _)| key.as_str() != "size") {
- row_label(ui, &key.replace('_', " "));
- ui.label(RichText::new(v.as_f64().map(|x| crate::prefs::show_mm(app, x, 1)).unwrap_or_else(|| v.to_string())).color(t.text_dim));
- ui.end_row();
+ form_row(ui, &key.replace('_', " "), |ui| {
+ crate::ui_kit::cell_text(ui, &v.as_f64().map(|x| crate::prefs::show_mm(app, x, 1)).unwrap_or_else(|| v.to_string()));
+ });
}
}
if inputs.first().is_some_and(|i| i.items.is_empty()) {
- row_label(ui, "");
- ui.label(RichText::new(crate::i18n::tr_label("pick a hole to seat it, or OK places it at the origin")).color(t.text_dim));
- ui.end_row();
+ ui.vertical(|ui| {
+ crate::ui_kit::note(ui, "parts_placement", crate::i18n::tr_label("pick a hole to seat it, or OK places it at the origin"));
+ });
}
false
}
diff --git a/crates/ui-egui/src/dialogs_plastic.rs b/crates/ui-egui/src/dialogs_plastic.rs
index 8539145d40..7e64e50517 100644
--- a/crates/ui-egui/src/dialogs_plastic.rs
+++ b/crates/ui-egui/src/dialogs_plastic.rs
@@ -9,7 +9,7 @@ use solidcraft_engine::doc::plastic::PlasticRule;
use solidcraft_engine::geom::Vec3;
use crate::SolveApp;
-use crate::dialogs::{Kind, combo, face_sel, field, form_row, row_label, shown_expr};
+use crate::dialogs::{Kind, combo, face_sel, field, form_row, shown_expr};
use crate::selection::{BODIES, FACES, PLANAR_FACES, SelInput};
#[derive(Clone, Debug)]
@@ -251,9 +251,7 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Pl, inputs: &[SelInpu
let mut names: Vec<String> = rules.iter().map(|r| r.name.clone()).collect();
names.push("New rule…".into());
let refs: Vec<&str> = names.iter().map(String::as_str).collect();
- row_label(ui, "Rule");
- combo(ui, "pl_rules", &refs, pick);
- ui.end_row();
+ form_row(ui, "Rule", |ui| combo(ui, "pl_rules", &refs, pick));
if *loaded != Some(*pick) {
let base = rules.get(*pick).or(rules.first()).cloned();
if let Some(b) = base {
@@ -266,20 +264,18 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Pl, inputs: &[SelInpu
*loaded = Some(*pick);
}
if *pick >= rules.len() {
- row_label(ui, "Name");
- ui.text_edit_singleline(name);
- ui.end_row();
+ form_row(ui, "Name", |ui| {
+ crate::ui_kit::text_field(ui, name, "Name");
+ });
}
let keys = rule_keys();
for (i, v) in values.iter_mut().enumerate() {
let label = if i == 0 { "Material".to_string() } else { keys.get(i - 1).map(|k| label_of(k)).unwrap_or_default() };
- row_label(ui, &label);
- enter |= if i == 0 { ui.text_edit_singleline(v).lost_focus() && ui.input(|x| x.key_pressed(egui::Key::Enter)) } else { field(ui, v) };
- ui.end_row();
+ form_row(ui, &label, |ui| {
+ enter |= if i == 0 { crate::ui_kit::text_field(ui, v, "Material").0 } else { field(ui, v) };
+ });
}
- row_label(ui, "Active rule");
- ui.checkbox(active, "");
- ui.end_row();
+ form_row(ui, "Active rule", |ui| crate::ui_kit::checkbox(ui, "", active));
}
Pl::Assign { rule } => {
let mut names: Vec<String> = vec!["(no rule)".into()];
diff --git a/crates/ui-egui/src/dialogs_save_mesh.rs b/crates/ui-egui/src/dialogs_save_mesh.rs
index fd5025a222..b2821bc375 100644
--- a/crates/ui-egui/src/dialogs_save_mesh.rs
+++ b/crates/ui-egui/src/dialogs_save_mesh.rs
@@ -15,7 +15,7 @@ use solidcraft_engine::Sel;
use solidcraft_engine::slicers::{self, Slicer};
use crate::SolveApp;
-use crate::dialogs::{Kind, combo, row_label};
+use crate::dialogs::{Kind, combo, form_row};
use crate::selection::{BODIES, SelInput};
use crate::theme::Tokens;
@@ -150,29 +150,29 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut SaveMesh) -> bool {
}
k.send &= !entries.is_empty();
}
- row_label(ui, "Format");
- combo(ui, "sm_format", &FORMATS.map(|f| f.0), &mut k.format);
- ui.end_row();
+ form_row(ui, "Format", |ui| {
+ combo(ui, "sm_format", &FORMATS.map(|f| f.0), &mut k.format);
+ });
// A browser has no installed programs to send a file to.
if app.services.pick_program.is_none() {
k.send = false;
return false;
}
- row_label(ui, "Send to slicer");
- ui.checkbox(&mut k.send, "");
- ui.end_row();
+ form_row(ui, "Send to slicer", |ui| {
+ crate::ui_kit::checkbox(ui, "", &mut k.send);
+ });
- row_label(ui, "Slicer");
- if let Some(path) = app.slicer_menu.picked.take() {
- match add_custom(app, &path) {
- Ok(()) => k.slicer = path,
- Err(e) => app.set_status(e, true),
+ form_row(ui, "Slicer", |ui| {
+ if let Some(path) = app.slicer_menu.picked.take() {
+ match add_custom(app, &path) {
+ Ok(()) => k.slicer = path,
+ Err(e) => app.set_status(e, true),
+ }
}
- }
- let choosing = app.file_picker_busy();
- ui.add_enabled_ui(k.send && !choosing, |ui| slicer_combo(app, ui, k));
- ui.end_row();
+ let choosing = app.file_picker_busy();
+ ui.add_enabled_ui(k.send && !choosing, |ui| slicer_combo(app, ui, k));
+ });
false
}
@@ -185,7 +185,7 @@ fn slicer_combo(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut SaveMesh) {
let mut pick_custom = false;
let mut delete: Option<String> = None;
let mut chosen: Option<String> = None;
- let r = egui::ComboBox::from_id_salt("sm_slicer").selected_text(text).width(crate::dialogs::FIELD_W).show_ui(ui, |ui| {
+ let r = crate::ui_kit::dropdown_menu(ui, "sm_slicer", &text, |ui| {
let frame = ctx.cumulative_frame_nr();
ctx.data_mut(|d| d.insert_temp(egui::Id::new("sc_slicer_popup"), frame));
for e in &entries {
@@ -193,8 +193,7 @@ fn slicer_combo(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut SaveMesh) {
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click());
let selected = e.key == k.slicer;
if resp.hovered() || selected {
- let v = ui.visuals();
- let fill = if resp.hovered() { v.widgets.hovered.bg_fill } else { v.selection.bg_fill.gamma_multiply(0.5) };
+ let fill = if resp.hovered() { Tokens::get().hover } else { Tokens::get().selected_bg };
ui.painter().rect_filled(rect, 2.0, fill);
}
paint_icon(ui, egui::Rect::from_min_size(rect.left_center() + vec2(3.0, -ICON / 2.0), vec2(ICON, ICON)), tex, &e.slicer.name);
@@ -203,7 +202,7 @@ fn slicer_combo(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut SaveMesh) {
egui::Align2::LEFT_CENTER,
&e.slicer.name,
egui::FontId::proportional(crate::theme::Tokens::get().font_button),
- ui.visuals().text_color(),
+ Tokens::get().text,
);
crate::scenario::publish_handle(&format!("dialog:Slicer:{}", e.slicer.name), rect.center());
if e.user {
@@ -223,7 +222,7 @@ fn slicer_combo(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut SaveMesh) {
}
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click());
if resp.hovered() {
- ui.painter().rect_filled(rect, 2.0, ui.visuals().widgets.hovered.bg_fill);
+ ui.painter().rect_filled(rect, 2.0, Tokens::get().hover);
}
ui.painter().text(
rect.left_center() + vec2(ICON + 9.0, 0.0),
@@ -240,7 +239,7 @@ fn slicer_combo(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut SaveMesh) {
});
if let Some(e) = current {
let tex = icon(&mut app.slicer_menu, &ctx, e);
- let rect = r.response.rect;
+ let rect = r.rect;
let at = egui::Rect::from_min_size(rect.left_center() + vec2(ui.spacing().button_padding.x + 1.0, -ICON / 2.0), vec2(ICON, ICON));
paint_icon(ui, at, tex, &e.slicer.name);
}
diff --git a/crates/ui-egui/src/dialogs_sheet.rs b/crates/ui-egui/src/dialogs_sheet.rs
index 48982b8cc7..2337aeee22 100644
--- a/crates/ui-egui/src/dialogs_sheet.rs
+++ b/crates/ui-egui/src/dialogs_sheet.rs
@@ -12,7 +12,7 @@ use solidcraft_engine::doc::{FeatureKind, ProfileSel};
use solidcraft_engine::geom::Vec3;
use crate::SolveApp;
-use crate::dialogs::{Dialog, Kind, combo, edge_sel, face_sel, field, form_row, profile_indices, row_label};
+use crate::dialogs::{Dialog, Kind, combo, edge_sel, face_sel, field, form_row, profile_indices};
use crate::selection::{AXES, BODIES, CURVES, EDGES, PLANAR_FACES, PROFILES, SelInput};
use crate::theme::Tokens;
@@ -316,9 +316,7 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Sm, inputs: &mut [Sel
let mut names: Vec<String> = rules.iter().map(|r| r.name.clone()).collect();
names.push("New rule…".into());
let refs: Vec<&str> = names.iter().map(String::as_str).collect();
- row_label(ui, "Rule");
- combo(ui, "sm_rules", &refs, pick);
- ui.end_row();
+ form_row(ui, "Rule", |ui| combo(ui, "sm_rules", &refs, pick));
if *loaded != Some(*pick) {
// Show the picked rule (a new one starts from the one shown before).
let base = rules.get(*pick).cloned().unwrap_or_else(|| rules.first().cloned().unwrap_or_else(SheetRule::steel));
@@ -340,37 +338,32 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Sm, inputs: &mut [Sel
*loaded = Some(*pick);
}
if *pick >= rules.len() {
- row_label(ui, "Name");
- ui.text_edit_singleline(name);
- ui.end_row();
+ form_row(ui, "Name", |ui| {
+ crate::ui_kit::text_field(ui, name, "Name");
+ });
}
for ((key, label), v) in RULE_FIELDS.iter().zip(values.iter_mut()) {
if *key == "corner_relief" {
// The shape goes with its size, the row below.
- row_label(ui, "Corner Relief Shape");
- combo(ui, "sm_relief_shape", &RELIEF_SHAPE_LABELS, relief);
- ui.end_row();
+ form_row(ui, "Corner Relief Shape", |ui| combo(ui, "sm_relief_shape", &RELIEF_SHAPE_LABELS, relief));
}
- row_label(ui, label);
- enter |= field(ui, v);
- ui.end_row();
+ form_row(ui, label, |ui| {
+ enter |= field(ui, v);
+ });
}
- row_label(ui, "Active rule");
- ui.checkbox(active, "");
- ui.end_row();
- if *pick < rules.len() && !app.session.doc.sheet.rules.is_empty() {
- row_label(ui, "");
- if ui.button(crate::i18n::tr_label("Delete rule")).clicked() {
- let n = rules.get(*pick).map(|r| r.name.clone()).unwrap_or_default();
- match app.run("sheet.manage_rules", json!({"name": n, "delete": true})) {
- Ok(_) => {
- *pick = 0;
- *loaded = None;
- }
- Err(e) => app.set_status(e, true),
+ form_row(ui, "Active rule", |ui| crate::ui_kit::checkbox(ui, "", active));
+ if *pick < rules.len()
+ && !app.session.doc.sheet.rules.is_empty()
+ && crate::ui_kit::secondary_button(ui, crate::i18n::tr_label("Delete rule")).clicked()
+ {
+ let n = rules.get(*pick).map(|r| r.name.clone()).unwrap_or_default();
+ match app.run("sheet.manage_rules", json!({"name": n, "delete": true})) {
+ Ok(_) => {
+ *pick = 0;
+ *loaded = None;
}
+ Err(e) => app.set_status(e, true),
}
- ui.end_row();
}
}
Sm::FlatPattern { data, key, status } => {
@@ -387,56 +380,56 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Sm, inputs: &mut [Sel
match data {
Some(Ok(v)) => {
let size = &v["flat_size_mm"];
- row_label(ui, "Body");
- ui.label(v["body"].as_str().unwrap_or(""));
- ui.end_row();
- row_label(ui, "Flat size");
- ui.label(format!(
- "{} × {} × {}",
- crate::prefs::show_mm(app, size[0].as_f64().unwrap_or(0.0), 1),
- crate::prefs::show_mm(app, size[1].as_f64().unwrap_or(0.0), 1),
- crate::prefs::show_mm(app, size[2].as_f64().unwrap_or(0.0), 1)
- ));
- ui.end_row();
+ form_row(ui, "Body", |ui| {
+ ui.label(v["body"].as_str().unwrap_or(""));
+ });
+ form_row(ui, "Flat size", |ui| {
+ ui.label(format!(
+ "{} × {} × {}",
+ crate::prefs::show_mm(app, size[0].as_f64().unwrap_or(0.0), 1),
+ crate::prefs::show_mm(app, size[1].as_f64().unwrap_or(0.0), 1),
+ crate::prefs::show_mm(app, size[2].as_f64().unwrap_or(0.0), 1)
+ ));
+ });
let bends = v["bends"].as_array().cloned().unwrap_or_default();
- row_label(ui, "Bends");
- ui.label(format!("{}", bends.len()));
- ui.end_row();
+ form_row(ui, "Bends", |ui| {
+ ui.label(format!("{}", bends.len()));
+ });
for b in bends.iter().take(50) {
let up = b["direction"] == "up";
let (up_col, down_col) = bend_colors();
- row_label(ui, &format!(" Bend {}", b["bend"].as_u64().unwrap_or(0)));
- ui.label(
- RichText::new(format!(
- "{} {:.1}° R{}",
- if up { "Up" } else { "Down" },
- b["angle_deg"].as_f64().unwrap_or(0.0),
- crate::prefs::show_mm(app, b["radius"].as_f64().unwrap_or(0.0), 1)
- ))
- .color(if up { up_col } else { down_col }),
- );
- ui.end_row();
- }
- row_label(ui, "");
- if ui.button("Export DXF…").clicked() {
- *status = Some(export_flat(app, v["body"].as_str().unwrap_or(""), "dxf"));
- }
- ui.end_row();
- row_label(ui, "");
- if ui.button("Export Bend Table…").clicked() {
- *status = Some(export_flat(app, v["body"].as_str().unwrap_or(""), "csv"));
+ form_row(ui, &format!(" Bend {}", b["bend"].as_u64().unwrap_or(0)), |ui| {
+ ui.label(
+ RichText::new(format!(
+ "{} {:.1}° R{}",
+ if up { "Up" } else { "Down" },
+ b["angle_deg"].as_f64().unwrap_or(0.0),
+ crate::prefs::show_mm(app, b["radius"].as_f64().unwrap_or(0.0), 1)
+ ))
+ .color(if up { up_col } else { down_col }),
+ );
+ });
}
- ui.end_row();
+ ui.vertical(|ui| {
+ if crate::ui_kit::secondary_button(ui, crate::i18n::tr_label("Export DXF…")).clicked() {
+ *status = Some(export_flat(app, v["body"].as_str().unwrap_or(""), "dxf"));
+ }
+ });
+ ui.vertical(|ui| {
+ if crate::ui_kit::secondary_button(ui, crate::i18n::tr_label("Export Bend Table…")).clicked() {
+ *status = Some(export_flat(app, v["body"].as_str().unwrap_or(""), "csv"));
+ }
+ });
if let Some(s) = status {
- row_label(ui, "");
- ui.add(egui::Label::new(RichText::new(s.as_str()).color(t.text_dim)).wrap());
- ui.end_row();
+ ui.vertical(|ui| {
+ ui.add(egui::Label::new(RichText::new(s.as_str()).color(t.text_dim)).wrap());
+ });
}
}
Some(Err(e)) => {
- row_label(ui, "");
- ui.add(egui::Label::new(RichText::new(e.as_str()).color(t.error)).wrap());
- ui.end_row();
+ ui.vertical(|ui| {
+ ui.add(egui::Label::new(RichText::new(e.as_str()).color(t.error)).wrap());
+ });
}
None => {}
}
diff --git a/crates/ui-egui/src/dialogs_surface.rs b/crates/ui-egui/src/dialogs_surface.rs
index 78014c4585..ac21d062a5 100644
--- a/crates/ui-egui/src/dialogs_surface.rs
+++ b/crates/ui-egui/src/dialogs_surface.rs
@@ -304,13 +304,13 @@ pub fn rows(ui: &mut egui::Ui, k: &mut Surf) -> bool {
combo(ui, "bl_cont0", &BLEND_CONTINUITY.map(|(label, _)| label), from);
});
form_row(ui, "Start bulge", |ui| {
- ui_kit::bulge_field(ui, from_bulge);
+ ui_kit::scalar_field(ui, from_bulge, -0.9..=3.0);
});
form_row(ui, "End continuity", |ui| {
combo(ui, "bl_cont1", &BLEND_CONTINUITY.map(|(label, _)| label), to);
});
form_row(ui, "End bulge", |ui| {
- ui_kit::bulge_field(ui, to_bulge);
+ ui_kit::scalar_field(ui, to_bulge, -0.9..=3.0);
});
ui_kit::options(ui, "blend_options", &mut [("Stitch to both bodies", stitch)]);
}
diff --git a/crates/ui-egui/src/dialogs_view_dxf.rs b/crates/ui-egui/src/dialogs_view_dxf.rs
index 7a7a757cb3..32aad8ba0b 100644
--- a/crates/ui-egui/src/dialogs_view_dxf.rs
+++ b/crates/ui-egui/src/dialogs_view_dxf.rs
@@ -1,4 +1,5 @@
//! Export the camera at the instant Export is pressed, with a remembered hidden-edge choice.
+use crate::dialogs::form_row;
use crate::{SolveApp, dialogs::Kind, selection::SelInput};
use serde_json::json;
@@ -11,24 +12,24 @@ pub fn start(app: &SolveApp, id: &str) -> Option<(Kind, Vec<SelInput>)> {
}
pub fn rows(app: &SolveApp, ui: &mut egui::Ui, dashed: &mut bool, tolerance: &mut f64) {
- crate::dialogs::row_label(ui, "Hidden edges");
- ui.vertical(|ui| {
- let r = ui.radio_value(dashed, false, app.tr_label("Do not export hidden edges"));
- crate::scenario::publish_handle("dialog:dxf:omit", r.rect.center());
- let r = ui.radio_value(dashed, true, app.tr_label("Export hidden edges as dashed lines"));
- crate::scenario::publish_handle("dialog:dxf:dashed", r.rect.center());
+ crate::ui_kit::note(ui, "hidden", app.tr_label("Hidden edges"));
+ for (value, key, label) in [(false, "omit", "Do not export hidden edges"), (true, "dashed", "Export hidden edges as dashed lines")] {
+ let r = crate::ui_kit::list_picker(ui, key, app.tr_label(label), *dashed == value);
+ crate::scenario::publish_handle(&format!("dialog:dxf:{key}"), r.rect.center());
+ if r.clicked() {
+ *dashed = value;
+ }
+ }
+ form_row(ui, "dxf.tolerance", |ui| {
+ let r = crate::ui_kit::number_field(ui, tolerance, 0.0001..=1.0, 0.001, " mm");
+ crate::scenario::publish_handle("dialog:dxf:tolerance", r.rect.center());
});
- ui.end_row();
- crate::dialogs::row_label(ui, "dxf.tolerance");
- let r = ui.add(egui::DragValue::new(tolerance).range(0.0001..=1.0).speed(0.001).max_decimals(4).suffix(" mm"));
- crate::scenario::publish_handle("dialog:dxf:tolerance", r.rect.center());
- ui.end_row();
- crate::dialogs::row_label(ui, "Projection");
- ui.label(app.tr_label(if app.cam.fov > 0.0 { "Current perspective view" } else { "Current orthographic view (1:1 mm)" }));
- ui.end_row();
- crate::dialogs::row_label(ui, "");
- ui.add(egui::Label::new(app.tr_label("dxf.tolerance_help")).wrap());
- ui.end_row();
+ crate::ui_kit::note(
+ ui,
+ "projection",
+ app.tr_label(if app.cam.fov > 0.0 { "Current perspective view" } else { "Current orthographic view (1:1 mm)" }),
+ );
+ crate::ui_kit::note(ui, "tolerance", app.tr_label("dxf.tolerance_help"));
}
pub fn run(app: &mut SolveApp, dashed: bool, tolerance: f64) -> Result<(), String> {
diff --git a/crates/ui-egui/src/dim_view.rs b/crates/ui-egui/src/dim_view.rs
index 39f9306975..25c1a0b3da 100644
--- a/crates/ui-egui/src/dim_view.rs
+++ b/crates/ui-egui/src/dim_view.rs
@@ -9,7 +9,6 @@
//! Everything acts through commands: `sketch.dimension_text`, `sketch.delete`,
//! `parameters.change`.
-use crate::fonts::RichTextExt as _;
use std::cell::RefCell;
use std::sync::Arc;
@@ -697,48 +696,50 @@ fn edit_box(app: &mut SolveApp, ctx: &egui::Context) {
anchor.y = anchor.y.clamp(rect.top(), (rect.bottom() - 80.0).max(rect.top()));
}
crate::frame::area(egui::Id::new("sc_dim_edit_area")).fixed_pos(anchor).order(egui::Order::Foreground).show(ctx, |ui| {
- egui::Frame::popup(ui.style()).inner_margin(egui::Margin::symmetric(3, 1)).show(ui, |ui| {
- ui.set_max_width(popup_width);
- ui.label(egui::RichText::new(format!("Dimension: {}", e.param)).semibold().color(crate::theme::Tokens::get().text))
- .on_hover_text("Click another driving dimension to insert its name");
- let r = ui.add(egui::TextEdit::singleline(&mut e.expr).id(id).desired_width(popup_width));
- crate::theme::TabAccent::number_focus(ui, &r);
- if r.has_focus() {
- e.selection = egui::TextEdit::load_state(ctx, id).and_then(|s| s.cursor.char_range());
- }
- let completed = crate::params_dialog::complete(ui, &r, &mut e.expr);
- if completed {
- e.selection = egui::TextEdit::load_state(ctx, id).and_then(|s| s.cursor.char_range());
- }
- if let Some(live) = e.live.as_mut() {
- live.typed |= r.changed() || completed;
- }
- if let Some(error) = e.draft.as_ref().and_then(|d| d.error.as_ref()) {
- ui.add(egui::Label::new(egui::RichText::new(error).color(Tokens::get().error)).wrap());
- }
- if e.fresh == FRESH {
- // The whole value is selected, so typing replaces it.
- let n = e.expr.chars().count();
- let mut s = egui::text_edit::TextEditState::load(ui.ctx(), id).unwrap_or_default();
- s.cursor.set_char_range(Some(egui::text_selection::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(n))));
- e.selection = s.cursor.char_range();
- s.store(ui.ctx(), id);
- }
- let enter = ui.input(|i| i.key_pressed(egui::Key::Enter));
- if r.lost_focus() && enter {
- done = Some(true);
- } else if e.fresh > 0 {
- if !r.has_focus() {
- r.request_focus();
+ egui::Frame::popup(ui.style()).fill(Tokens::get().dialog_body).inner_margin(Tokens::get().space_4).show(ui, |ui| {
+ crate::ui_kit::scope(ui, |ui| {
+ ui.set_max_width(popup_width);
+ crate::ui_kit::inline_text(ui, &crate::i18n::format("dialog.dimension_name", &[("name", &e.param)]))
+ .on_hover_text(crate::i18n::tr("dialog.dimension_insert_hint"));
+ let r = crate::ui_kit::cell_editor(ui, id, &mut e.expr, "", false);
+ crate::theme::TabAccent::number_focus(ui, &r);
+ if r.has_focus() {
+ e.selection = egui::TextEdit::load_state(ctx, id).and_then(|s| s.cursor.char_range());
}
- } else if r.lost_focus() {
- done = Some(false);
- }
- if ui.input(|i| i.key_pressed(egui::Key::Escape)) {
- done = Some(false);
- // Esc cancels the whole dimension, picks included.
- escaped = true;
- }
+ let completed = crate::params_dialog::complete(ui, &r, &mut e.expr);
+ if completed {
+ e.selection = egui::TextEdit::load_state(ctx, id).and_then(|s| s.cursor.char_range());
+ }
+ if let Some(live) = e.live.as_mut() {
+ live.typed |= r.changed() || completed;
+ }
+ if let Some(error) = e.draft.as_ref().and_then(|d| d.error.as_ref()) {
+ crate::ui_kit::text_block(ui, "dimension_error", error, true);
+ }
+ if e.fresh == FRESH {
+ // The whole value is selected, so typing replaces it.
+ let n = e.expr.chars().count();
+ let mut s = egui::text_edit::TextEditState::load(ui.ctx(), id).unwrap_or_default();
+ s.cursor.set_char_range(Some(egui::text_selection::CCursorRange::two(egui::text::CCursor::new(0), egui::text::CCursor::new(n))));
+ e.selection = s.cursor.char_range();
+ s.store(ui.ctx(), id);
+ }
+ let enter = ui.input(|i| i.key_pressed(egui::Key::Enter));
+ if r.lost_focus() && enter {
+ done = Some(true);
+ } else if e.fresh > 0 {
+ if !r.has_focus() {
+ r.request_focus();
+ }
+ } else if r.lost_focus() {
+ done = Some(false);
+ }
+ if ui.input(|i| i.key_pressed(egui::Key::Escape)) {
+ done = Some(false);
+ // Esc cancels the whole dimension, picks included.
+ escaped = true;
+ }
+ });
});
});
e.fresh = e.fresh.saturating_sub(1);
diff --git a/crates/ui-egui/src/documents.rs b/crates/ui-egui/src/documents.rs
index e89b17243a..343c8ea013 100644
--- a/crates/ui-egui/src/documents.rs
+++ b/crates/ui-egui/src/documents.rs
@@ -11,6 +11,7 @@ use solidcraft_engine::render::Camera;
use crate::SolveApp;
use crate::theme::Tokens;
+use crate::ui_kit;
/// Most designs open at once.
pub const MAX_OPEN: usize = 32;
@@ -464,12 +465,8 @@ pub fn tabs(app: &mut SolveApp, ui: &mut egui::Ui, r: Rect, x0: f32, x1: f32) {
crate::frame::area(id.with("area")).fixed_pos(pos2(mr.left(), r.bottom())).order(egui::Order::Foreground).show(ui.ctx(), |ui| {
crate::context_menu::menu_frame(ui, |ui| {
for (i, (name, dirty)) in info.iter().enumerate() {
- let item = crate::context_menu::Item::action(
- "doc",
- &format!("{name}{}", if *dirty { " •" } else { "" }),
- if i == app.docs.active { "box" } else { "" },
- );
- if crate::context_menu::list_row(ui, &item).is_some() {
+ let label = format!("{name}{}", if *dirty { " •" } else { "" });
+ if ui_kit::list_picker(ui, &format!("document:{i}"), &label, i == app.docs.active).clicked() {
pick = Some(i);
}
}
@@ -552,8 +549,9 @@ pub fn prompt(app: &mut SolveApp, ctx: &egui::Context) {
let name = tabs_info(app).get(i).map(|x| x.0.clone()).unwrap_or_default();
let name_display = crate::i18n::tr_name(&name);
let mut answer: Option<Answer> = None;
- // Left and Right move between the buttons (Save is picked first); Enter gives the picked one.
- let order = [Answer::Save, Answer::DontSave, Answer::Cancel];
+ // Left and Right move between the buttons as they are laid out (Save is picked first, at the
+ // right); Enter gives the picked one.
+ let order = [Answer::Cancel, Answer::DontSave, Answer::Save];
let (left, right, enter) = ctx.input_mut(|x| {
(
x.consume_key(egui::Modifiers::NONE, egui::Key::ArrowLeft),
@@ -561,7 +559,7 @@ pub fn prompt(app: &mut SolveApp, ctx: &egui::Context) {
x.consume_key(egui::Modifiers::NONE, egui::Key::Enter),
)
});
- let at = order.iter().position(|a| *a == app.docs.choice).unwrap_or(0);
+ let at = order.iter().position(|a| *a == app.docs.choice).unwrap_or(order.len() - 1);
let at = if left {
at.saturating_sub(1)
} else if right {
@@ -575,26 +573,25 @@ pub fn prompt(app: &mut SolveApp, ctx: &egui::Context) {
answer = Some(choice);
}
let title = crate::i18n::format("document.save_changes", &[("name", &name_display)]);
- crate::frame::window(ctx, title, crate::frame::Width::Normal)
- .id(egui::Id::new("sc_close_prompt"))
- .collapsible(false)
- .resizable(false)
- .anchor(Align2::CENTER_CENTER, vec2(0.0, 0.0))
- .show(ctx, |ui| {
- ui.label(crate::i18n::format("document.unsaved_changes", &[("name", &name_display)]));
- ui.add_space(8.0);
- ui.horizontal(|ui| {
- if ui.add(egui::Button::new(crate::i18n::tr("ui.save")).selected(choice == Answer::Save)).clicked() {
- answer = Some(Answer::Save);
- }
- if ui.add(egui::Button::new(crate::i18n::tr("ui.don_t_save")).selected(choice == Answer::DontSave)).clicked() {
- answer = Some(Answer::DontSave);
- }
- if ui.add(egui::Button::new(crate::i18n::tr("ui.cancel")).selected(choice == Answer::Cancel)).clicked() {
- answer = Some(Answer::Cancel);
- }
+ let (closed, action) =
+ ui_kit::Prompt::new(egui::Id::new("sc_close_prompt"), solidcraft_engine::find_command("file.save").map_or("", |c| c.icon), &title)
+ .anchor(Align2::CENTER_CENTER, vec2(0.0, 0.0))
+ .actions(crate::i18n::tr("ui.save"), crate::i18n::tr("ui.cancel"), Some(crate::i18n::tr("ui.don_t_save")))
+ .selected(match choice {
+ Answer::Save => ui_kit::Action::Ok,
+ Answer::DontSave => ui_kit::Action::Apply,
+ Answer::Cancel => ui_kit::Action::Cancel,
+ })
+ .show(ctx, true, |ui| {
+ ui_kit::text_block(ui, "unsaved", &crate::i18n::format("document.unsaved_changes", &[("name", &name_display)]), false);
});
- });
+ answer = match action {
+ ui_kit::Action::Ok => Some(Answer::Save),
+ ui_kit::Action::Apply => Some(Answer::DontSave),
+ ui_kit::Action::Cancel => Some(Answer::Cancel),
+ ui_kit::Action::None if closed => Some(Answer::Cancel),
+ ui_kit::Action::None => answer,
+ };
if ctx.input(|x| x.key_pressed(egui::Key::Escape)) {
answer = Some(Answer::Cancel);
app.esc_handled = true;
diff --git a/crates/ui-egui/src/expression_complete.rs b/crates/ui-egui/src/expression_complete.rs
index 42b139b27b..4428f99183 100644
--- a/crates/ui-egui/src/expression_complete.rs
+++ b/crates/ui-egui/src/expression_complete.rs
@@ -1,6 +1,7 @@
//! Focus-scoped completion keyboard handling before editors and CAD shortcuts see input.
-use egui::{Key, RichText};
+use crate::ui_kit;
+use egui::Key;
use crate::params_dialog::{suggestions_for, word_before};
use crate::theme::Tokens;
@@ -123,31 +124,28 @@ pub(crate) fn complete(ui: &mut egui::Ui, resp: &egui::Response, text: &mut Stri
let mut pick = if popup.accept { list.get(popup.selected).map(|s| s.text.clone()) } else { None };
popup.accept = false;
let t = Tokens::get();
- crate::frame::area(resp.id.with("completions")).order(egui::Order::Tooltip).fixed_pos(resp.rect.left_bottom() + egui::vec2(0.0, 2.0)).show(
+ let options: Vec<_> = list
+ .iter()
+ .map(|suggestion| ui_kit::PopupOption {
+ text: &suggestion.text,
+ detail: &suggestion.detail,
+ color: match suggestion.kind.as_str() {
+ "parameter" => t.text,
+ "function" => t.accent,
+ _ => t.text_dim,
+ },
+ })
+ .collect();
+ if let Some(index) = ui_kit::popup_list(
&ctx,
- |ui| {
- egui::Frame::popup(ui.style()).show(ui, |ui| {
- ui.set_min_width(resp.rect.width().max(180.0));
- for (i, suggestion) in list.iter().enumerate() {
- let colour = match suggestion.kind.as_str() {
- "parameter" => t.text,
- "function" => t.accent,
- _ => t.text_dim,
- };
- let r = ui
- .add(egui::Button::new(RichText::new(&suggestion.text).color(colour)).selected(i == popup.selected))
- .on_hover_text(&suggestion.detail);
- if i == popup.selected {
- ui.label(RichText::new(&suggestion.detail).small().color(t.text_dim));
- }
- if r.clicked() {
- pick = Some(suggestion.text.clone());
- }
- }
- ui.label(RichText::new("↑ ↓ choose · Enter / Tab complete · Esc dismiss").small().color(t.text_dim));
- });
- },
- );
+ resp.id.with("completions"),
+ resp.rect,
+ popup.selected,
+ &options,
+ crate::i18n::tr_label("↑ ↓ choose · Enter / Tab complete · Esc dismiss"),
+ ) {
+ pick = list.get(index).map(|suggestion| suggestion.text.clone());
+ }
ctx.data_mut(|d| d.insert_temp(popup_id(), popup));
let Some(pick) = pick else { return false };
let chars: Vec<char> = text.chars().collect();
diff --git a/crates/ui-egui/src/file_load.rs b/crates/ui-egui/src/file_load.rs
index b72deb4234..92c445eeb5 100644
--- a/crates/ui-egui/src/file_load.rs
+++ b/crates/ui-egui/src/file_load.rs
@@ -7,7 +7,6 @@
//! control-channel commands that change the design are held until the file is in. A control
//! (MCP) `doc.open` or import is answered when its file finishes loading.
-use crate::fonts::RichTextExt as _;
use std::collections::VecDeque;
use std::sync::{
Arc,
@@ -20,6 +19,7 @@ use solidcraft_engine::{Session, doc::Document, doc::progress::Progress};
use crate::SolveApp;
use crate::control::ControlResponse;
+use crate::ui_kit;
/// What a file operation does with its file.
#[derive(Clone, Debug, PartialEq)]
@@ -901,8 +901,6 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
m.surrender_focus(id);
}
});
- let t = crate::theme::Tokens::get();
- let mut cancel = ctx.input(|i| i.key_pressed(egui::Key::Escape));
let id = egui::Id::new("file_loading");
let card_id = id.with("card");
// Above the dialogs over the design; menus, tooltips and the resize edges stay above it.
@@ -913,65 +911,63 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
ui.interact(cover, egui::Id::new("file_loading_block"), egui::Sense::click_and_drag());
ui.painter().rect_filled(cover, 0.0, egui::Color32::from_black_alpha(70));
});
- let width = 340.0f32.min(cover.width() - 16.0).max(120.0);
- // Anchored at its top with Cancel in the heading row: the card grows downwards (the saved
- // preview, the progress bar) and Cancel never moves under the pointer.
+ // Anchored at its top: the card grows downwards (the saved preview) and Cancel stays put.
let top = egui::pos2(centre.x, (centre.y - 120.0).max(cover.top() + 8.0));
- egui::Area::new(card_id).order(egui::Order::Middle).pivot(egui::Align2::CENTER_TOP).fixed_pos(top).show(ctx, |child| {
- egui::Frame::popup(child.style()).fill(t.panel).show(child, |ui| {
- ui.set_width(width - 16.0);
- ui.horizontal(|ui| {
- ui.label(
- egui::RichText::new(if cancelled && export {
- crate::i18n::tr_label("dxf.cancelling")
- } else if cancelled {
- "Waiting for file operation"
- } else {
- match r.request.kind {
- Kind::Insert => "Inserting geometry",
- Kind::Open => "Opening design",
- Kind::Recover { .. } => "Recovering design",
- Kind::ExportDxf => crate::i18n::tr_label("dxf.exporting"),
- }
- })
- .semibold()
- .color(crate::theme::Tokens::get().text)
- .size(crate::theme::Tokens::get().font_heading),
- );
- ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
- let b = ui.button(crate::i18n::tr("ui.cancel"));
- crate::scenario::publish_handle("file_loading:cancel", b.rect.center());
- cancel |= b.clicked();
- });
- });
- ui.label(egui::RichText::new(format!("{name}…")).weak());
+ let title = if cancelled && export {
+ crate::i18n::tr_label("dxf.cancelling")
+ } else if cancelled {
+ crate::i18n::tr("file_load.waiting")
+ } else {
+ crate::i18n::tr(match r.request.kind {
+ Kind::Insert => "file_load.inserting",
+ Kind::Open => "file_load.opening",
+ Kind::Recover { .. } => "file_load.recovering",
+ Kind::ExportDxf => "dxf.exporting",
+ })
+ };
+ let icon = match r.request.kind {
+ Kind::Insert => "import",
+ Kind::Open => "open",
+ Kind::Recover { .. } => "restore",
+ Kind::ExportDxf => "export",
+ };
+ let (closed, action) = ui_kit::Prompt::new(card_id, icon, title)
+ .cards(((cover.width() - 16.0) / crate::theme::Tokens::get().form_card_width).clamp(0.5, 1.3))
+ .placed(egui::Align2::CENTER_TOP, top)
+ .actions("", crate::i18n::tr("ui.cancel"), None)
+ .show(ctx, true, |ui| {
+ ui_kit::text_block(ui, "name", &format!("{name}…"), false);
if let Some(preview) = r.preview.as_ref().filter(|_| !cancelled) {
- let w = ui.available_width().min(320.0);
+ let w = ui.available_width();
ui.image((preview.id(), egui::vec2(w, w * 200.0 / 320.0)));
let note = match r.built {
- Some(built) => format!("Built so far: {built} of {total} features."),
- None => crate::i18n::tr_label("Saved preview. Geometry is being checked before editing.").to_string(),
+ Some(built) => crate::i18n::format("file_load.built", &[("built", &built.to_string()), ("total", &total.to_string())]),
+ None => crate::i18n::tr("file_load.preview_note").to_string(),
};
- ui.label(egui::RichText::new(note).small().weak());
+ ui_kit::note(ui, "preview", &note);
}
- ui.add_space(4.0);
+ let status = if cancelled && export {
+ crate::i18n::tr_label("dxf.cancel_wait").to_string()
+ } else if cancelled {
+ crate::i18n::tr("file_load.stopping").to_string()
+ } else {
+ match (phase, work) {
+ (_, work) if r.request.kind == Kind::ExportDxf => crate::dialogs_view_dxf::progress_text(work),
+ (_, Some(("reading", d, t))) => {
+ crate::i18n::format("file_load.reading_percent", &[("percent", &(d * 100 / t.max(1)).to_string())])
+ }
+ (_, Some((_, d, t))) => crate::i18n::format("file_load.converting", &[("done", &(d + 1).to_string()), ("total", &t.to_string())]),
+ (1, _) => crate::i18n::tr("file_load.preparing_view").to_string(),
+ (2, _) => crate::i18n::tr("file_load.preparing_thumbnail").to_string(),
+ _ if total > 0 => {
+ crate::i18n::format("file_load.rebuilding", &[("done", &(done + 1).min(total).to_string()), ("total", &total.to_string())])
+ }
+ _ => crate::i18n::tr("file_load.reading").to_string(),
+ }
+ };
ui.horizontal(|ui| {
ui.spinner();
- ui.label(if cancelled && export {
- crate::i18n::tr_label("dxf.cancel_wait").to_string()
- } else if cancelled {
- "Waiting for the previous operation to stop...".to_string()
- } else {
- match (phase, work) {
- (_, work) if r.request.kind == Kind::ExportDxf => crate::dialogs_view_dxf::progress_text(work),
- (_, Some(("reading", d, t))) => format!("Reading the file... {}%", d * 100 / t.max(1)),
- (_, Some((_, d, t))) => format!("Converting solid {} of {t}", d + 1),
- (1, _) => "Preparing the view...".into(),
- (2, _) => "Preparing the thumbnail...".into(),
- _ if total > 0 => format!("Rebuilding feature {} of {total}", (done + 1).min(total)),
- _ => "Reading the file...".into(),
- }
- });
+ ui_kit::text_block(ui, "status", &status, false);
});
// Always there, so the card keeps its height as the phases change.
let fraction = if cancelled {
@@ -985,9 +981,13 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
} else {
1.0
};
- ui.add(egui::ProgressBar::new(fraction).desired_height(6.0));
+ ui_kit::progress(ui, "file_load", fraction);
});
- });
+ // Cancel (and Esc) was a handle of its own before the card became a kit Prompt.
+ if let Some(at) = crate::scenario::handle_at("dialog:cancel") {
+ crate::scenario::publish_handle("file_loading:cancel", at);
+ }
+ let cancel = closed || action == ui_kit::Action::Cancel;
if cancel && !cancelled {
// Keep the running job until it exits: cancelling must not allow another large
// import to overlap it in memory. The rebuild stops at its next feature and the
diff --git a/crates/ui-egui/src/help.rs b/crates/ui-egui/src/help.rs
index fe38a3f3b8..9d4c73db20 100644
--- a/crates/ui-egui/src/help.rs
+++ b/crates/ui-egui/src/help.rs
@@ -3,11 +3,8 @@
//! (read only), Messages (every status message of the run, #2763), and Report an Issue, which
//! opens a local editable report draft.
-use crate::fonts::RichTextExt as _;
-use egui::{RichText, vec2};
-
use crate::SolveApp;
-use crate::theme::Tokens;
+use crate::ui_kit;
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
pub const COMMIT: &str = env!("SOLIDCRAFT_COMMIT");
@@ -16,11 +13,6 @@ pub const BUILD_DATE: &str = env!("SOLIDCRAFT_BUILD_DATE");
pub const DOCS_URL: &str = "https://docs.solidcraft.io/";
const ATTRIBUTION: &str = include_str!("../../../ATTRIBUTION.md");
use solidcraft_engine::licences::{LICENSE_APACHE, LICENSE_MIT, NOTICE, THIRD_PARTY};
-/// Fonts: what this build carries.
-pub const FONTS: &str = "The interface uses egui's built-in fonts (Ubuntu Light and Hack, under the Ubuntu Font Licence and \
-the MIT/Bitstream Vera licence; Noto Emoji and the emoji icon font, under the OFL and MIT). Sketch text uses Liberation Sans \
-(SIL OFL 1.1). The Crafting Apps' optional font pack, craft-fonts (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans \
-CJK SC, Noto Sans Arabic; SIL OFL 1.1), is not bundled in SolidCraft builds.";
#[derive(Default)]
pub struct HelpState {
@@ -106,67 +98,52 @@ fn about(app: &mut SolveApp, ctx: &egui::Context) {
if !app.help.about {
return;
}
- let t = Tokens::get();
- let mut open = true;
- crate::frame::window(ctx, crate::i18n::tr_label("About SolidCraft"), crate::frame::Width::Normal)
- .id(egui::Id::new("sc_about"))
- .open(&mut open)
- .default_size(vec2(440.0, 560.0))
- .show(ctx, |ui| {
- ui.label(RichText::new("SolidCraft").size(crate::theme::Tokens::get().font_title).semibold().color(crate::theme::Tokens::get().text));
- ui.label(format!("Version {VERSION} · commit {COMMIT} · built {BUILD_DATE}"));
- ui.label(RichText::new(crate::i18n::tr_label("Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.")).color(t.text_dim));
- ui.add_space(6.0);
- ui.horizontal(|ui| {
- if ui.button(crate::i18n::tr_label("Copy diagnostic information")).clicked() {
- ctx.copy_text(diagnostics(app));
- }
- });
- ui.separator();
- egui::ScrollArea::vertical().show(ui, |ui| {
- egui::CollapsingHeader::new("Attributions (ATTRIBUTION.md)").show(ui, |ui| {
- ui.label(RichText::new(ATTRIBUTION).monospace().size(crate::theme::Tokens::get().font_small));
+ let (closed, action) = ui_kit::Prompt::new(egui::Id::new("sc_about"), "help", crate::i18n::tr_label("About SolidCraft"))
+ .cards(2.0)
+ .actions("", "Close", None)
+ .show(ctx, true, |ui| {
+ ui_kit::text_block(
+ ui,
+ "version",
+ &crate::i18n::format("help.build", &[("version", VERSION), ("commit", COMMIT), ("date", BUILD_DATE)]),
+ false,
+ );
+ ui_kit::note(ui, "description", crate::i18n::tr_label("Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0."));
+ let copy = ui_kit::secondary_button(ui, crate::i18n::tr_label("Copy diagnostic information"));
+ crate::scenario::publish_rect("about:copy_diagnostics", copy.rect);
+ crate::scenario::publish_handle("about:copy_diagnostics", copy.rect.center());
+ if copy.clicked() {
+ ctx.copy_text(diagnostics(app));
+ }
+ egui::ScrollArea::vertical().max_height(crate::theme::Tokens::get().control_height * 15.0).show(ui, |ui| {
+ ui_kit::section(ui, "attributions", crate::i18n::tr("help.attributions"), false, |ui| {
+ ui_kit::text_block(ui, "attributions", ATTRIBUTION, false);
});
- egui::CollapsingHeader::new("Fonts").show(ui, |ui| {
- ui.label(FONTS);
+ ui_kit::section(ui, "fonts", crate::i18n::tr("help.fonts"), false, |ui| {
+ ui_kit::text_block(ui, "fonts", crate::i18n::tr("help.font_details"), false);
});
- egui::CollapsingHeader::new("Licences").show(ui, |ui| {
- egui::CollapsingHeader::new("NOTICE").show(ui, |ui| {
- ui.label(RichText::new(NOTICE).monospace().size(crate::theme::Tokens::get().font_small));
- });
- egui::CollapsingHeader::new("MIT licence").show(ui, |ui| {
- ui.label(RichText::new(LICENSE_MIT).monospace().size(crate::theme::Tokens::get().font_small));
- });
- egui::CollapsingHeader::new("Apache licence 2.0").show(ui, |ui| {
- ui.label(RichText::new(LICENSE_APACHE).monospace().size(crate::theme::Tokens::get().font_small));
- });
- egui::CollapsingHeader::new("Third-party licences").show(ui, |ui| {
- if ui.button(crate::i18n::tr_label("Copy all licences")).clicked() {
+ ui_kit::section(ui, "licences", crate::i18n::tr("help.licences"), false, |ui| {
+ for (id, title, text) in
+ [("notice", "help.notice", NOTICE), ("mit", "help.mit", LICENSE_MIT), ("apache", "help.apache", LICENSE_APACHE)]
+ {
+ ui_kit::section(ui, id, crate::i18n::tr(title), false, |ui| {
+ ui_kit::text_block(ui, id, text, false);
+ });
+ }
+ ui_kit::section(ui, "third_party", crate::i18n::tr("help.third_party"), false, |ui| {
+ if ui_kit::secondary_button(ui, crate::i18n::tr_label("Copy all licences")).clicked() {
ctx.copy_text(solidcraft_engine::licences::all());
}
- third_party(ui);
+ ui_kit::text_lines(ui, "sc_third_party", THIRD_PARTY);
});
});
});
});
- if !open {
+ if closed || action == ui_kit::Action::Cancel {
app.help.about = false;
}
}
-/// THIRD-PARTY-LICENSES.txt (over 10 000 lines): only the lines in view are laid out.
-fn third_party(ui: &mut egui::Ui) {
- let lines: Vec<&str> = THIRD_PARTY.lines().collect();
- let font = egui::FontId::monospace(crate::theme::Tokens::get().font_small);
- let row_h = ui.fonts_mut(|f| f.row_height(&font));
- egui::ScrollArea::both().id_salt("sc_third_party").max_height(360.0).show_rows(ui, row_h, lines.len(), |ui, rows| {
- for line in lines.get(rows).unwrap_or_default() {
- // One row per line (show_rows needs equal rows): long lines scroll sideways.
- ui.add(egui::Label::new(RichText::new(*line).font(font.clone())).extend());
- }
- });
-}
-
#[cfg(test)]
mod tests {
use super::*;
diff --git a/crates/ui-egui/src/install.rs b/crates/ui-egui/src/install.rs
index 5314e3d1ca..f106dc8f4c 100644
--- a/crates/ui-egui/src/install.rs
+++ b/crates/ui-egui/src/install.rs
@@ -7,10 +7,8 @@
//! Safari installs web apps too (Add to Home Screen on iPhone and iPad, Add to Dock on a Mac) but
//! offers no prompt a page can show. There the item opens a window with the steps.
-use egui::RichText;
-
use crate::SolveApp;
-use crate::theme::Tokens;
+use crate::ui_kit;
/// How the browser installs the app.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -86,31 +84,20 @@ pub fn start(app: &mut SolveApp, offer: Offer) {
}
}
-/// The window with Safari's steps, while open.
+/// The card with Safari's steps, while open.
pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
let Some(steps) = app.install_steps else { return };
- let t = Tokens::get();
let (lines, after) = steps.messages();
- let mut open = true;
- let mut done = false;
- crate::frame::window(ctx, crate::i18n::tr("install.title"), crate::frame::Width::Normal)
- .id(egui::Id::new("sc_install_steps"))
- .open(&mut open)
- .resizable(false)
- .show(ctx, |ui| {
- ui.label(crate::i18n::tr("install.steps_intro"));
- ui.add_space(4.0);
+ let (closed, action) = ui_kit::Prompt::new(egui::Id::new("sc_install_steps"), "web", crate::i18n::tr("install.title"))
+ .actions("", crate::i18n::tr("install.done"), None)
+ .show(ctx, true, |ui| {
+ ui_kit::text_block(ui, "intro", crate::i18n::tr("install.steps_intro"), false);
for (i, id) in lines.iter().enumerate() {
- ui.label(format!("{}. {}", i + 1, crate::i18n::tr(id)));
- }
- ui.add_space(4.0);
- ui.add(egui::Label::new(RichText::new(crate::i18n::tr(after)).color(t.text_dim)).wrap());
- ui.add_space(6.0);
- if ui.button(crate::i18n::tr("install.done")).clicked() {
- done = true;
+ ui_kit::text_block(ui, &format!("step:{i}"), &format!("{}. {}", i + 1, crate::i18n::tr(id)), false);
}
+ ui_kit::note(ui, "after", crate::i18n::tr(after));
});
- if !open || done {
+ if closed || action != ui_kit::Action::None {
app.install_steps = None;
}
}
diff --git a/crates/ui-egui/src/issue_report.rs b/crates/ui-egui/src/issue_report.rs
index 1b095dbf6e..942f4b50c7 100644
--- a/crates/ui-egui/src/issue_report.rs
+++ b/crates/ui-egui/src/issue_report.rs
@@ -1,13 +1,12 @@
//! Reviewed issue drafts with local evidence; never publishes or uploads a report.
-use crate::fonts::RichTextExt as _;
use std::fmt::Write as _;
use std::hash::{Hash, Hasher};
use std::sync::Arc;
-use egui::{ColorImage, RichText, TextureHandle, vec2};
+use egui::{ColorImage, TextureHandle, vec2};
-use crate::{SolveApp, dialogs, help};
+use crate::{SolveApp, dialogs, help, ui_kit};
const MAX_BODY: usize = 24_000;
const MAX_IMAGE_PIXELS: usize = 16_000_000;
@@ -504,53 +503,70 @@ pub(crate) fn receive(app: &mut SolveApp, token: u64, image: Arc<ColorImage>) {
}
}
-/// The report window is hidden only while a frame is captured, so it cannot cover the evidence.
+/// The report card is hidden only while a frame is captured, so it cannot cover the evidence.
pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
if pending(app) {
return;
}
let Some(mut draft) = app.issue_report.draft.take() else { return };
- let mut open = true;
let mut retake = false;
- let mut close = false;
+ let t = crate::theme::Tokens::get();
let screen = ctx.content_rect();
- let max_width = (screen.width() - 48.0).clamp(100.0, crate::frame::WINDOW_WIDE_MAX_W);
- crate::frame::window(ctx, crate::i18n::tr_label("Create Issue — review draft"), crate::frame::Width::Wide)
- .id(egui::Id::new("sc_issue_report"))
- .open(&mut open)
- .resizable(true)
- .default_width((screen.width() - 32.0).clamp(100.0, 640.0))
- .max_width(max_width)
- .max_height((screen.height() - 32.0).max(100.0))
- .show(ctx, |ui| {
- // Only the editable report and evidence scroll. Keep the submission guide
- // and actions visible even when a screenshot or long report needs more room.
- egui::ScrollArea::vertical().id_salt("issue-report-review").max_height((screen.height() - 260.0).clamp(80.0, 520.0)).show(ui, |ui| {
- ui.label(crate::i18n::tr_label("Review the report and screenshot before opening GitHub."));
- // TextEdit rounds its allocation to physical pixels. Leaving one pixel of
- // room prevents that rounding from increasing the window width every frame
- // at fractional display/UI scales (for example 140%).
- let editor_width = |ui: &egui::Ui| (ui.available_width() - ui.ctx().pixels_per_point().recip()).max(24.0);
- ui.add(
- egui::TextEdit::singleline(&mut draft.title)
- .id(egui::Id::new("issue_report_title"))
- .hint_text(crate::i18n::tr_label("Issue title"))
- .char_limit(160)
- .desired_width(editor_width(ui)),
- );
+ let cards = ((screen.width() - 2.0 * t.space_16) / t.form_card_width).clamp(0.5, 2.6);
+ // The card's own header, footer and margins come on top of the scrolling body.
+ let chrome = ui_kit::header_height() + t.form_footer_height + 6.0 * t.space_8;
+ let scroll = (screen.height() - 2.0 * t.space_16 - chrome).clamp(60.0, 640.0);
+ let mut link = None;
+ let (closed, action) = ui_kit::Prompt::new(egui::Id::new("sc_issue_report"), "bug_report", crate::i18n::tr_label("Create Issue — review draft"))
+ .cards(cards)
+ .fields()
+ .keep_open_on_escape()
+ .actions(crate::i18n::tr_label("Open GitHub draft"), crate::i18n::tr_label("Close draft"), Some(crate::i18n::tr_label("Copy report")))
+ .show(ctx, true, |ui| {
+ // Only the review scrolls: the submission actions stay in the footer even when a
+ // screenshot or a long report needs more room.
+ egui::ScrollArea::vertical().id_salt("issue-report-review").max_height(scroll).auto_shrink([false, true]).show(ui, |ui| {
+ ui_kit::text_block(ui, "review", crate::i18n::tr_label("Review the report and screenshot before opening GitHub."), false);
+ ui.horizontal_wrapped(|ui| {
+ retake = ui_kit::secondary_button(ui, crate::i18n::tr_label("Retake screenshot")).clicked();
+ if ui_kit::enabled_button(ui, "Copy screenshot", draft.image.is_some()).clicked()
+ && let Some(image) = draft.image.as_ref()
+ {
+ ctx.copy_image((**image).clone());
+ draft.note = crate::i18n::tr("issue.note_image_copied").into();
+ }
+ if ui_kit::enabled_button(ui, crate::i18n::tr("issue.save_screenshot"), draft.image.is_some() && app.services.pick_save.is_some())
+ .clicked()
+ && let Some(image) = draft.image.clone()
+ {
+ app.pick_save(&format!("solidcraft-issue-{}.png", app.shot_token), &["png"], move |app, path| {
+ let Some(path) = path else { return };
+ let result = crate::control::save_screenshot(&image, Some(&path));
+ if let Some(draft) = app.issue_report.draft.as_mut() {
+ draft.note = if result.get("ok").and_then(serde_json::Value::as_bool) == Some(true) {
+ crate::i18n::tr("issue.note_saved").into()
+ } else {
+ crate::i18n::format("issue.note_save_failed", &[("error", &debug(&result.get("error"), 1000))])
+ };
+ }
+ });
+ }
+ if ui_kit::enabled_button(ui, "Remove screenshot", draft.image.is_some()).clicked() {
+ draft.image = None;
+ draft.texture = None;
+ draft.note = crate::i18n::tr("issue.note_removed").into();
+ }
+ });
+ ui_kit::cell_editor(ui, egui::Id::new("issue_report_title"), &mut draft.title, "Issue title", false);
egui::ScrollArea::vertical().id_salt("issue-report-body").max_height((screen.height() * 0.35).clamp(72.0, 240.0)).show(ui, |ui| {
- ui.add(
- egui::TextEdit::multiline(&mut draft.body)
- .id(egui::Id::new("issue_report_body"))
- .char_limit(MAX_BODY)
- .desired_rows(5)
- .desired_width(editor_width(ui)),
- );
+ ui_kit::text_area(ui, crate::i18n::tr("issue.body_label"), egui::Id::new("issue_report_body"), &mut draft.body, 5, MAX_BODY);
});
truncate(&mut draft.title, 160);
truncate(&mut draft.body, MAX_BODY);
- ui.label(RichText::new(crate::i18n::tr_label("Remove private design details or paths before sharing.")).small());
- ui.add(egui::Label::new(&draft.note).wrap());
+ ui_kit::note(ui, "private", crate::i18n::tr_label("Remove private design details or paths before sharing."));
+ if !draft.note.is_empty() {
+ ui_kit::note(ui, "note", &draft.note);
+ }
if let Some(image) = draft.image.as_ref() {
let texture =
draft.texture.get_or_insert_with(|| ctx.load_texture("issue-report-frame", image.clone(), egui::TextureOptions::LINEAR));
@@ -560,79 +576,45 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
.maintain_aspect_ratio(true),
);
}
- });
- ui.horizontal_wrapped(|ui| {
- retake = ui.button(crate::i18n::tr_label("Retake screenshot")).clicked();
- if ui.add_enabled(draft.image.is_some(), egui::Button::new(crate::i18n::tr_label("Copy screenshot"))).clicked()
- && let Some(image) = draft.image.as_ref()
- {
- ctx.copy_image((**image).clone());
- draft.note = "Paste the image into the GitHub draft, or save the PNG if image copying is unavailable.".into();
- }
- if ui.add_enabled(draft.image.is_some() && app.services.pick_save.is_some(), egui::Button::new("Save screenshot…")).clicked()
- && let Some(image) = draft.image.clone()
- {
- app.pick_save(&format!("solidcraft-issue-{}.png", app.shot_token), &["png"], move |app, path| {
- let Some(path) = path else { return };
- let result = crate::control::save_screenshot(&image, Some(&path));
- if let Some(draft) = app.issue_report.draft.as_mut() {
- draft.note = if result.get("ok").and_then(serde_json::Value::as_bool) == Some(true) {
- "Screenshot saved. Attach the PNG in the GitHub draft.".into()
- } else {
- format!("Could not save screenshot: {}", debug(&result.get("error"), 1000))
- };
- }
- });
- }
- if ui.add_enabled(draft.image.is_some(), egui::Button::new(crate::i18n::tr_label("Remove screenshot"))).clicked() {
- draft.image = None;
- draft.texture = None;
- draft.note = "Screenshot removed from this draft.".into();
- }
- });
- ui.separator();
- ui.label(RichText::new(crate::i18n::tr_label("Send your report on GitHub")).semibold().color(crate::theme::Tokens::get().text));
- let (url, copy_needed) = draft_url(&draft.title, &draft.body);
- ui.add(
- egui::Label::new(crate::i18n::tr_label(if copy_needed {
- "1. Open GitHub draft below, then paste the report copied to your clipboard."
- } else {
- "1. Open GitHub draft below. Your title and report will be filled in."
- }))
- .wrap(),
- );
- ui.add(egui::Label::new(crate::i18n::tr_label("2. Attach your screenshot: copy and paste it, or save and upload the PNG.")).wrap());
- ui.add(egui::Label::new(crate::i18n::tr_label("3. Click Submit new issue on GitHub to send your report.")).wrap());
- ui.horizontal_wrapped(|ui| {
- let t = crate::theme::Tokens::get();
- if crate::frame::add_outlined(
+ ui_kit::divider(ui, "send");
+ ui_kit::text_block(ui, "send", crate::i18n::tr_label("Send your report on GitHub"), false);
+ let (url, copy_needed) = draft_url(&draft.title, &draft.body);
+ link = Some((url, copy_needed));
+ ui_kit::text_block(
ui,
- egui::Button::new(RichText::new(crate::i18n::tr_label("Open GitHub draft")).semibold().color(t.text))
- .fill(t.accent_soft)
- .stroke(egui::Stroke::new(1.0, t.accent)),
- 1.0,
- )
- .clicked()
- {
- if copy_needed {
- ctx.copy_text(draft.body.clone());
- }
- ctx.open_url(egui::OpenUrl::new_tab(url));
- draft.note = if copy_needed {
- "Report copied. Paste into the GitHub draft, attach the screenshot, then click Submit new issue on GitHub."
+ "step1",
+ crate::i18n::tr_label(if copy_needed {
+ "1. Open GitHub draft below, then paste the report copied to your clipboard."
} else {
- "Review the GitHub draft and attach the screenshot. GitHub's Submit new issue button publishes it."
- }
- .into();
- }
- if ui.button(crate::i18n::tr_label("Copy report")).clicked() {
- ctx.copy_text(draft.body.clone());
- draft.note = "Report copied. Paste it into the GitHub draft if needed.".into();
- }
- close = ui.button(crate::i18n::tr_label("Close draft")).clicked();
+ "1. Open GitHub draft below. Your title and report will be filled in."
+ }),
+ false,
+ );
+ ui_kit::text_block(
+ ui,
+ "step2",
+ crate::i18n::tr_label("2. Attach your screenshot: copy and paste it, or save and upload the PNG."),
+ false,
+ );
+ ui_kit::text_block(ui, "step3", crate::i18n::tr_label("3. Click Submit new issue on GitHub to send your report."), false);
});
});
- if open && !close {
+ let open = !(closed || action == ui_kit::Action::Cancel);
+ match (action, link) {
+ (ui_kit::Action::Ok, Some((url, copy_needed))) => {
+ if copy_needed {
+ ctx.copy_text(draft.body.clone());
+ }
+ ctx.open_url(egui::OpenUrl::new_tab(url));
+ draft.note = crate::i18n::tr(if copy_needed { "issue.note_opened_copied" } else { "issue.note_opened" }).into();
+ }
+ (ui_kit::Action::Apply, _) => {
+ ctx.copy_text(draft.body.clone());
+ draft.note = crate::i18n::tr("issue.note_report_copied").into();
+ }
+ _ => {}
+ }
+ if open {
app.issue_report.draft = Some(draft);
if retake {
let dialog = app.dialog.clone();
diff --git a/crates/ui-egui/src/keymap.rs b/crates/ui-egui/src/keymap.rs
index fe004b4a55..183647de10 100644
--- a/crates/ui-egui/src/keymap.rs
+++ b/crates/ui-egui/src/keymap.rs
@@ -3,15 +3,13 @@
//! already uses is reported and only taken over on request; keys the app itself handles (Esc, S,
//! V, Delete, Ctrl+Z…) can't be bound. Changes are kept between runs.
-use crate::fonts::RichTextExt as _;
use std::collections::BTreeMap;
-use egui::RichText;
use serde_json::{Value, json};
use solidcraft_engine::command_specs;
use crate::SolveApp;
-use crate::theme::Tokens;
+use crate::ui_kit;
/// Keys the application handles before any command shortcut.
pub const RESERVED: &[&str] = &[
@@ -193,90 +191,113 @@ pub fn page(app: &mut SolveApp, ui: &mut egui::Ui) {
}
}
}
- let t = Tokens::get();
let mut action: Option<(String, &str)> = None;
- {
- {
- ui.horizontal(|ui| {
- ui.add(
- egui::TextEdit::singleline(&mut app.keymap.filter)
- .hint_text(crate::i18n::tr_label("Filter commands or keys"))
- .desired_width(300.0),
- );
- if !app.keymap.read_only && ui.button(app.tr_label("Reset All")).clicked() {
- action = Some((String::new(), "reset_all"));
- }
- if ui.button(app.tr_label("Export…")).on_hover_text(app.tr_label("Keys, S box favourites and the toolbar, as a file")).clicked() {
- action = Some((String::new(), "export"));
+ ui_kit::scope(ui, |ui| {
+ let filter =
+ ui_kit::search_field(ui, egui::Id::new("sc_keymap_filter"), &mut app.keymap.filter, crate::i18n::tr_label("Filter commands or keys"));
+ crate::scenario::publish_rect("keymap:filter", filter.rect);
+ crate::scenario::publish_handle("keymap:filter", filter.rect.center());
+ ui.horizontal_wrapped(|ui| {
+ if !app.keymap.read_only && ui_kit::secondary_button(ui, app.tr_label("Reset All")).clicked() {
+ action = Some((String::new(), "reset_all"));
+ }
+ if ui_kit::secondary_button(ui, app.tr_label("Export…"))
+ .on_hover_text(app.tr_label("Keys, S box favourites and the toolbar, as a file"))
+ .clicked()
+ {
+ action = Some((String::new(), "export"));
+ }
+ if !app.keymap.read_only && ui_kit::secondary_button(ui, app.tr_label("Import…")).clicked() {
+ action = Some((String::new(), "import"));
+ }
+ });
+ if let Some(m) = &app.keymap.message {
+ ui_kit::text_block(ui, "keymap_message", m, true);
+ }
+ if let Some((id, key, _)) = app.keymap.conflict.clone() {
+ ui.horizontal_wrapped(|ui| {
+ let replace = ui_kit::secondary_button(ui, crate::i18n::format("keymap.use_anyway", &[("key", &key)]));
+ crate::scenario::publish_rect("keymap:replace", replace.rect);
+ crate::scenario::publish_handle("keymap:replace", replace.rect.center());
+ if replace.clicked() {
+ action = Some((format!("{id}\n{key}"), "replace"));
}
- if !app.keymap.read_only && ui.button(app.tr_label("Import…")).clicked() {
- action = Some((String::new(), "import"));
+ if ui_kit::secondary_button(ui, app.tr_label("Cancel")).clicked() {
+ action = Some((String::new(), "cancel"));
}
});
- if let Some(m) = &app.keymap.message {
- ui.label(RichText::new(m).color(t.warning));
- }
- if let Some((id, key, _)) = app.keymap.conflict.clone() {
- ui.horizontal(|ui| {
- if ui.button(format!("Use {key} here anyway")).clicked() {
- action = Some((format!("{id}\n{key}"), "replace"));
- }
- if ui.button(app.tr_label("Cancel")).clicked() {
- action = Some((String::new(), "cancel"));
- }
- });
- }
- ui.label(
- RichText::new(
- app.tr_label("Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation)."),
- )
- .size(crate::theme::Tokens::get().font_small)
- .color(t.text_dim),
- );
- ui.separator();
- let q = app.keymap.filter.to_lowercase();
- egui::ScrollArea::both().max_height(330.0).auto_shrink([false, true]).show(ui, |ui| {
- egui::Grid::new("sc_keymap_grid").num_columns(4).striped(true).spacing([10.0, 4.0]).show(ui, |ui| {
+ }
+ ui_kit::note(ui, "navigation", app.tr_label("Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation)."));
+ let q = app.keymap.filter.to_lowercase();
+ egui::ScrollArea::vertical()
+ .id_salt("sc_keymap_scroll")
+ .max_height(crate::theme::Tokens::get().control_height * 14.0)
+ .auto_shrink([false, true])
+ .show(ui, |ui| {
+ let columns = [
+ ui_kit::Column { label: "Command", width: 1.5 },
+ ui_kit::Column { label: crate::i18n::tr("keymap.command_id"), width: 1.8 },
+ ui_kit::Column { label: "Keyboard Shortcuts", width: 1.0 },
+ ui_kit::Column { label: "", width: 1.2 },
+ ];
+ ui_kit::table(ui, "keymap", &columns, crate::i18n::tr("keymap.empty"), |ui, table| {
for c in command_specs() {
let key = effective(app, c.id).unwrap_or_default();
let translated_label = app.tr_label(c.label);
if !q.is_empty() && ![c.label, c.id, key.as_str(), translated_label].iter().any(|s| s.to_lowercase().contains(&q)) {
continue;
}
- ui.label(translated_label);
- ui.label(RichText::new(c.id).size(crate::theme::Tokens::get().font_panel).color(t.text_dim));
- let capturing = app.keymap.capturing.as_deref() == Some(c.id);
- let changed = app.keymap.custom.contains_key(c.id);
- let text = if capturing {
- app.tr_label("press a key…").to_string()
- } else if key.is_empty() {
- "—".to_string()
- } else {
- key.clone()
- };
- if app.keymap.read_only {
- ui.label(RichText::new(text).semibold().color(crate::theme::Tokens::get().text));
- ui.end_row();
- continue;
- }
- let b = egui::Button::new(RichText::new(text).color(if changed { t.accent } else { t.text })).min_size(egui::vec2(80.0, 0.0));
- if ui.add(b).on_hover_text(app.tr_label("Click, then press the new key")).clicked() {
- action = Some((c.id.to_string(), "capture"));
- }
- ui.horizontal(|ui| {
- if ui.add_enabled(!key.is_empty(), egui::Button::new(app.tr_label("Clear")).small()).clicked() {
- action = Some((c.id.to_string(), "clear"));
- }
- if ui.add_enabled(changed, egui::Button::new(app.tr_label("Reset")).small()).clicked() {
- action = Some((c.id.to_string(), "reset"));
- }
+ table.row(ui, c.id, app.keymap.capturing.as_deref() == Some(c.id), |row| {
+ row.cell(|ui| {
+ ui_kit::cell_text(ui, translated_label);
+ });
+ row.cell(|ui| {
+ ui_kit::cell_text(ui, c.id);
+ });
+ let capturing = app.keymap.capturing.as_deref() == Some(c.id);
+ let changed = app.keymap.custom.contains_key(c.id);
+ let text = if capturing {
+ app.tr_label("press a key…").to_string()
+ } else if key.is_empty() {
+ "—".to_string()
+ } else {
+ key.clone()
+ };
+ row.cell(|ui| {
+ if app.keymap.read_only {
+ ui_kit::cell_text(ui, &text);
+ } else {
+ let capture = ui_kit::secondary_button(ui, &text).on_hover_text(app.tr_label("Click, then press the new key"));
+ crate::scenario::publish_rect(&format!("keymap:capture:{}", c.id), capture.rect);
+ crate::scenario::publish_handle(&format!("keymap:capture:{}", c.id), capture.rect.center());
+ if capture.clicked() {
+ action = Some((c.id.to_string(), "capture"));
+ }
+ }
+ });
+ row.cell(|ui| {
+ if !app.keymap.read_only {
+ ui.horizontal(|ui| {
+ let clear = ui_kit::enabled_button(ui, app.tr_label("Clear"), !key.is_empty());
+ crate::scenario::publish_rect(&format!("keymap:clear:{}", c.id), clear.rect);
+ crate::scenario::publish_handle(&format!("keymap:clear:{}", c.id), clear.rect.center());
+ if clear.clicked() {
+ action = Some((c.id.to_string(), "clear"));
+ }
+ let reset = ui_kit::enabled_button(ui, app.tr_label("Reset"), changed);
+ crate::scenario::publish_rect(&format!("keymap:reset:{}", c.id), reset.rect);
+ crate::scenario::publish_handle(&format!("keymap:reset:{}", c.id), reset.rect.center());
+ if reset.clicked() {
+ action = Some((c.id.to_string(), "reset"));
+ }
+ });
+ }
+ });
});
- ui.end_row();
}
});
});
- }
- }
+ });
match action {
Some((id, "capture")) => {
app.keymap.capturing = Some(id);
@@ -367,3 +388,43 @@ mod tests {
#[cfg(test)]
#[path = "sketch_shortcut_tests.rs"]
mod sketch_shortcut_tests;
+
+#[cfg(test)]
+mod card_tests {
+ use super::*;
+ use crate::scenario::{self, Harness};
+
+ #[test]
+ fn shortcut_card_captures_clears_resets_and_esc_cancels_capture_only() {
+ let mut h = Harness::new();
+ h.app.home.open = false;
+ h.app.keymap.filter = "solid.extrude".into();
+ h.call("ui.prefs", json!({"open":"Keyboard Shortcuts"}));
+ for (action, expected) in [("capture", "Shift+E"), ("clear", ""), ("reset", "E")] {
+ h.step(&json!({"click":{"handle":format!("keymap:{action}:solid.extrude")}})).unwrap();
+ if action == "capture" {
+ h.step(&json!({"key":"E","shift":true})).unwrap();
+ }
+ assert_eq!(effective(&h.app, "solid.extrude").unwrap_or_default(), expected);
+ }
+ h.step(&json!({"click":{"handle":"keymap:capture:solid.extrude"}})).unwrap();
+ h.step(&json!({"key":"Escape"})).unwrap();
+ assert!(h.app.prefs_window.open && h.app.keymap.capturing.is_none());
+ h.step(&json!({"key":"Escape"})).unwrap();
+ assert!(!h.app.prefs_window.open);
+ }
+
+ #[test]
+ fn help_shortcuts_card_keeps_rebinding_read_only() {
+ let mut h = Harness::new();
+ h.app.home.open = false;
+ h.app.keymap.filter = "solid.extrude".into();
+ h.call("ui.help", json!({"item":"shortcuts"}));
+ assert!(h.app.keymap.read_only);
+ assert!(scenario::handle_at("keymap:filter").is_some());
+ for action in ["capture", "clear", "reset"] {
+ assert!(scenario::handle_at(&format!("keymap:{action}:solid.extrude")).is_none());
+ }
+ assert_eq!(effective(&h.app, "solid.extrude").as_deref(), Some("E"));
+ }
+}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index bfa139363c..0efbe019ae 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -13,6 +13,8 @@ pub mod agent_chat;
pub mod agent_cursor;
pub mod bom_panel;
pub mod browser;
+pub mod browser_canvas;
+pub mod browser_prompts;
pub mod canvas;
#[cfg(test)]
mod colour_tokens_tests;
@@ -78,6 +80,8 @@ mod linked_source;
mod loft_rails_dialog_tests;
#[cfg(test)]
mod look_at_tests;
+#[cfg(test)]
+mod manage_dialogs_tests;
mod material_card_review;
#[cfg(test)]
@@ -90,6 +94,8 @@ mod pattern_arrow_tests;
#[cfg(test)]
mod scale_tests;
#[cfg(test)]
+mod prompt_cards_tests;
+#[cfg(test)]
mod surface_clamp_tests;
#[cfg(test)]
mod surface_errors_tests;
@@ -143,6 +149,7 @@ pub(crate) mod pick_buffer;
pub(crate) mod pick_index;
pub(crate) mod plugins;
pub mod prefs;
+pub mod prefs_notice;
#[cfg(test)]
mod preselect_tests;
pub mod preview;
@@ -1594,7 +1601,7 @@ impl SolveApp {
material_card_review::show(self, ui.ctx());
recovery_ui::show(self, ui.ctx());
stand_up::show(self, ui.ctx());
- prefs::show_reset_notice(self, ui.ctx());
+ prefs_notice::show(self, ui.ctx());
context_menu::show(self, ui.ctx());
mouse_gesture::show(self, ui.ctx());
delete::show(self, ui.ctx());
diff --git a/crates/ui-egui/src/manage_dialogs_tests.rs b/crates/ui-egui/src/manage_dialogs_tests.rs
new file mode 100644
index 0000000000..f36f3de9b5
--- /dev/null
+++ b/crates/ui-egui/src/manage_dialogs_tests.rs
@@ -0,0 +1,193 @@
+//! Manage cards keep their commands, dense chrome and public interaction handles.
+use crate::{
+ dialogs,
+ scenario::{self, Harness},
+ shell::LayoutMode,
+ theme::Tokens,
+};
+use serde_json::json;
+use solidcraft_engine::Sel;
+
+fn fixture() -> Harness {
+ let mut h = Harness::new();
+ h.app.home.open = false;
+ h.call("ui.resize", json!({"width":1600,"height":1200}));
+ h.app.run("solid.box", json!({"length":10,"width":10,"height":10})).unwrap();
+ h.app.run("parameters.add", json!({"name":"width","expression":"10 mm"})).unwrap();
+ h.app.session.selection = vec![Sel::Body { name: "Body1".into() }];
+ h
+}
+
+fn chrome(h: &Harness) {
+ for key in ["dialog:close", "dialog:ok", "dialog:cancel"] {
+ assert!(scenario::handle_at(key).is_some(), "missing {key}");
+ }
+ assert_eq!(scenario::rect_of("dialog:header").unwrap().height(), Tokens::get().form_header_height);
+ assert!(scenario::rect_of("dialog:hint:manage").is_some());
+ let footer = scenario::rect_of("dialog:footer").unwrap();
+ assert!(h.ctx.content_rect().contains_rect(footer));
+}
+
+fn form(command: &str, labels: &[&str]) {
+ for layout in [LayoutMode::Docked, LayoutMode::Floating] {
+ let mut h = fixture();
+ h.call("ui.set", json!({"layout":layout}));
+ h.app.start(command);
+ h.frames(3);
+ chrome(&h);
+ for label in labels {
+ assert!(scenario::rect_of(&format!("dialog:row:{label}")).is_some(), "{command}: {label}");
+ }
+ let before = dialogs::apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap();
+ h.frames(3);
+ assert_eq!(before, dialogs::apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap());
+ h.step(&json!({"click":{"handle":"dialog:cancel"}})).unwrap();
+ assert!(h.app.dialog.is_none());
+ }
+}
+
+#[test]
+fn physical_material_is_dense_and_keeps_assignment() {
+ form("material.assign", &["Bodies", "Material"]);
+ let mut h = fixture();
+ h.app.start("material.assign");
+ h.frames(3);
+ let commands = dialogs::apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap();
+ assert_eq!(commands[0].0, "material.assign");
+ assert_eq!(commands[0].1["bodies"], json!(["Body1"]));
+ assert!(commands[0].1["material"].is_string());
+}
+
+#[test]
+fn appearance_is_dense_and_preserves_color_opacity_and_targets() {
+ form("appearance.assign", &["Objects", "Apply To", "Colour", "Opacity", "Library", "Search"]);
+ let mut h = fixture();
+ h.app.run("appearance.assign", json!({"bodies":["Body1"],"color":"#336699","opacity":0.123456})).unwrap();
+ h.app.start("appearance.assign");
+ let before = dialogs::apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap();
+ h.frames(4);
+ let after = dialogs::apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap();
+ assert_eq!(before, after);
+ assert_eq!(after[0].1["opacity"], 0.123456);
+}
+
+#[test]
+fn sheet_rule_manager_is_dense() {
+ form("sheet.manage_rules", &["Rule", "Thickness", "K Factor", "Active rule"]);
+}
+
+#[test]
+fn plastic_rule_manager_is_dense() {
+ form("plastic.manage_rules", &["Rule", "Material", "Active rule"]);
+}
+
+#[test]
+fn plastic_assignment_remains_dense() {
+ form("plastic.assign_rule", &["Bodies", "Rule"]);
+}
+
+fn configurations(command: &str) {
+ let mut h = fixture();
+ h.app.run("config.configure", json!({"params":["width"]})).unwrap();
+ h.app.start(command);
+ h.frames(4);
+ chrome(&h);
+ for label in ["Configuration", "width", "Actions"] {
+ assert!(scenario::rect_of(&format!("dialog:column:configuration_table:{label}")).is_some());
+ }
+ assert_eq!(scenario::rect_of("dialog:table:configuration_table:Default").unwrap().height(), Tokens::get().control_height);
+ assert!(h.widget("Add Column").is_some());
+ assert!(h.widget("Add Row").is_some());
+ h.step(&json!({"widget":"Add Row"})).unwrap();
+ assert_eq!(h.app.session.doc.configs.rows.len(), 2);
+ h.step(&json!({"click":{"handle":"config:cell:Configuration2:param:width"}})).unwrap();
+ h.step(&json!({"key":"A","cmd":true})).unwrap();
+ h.step(&json!({"text":"25 mm"})).unwrap();
+ h.step(&json!({"key":"Enter"})).unwrap();
+ assert!(h.app.dialog.is_some(), "cell Enter leaves the configuration table open");
+ assert_eq!(h.app.session.doc.configs.rows.iter().find(|row| row.name == "Configuration2").unwrap().cells[0], "25 mm");
+ assert_eq!(h.app.session.doc.param("width").unwrap().expr, "10 mm", "editing an inactive row does not activate it");
+ h.step(&json!({"click":{"handle":"dialog:ok"}})).unwrap();
+ assert!(h.app.dialog.is_none());
+ assert_eq!(h.app.session.doc.configs.rows.len(), 2);
+}
+
+#[test]
+fn configuration_table_is_dense_and_adds_rows() {
+ configurations("config.table");
+}
+
+#[test]
+fn configure_alias_is_dense_and_adds_rows() {
+ configurations("config.configure");
+}
+
+#[test]
+fn parameters_are_dense_and_keep_inline_edits_order_and_undo() {
+ let mut h = fixture();
+ h.app.run("parameters.add", json!({"name":"height","expression":"20 mm"})).unwrap();
+ h.app.start("parameters.change");
+ h.frames(4);
+ chrome(&h);
+ for label in ["Name", "Unit", "Expression", "Value", "Comment", "Actions"] {
+ assert!(scenario::rect_of(&format!("dialog:column:user:{label}")).is_some());
+ }
+ h.step(&json!({"click":{"handle":"param:height"}})).unwrap();
+ h.step(&json!({"key":"A","cmd":true})).unwrap();
+ h.step(&json!({"text":"25 mm"})).unwrap();
+ h.step(&json!({"key":"Enter"})).unwrap();
+ assert_eq!(h.app.session.doc.param("height").unwrap().expr, "25 mm");
+ assert!(h.app.params.is_some(), "cell Enter does not close the editor");
+ h.step(&json!({"click":{"handle":"param:before:height"}})).unwrap();
+ let names: Vec<_> = h.app.session.doc.params.iter().filter(|p| !p.model).map(|p| p.name.as_str()).collect();
+ assert_eq!(names, ["height", "width"]);
+ h.app.run("edit.undo", json!({})).unwrap();
+ let names: Vec<_> = h.app.session.doc.params.iter().filter(|p| !p.model).map(|p| p.name.as_str()).collect();
+ assert_eq!(names, ["width", "height"]);
+ h.step(&json!({"click":{"handle":"params:close"}})).unwrap();
+ assert!(h.app.params.is_none());
+}
+
+#[test]
+fn material_review_is_dense_and_cancel_keeps_history() {
+ let mut h = fixture();
+ let before = (h.app.session.doc.clone(), h.app.session.undo.len());
+ h.app.start("material.properties.validate");
+ h.frames(3);
+ chrome(&h);
+ assert!(h.widget("Review card").is_some());
+ h.step(&json!({"click":{"handle":"dialog:cancel"}})).unwrap();
+ assert!(h.app.material_card_review.is_none());
+ assert!(std::sync::Arc::ptr_eq(&before.0, &h.app.session.doc));
+ assert_eq!(before.1, h.app.session.undo.len());
+}
+
+#[test]
+fn wide_managers_leave_the_active_sketch_palette_visible() {
+ for command in ["parameters.change", "config.table", "material.properties.validate"] {
+ for width in [1000, 1600] {
+ let mut h = fixture();
+ h.call("ui.resize", json!({"width":width,"height":1000}));
+ h.app.run("sketch.create", json!({"plane":"XY"})).unwrap();
+ h.frames(3);
+ h.app.start(command);
+ h.frames(4);
+ let palette = h.app.viewport.palette_rect.unwrap();
+ let header = scenario::rect_of("dialog:header").unwrap();
+ assert!(header.right() <= palette.left(), "{command}, {width}: {header:?} overlaps {palette:?}");
+ assert!(h.ctx.content_rect().contains_rect(header));
+ assert!(scenario::handle_at("sketch_palette:status_header").is_some());
+ }
+ }
+}
+
+#[test]
+fn appearance_card_keeps_the_standard_width_with_no_preselection() {
+ let mut h = fixture();
+ h.app.session.selection.clear();
+ h.app.start("appearance.assign");
+ h.frames(4);
+ let header = scenario::rect_of("dialog:header").unwrap();
+ let card = h.ctx.memory(|m| m.area_rect(egui::Id::new(("sc_dialog", "APPEARANCE")))).unwrap();
+ assert!(card.width() <= Tokens::get().form_card_width + 2.0, "card {card:?}, header {header:?}");
+}
diff --git a/crates/ui-egui/src/material_card_review.rs b/crates/ui-egui/src/material_card_review.rs
index 4205d1257c..bb09e9b267 100644
--- a/crates/ui-egui/src/material_card_review.rs
+++ b/crates/ui-egui/src/material_card_review.rs
@@ -1,10 +1,8 @@
//! Candidate review through the existing validator, independent of assigned-card persistence.
-use crate::fonts::RichTextExt as _;
-use egui::RichText;
use serde_json::{Value, json};
use solidcraft_engine::doc::physical_material::{Family, MaterialCard, PropertyData, admit_card};
-use crate::{SolveApp, i18n::tr, theme::Tokens};
+use crate::{SolveApp, i18n::tr, ui_kit};
const MAX_BYTES: usize = 256 * 1024;
const KINDS: [&str; 9] = [
@@ -51,50 +49,80 @@ impl ReviewWindow {
/// Open only through ui.start; executing the validator never opens a window.
pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
let Some(mut window) = app.material_card_review.take() else { return };
- let mut open = true;
+ let viewport = crate::shell::content_rect(app, app.viewport.rect.unwrap_or_else(|| ctx.content_rect()));
+ if !viewport.is_finite() || !viewport.is_positive() {
+ app.material_card_review = Some(window);
+ return;
+ }
+ let palette = app.viewport.palette_rect.filter(|r| r.is_finite() && r.is_positive());
+ let side =
+ if palette.is_some() && crate::sketch_palette::fits_beside_a_dialog(app, ctx) { crate::frame::Side::Left } else { crate::frame::Side::Right };
+ let top = crate::shell::panel_top(app, viewport, viewport.bottom(), side);
+ let docked = egui::pos2(side.anchor_x(viewport), top);
+ let title = tr("ui.material_review.title");
+ let moved = crate::frame::dock_offset(ctx, "material_card_review");
+ let anchor = crate::frame::offset_anchor(docked, moved, viewport, side);
+ let panel = ui_kit::Panel::new(
+ title,
+ egui::Id::new("sc_material_card_review"),
+ anchor,
+ viewport,
+ side,
+ ui_kit::Panel::feature_frame(ctx, app.ui.layout, side),
+ )
+ .wide();
+ let panel = if side == crate::frame::Side::Left {
+ let available = palette.map_or(viewport.width(), |r| (r.left() - viewport.left() - crate::theme::Tokens::get().space_8).max(0.0));
+ panel.width((crate::theme::Tokens::get().form_card_width * 3.0).min(available))
+ } else {
+ panel
+ };
let mut close = false;
- crate::frame::window(ctx, tr("ui.material_review.title"), crate::frame::Width::Wide)
- .id(egui::Id::new("sc_material_card_review"))
- .open(&mut open)
- .show(ctx, |ui| {
- ui.label(tr("ui.material_review.scope"));
- egui::ScrollArea::vertical().max_height((ctx.content_rect().height() - 180.0).max(100.0)).show(ui, |ui| {
- ui.label(tr("ui.material_review.input"));
- let response = ui.add(
- egui::TextEdit::multiline(&mut window.input)
- .id(egui::Id::new("sc_material_card_input"))
- .desired_width(f32::INFINITY)
- .desired_rows(5)
- .char_limit(MAX_BYTES),
- );
+ panel.window().show(ctx, |ui| {
+ let (closed, action) = panel.feature(
+ ui,
+ ui_kit::FeatureOptions {
+ icon: solidcraft_engine::find_command("material.properties.validate").map_or("", |c| c.icon),
+ title,
+ drag_key: "material_card_review",
+ moved,
+ docked,
+ apply_label: None,
+ },
+ false,
+ true,
+ |ui| {
+ ui_kit::hint(ui, "manage", tr("ui.material_review.scope"));
+ ui_kit::text_block(ui, "material_input_label", tr("ui.material_review.input"), false);
+ let response =
+ ui_kit::text_area(ui, tr("ui.material_review.input"), egui::Id::new("sc_material_card_input"), &mut window.input, 5, MAX_BYTES);
+ crate::scenario::publish_handle("review:input", response.rect.center());
if response.changed() {
window.reviewed = None;
window.error = None;
}
- if ui.button(tr("ui.material_review.review")).clicked() {
+ if ui_kit::secondary_button(ui, tr("ui.material_review.review")).clicked() {
window.review(app);
}
if let Some(error) = &window.error {
- ui.colored_label(Tokens::get().error, error);
+ ui_kit::text_block(ui, "material_error", error, true);
}
if let Some((card, report)) = &window.reviewed {
show_card(ui, card, report);
}
- });
- ui.separator();
- close = ui.button(tr("ui.close")).clicked();
- });
- if open && !close {
+ ui_kit::ComputeStatus { text: None, busy: false, applying: false }
+ },
+ );
+ close = closed || matches!(action, ui_kit::Action::Ok | ui_kit::Action::Cancel);
+ });
+ if !close {
app.material_card_review = Some(window);
}
}
fn value(ui: &mut egui::Ui, field: &str, value: Option<String>, unit: &str) {
- ui.horizontal_wrapped(|ui| {
- ui.monospace(field);
- ui.label(value.unwrap_or_else(|| tr("ui.material_review.unknown").to_string()));
- ui.label(unit);
- });
+ let value = value.unwrap_or_else(|| tr("ui.material_review.unknown").to_string());
+ ui_kit::text_block(ui, field, &format!("{field}: {value} {unit}"), false);
}
fn numbers(ui: &mut egui::Ui, field: &str, values: &[f64], unit: &str) {
@@ -102,19 +130,19 @@ fn numbers(ui: &mut egui::Ui, field: &str, values: &[f64], unit: &str) {
}
fn show_card(ui: &mut egui::Ui, card: &MaterialCard, report: &Value) {
- ui.separator();
- ui.heading(&card.designation);
+ ui_kit::divider(ui, "material_card");
+ ui_kit::text_block(ui, "designation", &card.designation, false);
// Schema identifiers are inert metadata, not translated source claims or assigned body axes.
let family = serde_json::to_value(card.family).unwrap_or(Value::Null);
value(ui, "family", family.as_str().map(str::to_string), "");
- ui.label(egui::RichText::new(tr("ui.material_review.properties")).semibold().color(crate::theme::Tokens::get().text));
+ ui_kit::text_block(ui, "properties", tr("ui.material_review.properties"), false);
for kind in KINDS {
let label = format!("ui.material_review.{kind}");
let Some(property) = card.properties.iter().find(|p| p.data.kind() == kind) else {
- ui.label(format!("{}: {}", tr(&label), tr("ui.material_review.unknown")));
+ ui_kit::text_block(ui, kind, &format!("{}: {}", tr(&label), tr("ui.material_review.unknown")), false);
continue;
};
- egui::CollapsingHeader::new(tr(&label)).id_salt(kind).default_open(true).show(ui, |ui| {
+ ui_kit::section(ui, kind, tr(&label), true, |ui| {
show_data(ui, &property.data);
if let Some(axes) = serde_json::to_value(&property.data)
.ok()
@@ -122,9 +150,9 @@ fn show_card(ui: &mut egui::Ui, card: &MaterialCard, report: &Value) {
{
let axes = if axes == "wood_lrt" { "wood_lrt (1=L, 2=R, 3=T)".to_string() } else { axes };
value(ui, "axes", Some(axes), "");
- ui.label(tr("ui.material_review.axes"));
+ ui_kit::text_block(ui, "axes", tr("ui.material_review.axes"), false);
}
- ui.label(egui::RichText::new(tr("ui.material_review.conditions")).semibold().color(crate::theme::Tokens::get().text));
+ ui_kit::text_block(ui, "conditions", tr("ui.material_review.conditions"), false);
let c = &property.conditions;
value(ui, "temperature_k", c.temperature_k.map(|v| v.to_string()), "K");
value(ui, "state", c.state.clone(), "");
@@ -134,9 +162,9 @@ fn show_card(ui: &mut egui::Ui, card: &MaterialCard, report: &Value) {
if card.family == Family::Polymer || c.strain_rate_per_s.is_some() {
value(ui, "strain_rate_per_s", c.strain_rate_per_s.map(|v| v.to_string()), "s⁻¹");
}
- ui.label(egui::RichText::new(tr("ui.material_review.source")).semibold().color(crate::theme::Tokens::get().text));
+ ui_kit::text_block(ui, "source", tr("ui.material_review.source"), false);
if let Some(source) = card.sources.iter().find(|s| s.id == property.source_id) {
- ui.label(&source.title);
+ ui_kit::text_block(ui, "source_title", &source.title, false);
value(ui, "source_id", Some(source.id.clone()), "");
value(ui, "kind", serde_json::to_value(source.kind).ok().and_then(|v| v.as_str().map(str::to_string)), "");
value(ui, "license", source.license.clone(), "");
@@ -145,12 +173,12 @@ fn show_card(ui: &mut egui::Ui, card: &MaterialCard, report: &Value) {
});
}
if let Some(moduli) = report.get("validation").and_then(|v| v.get("isotropic_moduli")).filter(|v| v.is_object()) {
- ui.label(egui::RichText::new(tr("ui.material_review.derived")).semibold().color(crate::theme::Tokens::get().text));
+ ui_kit::text_block(ui, "derived", tr("ui.material_review.derived"), false);
for field in ["shear_pa", "bulk_pa"] {
value(ui, field, moduli.get(field).and_then(Value::as_f64).map(|v| format!("{v:e}")), "Pa");
}
}
- ui.label(RichText::new(tr("ui.material_review.claims")).small().color(Tokens::get().text_dim));
+ ui_kit::note(ui, "claims", tr("ui.material_review.claims"));
}
fn show_data(ui: &mut egui::Ui, data: &PropertyData) {
@@ -218,11 +246,11 @@ mod tests {
assert_eq!(report["validation"]["source_review_required"], json!(["example"]));
assert!(h.widget("Original synthetic candidate").is_some());
assert!(h.widget("Density: Unknown").is_some());
- assert!(h.widget("Pa").is_some());
+ assert!(h.widget("E: 1.2e10 Pa").is_some());
h.ctx.memory_mut(|m| m.request_focus(egui::Id::new("sc_material_card_input")));
h.step(&json!({"text":" "})).unwrap();
assert!(h.app.material_card_review.as_ref().unwrap().reviewed.is_none(), "editing invalidates the old report");
- h.step(&json!({"widget":"Close"})).unwrap();
+ h.step(&json!({"click":{"handle":"dialog:close"}})).unwrap();
assert!(h.app.material_card_review.is_none());
assert!(Arc::ptr_eq(&doc, &h.app.session.doc));
assert_eq!(
@@ -282,7 +310,14 @@ mod tests {
h.frames(2);
h.step(&json!({"widget":"Review card"})).unwrap();
assert!(h.app.material_card_review.as_ref().unwrap().error.is_none(), "{card}");
- assert!(h.widget(unit).is_some(), "expected {unit} for {card}");
+ assert!(
+ h.output
+ .accesskit_update
+ .iter()
+ .flat_map(|tree| &tree.nodes)
+ .any(|(_, node)| node.label().or_else(|| node.value()).is_some_and(|label| label.ends_with(unit))),
+ "expected {unit} for {card}"
+ );
assert!(h.widget("Original illustrative <b>source</b>").is_some(), "source is displayed as literal text");
}
}
diff --git a/crates/ui-egui/src/measurement_ui_tests.rs b/crates/ui-egui/src/measurement_ui_tests.rs
index a22fb51495..7d907cefd9 100644
--- a/crates/ui-egui/src/measurement_ui_tests.rs
+++ b/crates/ui-egui/src/measurement_ui_tests.rs
@@ -127,10 +127,18 @@ fn measurement_axis_distances_can_be_disabled_saved_and_restored_in_preferences(
let mut h = vertex_measurement([0., 0., 0.], [-3., 4., -12.]);
let measurement = result(&h).clone();
h.call("ui.prefs", json!({"open":"Graphics"}));
- // The graphics page scrolls; the checkbox sits below the fold since the graphics preset
- // and ambient occlusion rows were added, so scroll to it as the scenario tests do.
- h.call("ui.scroll", json!({"x":800.0,"y":500.0,"delta":-3000.0}));
- let checkbox = crate::scenario::rect_of("prefs:measure_axis_distances").unwrap().center();
+ // The kit's 24 pt rows scroll inside the bounded Preferences page.
+ let page = crate::scenario::rect_of("prefs:page_body").unwrap();
+ for _ in 0..8 {
+ if page.contains_rect(crate::scenario::rect_of("prefs:measure_axis_distances").unwrap()) {
+ break;
+ }
+ h.call("ui.scroll", json!({"x":page.center().x,"y":page.center().y,"delta":-100}));
+ h.frames(12);
+ }
+ let checkbox_rect = crate::scenario::rect_of("prefs:measure_axis_distances").unwrap();
+ assert!(page.contains_rect(checkbox_rect), "the toggle must be visible before clicking: {checkbox_rect:?} in {page:?}");
+ let checkbox = checkbox_rect.center();
h.call("ui.click", json!({"x":checkbox.x,"y":checkbox.y}));
assert!(!h.app.preferences.measure_axis_distances);
assert!(crate::scenario::handle_at("measure:label").is_some(), "total stays visible");
diff --git a/crates/ui-egui/src/params_dialog.rs b/crates/ui-egui/src/params_dialog.rs
index 0a73a70a5f..ea3f60f27a 100644
--- a/crates/ui-egui/src/params_dialog.rs
+++ b/crates/ui-egui/src/params_dialog.rs
@@ -9,14 +9,12 @@
//! [`complete`] adds suggestions (parameters, functions, units) under any expression box: the
//! names come from `parameters.complete`, cached per document revision by [`publish`].
-use crate::fonts::RichTextExt as _;
use std::sync::Arc;
-use egui::RichText;
use serde_json::{Value, json};
use crate::SolveApp;
-use crate::theme::Tokens;
+use crate::ui_kit::{self, Column};
const UNITS: [&str; 9] = ["mm", "cm", "m", "in", "ft", "deg", "rad", "", "um"];
/// The expression a new parameter row starts with.
@@ -138,100 +136,121 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
publish(app, ctx);
}
let Some(mut d) = app.params.take() else { return };
- let t = Tokens::get();
- let mut open = true;
- let all = if let Some((rev, r)) = d.listed.as_ref().filter(|(rev, _)| *rev == app.session.revision) {
- let _ = rev;
- r.clone()
+ ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter));
+ let viewport = crate::shell::content_rect(app, app.viewport.rect.unwrap_or_else(|| ctx.content_rect()));
+ if !viewport.is_finite() || !viewport.is_positive() {
+ app.params = Some(d);
+ return;
+ }
+ let palette = app.viewport.palette_rect.filter(|r| r.is_finite() && r.is_positive());
+ let side =
+ if palette.is_some() && crate::sketch_palette::fits_beside_a_dialog(app, ctx) { crate::frame::Side::Left } else { crate::frame::Side::Right };
+ let top = crate::shell::panel_top(app, viewport, viewport.bottom(), side);
+ let docked = egui::pos2(side.anchor_x(viewport), top);
+ let moved = crate::frame::dock_offset(ctx, "PARAMETERS");
+ let anchor = crate::frame::offset_anchor(docked, moved, viewport, side);
+ let title = crate::i18n::tr_label("PARAMETERS");
+ let panel =
+ ui_kit::Panel::new(title, egui::Id::new("sc_params_dialog"), anchor, viewport, side, ui_kit::Panel::feature_frame(ctx, app.ui.layout, side))
+ .wide();
+ let panel = if side == crate::frame::Side::Left {
+ let available = palette.map_or(viewport.width(), |r| (r.left() - viewport.left() - crate::theme::Tokens::get().space_8).max(0.0));
+ panel.width((crate::theme::Tokens::get().form_card_width * 3.0).min(available))
+ } else {
+ panel
+ };
+ let all = if let Some((_, rows)) = d.listed.as_ref().filter(|(rev, _)| *rev == app.session.revision) {
+ rows.clone()
} else {
- let r = Arc::new(rows(app));
- d.listed = Some((app.session.revision, r.clone()));
+ let rows = Arc::new(rows(app));
+ d.listed = Some((app.session.revision, rows.clone()));
d.lists += 1;
- r
+ rows
};
- crate::frame::window(
- ctx,
- RichText::new(crate::i18n::tr_label("PARAMETERS"))
- .semibold()
- .color(crate::theme::Tokens::get().text)
- .size(crate::theme::Tokens::get().font_button),
- crate::frame::Width::Wide,
- )
- .id(egui::Id::new("sc_params_dialog"))
- .open(&mut open)
- .default_width(740.0)
- .default_height(520.0)
- .resizable(true)
- .collapsible(false)
- .show(ctx, |ui| {
- ui.horizontal(|ui| {
- ui.add(egui::TextEdit::singleline(&mut d.filter).hint_text(crate::i18n::tr_label("Filter")).desired_width(180.0));
- ui.separator();
- if ui.button("Import…").on_hover_text(crate::i18n::tr_label("CSV or JSON: updates existing parameters, adds new ones")).clicked() {
- app.pick_open_command("parameters.import", json!({}), &[]);
- }
- for (label, ext) in [("Export CSV…", "csv"), ("Export JSON…", "json")] {
- if ui.button(label).clicked() {
- app.pick_save_command(&format!("parameters.{ext}"), &[ext], "parameters.export", json!({"format": ext}));
+ let mut close = false;
+ panel.window().show(ctx, |ui| {
+ let (closed, action) = panel.feature(
+ ui,
+ ui_kit::FeatureOptions {
+ icon: solidcraft_engine::find_command("parameters.change").map_or("", |c| c.icon),
+ title,
+ drag_key: "PARAMETERS",
+ moved,
+ docked,
+ apply_label: None,
+ },
+ false,
+ true,
+ |ui| {
+ ui_kit::hint(ui, "manage", crate::i18n::tr("manage.parameters_hint"));
+ ui_kit::row(ui, "Filter", |ui| {
+ let id = ui.make_persistent_id("parameter_filter");
+ ui_kit::search_field(ui, id, &mut d.filter, "Filter");
+ });
+ ui.horizontal_wrapped(|ui| {
+ if ui_kit::secondary_button(ui, crate::i18n::tr_label("Import…"))
+ .on_hover_text(crate::i18n::tr_label("CSV or JSON: updates existing parameters, adds new ones"))
+ .clicked()
+ {
+ app.pick_open_command("parameters.import", json!({}), &[]);
+ }
+ for (label, ext) in [("Export CSV…", "csv"), ("Export JSON…", "json")] {
+ if ui_kit::secondary_button(ui, crate::i18n::tr_label(label)).clicked() {
+ app.pick_save_command(&format!("parameters.{ext}"), &[ext], "parameters.export", json!({"format": ext}));
+ }
+ }
+ });
+ if let Some(error) = &d.error {
+ ui_kit::text_block(ui, "parameters_error", error, true);
}
- }
- });
- if let Some(e) = &d.error {
- ui.label(RichText::new(e).color(t.error));
- }
- ui.separator();
- let f = d.filter.to_ascii_lowercase();
- let visible: Vec<&Row> = all
- .iter()
- .filter(|r| {
- f.is_empty()
- || r.name.to_ascii_lowercase().contains(&f)
- || r.comment.to_ascii_lowercase().contains(&f)
- || r.group.to_ascii_lowercase().contains(&f)
- })
- .collect();
- egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
- let favs: Vec<&Row> = visible.iter().copied().filter(|r| r.favorite).collect();
- if !favs.is_empty() {
- section(ui, &t, "Favorites");
- table(app, ui, &mut d, &favs, "fav");
- }
- section(ui, &t, "User Parameters");
- let users: Vec<&Row> = visible.iter().copied().filter(|r| r.source == "user").collect();
- table(app, ui, &mut d, &users, "user");
- section(ui, &t, "Model Parameters");
- let mut groups: Vec<String> = Vec::new();
- for r in visible.iter().filter(|r| r.source != "user") {
- if !groups.contains(&r.group) {
- groups.push(r.group.clone());
+ let filter = d.filter.to_ascii_lowercase();
+ let visible: Vec<_> = all
+ .iter()
+ .filter(|r| {
+ filter.is_empty()
+ || r.name.to_ascii_lowercase().contains(&filter)
+ || r.comment.to_ascii_lowercase().contains(&filter)
+ || r.group.to_ascii_lowercase().contains(&filter)
+ })
+ .collect();
+ let favorites: Vec<_> = visible.iter().copied().filter(|r| r.favorite).collect();
+ if !favorites.is_empty() {
+ ui_kit::section(ui, "favorites", "Favorites", true, |ui| table(app, ui, &mut d, &favorites, "fav"));
}
- }
- for g in groups {
- let members: Vec<&Row> = visible.iter().copied().filter(|r| r.source != "user" && r.group == g).collect();
- egui::CollapsingHeader::new(RichText::new(&g).semibold().color(crate::theme::Tokens::get().text))
- .id_salt(("pgroup", &g))
- .default_open(true)
- .show(ui, |ui| {
- table(app, ui, &mut d, &members, &g);
- });
- }
- });
+ ui_kit::section(ui, "users", "User Parameters", true, |ui| {
+ let users: Vec<_> = visible.iter().copied().filter(|r| r.source == "user").collect();
+ table(app, ui, &mut d, &users, "user");
+ add_row(app, ui, &mut d);
+ });
+ ui_kit::section(ui, "models", "Model Parameters", true, |ui| {
+ let mut groups = Vec::new();
+ for r in visible.iter().filter(|r| r.source != "user") {
+ if !groups.contains(&r.group) {
+ groups.push(r.group.clone());
+ }
+ }
+ for group in groups {
+ let members: Vec<_> = visible.iter().copied().filter(|r| r.source != "user" && r.group == group).collect();
+ ui_kit::section(ui, ("pgroup", &group), &group, true, |ui| table(app, ui, &mut d, &members, &group));
+ }
+ });
+ ui_kit::ComputeStatus { text: None, busy: false, applying: false }
+ },
+ );
+ close = closed || matches!(action, ui_kit::Action::Ok | ui_kit::Action::Cancel);
});
- // The title bar's close button, for scenarios and demos.
- if let Some(r) = ctx.memory(|m| m.area_rect(egui::Id::new("sc_params_dialog"))) {
- crate::scenario::publish_handle("params:close", egui::pos2(r.right() - 16.0, r.top() + 15.0));
- crate::scenario::publish_handle("params:title", egui::pos2(r.center().x, r.top() + 15.0));
+ // Each cell owns fresh Enter from raw events. The panel itself must not submit on
+ // Enter in the filter or with unrelated focus (the legacy editor left those alone), but
+ // the filter, rename and comment fields still see Enter first to give up focus.
+ if let Some(at) = crate::scenario::handle_at("dialog:close") {
+ crate::scenario::publish_handle("params:close", at);
}
- if !open {
- app.params = None;
- return;
+ if let Some(rect) = crate::scenario::rect_of("dialog:header") {
+ crate::scenario::publish_handle("params:title", rect.center());
+ }
+ if !close {
+ app.params = Some(d);
}
- app.params = Some(d);
-}
-
-fn section(ui: &mut egui::Ui, t: &Tokens, title: &str) {
- ui.add_space(6.0);
- ui.label(RichText::new(title).semibold().color(t.text));
}
/// Live check of an expression typed for a parameter of this unit: Ok(shown value) or the message.
@@ -259,175 +278,151 @@ fn new_check(app: &mut SolveApp, d: &mut ParamsDialog, unit: &str) -> Result<Str
r
}
-/// Height of a row in the tables: tall enough for the text boxes and the combo box.
-fn row_height(ui: &egui::Ui) -> f32 {
- ui.spacing().interact_size.y.max(20.0)
-}
-
fn table(app: &mut SolveApp, ui: &mut egui::Ui, d: &mut ParamsDialog, rows: &[&Row], salt: &str) {
- let t = Tokens::get();
- egui::Grid::new(("ptable", salt)).num_columns(7).striped(true).spacing([10.0, 4.0]).show(ui, |ui| {
- for h in ["", "Name", "Unit", "Expression", "Value", "Comment", ""] {
- let resp = ui.label(RichText::new(h).color(t.text_dim).small());
- crate::scenario::publish_rect(&format!("param:heading:{salt}:{h}"), resp.rect);
- }
- ui.end_row();
- // Only the rows in view are laid out (#2723); the others take their height, so the
- // scroll bar and the columns stay as they are. A row being edited stays drawn.
- let row_h = row_height(ui);
- let clip = ui.clip_rect();
- for (i, r) in rows.iter().enumerate() {
- let top = ui.cursor().min.y;
- let in_view = top + row_h >= clip.min.y && top <= clip.max.y;
- let busy = d.editing.contains_key(&r.name) || d.comments.contains_key(&r.name) || d.renaming.as_ref().is_some_and(|(o, _)| *o == r.name);
- if !in_view && !busy {
- ui.allocate_space(egui::vec2(0.0, row_h));
- ui.end_row();
- continue;
- }
- ui.horizontal(|ui| {
- ui.set_min_height(row_h);
- // Favourite star.
- let star = if r.favorite { RichText::new("★").color(t.accent) } else { RichText::new("☆").color(t.text_dim) };
- if ui.add(egui::Button::new(star).frame(false)).on_hover_text(crate::i18n::tr_label("Favourite")).clicked() {
- d.error = app.run("parameters.favorite", json!({"name": r.name, "favorite": !r.favorite})).err();
- }
- // Up and down past the neighbouring user parameter (#1187), in the user table only:
- // the favourites table lists favourites first whatever their order.
- if salt == "user" {
- for (glyph, tip, neighbour, side) in
- [("▲", "Move up", i.checked_sub(1).and_then(|j| rows.get(j)), "before"), ("▼", "Move down", rows.get(i + 1), "after")]
- {
- let button = egui::Button::new(RichText::new(glyph).small().color(t.text_dim)).frame_when_inactive(false);
- let resp = ui.add_enabled(neighbour.is_some(), button).on_hover_text(crate::i18n::tr_label(tip));
- crate::scenario::publish_handle(&format!("param:{}:{}", side, r.name), resp.rect.center());
- if resp.clicked()
- && let Some(n) = neighbour
+ let columns = [
+ Column { label: "", width: 1.6 },
+ Column { label: "Name", width: 1.1 },
+ Column { label: "Unit", width: 0.65 },
+ Column { label: "Expression", width: 1.6 },
+ Column { label: "Value", width: 1.2 },
+ Column { label: "Comment", width: 1.5 },
+ Column { label: "Actions", width: 0.7 },
+ ];
+ ui_kit::table(ui, salt, &columns, crate::i18n::tr("manage.empty"), |ui, table| {
+ for (index, r) in rows.iter().enumerate() {
+ // Skip cells outside the clip while preserving the table's row geometry (#2723).
+ // Drafts remain live until their edits have been committed.
+ let busy =
+ d.editing.contains_key(&r.name) || d.comments.contains_key(&r.name) || d.renaming.as_ref().is_some_and(|(old, _)| *old == r.name);
+ table.row_visible(ui, &r.name, false, busy, |row| {
+ row.cell(|ui| {
+ let star = if r.favorite { "★" } else { "☆" };
+ if ui_kit::small_button(ui, star).on_hover_text(crate::i18n::tr_label("Favourite")).clicked() {
+ d.error = app.run("parameters.favorite", json!({"name": r.name, "favorite": !r.favorite})).err();
+ }
+ if salt == "user" {
+ for (glyph, tip, neighbour, side) in [
+ ("▲", "Move up", index.checked_sub(1).and_then(|i| rows.get(i)), "before"),
+ ("▼", "Move down", rows.get(index + 1), "after"),
+ ] {
+ let response = ui_kit::enabled_button(ui, glyph, neighbour.is_some()).on_hover_text(crate::i18n::tr_label(tip));
+ crate::scenario::publish_handle(&format!("param:{side}:{}", r.name), response.rect.center());
+ if response.clicked()
+ && let Some(neighbour) = neighbour
+ {
+ d.error = app.run("parameters.move", json!({"name":r.name, side:neighbour.name})).err();
+ }
+ }
+ }
+ });
+ row.cell(|ui| match &mut d.renaming {
+ Some((old, new)) if *old == r.name => {
+ let id = ui.make_persistent_id(("rename", &r.name));
+ let focused = ui.memory(|m| m.has_focus(id) || m.had_focus_last_frame(id));
+ let response = ui_kit::cell_editor(ui, id, new, "Name", false);
+ let entered = enter_for(ui, focused);
+ if response.lost_focus() || entered {
+ let (old, new) = (old.clone(), new.trim().to_owned());
+ if !new.is_empty() && new != old {
+ d.error = app.run("parameters.rename", json!({"name":old,"new_name":new})).err();
+ }
+ d.renaming = None;
+ } else if !response.has_focus() {
+ response.request_focus();
+ }
+ }
+ _ => {
+ let response = ui_kit::cell_text(ui, &r.name).on_hover_text(crate::i18n::tr_label("Double-click to rename"));
+ crate::scenario::publish_handle(&format!("param:name:{}", r.name), response.rect.center());
+ if response.double_clicked() {
+ d.renaming = Some((r.name.clone(), r.name.clone()));
+ }
+ }
+ });
+ row.cell(|ui| {
+ if r.source == "user" {
+ let mut selected = UNITS.iter().position(|u| *u == r.unit).unwrap_or(0);
+ let before = selected;
+ let labels: Vec<_> = UNITS.iter().map(|u| unit_label(u)).collect();
+ ui_kit::dropdown(ui, &format!("punit:{salt}:{}", r.name), &mut selected, &labels);
+ if selected != before
+ && let Some(unit) = UNITS.get(selected)
{
- d.error = app.run("parameters.move", json!({"name": r.name, side: n.name})).err();
+ d.error = app.run("parameters.change", json!({"name":r.name,"expression":r.expression,"unit":unit})).err();
}
+ } else {
+ ui_kit::cell_text(ui, unit_label(&r.unit));
}
- }
- });
- // Name: double-click to rename.
- match &mut d.renaming {
- Some((old, new)) if *old == r.name => {
- let resp = ui.add_sized([110.0, 20.0], egui::TextEdit::singleline(new));
- if resp.lost_focus() {
- let (old, new) = (old.clone(), new.trim().to_string());
- if !new.is_empty() && new != old {
- d.error = app.run("parameters.rename", json!({"name": old, "new_name": new})).err();
+ });
+ let mut expression = d.editing.get(&r.name).cloned().unwrap_or_else(|| r.expression.clone());
+ let live = (expression != r.expression).then(|| check(app, &expression, &r.unit));
+ let invalid = matches!(live, Some(Err(_))) || (live.is_none() && r.error.is_some());
+ row.cell(|ui| {
+ let id = ui.make_persistent_id(("pexpr", salt, &r.name));
+ let focused = ui.memory(|m| m.has_focus(id) || m.had_focus_last_frame(id));
+ let response = ui_kit::cell_editor(ui, id, &mut expression, "Expression", invalid);
+ crate::scenario::publish_handle(&format!("param:{}", r.name), response.rect.center());
+ if salt == "fav" {
+ crate::scenario::publish_handle(&format!("param:favorite:{}", r.name), response.rect.center());
+ }
+ let completed = complete(ui, &response, &mut expression);
+ if response.changed() || completed {
+ d.editing.insert(r.name.clone(), expression.clone());
+ }
+ if response.has_focus() && matches!(live, Some(Ok(_))) {
+ d.preview = Some((r.name.clone(), expression.clone()));
+ }
+ let entered = !completed && enter_for(ui, focused);
+ if !completed && (response.lost_focus() || entered) {
+ d.preview = None;
+ if expression != r.expression {
+ d.error = check(app, &expression, &r.unit)
+ .and_then(|_| app.run("parameters.change", json!({"name":r.name,"expression":expression})))
+ .err();
+ if d.error.is_none() {
+ d.editing.remove(&r.name);
+ }
+ } else {
+ d.editing.remove(&r.name);
}
- d.renaming = None;
- } else if !resp.has_focus() {
- // Only take focus once: requesting it every frame resets the text box's
- // focus lock, so arrow keys would move focus away and end the rename.
- resp.request_focus();
}
- }
- _ => {
- let name = if r.source == "user" { RichText::new(&r.name) } else { RichText::new(&r.name).color(t.text_dim) };
- let resp =
- ui.add(egui::Label::new(name).sense(egui::Sense::click())).on_hover_text(crate::i18n::tr_label("Double-click to rename"));
- crate::scenario::publish_handle(&format!("param:name:{}", r.name), resp.rect.center());
- if resp.double_clicked() {
- d.renaming = Some((r.name.clone(), r.name.clone()));
+ });
+ row.cell(|ui| {
+ let (text, error) = match (&live, &r.error) {
+ (Some(Err(message)), _) | (None, Some(message)) => (message.clone(), true),
+ (Some(Ok(value)), _) => (value.clone(), false),
+ (None, None) => (show_value(r), false),
+ };
+ ui_kit::text_block(ui, &format!("value:{}", r.name), &text, error).on_hover_text(&text);
+ });
+ row.cell(|ui| {
+ let mut comment = d.comments.get(&r.name).cloned().unwrap_or_else(|| r.comment.clone());
+ let id = ui.make_persistent_id(("comment", &r.name));
+ let focused = ui.memory(|m| m.has_focus(id) || m.had_focus_last_frame(id));
+ let response = ui_kit::cell_editor(ui, id, &mut comment, "Comment", false);
+ let entered = enter_for(ui, focused);
+ if response.changed() {
+ d.comments.insert(r.name.clone(), comment.clone());
}
- }
- }
- // Unit: user parameters choose it; others follow their input.
- if r.source == "user" {
- let mut sel = UNITS.iter().position(|u| *u == r.unit).unwrap_or(0);
- let before = sel;
- egui::ComboBox::from_id_salt(("punit", salt, &r.name)).width(56.0).selected_text(unit_label(&r.unit)).show_ui(ui, |ui| {
- for (i, u) in UNITS.iter().enumerate() {
- ui.selectable_value(&mut sel, i, unit_label(u));
+ if response.lost_focus() || entered {
+ if comment != r.comment {
+ d.error = app.run("parameters.comment", json!({"name":r.name,"comment":comment})).err();
+ }
+ d.comments.remove(&r.name);
}
});
- if sel != before
- && let Some(u) = UNITS.get(sel)
- {
- d.error = app.run("parameters.change", json!({"name": r.name, "expression": r.expression, "unit": u})).err();
- }
- } else {
- ui.label(RichText::new(unit_label(&r.unit)).color(t.text_dim));
- }
- // Expression: live check, applied on Enter or leaving the field.
- let mut e = d.editing.get(&r.name).cloned().unwrap_or_else(|| r.expression.clone());
- let live = if e != r.expression { Some(check(app, &e, &r.unit)) } else { None };
- let bad = matches!(live, Some(Err(_))) || (live.is_none() && r.error.is_some());
- let mut te = egui::TextEdit::singleline(&mut e).desired_width(170.0);
- if bad {
- te = te.text_color(t.error);
- }
- // Per table: a favourite is listed twice, and one id would give both boxes the focus and
- // each key to both (#1767).
- let id = ui.make_persistent_id(("pexpr", salt, &r.name));
- let focused = ui.memory(|m| m.has_focus(id));
- let resp = ui.add_sized([170.0, 20.0], te.id(id));
- crate::scenario::publish_handle(&format!("param:{}", r.name), resp.rect.center());
- if salt == "fav" {
- crate::scenario::publish_handle(&format!("param:favorite:{}", r.name), resp.rect.center());
- }
- let completed = complete(ui, &resp, &mut e);
- if resp.changed() || completed {
- d.editing.insert(r.name.clone(), e.clone());
- }
- if resp.has_focus() && matches!(live, Some(Ok(_))) {
- d.preview = Some((r.name.clone(), e.clone()));
- }
- if !completed && (resp.lost_focus() || enter_for(ui, focused)) {
- d.preview = None;
- if e != r.expression {
- let res = check(app, &e, &r.unit).and_then(|_| app.run("parameters.change", json!({"name": r.name, "expression": e})));
- d.error = res.err();
- if d.error.is_none() {
- d.editing.remove(&r.name);
+ row.cell(|ui| {
+ if r.source == "user" && ui_kit::small_button(ui, crate::i18n::tr_label("Delete")).clicked() {
+ d.error = app.run("parameters.delete", json!({"name":r.name})).err();
}
- } else {
- d.editing.remove(&r.name);
- }
- }
- // Value, or why it has none.
- match (&live, &r.error) {
- (Some(Err(m)), _) => ui.label(RichText::new(m).color(t.error)).on_hover_text(m),
- (Some(Ok(v)), _) => ui.label(RichText::new(v).color(t.accent)),
- (None, Some(m)) => ui.label(RichText::new(m).color(t.error)).on_hover_text(m),
- (None, None) => ui.label(RichText::new(show_value(r)).color(t.text_dim)),
- };
- // Comment.
- let mut c = d.comments.get(&r.name).cloned().unwrap_or_else(|| r.comment.clone());
- let cr = ui.add_sized([150.0, 20.0], egui::TextEdit::singleline(&mut c).hint_text("comment"));
- if cr.changed() {
- d.comments.insert(r.name.clone(), c.clone());
- }
- if cr.lost_focus() {
- if c != r.comment {
- d.error = app.run("parameters.comment", json!({"name": r.name, "comment": c})).err();
- }
- d.comments.remove(&r.name);
- }
- // Delete (user parameters; refused while used, the message says by what).
- if r.source == "user" {
- // Outlined on hover like the expression and comment fields; the label says what it does.
- if ui.add(egui::Button::new(RichText::new("Delete").small().color(t.text_dim)).frame_when_inactive(false)).clicked() {
- d.error = app.run("parameters.delete", json!({"name": r.name})).err();
- }
- } else {
- ui.label("");
- }
- ui.end_row();
- }
- // The add row is the user table's last row, so its fields sit under the headings,
- // with or without user parameters (#2920).
- if salt == "user" {
- add_row(app, ui, d);
+ });
+ });
}
});
}
fn unit_label(u: &str) -> &str {
- if u.is_empty() { "none" } else { u }
+ if u.is_empty() { crate::i18n::tr_label("none") } else { u }
}
/// Only a fresh Enter in this field submits; held keys and unrelated focus do not.
@@ -447,53 +442,36 @@ fn enter_for(ui: &mut egui::Ui, focused: bool) -> bool {
/// The add row, one cell per column of the user table it ends.
fn add_row(app: &mut SolveApp, ui: &mut egui::Ui, d: &mut ParamsDialog) {
- let t = Tokens::get();
+ let mut submit = false;
let name_id = ui.make_persistent_id("pnew_name");
let expr_id = ui.make_persistent_id("pnew_expr");
let comment_id = ui.make_persistent_id("pnew_comment");
let focused_id = ui.memory(|m| [name_id, expr_id, comment_id].into_iter().find(|id| m.has_focus(*id)));
- // The column of the favourite and move buttons.
- ui.label("");
- // Sized like the rows' boxes: in a grid cell a text box only gets the column's width so far.
- let name = ui.add_sized(
- [120.0, 20.0],
- egui::TextEdit::singleline(&mut d.new_name).id(name_id).hint_text(crate::i18n::tr_label("new parameter")).desired_width(120.0),
- );
+ let name = ui_kit::row(ui, "Name", |ui| ui_kit::cell_editor(ui, name_id, &mut d.new_name, "new parameter", false));
crate::scenario::publish_handle("param:new:name", name.rect.center());
- crate::scenario::publish_rect("param:new:name", name.rect);
- let unit_response = egui::ComboBox::from_id_salt("pnew_unit")
- .width(56.0)
- .selected_text(unit_label(UNITS.get(d.new_unit).copied().unwrap_or("mm")))
- .show_ui(ui, |ui| {
- for (i, u) in UNITS.iter().enumerate() {
- ui.selectable_value(&mut d.new_unit, i, unit_label(u));
- }
- });
- crate::scenario::publish_handle("param:new:unit", unit_response.response.rect.center());
- crate::scenario::publish_rect("param:new:unit", unit_response.response.rect);
+ let units: Vec<_> = UNITS.iter().map(|u| unit_label(u)).collect();
+ let unit_response = ui_kit::row(ui, "Unit", |ui| ui_kit::dropdown(ui, "pnew_unit", &mut d.new_unit, &units));
+ crate::scenario::publish_handle("param:new:unit", unit_response.rect.center());
let unit = UNITS.get(d.new_unit).copied().unwrap_or("mm");
- let bad = new_check(app, d, unit).is_err();
- let mut te = egui::TextEdit::singleline(&mut d.new_expr).id(expr_id).desired_width(170.0);
- if bad {
- te = te.text_color(t.error);
- }
- let resp = ui.add_sized([170.0, 20.0], te);
- crate::scenario::publish_handle("param:new:expression", resp.rect.center());
- crate::scenario::publish_rect("param:new:expression", resp.rect);
- let completed = complete(ui, &resp, &mut d.new_expr);
+ let invalid = new_check(app, d, unit).is_err();
+ ui_kit::row(ui, "Expression", |ui| {
+ let response = ui_kit::cell_editor(ui, expr_id, &mut d.new_expr, "Expression", invalid);
+ crate::scenario::publish_handle("param:new:expression", response.rect.center());
+ let completed = complete(ui, &response, &mut d.new_expr);
+ submit = !completed && enter_for(ui, focused_id.is_some());
+ });
let live = new_check(app, d, unit);
- let value = match &live {
- Ok(v) => ui.label(RichText::new(v).color(t.text_dim)),
- Err(m) => ui.label(RichText::new(m).color(t.error)),
+ let (text, error) = match &live {
+ Ok(value) => (value, false),
+ Err(message) => (message, true),
};
- crate::scenario::publish_rect("param:new:value", value.rect);
- let comment =
- ui.add_sized([150.0, 20.0], egui::TextEdit::singleline(&mut d.new_comment).id(comment_id).hint_text("comment").desired_width(150.0));
+ ui_kit::row(ui, "Value", |ui| ui_kit::text_block(ui, "new_value", text, error).on_hover_text(text));
+ let comment = ui_kit::row(ui, "Comment", |ui| ui_kit::cell_editor(ui, comment_id, &mut d.new_comment, "Comment", false));
crate::scenario::publish_handle("param:new:comment", comment.rect.center());
- crate::scenario::publish_rect("param:new:comment", comment.rect);
- let submit = !completed && enter_for(ui, focused_id.is_some());
- let ok = !d.new_name.trim().is_empty() && live.is_ok();
- if ui.add_enabled(ok, egui::Button::new(crate::i18n::tr_label("Add"))).clicked() || submit {
+ // Enter from name/comment owns submission too, not the panel footer.
+ submit |= enter_for(ui, focused_id.is_some());
+ let valid = !d.new_name.trim().is_empty() && live.is_ok();
+ if ui_kit::enabled_button(ui, "Add", valid).clicked() || submit {
if let Err(error) = &live {
d.error = Some(error.clone());
if let Some(id) = focused_id {
@@ -501,8 +479,8 @@ fn add_row(app: &mut SolveApp, ui: &mut egui::Ui, d: &mut ParamsDialog) {
}
return;
}
- let p = json!({"name": d.new_name.trim(), "expression": d.new_expr, "unit": unit, "comment": d.new_comment});
- match app.run("parameters.add", p) {
+ let params = json!({"name":d.new_name.trim(),"expression":d.new_expr,"unit":unit,"comment":d.new_comment});
+ match app.run("parameters.add", params) {
Ok(_) => {
d.new_name.clear();
d.new_expr = NEW_EXPR.into();
@@ -510,8 +488,8 @@ fn add_row(app: &mut SolveApp, ui: &mut egui::Ui, d: &mut ParamsDialog) {
d.error = None;
name.request_focus();
}
- Err(e) => {
- d.error = Some(e);
+ Err(error) => {
+ d.error = Some(error);
if let Some(id) = focused_id {
ui.memory_mut(|m| m.request_focus(id));
}
@@ -705,30 +683,4 @@ mod tests {
let d = h.app.params.as_ref().unwrap();
assert!(d.listed.as_ref().unwrap().1.iter().any(|r| r.name == "p1" && r.comment == "hello"));
}
-
- /// The add row's fields start where their headings do (#2920): before the first user
- /// parameter, when the headings stood over nothing, and with one. Its text boxes keep
- /// the rows' widths, so "new parameter" is not cut short.
- #[test]
- fn the_add_row_lines_up_with_the_headings() {
- let mut h = crate::scenario::Harness::new();
- h.app.home.open = false;
- h.step(&json!({"start": "parameters.change"})).unwrap();
- let aligned = |case: &str| {
- for (heading, field) in [("Name", "name"), ("Unit", "unit"), ("Expression", "expression"), ("Value", "value"), ("Comment", "comment")] {
- let head = crate::scenario::rect_of(&format!("param:heading:user:{heading}")).unwrap();
- let cell = crate::scenario::rect_of(&format!("param:new:{field}")).unwrap();
- assert!((head.left() - cell.left()).abs() < 0.5, "{case}: {heading} heading at x {}, its field at x {}", head.left(), cell.left());
- }
- for (field, width) in [("name", 120.0), ("expression", 170.0), ("comment", 150.0)] {
- let cell = crate::scenario::rect_of(&format!("param:new:{field}")).unwrap();
- assert!(cell.width() >= width - 0.5, "{case}: the {field} box is {} wide", cell.width());
- }
- };
- h.frames(3);
- aligned("no user parameter");
- h.app.run("parameters.add", json!({"name": "width", "expression": "40 mm", "unit": "mm"})).unwrap();
- h.frames(3);
- aligned("one user parameter");
- }
}
diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs
index c54a302fab..8bbb2db779 100644
--- a/crates/ui-egui/src/prefs.rs
+++ b/crates/ui-egui/src/prefs.rs
@@ -8,8 +8,7 @@
//! Apply keeps them and stays open, and Restore Defaults resets the page shown. Everything is
//! kept between runs, except anti-aliasing, which needs a restart.
-use crate::fonts::RichTextExt as _;
-use egui::{Modifiers, Pos2, RichText};
+use egui::{Modifiers, Pos2};
use serde::{Deserialize, Serialize};
use serde_json::json;
pub use solidcraft_engine::doc::display_units::{format_length, length_number, length_precision, unit_scale};
@@ -29,6 +28,7 @@ pub fn stored(get: impl Fn(&str) -> Option<String>) -> Option<String> {
use crate::SolveApp;
use crate::theme::Tokens;
use crate::tool_modifiers::ModifierCombo;
+use crate::ui_kit;
use crate::viewport::NavMode;
pub const UNITS: [&str; 5] = ["mm", "cm", "m", "in", "ft"];
@@ -599,35 +599,32 @@ impl Snapshot {
fn theme_row(app: &mut SolveApp, ui: &mut egui::Ui) {
let choices = theme_choices(app);
let current = choices.iter().find(|(id, _)| *id == app.preferences.theme).map_or_else(|| app.preferences.theme.clone(), |(_, name)| name.clone());
- let first_imported = THEMES.len() + crate::theme_files::builtin().len();
let imported = app.preferences.custom_themes.iter().any(|t| t.id == app.preferences.theme);
let mut chosen: Option<String> = None;
let mut action: Option<&str> = None;
- ui.horizontal(|ui| {
- let combo = egui::ComboBox::from_id_salt("pref_theme").width(200.0).height(340.0).selected_text(current).show_ui(ui, |ui| {
- for (i, (id, name)) in choices.iter().enumerate() {
- if i == THEMES.len() || i == first_imported {
- ui.separator();
- }
- let item = ui.selectable_label(app.preferences.theme == *id, name);
+ ui_kit::row(ui, app.tr("ui.theme"), |ui| {
+ let combo = ui_kit::dropdown_menu(ui, "pref_theme", &current, |ui| {
+ for (id, name) in &choices {
+ let item = ui_kit::list_picker(ui, id, name, app.preferences.theme == *id);
crate::scenario::publish_handle(&format!("prefs:theme:{id}"), item.rect.center());
if item.clicked() {
chosen = Some(id.clone());
}
}
});
- crate::scenario::publish_handle("prefs:theme", combo.response.rect.center());
- if ui.button(app.tr_label("Import…")).on_hover_text(app.tr_label("Add a theme file (.json) and use it")).clicked() {
+ crate::scenario::publish_handle("prefs:theme", combo.rect.center());
+ });
+ ui.horizontal_wrapped(|ui| {
+ if ui_kit::secondary_button(ui, app.tr_label("Import…")).on_hover_text(app.tr_label("Add a theme file (.json) and use it")).clicked() {
action = Some("import");
}
- if ui
- .button(app.tr_label("Export…"))
+ if ui_kit::secondary_button(ui, app.tr_label("Export…"))
.on_hover_text(app.tr_label("Save the theme on now as a complete theme file, to start a new one from"))
.clicked()
{
action = Some("export");
}
- if imported && ui.button(app.tr_label("Remove")).on_hover_text(app.tr_label("Remove this imported theme")).clicked() {
+ if imported && ui_kit::secondary_button(ui, app.tr_label("Remove")).on_hover_text(app.tr_label("Remove this imported theme")).clicked() {
action = Some("remove");
}
});
@@ -674,46 +671,23 @@ fn ui_font_row(app: &mut SolveApp, ui: &mut egui::Ui) {
let builtin = app.tr_label("Built-in").to_string();
let current = if app.preferences.ui_font.trim().is_empty() { builtin.clone() } else { app.preferences.ui_font.clone() };
let families = crate::sketch_text::families(ui.ctx());
- let mut chosen: Option<String> = None;
- let combo = egui::ComboBox::from_id_salt("pref_ui_font")
- .width(220.0)
- .height(340.0)
- .selected_text(current)
- .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)
- .show_ui(ui, |ui| {
- let search = egui::TextEdit::singleline(&mut app.prefs_window.font_filter).hint_text(crate::i18n::tr("sketch_text.font_search"));
- ui.add(search.desired_width(f32::INFINITY));
- let filter = app.prefs_window.font_filter.trim().to_lowercase();
- egui::ScrollArea::vertical().max_height(280.0).min_scrolled_height(280.0).auto_shrink([false, false]).show(ui, |ui| {
- if builtin.to_lowercase().contains(&filter) {
- let item = ui.selectable_label(app.preferences.ui_font.trim().is_empty(), &builtin);
- crate::scenario::publish_handle("prefs:font_builtin", item.rect.center());
- if item.clicked() {
- chosen = Some(String::new());
- }
- }
- match &families {
- Some(list) => {
- for family in list.iter().filter(|f| f.to_lowercase().contains(&filter)) {
- let item = ui.selectable_label(app.preferences.ui_font == *family, family);
- crate::scenario::publish_handle(&format!("prefs:font:{family}"), item.rect.center());
- if item.clicked() {
- chosen = Some(family.clone());
- }
- }
- }
- None => {
- ui.label(crate::i18n::tr_label("Listing the installed fonts…"));
- }
- }
- });
- // Close the list from inside it: outside, `ui.close()` folds the Preferences
- // window's body instead, which egui keeps folded between runs (#1800).
- if chosen.is_some() {
- ui.close();
- }
- });
- crate::scenario::publish_handle("prefs:ui_font", combo.response.rect.center());
+ let mut values = vec![(String::new(), builtin.clone(), "prefs:font_builtin".to_string())];
+ if let Some(families) = &families {
+ values.extend(families.iter().map(|family| (family.clone(), family.clone(), format!("prefs:font:{family}"))));
+ }
+ let options: Vec<_> = values.iter().map(|(value, label, handle)| ui_kit::SearchOption { value, label, handle: Some(handle) }).collect();
+ let chosen = ui_kit::searchable_dropdown(
+ ui,
+ "pref_ui_font",
+ &current,
+ &mut app.prefs_window.font_filter,
+ &options,
+ None,
+ families.is_none().then(|| crate::i18n::tr_label("Listing the installed fonts…")),
+ );
+ if let Some(rect) = crate::scenario::rect_of(&format!("dialog:widget:{}", crate::i18n::tr_label("Interface font"))) {
+ crate::scenario::publish_handle("prefs:ui_font", rect.center());
+ }
if let Some(name) = chosen {
if name.is_empty() || crate::fonts::ui_font(&name).is_some() {
app.preferences.ui_font = name;
@@ -951,16 +925,8 @@ pub fn parse_number(text: &str) -> Option<f64> {
t.parse::<f64>().ok().filter(|v| v.is_finite())
}
-/// Edit a millimetre value through a control expressed in the current design units.
-/// Keep the stored value untouched unless the user actually changes the field.
-pub fn length_drag<'a>(value: &'a mut f64, units: &str, decimals: u8) -> egui::DragValue<'a> {
- let (scale, unit) = unit_scale(units);
- egui::DragValue::new(value)
- .speed(0.5)
- .suffix(format!(" {unit}"))
- .custom_formatter(move |mm, _| length_number(mm, unit, decimals))
- .custom_parser(move |text| parse_length_mm(text, scale))
-}
+// Existing callers retain their numeric-editor API; kit owns the widget.
+pub use crate::ui_kit::length_drag;
/// A length typed into a field, in millimetres: a bare number is in the design's units (`scale`
/// units per millimetre); an explicit unit ("10 mm", "0.5 in", "2 cm + 3 mm") is honoured.
@@ -1048,37 +1014,6 @@ impl SettingReset {
}
}
-/// Settings put back at start (`SolveApp::settings_reset`), until dismissed.
-pub fn show_reset_notice(app: &mut SolveApp, ctx: &egui::Context) {
- if app.settings_reset.is_empty() {
- return;
- }
- let mut ok = false;
- let mut prefs = false;
- crate::frame::window(ctx, app.tr("settings.reset_title"), crate::frame::Width::Normal)
- .id(egui::Id::new("sc_settings_reset"))
- .collapsible(false)
- .resizable(false)
- .show(ctx, |ui| {
- ui.label(app.tr("settings.reset_intro"));
- ui.add_space(4.0);
- for reset in &app.settings_reset {
- ui.label(format!("• {}", reset.message()));
- }
- ui.add_space(6.0);
- ui.horizontal(|ui| {
- ok = ui.button(app.tr("ui.heading_ok")).clicked();
- prefs = ui.button(app.tr("ui.open_preferences")).clicked();
- });
- });
- if ok || prefs {
- app.settings_reset.clear();
- }
- if prefs {
- open_at(app, PAGE_GRAPHICS);
- }
-}
-
/// The Preferences window can't be folded (`collapsible(false)`), but 0.14 and 0.15 folded it
/// when a font was picked, and egui keeps that in the saved window state: it then opened as its
/// title bar alone, for good (#1800). Unfold it.
@@ -1108,86 +1043,79 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
}
unfold(ctx);
let t = Tokens::get();
- let mut open = true;
let mut button: Option<&str> = None;
let before = app.preferences.clone();
- let shown = crate::frame::window(ctx, app.tr("ui.preferences"), crate::frame::Width::Wide)
- .id(egui::Id::new("sc_prefs"))
- .open(&mut open)
- .collapsible(false)
- .resizable(false)
- .show(ctx, |ui| {
- // One fixed size for every page (#290): the page is drawn into a clipped child of
- // that size and only that size is allocated, so no page (or translation) can widen
- // the window; descriptions wrap and tall pages scroll inside it.
- ui.set_max_width(PREFS_W);
- let (body, _) = ui.allocate_exact_size(egui::vec2(PREFS_W, PREFS_H), egui::Sense::hover());
- let mut child = ui.new_child(egui::UiBuilder::new().max_rect(body).layout(egui::Layout::left_to_right(egui::Align::Min)));
- child.shrink_clip_rect(body);
- let ui_body = &mut child;
- ui_body.vertical(|ui| {
- ui.set_width(PREFS_NAV_W);
- for (i, s) in PAGES.iter().enumerate() {
- if ui.selectable_label(app.prefs_window.section == i, app.tr_label(s)).clicked() {
- app.prefs_window.section = i;
- app.keymap.read_only = false;
- }
- }
- });
- ui_body.separator();
- ui_body.vertical(|ui| {
- ui.set_width(ui.available_width());
- ui.label(
- RichText::new(app.tr_label(PAGES.get(app.prefs_window.section).copied().unwrap_or_default()))
- .semibold()
- .color(crate::theme::Tokens::get().text)
- .size(crate::theme::Tokens::get().font_heading),
- );
- ui.add_space(6.0);
- if app.prefs_window.section == PAGE_SHORTCUTS {
- // The shortcuts table scrolls by itself.
- page(app, ui, &t);
- } else {
- egui::ScrollArea::vertical().id_salt("sc_prefs_page").auto_shrink([false, false]).show(ui, |ui| page(app, ui, &t));
- }
- });
- ui.separator();
- // Restore Defaults at the left; OK, Cancel and Apply flush right, as in every dialog.
- ui.horizontal(|ui| {
- ui.set_width(PREFS_W);
- if ui.button(app.tr("ui.restore_defaults")).on_hover_text(app.tr("ui.reset_the_settings_on_this_page")).clicked() {
- button = Some("defaults");
+ let capturing = crate::keymap::capturing(app);
+ let prompt = ui_kit::Prompt::new(egui::Id::new("sc_prefs"), "settings", app.tr("ui.preferences")).cards(3.0).fields().actions(
+ "OK",
+ "Cancel",
+ Some("Apply"),
+ );
+ let prompt = if capturing { prompt.keep_open_on_escape() } else { prompt };
+ let (closed, action) = prompt.show(ctx, true, |ui| {
+ // A fixed, clipped page viewport keeps every page and translation the same size.
+ let height = (ctx.content_rect().height() - t.form_header_height - t.form_footer_height - t.space_24 * 3.0)
+ .clamp(t.control_height * 4.0, t.control_height * 16.0);
+ let (body, _) = ui.allocate_exact_size(egui::vec2(ui.available_width(), height), egui::Sense::hover());
+ let mut child = ui.new_child(egui::UiBuilder::new().max_rect(body).layout(egui::Layout::left_to_right(egui::Align::Min)));
+ child.shrink_clip_rect(body);
+ child.vertical(|ui| {
+ ui.set_width(t.form_label_width * 2.0);
+ for (i, title) in PAGES.iter().enumerate() {
+ let tab = ui_kit::list_picker(ui, title, app.tr_label(title), app.prefs_window.section == i);
+ crate::scenario::publish_rect(&format!("prefs:page:{title}"), tab.rect);
+ crate::scenario::publish_handle(&format!("prefs:page:{title}"), tab.rect.center());
+ if tab.clicked() {
+ app.prefs_window.section = i;
+ app.keymap.read_only = false;
}
- ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
- // Right to left: Apply is the rightmost.
- for (key, id) in [("ui.apply", "apply"), ("ui.cancel", "cancel"), ("ui.heading_ok", "ok")] {
- let r = ui.button(app.tr(key));
- crate::scenario::publish_rect(&format!("prefs:{id}"), r.rect);
- if r.clicked() {
- button = Some(id);
- }
- }
- });
- crate::scenario::publish_rect("prefs:footer", ui.max_rect());
- });
+ }
+ });
+ child.separator();
+ child.vertical(|ui| {
+ ui.set_width(ui.available_width());
+ if app.prefs_window.section == PAGE_SHORTCUTS {
+ page(app, ui, &t);
+ } else {
+ let scroll = egui::ScrollArea::vertical()
+ .id_salt(("sc_prefs_page", app.prefs_window.section))
+ .auto_shrink([false, false])
+ .show(ui, |ui| page(app, ui, &t));
+ crate::scenario::publish_rect("prefs:page_body", scroll.inner_rect);
+ }
});
- if let Some(w) = &shown {
- crate::scenario::publish_rect("prefs:window", w.response.rect);
+ if ui_kit::secondary_button(ui, app.tr("ui.restore_defaults")).on_hover_text(app.tr("ui.reset_the_settings_on_this_page")).clicked() {
+ button = Some("defaults");
+ }
+ });
+ for name in ["window", "footer", "ok", "apply", "cancel"] {
+ if let Some(rect) = crate::scenario::rect_of(&format!("dialog:{name}")) {
+ crate::scenario::publish_rect(&format!("prefs:{name}"), rect);
+ crate::scenario::publish_handle(&format!("prefs:{name}"), rect.center());
+ }
}
crate::space_mouse_calibration::show(app, ctx);
+ if let Some(rect) = crate::scenario::rect_of("dialog:footer:actions") {
+ crate::scenario::publish_rect("prefs:actions", rect);
+ }
+ button = match action {
+ ui_kit::Action::Ok => Some("ok"),
+ ui_kit::Action::Apply => Some("apply"),
+ ui_kit::Action::Cancel => Some("cancel"),
+ ui_kit::Action::None => button,
+ };
if app.preferences.msaa != before.msaa {
save_graphics(app);
}
if app.preferences.up_axis != before.up_axis {
up_axis_changed(app);
}
- let esc = ctx.input(|i| i.key_pressed(egui::Key::Escape)) && !crate::keymap::capturing(app);
match button {
Some("defaults") => defaults(app, app.prefs_window.section),
Some("apply") => app.prefs_window.snapshot = Some(Snapshot::take(app)),
Some("ok") => close(app, false),
Some("cancel") => close(app, true),
- _ if !open || esc => close(app, !open || esc),
+ _ if closed => close(app, true),
_ => {}
}
}
@@ -1218,20 +1146,8 @@ fn up_axis_changed(app: &mut SolveApp) {
}
}
-/// The Preferences window's content size: the same on every page.
-const PREFS_W: f32 = 744.0;
-const PREFS_H: f32 = 400.0;
-/// The page list at its left.
-const PREFS_NAV_W: f32 = 128.0;
-
-/// One page of the dialog.
+/// One page of the dialog. Inputs share the kit's aligned rows and tokenised controls.
fn page(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) {
- let note = |ui: &mut egui::Ui, s: &str| {
- ui.label("");
- // Descriptions wrap within the page instead of widening it.
- ui.add(egui::Label::new(RichText::new(s).size(crate::theme::Tokens::get().font_small).color(t.text_dim)).wrap());
- ui.end_row();
- };
if app.prefs_window.section == PAGE_SHORTCUTS {
crate::keymap::page(app, ui);
return;
@@ -1244,406 +1160,356 @@ fn page(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) {
crate::plugins::page(app, ui);
return;
}
- egui::Grid::new(("sc_prefs_grid", app.prefs_window.section)).num_columns(2).spacing([16.0, 8.0]).show(ui, |ui| match app.prefs_window.section {
+ match app.prefs_window.section {
0 => {
- ui.label(app.tr("ui.language"));
- egui::ComboBox::from_id_salt("pref_language").selected_text(crate::i18n::Locale::for_language(&app.preferences.language).name()).show_ui(
- ui,
- |ui| {
+ ui_kit::row(ui, app.tr("ui.language"), |ui| {
+ ui_kit::dropdown_menu(ui, "pref_language", crate::i18n::Locale::for_language(&app.preferences.language).name(), |ui| {
for locale in crate::i18n::LOCALES {
- let (id, label) = (locale.id, locale.name);
- ui.selectable_value(&mut app.preferences.language, id.to_string(), label);
+ if ui_kit::list_picker(ui, locale.id, locale.name, app.preferences.language == locale.id).clicked() {
+ app.preferences.language = locale.id.into();
+ }
}
- },
- );
- ui.end_row();
- ui.label(app.tr("ui.theme"));
+ });
+ });
theme_row(app, ui);
- ui.end_row();
- ui.label(app.tr("ui.ui_scale"));
- let scale = ui.add(
- egui::Slider::new(&mut app.preferences.ui_scale, 0.5..=2.5).step_by(0.05).custom_formatter(|v, _| format!("{:.0} %", v * 100.0)),
- );
- crate::scenario::publish_rect("prefs:scale", scale.rect);
- ui.end_row();
+ ui_kit::row(ui, app.tr("ui.ui_scale"), |ui| {
+ let scale = ui_kit::formatted_slider(ui, &mut app.preferences.ui_scale, 0.5..=2.5, 0.05, |v| format!("{:.0} %", v * 100.0));
+ crate::scenario::publish_rect("prefs:scale", scale.rect);
+ });
if !cfg!(target_arch = "wasm32") {
- ui.label(app.tr_label("Interface font"));
- ui_font_row(app, ui);
- ui.end_row();
+ ui_kit::row(ui, app.tr_label("Interface font"), |ui| ui_font_row(app, ui));
}
- ui.label(app.tr("ui.feature_history"));
- let timeline_bottom = app.tr("ui.timeline_bottom").to_string();
- let timeline_left = app.tr("ui.timeline_left_sidebar").to_string();
- ui.horizontal(|ui| {
- ui.radio_value(&mut app.preferences.timeline_left, false, timeline_bottom);
- ui.radio_value(&mut app.preferences.timeline_left, true, timeline_left);
+ ui_kit::row(ui, app.tr("ui.feature_history"), |ui| {
+ let mut selected = usize::from(app.preferences.timeline_left);
+ if ui_kit::segmented(ui, &mut selected, &[crate::i18n::tr("ui.timeline_bottom"), crate::i18n::tr("ui.timeline_left_sidebar")]) {
+ app.preferences.timeline_left = selected == 1;
+ }
});
- ui.end_row();
- note(ui, app.tr("ui.timeline_left_note"));
- ui.label(app.tr_label("Parts browser"));
- let float_label = app.tr_label("Float it over the workspace").to_string();
- ui.checkbox(&mut app.preferences.browser_float, float_label);
- ui.end_row();
- note(ui, app.tr_label("The tree draws on a translucent card over the 3D view instead of a column of its own."));
- ui.label(app.tr("ui.units_of_new_designs"));
- egui::ComboBox::from_id_salt("pref_units").selected_text(app.preferences.default_units.clone()).show_ui(ui, |ui| {
- for u in UNITS {
- ui.selectable_value(&mut app.preferences.default_units, u.to_string(), u);
+ ui_kit::note(ui, "timeline", app.tr("ui.timeline_left_note"));
+ ui_kit::row(ui, app.tr_label("Parts browser"), |ui| {
+ ui_kit::checkbox(ui, crate::i18n::tr_label("Float it over the workspace"), &mut app.preferences.browser_float);
+ });
+ ui_kit::note(ui, "browser", app.tr_label("The tree draws on a translucent card over the 3D view instead of a column of its own."));
+ ui_kit::row(ui, app.tr("ui.units_of_new_designs"), |ui| {
+ let mut selected = UNITS.iter().position(|u| *u == app.preferences.default_units).unwrap_or(0);
+ ui_kit::dropdown(ui, "pref_units", &mut selected, &UNITS);
+ if let Some(unit) = UNITS.get(selected) {
+ app.preferences.default_units = (*unit).into();
}
});
- ui.end_row();
- ui.label(app.tr("ui.autosave_every"));
- if ui.add(egui::DragValue::new(&mut app.autosave_minutes).range(0.0..=120.0).speed(0.5).suffix(" min").custom_parser(parse_number)).changed() {
- set_autosave(app);
- }
- ui.end_row();
- note(ui, crate::i18n::tr_label("0 turns it off"));
- ui.label(app.tr("ui.length_decimals"));
- ui.add(egui::DragValue::new(&mut app.preferences.length_decimals).range(0..=6));
- ui.end_row();
- ui.label(app.tr("ui.angle_decimals"));
- ui.add(egui::DragValue::new(&mut app.preferences.angle_decimals).range(0..=6));
- ui.end_row();
- ui.label(app.tr("ui.agent_cursor"));
- let speed_label = app.tr("ui.agent_cursor_speed");
- let s = &mut app.ui.agent_cursor;
- ui.checkbox(&mut s.show, crate::i18n::tr_label("Show the pointer an AI agent moves (#35)"));
- ui.end_row();
- ui.label(speed_label);
- ui.add_enabled_ui(s.show, |ui| {
- crate::agent_cursor::speed_slider(ui, &mut s.speed);
+ ui_kit::row(ui, app.tr("ui.autosave_every"), |ui| {
+ if ui_kit::number_field(ui, &mut app.autosave_minutes, 0.0..=120.0, 0.5, crate::i18n::tr("prefs.minutes_suffix")).changed() {
+ set_autosave(app);
+ }
+ });
+ ui_kit::note(ui, "autosave", crate::i18n::tr_label("0 turns it off"));
+ ui_kit::row(ui, app.tr("ui.length_decimals"), |ui| {
+ ui_kit::number_field(ui, &mut app.preferences.length_decimals, 0..=6, 1.0, "");
+ });
+ ui_kit::row(ui, app.tr("ui.angle_decimals"), |ui| {
+ ui_kit::number_field(ui, &mut app.preferences.angle_decimals, 0..=6, 1.0, "");
+ });
+ ui_kit::row(ui, app.tr("ui.agent_cursor"), |ui| {
+ ui_kit::checkbox(ui, crate::i18n::tr_label("Show the pointer an AI agent moves (#35)"), &mut app.ui.agent_cursor.show);
});
- ui.end_row();
- ui.label("");
- ui.add_enabled(s.show, egui::Checkbox::new(&mut s.follow_camera, crate::i18n::tr_label("Follow the camera (Look At sketches)")));
- ui.end_row();
- crate::update::prefs_rows(app, ui, t);
+ ui_kit::row(ui, app.tr("ui.agent_cursor_speed"), |ui| {
+ ui.add_enabled_ui(app.ui.agent_cursor.show, |ui| {
+ crate::agent_cursor::speed_slider(ui, &mut app.ui.agent_cursor.speed);
+ });
+ });
+ ui.add_enabled_ui(app.ui.agent_cursor.show, |ui| {
+ ui_kit::checkbox(ui, crate::i18n::tr_label("Follow the camera (Look At sketches)"), &mut app.ui.agent_cursor.follow_camera);
+ });
+ crate::update::prefs_rows(app, ui);
}
1 => {
- ui.label(app.tr_label("Pan, zoom, orbit"));
- let current_preset_label = nav_preset(&app.preferences.nav).translated_label();
- egui::ComboBox::from_id_salt("pref_nav").selected_text(current_preset_label).show_ui(ui, |ui| {
- for p in &NAV_PRESETS {
- if ui.selectable_value(&mut app.preferences.nav, p.id.to_string(), p.translated_label()).clicked() {
- app.preferences.zoom_reverse = p.reverse_zoom;
+ ui_kit::row(ui, app.tr_label("Pan, zoom, orbit"), |ui| {
+ ui_kit::dropdown_menu(ui, "pref_nav", nav_preset(&app.preferences.nav).translated_label(), |ui| {
+ for p in &NAV_PRESETS {
+ if ui_kit::list_picker(ui, p.id, p.translated_label(), app.preferences.nav == p.id).clicked() {
+ app.preferences.nav = p.id.into();
+ app.preferences.zoom_reverse = p.reverse_zoom;
+ }
}
- }
+ });
});
- ui.end_row();
if app.preferences.nav == TOUCHPAD_NAV {
- note(ui, crate::i18n::tr("nav.touchpad.help"));
+ ui_kit::note(ui, "navigation", crate::i18n::tr("nav.touchpad.help"));
} else {
let snap_help = if app.preferences.nav == OPENSCAD_NAV { "" } else { "; hold Shift during orbit to snap" };
- let raw_help = format!("{}; Ctrl+left drag on empty space orbits{snap_help}; hold Space to pan; the wheel zooms", nav_preset(&app.preferences.nav).help);
- note(ui, crate::i18n::tr_label(&raw_help));
+ let raw_help = format!(
+ "{}; Ctrl+left drag on empty space orbits{snap_help}; hold Space to pan; the wheel zooms",
+ nav_preset(&app.preferences.nav).help
+ );
+ ui_kit::note(ui, "navigation", crate::i18n::tr_label(&raw_help));
}
- ui.label(crate::i18n::tr_label("Context menu"));
- ui.checkbox(&mut app.preferences.radial_context_menu, crate::i18n::tr_label("Radial context menu"));
- ui.end_row();
+ ui_kit::checkbox(ui, crate::i18n::tr_label("Radial context menu"), &mut app.preferences.radial_context_menu);
crate::mouse_gesture::nav_rows(app, ui, t);
- ui.label(crate::i18n::tr_label("View navigator"));
- let picker =
- egui::ComboBox::from_id_salt("pref_navigator_style").selected_text(crate::i18n::tr_label(app.preferences.navigator_style.label())).show_ui(ui, |ui| {
- for style in NavigatorStyle::ALL {
- let response = ui.selectable_value(&mut app.preferences.navigator_style, style, crate::i18n::tr_label(style.label()));
- crate::scenario::publish_rect(&format!("prefs:navigator:{}", style.label()), response.rect);
- crate::scenario::publish_handle(&format!("prefs:navigator:{}", style.label()), response.rect.center());
- }
- });
- crate::scenario::publish_rect("prefs:navigator", picker.response.rect);
- crate::scenario::publish_handle("prefs:navigator", picker.response.rect.center());
- ui.end_row();
- ui.label(crate::i18n::tr_label("Reverse zoom direction"));
- ui.checkbox(&mut app.preferences.zoom_reverse, "");
- ui.end_row();
- ui.label(crate::i18n::tr_label("Zoom to the cursor"));
- ui.checkbox(&mut app.preferences.zoom_to_cursor, "")
+ ui_kit::row(ui, app.tr_label("View navigator"), |ui| {
+ let picker =
+ ui_kit::dropdown_menu(ui, "pref_navigator_style", crate::i18n::tr_label(app.preferences.navigator_style.label()), |ui| {
+ for style in NavigatorStyle::ALL {
+ let r = ui_kit::list_picker(
+ ui,
+ style.label(),
+ crate::i18n::tr_label(style.label()),
+ app.preferences.navigator_style == style,
+ );
+ crate::scenario::publish_rect(&format!("prefs:navigator:{}", style.label()), r.rect);
+ crate::scenario::publish_handle(&format!("prefs:navigator:{}", style.label()), r.rect.center());
+ if r.clicked() {
+ app.preferences.navigator_style = style;
+ }
+ }
+ });
+ crate::scenario::publish_rect("prefs:navigator", picker.rect);
+ crate::scenario::publish_handle("prefs:navigator", picker.rect.center());
+ });
+ ui_kit::checkbox(ui, crate::i18n::tr_label("Reverse zoom direction"), &mut app.preferences.zoom_reverse);
+ ui_kit::checkbox(ui, crate::i18n::tr_label("Zoom to the cursor"), &mut app.preferences.zoom_to_cursor)
.on_hover_text(crate::i18n::tr_label("The wheel zooms toward the point under the cursor (off: toward the view's centre)"));
- ui.end_row();
- ui.label(crate::i18n::tr_label("Smooth wheel zoom"));
- ui.checkbox(&mut app.preferences.smooth_wheel_zoom, "")
+ ui_kit::checkbox(ui, crate::i18n::tr_label("Smooth wheel zoom"), &mut app.preferences.smooth_wheel_zoom)
.on_hover_text(crate::i18n::tr_label("Turn off to apply each wheel event immediately, without a smoothing tail"));
- ui.end_row();
- ui.label(crate::i18n::tr_label("Two-finger scroll pans"));
let touchpad = app.preferences.nav == TOUCHPAD_NAV;
- ui.add_enabled(!touchpad, egui::Checkbox::new(&mut app.preferences.trackpad_pan, "")).on_hover_text(if touchpad {
- crate::i18n::tr("nav.touchpad.scroll")
- } else {
- crate::i18n::tr_label("Trackpad gestures pan (off: they zoom like the wheel); mouse wheel zooms, thumb wheel pans sideways, pinch always zooms")
+ ui.add_enabled_ui(!touchpad, |ui| {
+ ui_kit::checkbox(ui, crate::i18n::tr_label("Two-finger scroll pans"), &mut app.preferences.trackpad_pan).on_hover_text(if touchpad {
+ crate::i18n::tr("nav.touchpad.scroll")
+ } else {
+ crate::i18n::tr_label(
+ "Trackpad gestures pan (off: they zoom like the wheel); mouse wheel zooms, thumb wheel pans sideways, pinch always zooms",
+ )
+ });
});
- ui.end_row();
- ui.label(crate::i18n::tr_label("Reverse horizontal pan direction"));
- ui.checkbox(&mut app.preferences.pan_reverse_x, "")
+ ui_kit::checkbox(ui, crate::i18n::tr_label("Reverse horizontal pan direction"), &mut app.preferences.pan_reverse_x)
.on_hover_text(crate::i18n::tr_label("Horizontal two-finger scrolling and the thumb wheel pan the other way"));
- ui.end_row();
- ui.label(crate::i18n::tr_label("Orbit around"));
- // Wrapped: three choices, and German or Russian labels are long.
- ui.horizontal_wrapped(|ui| {
- ui.radio_value(&mut app.preferences.orbit_around, OrbitAround::Origin, crate::i18n::tr_label("Origin"));
- ui.radio_value(&mut app.preferences.orbit_around, OrbitAround::ViewCentre, crate::i18n::tr_label("View centre"));
- ui.radio_value(&mut app.preferences.orbit_around, OrbitAround::Cursor, crate::i18n::tr_label("Point under the cursor"));
- });
- ui.end_row();
- ui.label(crate::i18n::tr_label("Middle double-click"));
- let current = MiddleDoubleClick::of(app);
- egui::ComboBox::from_id_salt("pref_middle_double_click").selected_text(crate::i18n::tr_label(current.label())).show_ui(ui, |ui| {
- for (m, id, label) in MiddleDoubleClick::ALL {
- if ui.selectable_label(current == m, crate::i18n::tr_label(label)).clicked() {
- app.preferences.middle_double_click = id.into();
- }
+ ui_kit::row(ui, app.tr_label("Orbit around"), |ui| {
+ let modes = [OrbitAround::Origin, OrbitAround::ViewCentre, OrbitAround::Cursor];
+ let mut selected = modes.iter().position(|m| *m == app.preferences.orbit_around).unwrap_or(1);
+ if ui_kit::segmented(
+ ui,
+ &mut selected,
+ &[crate::i18n::tr_label("Origin"), crate::i18n::tr_label("View centre"), crate::i18n::tr_label("Point under the cursor")],
+ ) && let Some(mode) = modes.get(selected)
+ {
+ app.preferences.orbit_around = *mode;
}
- })
- .response
- .on_hover_text(crate::i18n::tr_label("Double-clicking the middle button in the view: Home (the home view, framing what is shown), Fit (frame what is shown, keeping the orientation) or nothing"));
- ui.end_row();
- ui.label(crate::i18n::tr_label("Animate view changes"));
- ui.checkbox(&mut app.preferences.look_at_anim, crate::i18n::tr_label("Axis view, Look At, Home and Fit"));
- ui.end_row();
- ui.label(crate::i18n::tr_label("Animation speed"));
- ui.add_enabled(
- app.preferences.look_at_anim,
- egui::Slider::new(&mut app.preferences.look_at_speed, 0.5..=3.0).step_by(0.25).custom_formatter(|v, _| format!("{v:.2}×")),
- );
- ui.end_row();
- ui.label(crate::i18n::tr_label("3D mouse"));
- ui.checkbox(&mut app.preferences.space_mouse_enabled, crate::i18n::tr_label("Navigate with SpaceNavigator / SpaceMouse"));
- ui.end_row();
- ui.label(crate::i18n::tr_label("3D mouse speed"));
- ui.add_enabled(
- app.preferences.space_mouse_enabled,
- egui::Slider::new(&mut app.preferences.space_mouse_speed, 0.25..=3.0).step_by(0.05).custom_formatter(|v, _| format!("{v:.2}×")),
- );
- ui.end_row();
+ });
+ ui_kit::row(ui, app.tr_label("Middle double-click"), |ui| {
+ let current = MiddleDoubleClick::of(app);
+ ui_kit::dropdown_menu(ui, "pref_middle_double_click", crate::i18n::tr_label(current.label()), |ui| {
+ for (m, id, label) in MiddleDoubleClick::ALL { if ui_kit::list_picker(ui, id, crate::i18n::tr_label(label), current == m).clicked() { app.preferences.middle_double_click = id.into(); } }
+ }).on_hover_text(crate::i18n::tr_label("Double-clicking the middle button in the view: Home (the home view, framing what is shown), Fit (frame what is shown, keeping the orientation) or nothing"));
+ });
+ ui_kit::checkbox(ui, crate::i18n::tr_label("Animate view changes"), &mut app.preferences.look_at_anim)
+ .on_hover_text(crate::i18n::tr_label("Axis view, Look At, Home and Fit"));
+ ui_kit::row(ui, app.tr_label("Animation speed"), |ui| {
+ ui.add_enabled_ui(app.preferences.look_at_anim, |ui| {
+ ui_kit::formatted_slider(ui, &mut app.preferences.look_at_speed, 0.5..=3.0, 0.25, |v| format!("{v:.2}×"));
+ });
+ });
+ ui_kit::checkbox(ui, crate::i18n::tr_label("Navigate with SpaceNavigator / SpaceMouse"), &mut app.preferences.space_mouse_enabled);
+ ui_kit::row(ui, app.tr_label("3D mouse speed"), |ui| {
+ ui.add_enabled_ui(app.preferences.space_mouse_enabled, |ui| {
+ ui_kit::formatted_slider(ui, &mut app.preferences.space_mouse_speed, 0.25..=3.0, 0.05, |v| format!("{v:.2}×"));
+ });
+ });
for (axis, name) in SPACE_MOUSE_AXES.iter().enumerate() {
- ui.label(crate::i18n::tr_label(name));
- ui.horizontal(|ui| {
+ ui_kit::row(ui, crate::i18n::tr_label(name), |ui| {
ui.add_enabled_ui(app.preferences.space_mouse_enabled, |ui| {
- if let Some(reverse) = app.preferences.space_mouse_reverse.get_mut(axis) {
- ui.checkbox(reverse, crate::i18n::tr_label("Invert"));
- }
- if let Some(speed) = app.preferences.space_mouse_axis_speed.get_mut(axis) {
- ui.add(egui::Slider::new(speed, 0.0..=3.0).step_by(0.05).custom_formatter(|v, _| format!("{v:.2}×")));
- }
+ ui.horizontal(|ui| {
+ if let Some(reverse) = app.preferences.space_mouse_reverse.get_mut(axis) {
+ ui_kit::checkbox(ui, crate::i18n::tr_label("Invert"), reverse);
+ }
+ if let Some(speed) = app.preferences.space_mouse_axis_speed.get_mut(axis) {
+ ui_kit::formatted_slider(ui, speed, 0.0..=3.0, 0.05, |v| format!("{v:.2}×"));
+ }
+ });
});
});
- ui.end_row();
}
- ui.label(app.tr("ui.space_mouse_calibration"));
- ui.horizontal(|ui| {
+ ui_kit::row(ui, app.tr("ui.space_mouse_calibration"), |ui| {
let device = app.space_mouse.device.clone();
let saved = device.as_ref().is_some_and(|device| app.preferences.space_mouse_calibrations.contains_key(device));
ui.add_enabled_ui(app.preferences.space_mouse_enabled && device.is_some(), |ui| {
- if ui.button(app.tr("ui.space_mouse_calibrate")).on_hover_text(app.tr("ui.space_mouse_calibrate_tip")).clicked() {
+ if ui_kit::secondary_button(ui, app.tr("ui.space_mouse_calibrate"))
+ .on_hover_text(app.tr("ui.space_mouse_calibrate_tip"))
+ .clicked()
+ {
crate::space_mouse_calibration::start(app);
}
- if saved && ui.button(app.tr("ui.space_mouse_forget")).clicked()
+ if saved
+ && ui_kit::secondary_button(ui, app.tr("ui.space_mouse_forget")).clicked()
&& let Some(device) = &device
{
app.preferences.space_mouse_calibrations.remove(device);
}
});
- // With the device it's about, so it's clear which calibration is in use.
- ui.label(match (&device, saved) {
+ let status = match (&device, saved) {
(None, _) => app.tr("ui.space_mouse_none").to_owned(),
(Some(device), true) => format!("{} ({device})", app.tr("ui.space_mouse_calibrated")),
(Some(device), false) => format!("{} ({device})", app.tr("ui.space_mouse_not_calibrated")),
- });
+ };
+ ui_kit::text_block(ui, "calibration_status", &status, false);
});
- ui.end_row();
- // The calibrated device's dead zone, adjustable after calibrating.
let enabled = app.preferences.space_mouse_enabled;
let (label, tip) = (app.tr("ui.space_mouse_dead_zone").to_owned(), app.tr("ui.space_mouse_dead_zone_tip").to_owned());
let (device, raw) = (app.space_mouse.device.clone(), app.space_mouse.raw.into());
if let Some(calibration) = device.and_then(|device| app.preferences.space_mouse_calibrations.get_mut(&device)) {
- ui.label(label);
- ui.add_enabled_ui(enabled, |ui| {
- crate::space_mouse_calibration::dead_zone_slider(ui, &mut calibration.dead_zone_share).on_hover_text(tip);
+ ui_kit::row(ui, &label, |ui| {
+ ui.add_enabled_ui(enabled, |ui| {
+ ui_kit::formatted_slider(
+ ui,
+ &mut calibration.dead_zone_share,
+ 0.0..=solidcraft_space_mouse::MAX_DEAD_ZONE_SHARE,
+ 0.01,
+ |v| format!("{:.0} %", v * 100.0),
+ )
+ .on_hover_text(tip);
+ });
});
- ui.end_row();
- ui.label("");
crate::space_mouse_calibration::dead_zone_pads(ui, calibration, raw);
- ui.end_row();
}
- note(ui, crate::i18n::tr_label("Move and rotate the view together; sketches use pan and zoom only."));
+ ui_kit::note(ui, "space_mouse", crate::i18n::tr_label("Move and rotate the view together; sketches use pan and zoom only."));
}
PAGE_DESIGN => {
- ui.label(crate::i18n::tr_label("Default modelling orientation"));
- ui.horizontal(|ui| {
- ui.radio_value(&mut app.preferences.up_axis, "z".to_string(), crate::i18n::tr_label("Z up"));
- ui.radio_value(&mut app.preferences.up_axis, "y".to_string(), crate::i18n::tr_label("Y up"));
+ ui_kit::row(ui, app.tr_label("Default modelling orientation"), |ui| {
+ let mut selected = usize::from(app.preferences.up_axis == "y");
+ if ui_kit::segmented(ui, &mut selected, &[crate::i18n::tr_label("Z up"), crate::i18n::tr_label("Y up")]) {
+ app.preferences.up_axis = if selected == 1 { "y" } else { "z" }.into();
+ }
});
- ui.end_row();
- note(ui, crate::i18n::tr_label("Which axis points up in the views (axis view, Home, Look At). Designs are unchanged."));
- ui.label(crate::i18n::tr_label("Offer to stand up Y-up files"));
- ui.checkbox(&mut app.preferences.offer_stand_up, "")
+ ui_kit::note(
+ ui,
+ "orientation",
+ crate::i18n::tr_label("Which axis points up in the views (axis view, Home, Look At). Designs are unchanged."),
+ );
+ ui_kit::checkbox(ui, crate::i18n::tr_label("Offer to stand up Y-up files"), &mut app.preferences.offer_stand_up)
.on_hover_text(crate::i18n::tr_label("After a STEP or IGES file opens with Z up, offer a quarter turn about X"));
- ui.end_row();
}
- 4 => {
- ui.label(app.tr("ui.graphics_preset"));
- graphics_preset_selector(app, ui);
- ui.end_row();
- ui.label(crate::i18n::tr_label("Visual style"));
- let styles = ["Shaded with edges", "Shaded", "Wireframe", "Shaded with hidden edges"];
- let selected_label = crate::i18n::tr_label(styles[usize::from(app.ui.visual_style.min(3))]);
- egui::ComboBox::from_id_salt("pref_style").selected_text(selected_label).show_ui(ui, |ui| {
- for (i, s) in styles.iter().enumerate() {
- ui.selectable_value(&mut app.ui.visual_style, i as u8, crate::i18n::tr_label(s));
- }
+ PAGE_GRAPHICS => {
+ ui_kit::row(ui, app.tr("ui.graphics_preset"), |ui| graphics_preset_selector(app, ui));
+ ui_kit::row(ui, app.tr_label("Visual style"), |ui| {
+ let mut selected = usize::from(app.ui.visual_style.min(3));
+ ui_kit::dropdown(ui, "pref_style", &mut selected, &["Shaded with edges", "Shaded", "Wireframe", "Shaded with hidden edges"]);
+ app.ui.visual_style = selected as u8;
});
- ui.end_row();
- ui.label(crate::i18n::tr_label("Grid"));
- ui.checkbox(&mut app.ui.show_grid, "");
- ui.end_row();
- ui.label(crate::i18n::tr_label("Grid follows the view"));
- ui.add_enabled(app.ui.show_grid, egui::Checkbox::without_text(&mut app.preferences.grid_follows_view))
- .on_hover_text(crate::i18n::tr_label("Side views show the grid on the upright plane facing them instead of the ground"));
- ui.end_row();
- ui.label(crate::i18n::tr_label("Ground shadow"));
- ui.checkbox(&mut app.ui.ground_shadow, "");
- ui.end_row();
- ui.label(crate::i18n::tr_label("Ambient occlusion"));
- ambient_occlusion_checkbox(app, ui, "");
- ui.end_row();
- ui.label(crate::i18n::tr_label("Perspective view"));
- ui.checkbox(&mut app.ui.perspective, "");
- ui.end_row();
- // Keep accessibility controls visible before the longer rendering-quality controls.
- ui.label("");
- ui.end_row();
- ui.label(RichText::new(app.tr("ui.colour_vision")).semibold().color(crate::theme::Tokens::get().text));
- ui.label("");
- ui.end_row();
- ui.label(app.tr("ui.colour_vision_mode"));
- let mode = app.preferences.color_vision;
- let response = egui::ComboBox::from_id_salt("pref_color_vision").selected_text(app.tr(mode.label_id())).show_ui(ui, |ui| {
- for m in crate::theme::ColorVision::ALL {
- ui.selectable_value(&mut app.preferences.color_vision, m, crate::i18n::tr(m.label_id())).on_hover_text(crate::i18n::tr(m.help_id()));
- }
+ ui_kit::checkbox(ui, crate::i18n::tr_label("Grid"), &mut app.ui.show_grid);
+ ui.add_enabled_ui(app.ui.show_grid, |ui| {
+ ui_kit::checkbox(ui, crate::i18n::tr_label("Grid follows the view"), &mut app.preferences.grid_follows_view)
+ .on_hover_text(crate::i18n::tr_label("Side views show the grid on the upright plane facing them instead of the ground"));
});
- crate::scenario::publish_handle("prefs:color_vision", response.response.rect.center());
- if app.preferences.color_vision != mode {
- // At once, like the theme: the next frame draws in the new colours.
- ui.ctx().request_repaint();
- }
- ui.end_row();
- ui.label(app.tr("ui.colour_vision_sample"));
- colour_vision_sample(ui, t);
- ui.end_row();
- note(ui, app.tr("ui.colour_vision_note"));
- ui.label(app.tr("ui.anti_aliasing"));
- egui::ComboBox::from_id_salt("pref_msaa").selected_text(format!("{}×", app.preferences.msaa)).show_ui(ui, |ui| {
- for m in MSAA {
- // Counts the graphics device can't do would keep the window from opening.
- let ok = app.msaa_supported.is_empty() || app.msaa_supported.contains(&m);
- ui.add_enabled_ui(ok, |ui| ui.selectable_value(&mut app.preferences.msaa, m, format!("{m}×")))
- .inner
- .on_disabled_hover_text(app.tr("settings.msaa_unsupported"));
+ ui_kit::checkbox(ui, crate::i18n::tr_label("Ground shadow"), &mut app.ui.ground_shadow);
+ ambient_occlusion_checkbox(app, ui, "Ambient occlusion");
+ ui_kit::checkbox(ui, crate::i18n::tr_label("Perspective view"), &mut app.ui.perspective);
+ ui_kit::section(ui, "colour_vision", app.tr("ui.colour_vision"), true, |ui| {
+ let mode = app.preferences.color_vision;
+ ui_kit::row(ui, app.tr("ui.colour_vision_mode"), |ui| {
+ let response = ui_kit::dropdown_menu(ui, "pref_color_vision", crate::i18n::tr(mode.label_id()), |ui| {
+ for m in crate::theme::ColorVision::ALL {
+ if ui_kit::list_picker(ui, m.id(), crate::i18n::tr(m.label_id()), app.preferences.color_vision == m)
+ .on_hover_text(crate::i18n::tr(m.help_id()))
+ .clicked()
+ {
+ app.preferences.color_vision = m;
+ }
+ }
+ });
+ crate::scenario::publish_handle("prefs:color_vision", response.rect.center());
+ });
+ if app.preferences.color_vision != mode {
+ ui.ctx().request_repaint();
}
+ ui_kit::inline_text(ui, app.tr("ui.colour_vision_sample"));
+ colour_vision_sample(ui, t);
+ ui_kit::note(ui, "colour_vision", app.tr("ui.colour_vision_note"));
});
- ui.end_row();
- note(ui, app.tr("settings.msaa_applies_on_restart"));
- ui.label(app.tr("ui.display_quality"));
- {
+ ui_kit::row(ui, app.tr("ui.anti_aliasing"), |ui| {
+ ui_kit::dropdown_menu(ui, "pref_msaa", &format!("{}×", app.preferences.msaa), |ui| {
+ for m in MSAA {
+ let ok = app.msaa_supported.is_empty() || app.msaa_supported.contains(&m);
+ let r = ui
+ .add_enabled_ui(ok, |ui| ui_kit::list_picker(ui, &m.to_string(), &format!("{m}×"), app.preferences.msaa == m))
+ .inner
+ .on_disabled_hover_text(app.tr("settings.msaa_unsupported"));
+ if r.clicked() {
+ app.preferences.msaa = m;
+ }
+ }
+ });
+ });
+ ui_kit::note(ui, "msaa", app.tr("settings.msaa_applies_on_restart"));
+ ui_kit::row(ui, app.tr("ui.display_quality"), |ui| {
use solidcraft_engine::doc::display_quality::DisplayQuality;
let label = |q: DisplayQuality| crate::i18n::tr(&format!("ui.display_quality_{}", q.id())).to_string();
let current = DisplayQuality::parse(&app.preferences.display_quality).unwrap_or_default();
- egui::ComboBox::from_id_salt("pref_display_quality").selected_text(label(current)).show_ui(ui, |ui| {
+ ui_kit::dropdown_menu(ui, "pref_display_quality", &label(current), |ui| {
for q in DisplayQuality::ALL {
- if ui.selectable_label(q == current, label(q)).clicked() {
- app.preferences.display_quality = q.id().to_string();
+ if ui_kit::list_picker(ui, q.id(), &label(q), current == q).clicked() {
+ app.preferences.display_quality = q.id().into();
}
}
});
- }
- ui.end_row();
- note(ui, app.tr("settings.display_quality_note"));
- ui.label(app.tr("ui.supersampling"));
- let ss_label = |f: f32| if f > 1.0 { format!("{f}×") } else { crate::i18n::tr("ui.supersampling_off").to_string() };
- let adaptive = app.tr("ui.supersampling_adaptive").to_string();
- ui.horizontal(|ui| {
- egui::ComboBox::from_id_salt("pref_ssaa").selected_text(ss_label(app.preferences.supersampling)).show_ui(ui, |ui| {
+ });
+ ui_kit::note(ui, "quality", app.tr("settings.display_quality_note"));
+ ui_kit::row(ui, app.tr("ui.supersampling"), |ui| {
+ let ss_label = |f: f32| if f > 1.0 { format!("{f}×") } else { crate::i18n::tr("ui.supersampling_off").into() };
+ ui_kit::dropdown_menu(ui, "pref_ssaa", &ss_label(app.preferences.supersampling), |ui| {
for f in SUPERSAMPLING {
- ui.selectable_value(&mut app.preferences.supersampling, f, ss_label(f));
+ if ui_kit::list_picker(ui, &f.to_string(), &ss_label(f), app.preferences.supersampling == f).clicked() {
+ app.preferences.supersampling = f;
+ }
}
});
- ui.add_enabled(app.preferences.supersampling > 1.0, egui::Checkbox::new(&mut app.preferences.supersampling_adaptive, adaptive));
});
- ui.end_row();
- note(ui, app.tr("settings.supersampling_note"));
- ui.label(crate::i18n::tr_label("Renderer"));
- ui.label(match (&app.viewport.gpu, &app.help.gpu) {
- (Some(_), Some(g)) => format!("GPU: {g}"),
- (Some(_), None) => "GPU".to_string(),
- _ => "CPU (software)".to_string(),
+ ui.add_enabled_ui(app.preferences.supersampling > 1.0, |ui| {
+ ui_kit::checkbox(ui, crate::i18n::tr("ui.supersampling_adaptive"), &mut app.preferences.supersampling_adaptive);
+ });
+ ui_kit::note(ui, "supersampling", app.tr("settings.supersampling_note"));
+ ui_kit::row(ui, app.tr_label("Renderer"), |ui| {
+ let renderer = match (&app.viewport.gpu, &app.help.gpu) {
+ (Some(_), Some(g)) => format!("GPU: {g}"),
+ (Some(_), None) => "GPU".into(),
+ _ => crate::i18n::tr("prefs.cpu").into(),
+ };
+ ui_kit::inline_text(ui, &renderer);
});
- ui.end_row();
- ui.label(app.tr("settings.measure_axis_distances"));
- let response = ui.checkbox(&mut app.preferences.measure_axis_distances, "");
+ let response = ui_kit::checkbox(ui, app.tr("settings.measure_axis_distances"), &mut app.preferences.measure_axis_distances);
crate::scenario::publish_rect("prefs:measure_axis_distances", response.rect);
response.on_hover_text(app.tr("settings.measure_axis_distances_help"));
- ui.end_row();
- // Last, so the colour vision section above keeps its place on the page.
- ui.label("");
- ui.end_row();
- ui.label(app.tr("ui.frame_rate"));
- ui.checkbox(&mut app.preferences.show_frame_rate, "");
- ui.end_row();
- note(ui, app.tr("settings.frame_rate_note"));
+ ui_kit::checkbox(ui, app.tr("ui.frame_rate"), &mut app.preferences.show_frame_rate);
+ ui_kit::note(ui, "frame_rate", app.tr("settings.frame_rate_note"));
}
5 => {
- ui.label(crate::i18n::tr_label("Project face edges into new sketches"));
let mut auto = app.session.auto_project;
- if ui.checkbox(&mut auto, "").changed() {
- let _ = app.run("sketch.auto_project", json!({ "value": auto }));
+ if ui_kit::checkbox(ui, crate::i18n::tr_label("Project face edges into new sketches"), &mut auto).changed() {
+ let _ = app.run("sketch.auto_project", json!({"value": auto}));
}
- ui.end_row();
-
- ui.label("");
- ui.end_row();
- ui.label(RichText::new(crate::i18n::tr_label("Sketch modifiers")).strong());
- ui.label("");
- ui.end_row();
-
- ui.label(crate::i18n::tr_label("Suppress auto-snap while drawing / dragging"));
- snap_suppress_picker(ui, "pref_suppress_sketch_snap", &mut app.preferences.suppress_sketch_snap);
- ui.end_row();
- note(ui, crate::i18n::tr_label("ui.suppress_auto_snap_note"));
-
- ui.label(crate::i18n::tr_label("Manipulator free drag also on Alt/Option"));
- ui.checkbox(&mut app.preferences.manipulator_free_alt, "").on_hover_text(crate::i18n::tr_label(
- "On: Alt/Option or Ctrl/Cmd on extrude / gizmo arrows disables value snapping. Off: Ctrl/Cmd only.",
- ));
- ui.end_row();
+ ui_kit::section(ui, "sketch_modifiers", crate::i18n::tr_label("Sketch modifiers"), true, |ui| {
+ ui_kit::row(ui, crate::i18n::tr_label("Suppress auto-snap while drawing / dragging"), |ui| {
+ let combo = &mut app.preferences.suppress_sketch_snap;
+ ui_kit::dropdown_menu(ui, "pref_suppress_sketch_snap", &combo.label(), |ui| {
+ for choice in ModifierCombo::SNAP_SUPPRESS_CHOICES {
+ if ui_kit::list_picker(ui, &choice.label(), &choice.label(), *combo == choice).clicked() {
+ *combo = choice;
+ }
+ }
+ });
+ });
+ ui_kit::note(ui, "suppress_snap", crate::i18n::tr_label("ui.suppress_auto_snap_note"));
+ ui_kit::checkbox(ui, crate::i18n::tr_label("Manipulator free drag also on Alt/Option"), &mut app.preferences.manipulator_free_alt)
+ .on_hover_text(crate::i18n::tr_label(
+ "On: Alt/Option or Ctrl/Cmd on extrude / gizmo arrows disables value snapping. Off: Ctrl/Cmd only.",
+ ));
+ });
}
_ => {
- ui.label(crate::i18n::tr_label("Click selects whole bodies"));
- ui.checkbox(&mut app.ui.pick_bodies, "");
- ui.end_row();
-
- ui.label("");
- ui.end_row();
- ui.label(RichText::new(crate::i18n::tr_label("Selection modifiers")).strong());
- ui.label("");
- ui.end_row();
-
- ui.label(crate::i18n::tr_label("Shift+click adds without removing"));
- ui.checkbox(&mut app.preferences.selection_shift_add_only, "").on_hover_text(crate::i18n::tr_label(
- "On: Shift adds items, Ctrl/Cmd toggles. Off (default): Shift and Ctrl/Cmd both toggle.",
- ));
- ui.end_row();
- }
- });
-}
-
-/// Sketch snap-suppress picker: classic Ctrl/Cmd-or-Alt first, then single keys.
-fn snap_suppress_picker(ui: &mut egui::Ui, salt: &str, combo: &mut ModifierCombo) {
- let label = combo.label();
- egui::ComboBox::from_id_salt(salt).selected_text(label).show_ui(ui, |ui| {
- for c in ModifierCombo::SNAP_SUPPRESS_CHOICES {
- ui.selectable_value(combo, c, c.label());
+ ui_kit::checkbox(ui, crate::i18n::tr_label("Click selects whole bodies"), &mut app.ui.pick_bodies);
+ ui_kit::section(ui, "selection_modifiers", crate::i18n::tr_label("Selection modifiers"), true, |ui| {
+ ui_kit::checkbox(ui, crate::i18n::tr_label("Shift+click adds without removing"), &mut app.preferences.selection_shift_add_only)
+ .on_hover_text(crate::i18n::tr_label("On: Shift adds items, Ctrl/Cmd toggles. Off (default): Shift and Ctrl/Cmd both toggle."));
+ });
}
- });
+ }
}
/// The names under the Colour vision sample (message ids).
@@ -2734,8 +2600,7 @@ mod ui_scale_regression_tests {
/// Both display-setting surfaces dispatch the same programmatic command.
pub(crate) fn ambient_occlusion_checkbox(app: &mut SolveApp, ui: &mut egui::Ui, label: &str) {
let mut enabled = app.preferences.ambient_occlusion;
- let response = ui
- .checkbox(&mut enabled, crate::i18n::tr_label(label))
+ let response = ui_kit::checkbox(ui, crate::i18n::tr_label(label), &mut enabled)
.on_hover_text(crate::i18n::tr_label("Soft shading where opaque surfaces meet. Requires the GPU viewport."));
crate::scenario::publish_handle("view:ambient_occlusion", response.rect.center());
if response.changed() {
@@ -2793,19 +2658,16 @@ fn graphics_preset(prefs: &Prefs) -> &'static str {
pub(crate) fn graphics_preset_selector(app: &mut SolveApp, ui: &mut egui::Ui) {
let current = graphics_preset(&app.preferences);
let label = format!("ui.graphics_{current}");
- let response = egui::ComboBox::from_id_salt("graphics_preset")
- .selected_text(app.tr(&label))
- .show_ui(ui, |ui| {
- for (preset, label) in [("performance", "ui.graphics_performance"), ("quality", "ui.graphics_quality")] {
- let item = ui.selectable_label(current == preset, app.tr(label));
- crate::scenario::publish_handle(&format!("view:graphics_preset:{preset}"), item.rect.center());
- if item.clicked() {
- let _ = app.run("view.graphics_preset", json!({"preset":preset}));
- }
+ let response = ui_kit::dropdown_menu(ui, "graphics_preset", app.tr(&label), |ui| {
+ for (preset, label) in [("performance", "ui.graphics_performance"), ("quality", "ui.graphics_quality")] {
+ let item = ui_kit::list_picker(ui, preset, app.tr(label), current == preset);
+ crate::scenario::publish_handle(&format!("view:graphics_preset:{preset}"), item.rect.center());
+ if item.clicked() {
+ let _ = app.run("view.graphics_preset", json!({"preset":preset}));
}
- })
- .response
- .on_hover_text(app.tr("ui.graphics_preset_help"));
+ }
+ })
+ .on_hover_text(app.tr("ui.graphics_preset_help"));
crate::scenario::publish_handle("view:graphics_preset", response.rect.center());
}
diff --git a/crates/ui-egui/src/prefs_notice.rs b/crates/ui-egui/src/prefs_notice.rs
new file mode 100644
index 0000000000..7cbc2607f5
--- /dev/null
+++ b/crates/ui-egui/src/prefs_notice.rs
@@ -0,0 +1,27 @@
+//! The notice for settings put back at start because they would keep SolidCraft from starting
+//! on this computer (`SolveApp::settings_reset`), shown until dismissed.
+
+use crate::SolveApp;
+use crate::ui_kit;
+
+/// Draw the notice while any setting was reset. OK dismisses it; "Open Preferences" dismisses it
+/// and opens the Graphics page.
+pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
+ if app.settings_reset.is_empty() {
+ return;
+ }
+ let (closed, action) = ui_kit::Prompt::new(egui::Id::new("sc_settings_reset"), "settings", app.tr("settings.reset_title"))
+ .actions(app.tr("ui.open_preferences"), app.tr("ui.heading_ok"), None)
+ .show(ctx, true, |ui| {
+ ui_kit::text_block(ui, "intro", app.tr("settings.reset_intro"), false);
+ for (index, reset) in app.settings_reset.iter().enumerate() {
+ ui_kit::text_block(ui, &format!("reset:{index}"), &format!("• {}", reset.message()), false);
+ }
+ });
+ if closed || action != ui_kit::Action::None {
+ app.settings_reset.clear();
+ }
+ if action == ui_kit::Action::Ok {
+ crate::prefs::open_at(app, crate::prefs::PAGE_GRAPHICS);
+ }
+}
diff --git a/crates/ui-egui/src/prompt_cards_tests.rs b/crates/ui-egui/src/prompt_cards_tests.rs
new file mode 100644
index 0000000000..ba152a2aa5
--- /dev/null
+++ b/crates/ui-egui/src/prompt_cards_tests.rs
@@ -0,0 +1,230 @@
+//! The confirmation and notice prompts share the kit's card: header (icon, title, close), body
+//! and pinned footer. Each keeps its answers (buttons, close, Esc, Enter).
+use serde_json::json;
+use solidcraft_engine::Sel;
+
+use crate::scenario::{self, Harness};
+
+fn press(h: &mut Harness, widget: &str) {
+ h.frames(3);
+ h.step(&json!({"widget": widget})).unwrap_or_else(|e| panic!("{widget}: {e}"));
+ h.frames(2);
+}
+
+fn card_is_drawn(h: &mut Harness) {
+ h.frames(3);
+ for key in ["dialog:header", "dialog:footer"] {
+ let rect = scenario::rect_of(key).unwrap_or_else(|| panic!("missing {key}"));
+ assert!(rect.is_finite() && rect.is_positive(), "{key}: {rect:?}");
+ }
+ assert!(scenario::handle_at("dialog:close").is_some() && scenario::handle_at("dialog:cancel").is_some());
+}
+
+/// A sketch with an extrude built on it: deleting the sketch takes another feature along.
+fn with_dependent_feature() -> Harness {
+ let mut h = Harness::new();
+ h.app.home.open = false;
+ h.app.run("sketch.create", json!({"plane": "XY", "name": "Base"})).unwrap();
+ h.app.run("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [10, 10]})).unwrap();
+ h.app.run("sketch.finish", json!({})).unwrap();
+ h.app.run("solid.extrude", json!({"profile": {"sketch": "Base", "index": 0}, "distance": 5})).unwrap();
+ let sketch = h.app.session.doc.features.iter().find(|f| f.name == "Base").unwrap().id;
+ h.app.run("select.set", json!({"items": [Sel::Feature { id: sketch }]})).unwrap();
+ crate::delete::delete_selection(&mut h.app);
+ assert!(h.app.menu.confirm.is_some(), "deleting the sketch asks first");
+ h
+}
+
+#[test]
+fn delete_confirmation_deletes_on_the_primary_action_and_keeps_everything_otherwise() {
+ let mut h = with_dependent_feature();
+ let features = h.app.session.doc.features.len();
+ card_is_drawn(&mut h);
+ assert!(scenario::handle_at("dialog:Delete").is_some(), "the primary action says what it does");
+ press(&mut h, "Cancel");
+ assert!(h.app.menu.confirm.is_none() && h.app.session.doc.features.len() == features);
+
+ let mut h = with_dependent_feature();
+ h.frames(3);
+ h.step(&json!({"key": "Escape"})).unwrap();
+ h.frames(2);
+ assert!(h.app.menu.confirm.is_none() && h.app.session.doc.features.len() == features, "Esc keeps everything");
+
+ let mut h = with_dependent_feature();
+ h.frames(3);
+ h.step(&json!({"click": {"handle": "dialog:close"}})).unwrap();
+ h.frames(2);
+ assert!(h.app.menu.confirm.is_none() && h.app.session.doc.features.len() == features, "the close button keeps everything");
+
+ let mut h = with_dependent_feature();
+ h.frames(3);
+ h.step(&json!({"click": {"handle": "dialog:Delete"}})).unwrap();
+ h.frames(2);
+ assert!(h.app.menu.confirm.is_none() && h.app.session.doc.features.len() < features);
+}
+
+#[test]
+fn legacy_delete_dialog_is_a_dense_card_whose_primary_action_is_delete() {
+ let mut h = with_dependent_feature();
+ h.app.menu.confirm = None;
+ h.app.dialog = Some(crate::dialogs::Dialog::confirm_delete(1, vec!["Extrude1".into()], vec!["Hole1".into()]));
+ card_is_drawn(&mut h);
+ assert!(scenario::handle_at("dialog:Delete").is_some() && scenario::rect_of("dialog:row:Also deletes").is_some());
+ press(&mut h, "Cancel");
+ assert!(h.app.dialog.is_none());
+}
+
+#[test]
+fn measure_card_only_closes_and_rename_card_takes_a_name() {
+ let mut h = Harness::new();
+ h.app.home.open = false;
+ h.step(&json!({"start": "inspect.measure"})).unwrap();
+ card_is_drawn(&mut h);
+ assert!(scenario::handle_at("dialog:ok").is_none(), "Measure has nothing to confirm");
+ assert!(scenario::rect_of("dialog:hint:measure").is_some(), "it says what to pick");
+ h.step(&json!({"key": "Enter"})).unwrap();
+ h.frames(2);
+ assert!(h.app.dialog.is_some(), "Enter does not close Measure");
+ press(&mut h, "Close");
+ assert!(h.app.dialog.is_none());
+
+ h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10})).unwrap();
+ let id = h.app.session.doc.features.last().unwrap().id;
+ h.app.dialog = Some(crate::dialogs::Dialog::rename(id, "Block"));
+ card_is_drawn(&mut h);
+ assert!(scenario::handle_at("dialog:Name").is_some());
+ h.step(&json!({"key": "A", "cmd": true})).unwrap();
+ h.step(&json!({"text": "Housing"})).unwrap();
+ h.step(&json!({"key": "Enter"})).unwrap();
+ h.frames(3);
+ assert!(h.app.dialog.is_none(), "Enter accepts the name");
+ assert!(h.app.session.doc.features.iter().any(|f| f.name == "Housing"));
+}
+
+#[test]
+fn section_card_keeps_its_distance_and_flip() {
+ let mut h = Harness::new();
+ h.app.home.open = false;
+ h.app.run("solid.box", json!({"length": 40, "width": 30, "height": 20})).unwrap();
+ h.app.session.selection = vec![Sel::Plane { name: "XZ".into() }];
+ h.step(&json!({"start": "inspect.section"})).unwrap();
+ card_is_drawn(&mut h);
+ assert!(scenario::handle_at("dialog:Distance").is_some());
+ h.step(&json!({"widget": "Flip"})).unwrap();
+ h.frames(2);
+ assert!(matches!(h.app.dialog.as_ref().map(|d| &d.kind), Some(crate::dialogs::Kind::Section { flip: true, .. })));
+}
+
+#[test]
+fn save_prompt_moves_between_its_actions_with_the_arrow_keys() {
+ use crate::documents::Answer;
+ let mut h = Harness::new();
+ h.app.home.open = false;
+ h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10})).unwrap();
+ h.app.docs.closing = Some(h.app.docs.active);
+ h.frames(3);
+ card_is_drawn(&mut h);
+ for label in ["Save", "Don't Save", "Cancel"] {
+ assert!(scenario::handle_at(&format!("dialog:{label}")).is_some(), "{label}");
+ }
+ assert_eq!(h.app.docs.choice, Answer::Save);
+ // The buttons read Cancel, Don't Save, Save from the left: Left walks toward Cancel.
+ h.step(&json!({"key": "ArrowLeft"})).unwrap();
+ h.frames(2);
+ assert_eq!(h.app.docs.choice, Answer::DontSave);
+ h.step(&json!({"key": "ArrowRight"})).unwrap();
+ h.frames(2);
+ assert_eq!(h.app.docs.choice, Answer::Save);
+ h.step(&json!({"key": "ArrowLeft"})).unwrap();
+ h.step(&json!({"key": "ArrowLeft"})).unwrap();
+ h.frames(2);
+ assert_eq!(h.app.docs.choice, Answer::Cancel);
+ h.step(&json!({"key": "Enter"})).unwrap();
+ h.frames(2);
+ assert!(h.app.docs.closing.is_none(), "Enter gave the picked Cancel");
+ assert!(h.app.session.is_dirty(), "nothing was discarded");
+}
+
+#[test]
+fn capture_question_offers_capture_revert_and_cancel() {
+ let mut h = Harness::new();
+ h.app.home.open = false;
+ h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10})).unwrap();
+ let body = h.app.session.model.state().bodies[0].name.clone();
+ h.app.run("component.from_bodies", json!({"bodies": [body]})).unwrap();
+ let occ = h.app.session.doc.occurrences[0].id;
+ h.app.run("occurrence.move", json!({"occurrence": occ, "translate": [10, 0, 0], "capture": false})).unwrap();
+ h.app.start("sketch.create");
+ card_is_drawn(&mut h);
+ press(&mut h, "Cancel");
+ assert!(h.app.tree.capture_prompt.is_none() && !h.app.session.pending_moves.is_empty());
+ h.app.start("sketch.create");
+ press(&mut h, "Revert");
+ assert!(h.app.session.pending_moves.is_empty() && h.app.dialog.is_some());
+}
+
+/// Type `text` into the card's X distance field.
+fn type_distance(h: &mut Harness, text: &str) {
+ h.step(&json!({"click": {"handle": "occurrence-move:distance:0"}, "double": true})).unwrap();
+ h.frames(2);
+ h.step(&json!({"key": "A", "cmd": true})).unwrap();
+ h.step(&json!({"text": text})).unwrap();
+ h.step(&json!({"key": "Enter"})).unwrap();
+ h.frames(3);
+}
+
+#[test]
+fn occurrence_move_card_edits_distances_and_captures_or_reverts() {
+ let mut h = Harness::new();
+ h.app.home.open = false;
+ h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10})).unwrap();
+ let body = h.app.session.model.state().bodies[0].name.clone();
+ h.app.run("component.from_bodies", json!({"bodies": [body]})).unwrap();
+ let occ = h.app.session.doc.occurrences[0].id;
+ h.app.tree.occurrence_move = Some(crate::browser::OccMove::new(occ));
+ card_is_drawn(&mut h);
+ for k in 0..3 {
+ assert!(scenario::handle_at(&format!("occurrence-move:distance:{k}")).is_some());
+ assert!(scenario::handle_at(&format!("occurrence-move:angle:{k}")).is_some());
+ }
+ type_distance(&mut h, "5");
+ assert!(!h.app.session.pending_moves.is_empty(), "the move is pending");
+ press(&mut h, "Cancel");
+ assert!(h.app.tree.occurrence_move.is_none() && h.app.session.pending_moves.is_empty(), "Cancel puts the move back");
+
+ h.app.tree.occurrence_move = Some(crate::browser::OccMove::new(occ));
+ h.frames(3);
+ type_distance(&mut h, "5");
+ assert!(!h.app.session.pending_moves.is_empty(), "the move is pending");
+ press(&mut h, "Capture All Positions");
+ assert!(h.app.tree.occurrence_move.is_none() && h.app.session.pending_moves.is_empty());
+}
+
+#[test]
+fn settings_reset_notice_dismisses_or_opens_the_graphics_page() {
+ let mut h = Harness::new();
+ h.app.home.open = false;
+ h.app.settings_reset = vec![crate::prefs::SettingReset::Msaa { requested: 8, reset: 4, supported: vec![1, 4] }];
+ card_is_drawn(&mut h);
+ press(&mut h, "OK");
+ assert!(h.app.settings_reset.is_empty() && !h.app.prefs_window.open);
+ h.app.settings_reset = vec![crate::prefs::SettingReset::Msaa { requested: 8, reset: 4, supported: vec![1, 4] }];
+ h.frames(3);
+ press(&mut h, "Open Preferences");
+ assert!(h.app.settings_reset.is_empty() && h.app.prefs_window.open);
+ assert_eq!(h.app.prefs_window.section, crate::prefs::PAGE_GRAPHICS);
+}
+
+#[test]
+fn object_properties_card_only_closes() {
+ let mut h = Harness::new();
+ h.app.home.open = false;
+ h.app.run("solid.box", json!({"length": 10, "width": 20, "height": 30})).unwrap();
+ let v = h.app.run("inspect.measure", json!({})).unwrap();
+ h.app.menu.props = Some(("Body1".into(), v));
+ card_is_drawn(&mut h);
+ assert!(scenario::handle_at("dialog:ok").is_none());
+ assert!(scenario::rect_of("dialog:row:Mass").is_some() && scenario::rect_of("dialog:row:Volume").is_some());
+ press(&mut h, "Close");
+ assert!(h.app.menu.props.is_none());
+}
diff --git a/crates/ui-egui/src/recovery_ui.rs b/crates/ui-egui/src/recovery_ui.rs
index 9780d1fcbd..6a28e9b46a 100644
--- a/crates/ui-egui/src/recovery_ui.rs
+++ b/crates/ui-egui/src/recovery_ui.rs
@@ -1,11 +1,10 @@
//! Autosave ticks and the "Recover unsaved design?" window shown at launch.
-use crate::fonts::RichTextExt as _;
-use egui::RichText;
use serde_json::json;
use solidcraft_engine::recovery::{self, Autosaver, Entry};
use crate::SolveApp;
+use crate::ui_kit;
/// A command that ran at least this long counts as a big operation: autosave right after it.
pub const BIG_OPERATION_MS: f64 = 1500.0;
@@ -44,10 +43,10 @@ fn ago(secs: u64) -> String {
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(secs);
let d = now.saturating_sub(secs);
match d {
- 0..=59 => "just now".into(),
- 60..=3599 => format!("{} min ago", d / 60),
- 3600..=86_399 => format!("{} h ago", d / 3600),
- _ => format!("{} days ago", d / 86_400),
+ 0..=59 => crate::i18n::tr("recovery.just_now").to_string(),
+ 60..=3599 => crate::i18n::format("recovery.min_ago", &[("count", &(d / 60).to_string())]),
+ 3600..=86_399 => crate::i18n::format("recovery.hours_ago", &[("count", &(d / 3600).to_string())]),
+ _ => crate::i18n::format("recovery.days_ago", &[("count", &(d / 86_400).to_string())]),
}
}
@@ -57,42 +56,32 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
}
let dir = app.autosave.as_ref().map(|a| a.dir.clone()).or_else(recovery::default_dir);
let mut act: Option<(Entry, bool)> = None;
- let mut later = false;
- crate::frame::window(
- ctx,
- RichText::new(crate::i18n::tr_label("Recover unsaved design?"))
- .semibold()
- .color(crate::theme::Tokens::get().text)
- .size(crate::theme::Tokens::get().font_button),
- crate::frame::Width::Normal,
- )
- .collapsible(false)
- .resizable(false)
- .min_width(420.0)
- .anchor(egui::Align2::CENTER_CENTER, egui::vec2(0.0, 0.0))
- .show(ctx, |ui| {
- ui.label(crate::i18n::tr_label("SolidCraft closed before these designs were saved. Their last autosave can be opened."));
- ui.add_space(6.0);
- for e in app.recoverable.iter().take(20) {
- ui.label(RichText::new(&e.name).semibold().color(crate::theme::Tokens::get().text));
- let file = e.path.clone().unwrap_or_else(|| "never saved".into());
- ui.label(RichText::new(format!("{file} · {} features · autosaved {}", e.features, ago(e.saved_at))).small().weak());
- ui.horizontal(|ui| {
- if ui.button(crate::i18n::tr_label("Recover")).clicked() {
- act = Some((e.clone(), true));
- }
- if ui.button(crate::i18n::tr_label("Discard")).clicked() {
- act = Some((e.clone(), false));
- }
- });
- ui.separator();
- }
- ui.horizontal(|ui| {
- if ui.button(crate::i18n::tr_label("Later")).on_hover_text("Keep them; ask again next launch").clicked() {
- later = true;
+ let (closed, action) = ui_kit::Prompt::new(egui::Id::new("sc_recover_prompt"), "restore", crate::i18n::tr_label("Recover unsaved design?"))
+ .actions("", crate::i18n::tr_label("Later"), None)
+ .show(ctx, true, |ui| {
+ ui_kit::text_block(
+ ui,
+ "intro",
+ crate::i18n::tr_label("SolidCraft closed before these designs were saved. Their last autosave can be opened."),
+ false,
+ );
+ for (index, e) in app.recoverable.iter().take(20).enumerate() {
+ ui_kit::divider(ui, &format!("entry:{index}"));
+ ui_kit::label_actions(ui, &e.name, |ui| {
+ if ui_kit::secondary_button(ui, crate::i18n::tr_label("Recover")).clicked() {
+ act = Some((e.clone(), true));
+ }
+ if ui_kit::secondary_button(ui, crate::i18n::tr_label("Discard")).clicked() {
+ act = Some((e.clone(), false));
+ }
+ });
+ let file = e.path.clone().unwrap_or_else(|| crate::i18n::tr("recovery.never_saved").to_string());
+ let detail =
+ crate::i18n::format("recovery.detail", &[("file", &file), ("features", &e.features.to_string()), ("when", &ago(e.saved_at))]);
+ ui_kit::note(ui, &format!("detail:{index}"), &detail);
}
});
- });
+ let later = closed || action != ui_kit::Action::None;
let dir_s = dir.map(|d| d.to_string_lossy().to_string());
if let Some((e, recover)) = act {
app.recoverable.retain(|x| x.id != e.id);
@@ -114,3 +103,28 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
app.recoverable.clear();
}
}
+
+#[cfg(test)]
+mod tests {
+ use serde_json::json;
+ use solidcraft_engine::recovery::Entry;
+
+ fn entry(id: &str, name: &str) -> Entry {
+ Entry { id: id.into(), path: None, name: name.into(), saved_at: 0, features: 3 }
+ }
+
+ #[test]
+ fn recovered_sessions_are_a_card_with_one_row_each_and_later_keeps_them_for_next_launch() {
+ let mut h = crate::scenario::Harness::new();
+ h.app.home.open = false;
+ h.app.recoverable = vec![entry("a", "Bracket"), entry("b", "Housing")];
+ h.frames(4);
+ assert!(crate::scenario::handle_at("dialog:close").is_some(), "a kit card");
+ assert!(h.widget("Recover").is_some() && h.widget("Discard").is_some() && h.widget("Later").is_some());
+ assert!(crate::scenario::handle_at("dialog:cell:Bracket").is_some(), "one row per design");
+ assert!(crate::scenario::handle_at("dialog:cell:Housing").is_some());
+ h.step(&json!({"widget": "Later"})).unwrap();
+ h.frames(2);
+ assert!(h.app.recoverable.is_empty(), "Later hides the card for this launch");
+ }
+}
diff --git a/crates/ui-egui/src/render_workspace.rs b/crates/ui-egui/src/render_workspace.rs
index 481081c4ff..26e971f177 100644
--- a/crates/ui-egui/src/render_workspace.rs
+++ b/crates/ui-egui/src/render_workspace.rs
@@ -178,78 +178,84 @@ pub fn panel(app: &mut SolveApp, ui: &mut egui::Ui) {
.resizable(false)
.frame(egui::Frame::NONE.fill(Tokens::get().panel).inner_margin(10))
.show(ui, |ui| {
- egui::ScrollArea::vertical().show(ui, |ui| {
- ui.heading(app.tr("cmd.render_settings_get"));
- ui.label(app.tr("render.preview"));
- ui.small(app.tr("render.opaque_preview_help"));
- ui.separator();
- let names: Vec<_> = app.session.doc.render.setups.keys().cloned().collect();
- let old_name = app.render_workspace.view.name.clone();
- egui::ComboBox::from_id_salt("render_setups").selected_text(&old_name).show_ui(ui, |ui| {
- for name in names {
- ui.selectable_value(&mut app.render_workspace.view.name, name.clone(), name);
+ crate::ui_kit::scope(ui, |ui| {
+ egui::ScrollArea::vertical().show(ui, |ui| {
+ ui.heading(app.tr("cmd.render_settings_get"));
+ ui.label(app.tr("render.preview"));
+ ui.small(app.tr("render.opaque_preview_help"));
+ ui.separator();
+ let names: Vec<_> = app.session.doc.render.setups.keys().cloned().collect();
+ let old_name = app.render_workspace.view.name.clone();
+ crate::ui_kit::dropdown_menu(ui, "render_setups", &old_name, |ui| {
+ for name in names {
+ if crate::ui_kit::list_picker(ui, &name, &name, name == app.render_workspace.view.name).clicked() {
+ app.render_workspace.view.name = name;
+ ui.close();
+ }
+ }
+ });
+ ui.label(app.tr("render.setup_name"));
+ crate::ui_kit::bounded_cell_editor(ui, ui.id().with("render_setup_name"), &mut app.render_workspace.view.name, "", false, 128);
+ if app.render_workspace.view.name != old_name {
+ app.render_workspace.view.draft =
+ app.session.doc.render.setups.get(&app.render_workspace.view.name).cloned().unwrap_or_default();
+ app.render_workspace.view.dirty = false;
}
- });
- ui.label(app.tr("render.setup_name"));
- ui.add(egui::TextEdit::singleline(&mut app.render_workspace.view.name).char_limit(128));
- if app.render_workspace.view.name != old_name {
- app.render_workspace.view.draft = app.session.doc.render.setups.get(&app.render_workspace.view.name).cloned().unwrap_or_default();
- app.render_workspace.view.dirty = false;
- }
- ui.separator();
- ui.label(app.tr("render.background"));
- if ui.color_edit_button_srgb(&mut app.render_workspace.view.draft.background).changed() {
- app.render_workspace.view.dirty = true;
- }
- let mut perspective = app.cam.fov > 0.0;
- if ui.checkbox(&mut perspective, app.tr("render.perspective")).changed() {
- app.cam.fov = if perspective { std::f64::consts::FRAC_PI_4 } else { 0.0 };
- app.render_workspace.view.dirty = true;
- }
- if ui.button(app.tr("render.fit")).clicked() {
- match solidcraft_engine::product_scene::extract(&app.session) {
- Ok(scene) if !scene.bounds.is_empty() => app.cam.fit(&scene.bounds),
- Err(e) => app.set_status(e.to_string(), true),
- _ => {}
+ ui.separator();
+ ui.label(app.tr("render.background"));
+ if crate::ui_kit::color_field(ui, &mut app.render_workspace.view.draft.background).changed() {
+ app.render_workspace.view.dirty = true;
}
- }
- if ui.button(app.tr("render.restore_camera")).clicked() {
- let name = app.render_workspace.view.name.clone();
- if app.run("render.settings.apply", json!({"name":name})).is_ok() {
- app.follow_view_request(false);
+ let mut perspective = app.cam.fov > 0.0;
+ if crate::ui_kit::checkbox(ui, app.tr("render.perspective"), &mut perspective).changed() {
+ app.cam.fov = if perspective { std::f64::consts::FRAC_PI_4 } else { 0.0 };
+ app.render_workspace.view.dirty = true;
}
- }
- if ui.button(app.tr("render.save_setup")).clicked() {
- let name = app.render_workspace.view.name.clone();
- let setup = RenderSetup { camera: app.cam, ..app.render_workspace.view.draft.clone() };
- if app.run("render.settings.set", json!({"name":name,"set":setup})).is_ok() {
+ if crate::ui_kit::secondary_button(ui, app.tr("render.fit")).clicked() {
+ match solidcraft_engine::product_scene::extract(&app.session) {
+ Ok(scene) if !scene.bounds.is_empty() => app.cam.fit(&scene.bounds),
+ Err(e) => app.set_status(e.to_string(), true),
+ _ => {}
+ }
+ }
+ if crate::ui_kit::secondary_button(ui, app.tr("render.restore_camera")).clicked() {
+ let name = app.render_workspace.view.name.clone();
+ if app.run("render.settings.apply", json!({"name":name})).is_ok() {
+ app.follow_view_request(false);
+ }
+ }
+ if crate::ui_kit::secondary_button(ui, app.tr("render.save_setup")).clicked() {
+ let name = app.render_workspace.view.name.clone();
+ let setup = RenderSetup { camera: app.cam, ..app.render_workspace.view.draft.clone() };
+ if app.run("render.settings.set", json!({"name":name,"set":setup})).is_ok() {
+ app.render_workspace.view.dirty = false;
+ }
+ }
+ if app.render_workspace.view.dirty {
+ ui.label(app.tr("render.unsaved"));
+ }
+ if crate::ui_kit::secondary_button(ui, app.tr("render.reload_settings")).clicked() {
app.render_workspace.view.dirty = false;
+ app.render_workspace.revision = u64::MAX;
}
- }
- if app.render_workspace.view.dirty {
- ui.label(app.tr("render.unsaved"));
- }
- if ui.button(app.tr("render.reload_settings")).clicked() {
- app.render_workspace.view.dirty = false;
- app.render_workspace.revision = u64::MAX;
- }
- if app.render_workspace.view.draft.backend.as_str() != "builtin" || app.render_workspace.view.draft.mode != RenderMode::Preview {
- ui.label(app.tr("render.unavailable_preview"));
- if ui.button(app.tr("render.use_preview")).clicked() {
- app.render_workspace.view.draft.backend = solidcraft_engine::render::builtin_backend().id;
- app.render_workspace.view.draft.mode = RenderMode::Preview;
- app.render_workspace.view.dirty = true;
+ if app.render_workspace.view.draft.backend.as_str() != "builtin" || app.render_workspace.view.draft.mode != RenderMode::Preview {
+ ui.label(app.tr("render.unavailable_preview"));
+ if crate::ui_kit::secondary_button(ui, app.tr("render.use_preview")).clicked() {
+ app.render_workspace.view.draft.backend = solidcraft_engine::render::builtin_backend().id;
+ app.render_workspace.view.draft.mode = RenderMode::Preview;
+ app.render_workspace.view.dirty = true;
+ }
}
- }
- ui.separator();
- image_controls(app, ui);
- ui.separator();
- ui.small(app.tr("render.navigation_help"));
- if ui.button(app.tr("render.return_design")).clicked()
- && let Err(e) = enter(app, false)
- {
- app.set_status(e, true);
- }
+ ui.separator();
+ image_controls(app, ui);
+ ui.separator();
+ ui.small(app.tr("render.navigation_help"));
+ if crate::ui_kit::secondary_button(ui, app.tr("render.return_design")).clicked()
+ && let Err(e) = enter(app, false)
+ {
+ app.set_status(e, true);
+ }
+ });
});
});
}
@@ -259,11 +265,11 @@ fn image_controls(app: &mut SolveApp, ui: &mut egui::Ui) {
ui.small(app.tr("render.opaque_image_summary"));
ui.horizontal(|ui| {
ui.label(app.tr("render.image_width"));
- if ui.add(egui::DragValue::new(&mut app.render_workspace.view.draft.width).range(1..=4096)).changed() {
+ if crate::ui_kit::number_field(ui, &mut app.render_workspace.view.draft.width, 1..=4096, 1.0, "").changed() {
app.render_workspace.view.dirty = true;
}
ui.label(app.tr("render.image_height"));
- if ui.add(egui::DragValue::new(&mut app.render_workspace.view.draft.height).range(1..=4096)).changed() {
+ if crate::ui_kit::number_field(ui, &mut app.render_workspace.view.draft.height, 1..=4096, 1.0, "").changed() {
app.render_workspace.view.dirty = true;
}
});
@@ -273,15 +279,15 @@ fn image_controls(app: &mut SolveApp, ui: &mut egui::Ui) {
&& (w, h) != size
{
ui.small(app.tr("render.image_too_large"));
- if ui.button(format!("{} {w} × {h}", app.tr("render.image_use_largest"))).clicked() {
+ if crate::ui_kit::secondary_button(ui, format!("{} {w} × {h}", app.tr("render.image_use_largest"))).clicked() {
app.render_workspace.view.draft.width = u32::try_from(w).unwrap_or(1);
app.render_workspace.view.draft.height = u32::try_from(h).unwrap_or(1);
app.render_workspace.view.dirty = true;
}
}
let transparent_label = app.tr("render.image_transparent").to_string();
- ui.checkbox(&mut app.render_workspace.view.transparent, transparent_label);
- if ui.button(app.tr("render.image_check")).clicked() {
+ crate::ui_kit::checkbox(ui, &transparent_label, &mut app.render_workspace.view.transparent);
+ if crate::ui_kit::secondary_button(ui, app.tr("render.image_check")).clicked() {
let settings = RenderSetup { camera: app.cam, ..app.render_workspace.view.draft.clone() };
if app.run("render.preflight", json!({"settings":settings,"transparent_background":app.render_workspace.view.transparent})).is_ok() {
app.set_status(app.tr("render.image_supported").to_string(), false);
@@ -316,9 +322,9 @@ fn image_controls(app: &mut SolveApp, ui: &mut egui::Ui) {
if busy {
let done = status["progress"]["done"].as_u64().unwrap_or(0);
let total = status["progress"]["total"].as_u64().unwrap_or(1).max(1);
- ui.add(egui::ProgressBar::new((done as f64 / total as f64).clamp(0.0, 1.0) as f32));
+ crate::ui_kit::progress(ui, "render", (done as f64 / total as f64).clamp(0.0, 1.0) as f32);
ui.ctx().request_repaint();
- if ui.button(app.tr("render.image_cancel")).clicked() {
+ if crate::ui_kit::secondary_button(ui, app.tr("render.image_cancel")).clicked() {
let _ = app.run("render.cancel", json!({"job":job}));
}
}
@@ -333,7 +339,7 @@ fn image_controls(app: &mut SolveApp, ui: &mut egui::Ui) {
}
}
}
- if ui.add_enabled(!busy, egui::Button::new(app.tr("render.image_start"))).clicked() {
+ if crate::ui_kit::enabled_button(ui, app.tr("render.image_start"), !busy).clicked() {
let settings = RenderSetup { camera: app.cam, ..app.render_workspace.view.draft.clone() };
if let Ok(reply) = app.run("render.start", json!({"settings":settings,"transparent_background":app.render_workspace.view.transparent})) {
app.render_workspace.view.job = serde_json::from_value(reply["job"].clone()).ok();
@@ -341,8 +347,8 @@ fn image_controls(app: &mut SolveApp, ui: &mut egui::Ui) {
}
}
let overwrite_label = app.tr("render.image_overwrite").to_string();
- ui.checkbox(&mut app.render_workspace.view.overwrite, overwrite_label);
- if ui.add_enabled(app.render_workspace.view.completed.is_some(), egui::Button::new(app.tr("render.image_export"))).clicked()
+ crate::ui_kit::checkbox(ui, &overwrite_label, &mut app.render_workspace.view.overwrite);
+ if crate::ui_kit::enabled_button(ui, app.tr("render.image_export"), app.render_workspace.view.completed.is_some()).clicked()
&& let Some(job) = app.render_workspace.view.completed
{
export_image(app, job, app.render_workspace.view.overwrite);
diff --git a/crates/ui-egui/src/shortcut_box.rs b/crates/ui-egui/src/shortcut_box.rs
index ff2b35ed90..ba9abb1968 100644
--- a/crates/ui-egui/src/shortcut_box.rs
+++ b/crates/ui-egui/src/shortcut_box.rs
@@ -9,7 +9,7 @@ use serde_json::{Value, json};
use solidcraft_engine::command_specs;
use crate::theme::Tokens;
-use crate::{SolveApp, icons};
+use crate::{SolveApp, icons, ui_kit};
/// How many recent commands are kept.
const RECENT: usize = 12;
@@ -177,7 +177,7 @@ fn run_typed(app: &mut SolveApp, line: &str) {
let split = line.find(|c: char| c.is_whitespace() || c == '{').unwrap_or(line.len());
let (id, rest) = (line.get(..split).unwrap_or_default(), line.get(split..).unwrap_or_default().trim());
let Some(command) = solidcraft_engine::find_command(id) else {
- app.set_status(format!("no command `{id}`; the text before the JSON must be a command id"), true);
+ app.set_status(crate::i18n::format("shortcut.no_command", &[("id", id)]), true);
return;
};
match serde_json::from_str::<Value>(rest) {
@@ -185,7 +185,7 @@ fn run_typed(app: &mut SolveApp, line: &str) {
app.sbox.used(command.id);
let _ = app.run(command.id, params);
}
- Err(e) => app.set_status(format!("parameters must be JSON: {e}"), true),
+ Err(e) => app.set_status(crate::i18n::format("shortcut.json_error", &[("error", &e.to_string())]), true),
}
}
@@ -231,99 +231,97 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
);
let resp = crate::frame::area(egui::Id::new("sc_sbox")).fixed_pos(pos).order(egui::Order::Foreground).show(ctx, |ui| {
crate::context_menu::menu_frame(ui, |ui| {
- ui.set_width(w - 10.0);
- // Pinned commands: a mini toolbar.
- if !app.sbox.pinned.is_empty() {
- ui.horizontal_wrapped(|ui| {
- for id in app.sbox.pinned.clone() {
- let Some(c) = solidcraft_engine::find_command(&id) else { continue };
- let (r, resp) = ui.allocate_exact_size(vec2(28.0, 28.0), Sense::click());
- if resp.hovered() {
+ ui_kit::scope(ui, |ui| {
+ ui.set_width(w - 10.0);
+ // Pinned commands: a mini toolbar.
+ if !app.sbox.pinned.is_empty() {
+ ui.horizontal_wrapped(|ui| {
+ for id in app.sbox.pinned.clone() {
+ let Some(c) = solidcraft_engine::find_command(&id) else { continue };
+ let (r, resp) = ui.allocate_exact_size(vec2(28.0, 28.0), Sense::click());
+ if resp.hovered() {
+ ui.painter().rect_filled(r, 4.0, t.hover);
+ }
+ icons::paint(ui.painter(), r.shrink(5.0), c.icon, t.icon, t.icon_fill, t.accent);
+ if resp.on_hover_text(crate::i18n::tr_label(c.label)).clicked() {
+ picked = Some(c.id);
+ }
+ }
+ });
+ ui.separator();
+ }
+ let te = ui_kit::search_field(ui, egui::Id::new("sc_sbox_text"), &mut app.sbox.text, crate::i18n::tr_label("Search commands"));
+ crate::scenario::publish_rect("shortcut:search", te.rect);
+ if std::mem::take(&mut app.sbox.focus) {
+ te.request_focus();
+ }
+ if te.changed() {
+ app.sbox.index = 0;
+ }
+ ui.add_space(4.0);
+ if app.sbox.text.trim().is_empty() && !app.sbox.recent.is_empty() {
+ ui.label(egui::RichText::new(crate::i18n::tr_label("RECENT")).size(crate::theme::Tokens::get().font_micro).color(t.text_dim));
+ }
+ egui::ScrollArea::vertical().max_height(h - 90.0).show(ui, |ui| {
+ ui.spacing_mut().item_spacing.y = 0.0;
+ for (i, (id, label, icon, place)) in list.iter().enumerate().take(80) {
+ let enabled = solidcraft_engine::find_command(id).is_some_and(|c| c.info(&app.session).enabled);
+ let (r, resp) = ui.allocate_exact_size(vec2(w - 20.0, 26.0), Sense::click());
+ let lit = i == app.sbox.index || resp.hovered();
+ if lit {
ui.painter().rect_filled(r, 4.0, t.hover);
+ if i == app.sbox.index && (up || down) {
+ ui.scroll_to_rect(r, None);
+ }
}
- icons::paint(ui.painter(), r.shrink(5.0), c.icon, t.icon, t.icon_fill, t.accent);
- if resp.on_hover_text(crate::i18n::tr_label(c.label)).clicked() {
- picked = Some(c.id);
+ let ink = if enabled { t.icon } else { t.border };
+ icons::paint(
+ ui.painter(),
+ Rect::from_center_size(pos2(r.left() + 14.0, r.center().y), vec2(16.0, 16.0)),
+ icon,
+ ink,
+ t.icon_fill,
+ t.accent,
+ );
+ let col = if enabled { t.text } else { t.text_dim };
+ ui.painter().text(
+ pos2(r.left() + 30.0, r.center().y),
+ Align2::LEFT_CENTER,
+ label,
+ FontId::proportional(crate::theme::Tokens::get().font_button),
+ col,
+ );
+ let key = crate::keymap::effective(app, id).unwrap_or_default();
+ paint_key_and_place(ui.painter(), pos2(r.right() - 26.0, r.center().y), &key, *place, t.text_dim);
+ // The pin.
+ let pinned = app.sbox.pinned.iter().any(|p| p == id);
+ let pr = Rect::from_center_size(pos2(r.right() - 11.0, r.center().y), vec2(16.0, 16.0));
+ let presp = ui.interact(pr, ui.id().with(("pin", *id)), Sense::click());
+ if pinned || lit {
+ let c = pr.center();
+ let pts: Vec<Pos2> = (0..10)
+ .map(|k| {
+ let a = std::f32::consts::PI * (k as f32 / 5.0) - std::f32::consts::FRAC_PI_2;
+ let rr = if k % 2 == 0 { 6.0 } else { 2.6 };
+ c + vec2(a.cos() * rr, a.sin() * rr)
+ })
+ .collect();
+ if pinned {
+ ui.painter().add(egui::Shape::convex_polygon(pts.clone(), t.warning, Stroke::NONE));
+ }
+ ui.painter().add(egui::Shape::closed_line(pts, Stroke::new(1.0, if pinned { t.warning } else { t.text_dim })));
}
- }
- });
- ui.separator();
- }
- let te = ui.add(
- egui::TextEdit::singleline(&mut app.sbox.text)
- .hint_text(crate::i18n::tr_label("Search commands"))
- .desired_width(w - 20.0)
- .id(egui::Id::new("sc_sbox_text")),
- );
- if std::mem::take(&mut app.sbox.focus) {
- te.request_focus();
- }
- if te.changed() {
- app.sbox.index = 0;
- }
- ui.add_space(4.0);
- if app.sbox.text.trim().is_empty() && !app.sbox.recent.is_empty() {
- ui.label(egui::RichText::new(crate::i18n::tr_label("RECENT")).size(crate::theme::Tokens::get().font_micro).color(t.text_dim));
- }
- egui::ScrollArea::vertical().max_height(h - 90.0).show(ui, |ui| {
- ui.spacing_mut().item_spacing.y = 0.0;
- for (i, (id, label, icon, place)) in list.iter().enumerate().take(80) {
- let enabled = solidcraft_engine::find_command(id).is_some_and(|c| c.info(&app.session).enabled);
- let (r, resp) = ui.allocate_exact_size(vec2(w - 20.0, 26.0), Sense::click());
- let lit = i == app.sbox.index || resp.hovered();
- if lit {
- ui.painter().rect_filled(r, 4.0, t.hover);
- if i == app.sbox.index && (up || down) {
- ui.scroll_to_rect(r, None);
+ if presp.on_hover_text(crate::i18n::tr(if pinned { "shortcut.unpin" } else { "shortcut.pin" })).clicked() {
+ pin = Some(id);
+ } else if resp.clicked() && enabled {
+ picked = Some(id);
}
- }
- let ink = if enabled { t.icon } else { t.border };
- icons::paint(
- ui.painter(),
- Rect::from_center_size(pos2(r.left() + 14.0, r.center().y), vec2(16.0, 16.0)),
- icon,
- ink,
- t.icon_fill,
- t.accent,
- );
- let col = if enabled { t.text } else { t.text_dim };
- ui.painter().text(
- pos2(r.left() + 30.0, r.center().y),
- Align2::LEFT_CENTER,
- label,
- FontId::proportional(crate::theme::Tokens::get().font_button),
- col,
- );
- let key = crate::keymap::effective(app, id).unwrap_or_default();
- paint_key_and_place(ui.painter(), pos2(r.right() - 26.0, r.center().y), &key, *place, t.text_dim);
- // The pin.
- let pinned = app.sbox.pinned.iter().any(|p| p == id);
- let pr = Rect::from_center_size(pos2(r.right() - 11.0, r.center().y), vec2(16.0, 16.0));
- let presp = ui.interact(pr, ui.id().with(("pin", *id)), Sense::click());
- if pinned || lit {
- let c = pr.center();
- let pts: Vec<Pos2> = (0..10)
- .map(|k| {
- let a = std::f32::consts::PI * (k as f32 / 5.0) - std::f32::consts::FRAC_PI_2;
- let rr = if k % 2 == 0 { 6.0 } else { 2.6 };
- c + vec2(a.cos() * rr, a.sin() * rr)
- })
- .collect();
- if pinned {
- ui.painter().add(egui::Shape::convex_polygon(pts.clone(), t.warning, Stroke::NONE));
+ if resp.secondary_clicked() {
+ menu = Some((resp.interact_pointer_pos().unwrap_or(r.left_bottom()), id));
}
- ui.painter().add(egui::Shape::closed_line(pts, Stroke::new(1.0, if pinned { t.warning } else { t.text_dim })));
}
- if presp.on_hover_text(crate::i18n::tr(if pinned { "ui.sbox_unpin" } else { "ui.sbox_pin" })).clicked() {
- pin = Some(id);
- } else if resp.clicked() && enabled {
- picked = Some(id);
- }
- if resp.secondary_clicked() {
- menu = Some((resp.interact_pointer_pos().unwrap_or(r.left_bottom()), id));
- }
- }
- });
+ });
+ })
});
});
crate::scenario::publish_rect("ribbon:search_popup", resp.response.rect);
diff --git a/crates/ui-egui/src/sketch_dims.rs b/crates/ui-egui/src/sketch_dims.rs
index c81b638f09..b79ba23c1b 100644
--- a/crates/ui-egui/src/sketch_dims.rs
+++ b/crates/ui-egui/src/sketch_dims.rs
@@ -425,18 +425,8 @@ fn boxes(app: &SolveApp, ui: &mut egui::Ui, proj: &Proj, t: &mut Tool) -> Option
let pos = in_view(sp + vec2(-34.0, -11.0), view, ui.ctx().pointer_latest_pos());
crate::frame::area(egui::Id::new(("sc_dim_area", i))).fixed_pos(pos).order(egui::Order::Foreground).show(ui.ctx(), |ui| {
let fill = if b.locked { tk.accent_soft } else { tk.panel };
- egui::Frame::popup(ui.style()).fill(fill).inner_margin(egui::Margin::symmetric(3, 1)).show(ui, |ui| {
- let r = ui
- // The drawing tool handles Enter. Keep the text edit focused when a
- // rejected value needs correction, instead of surrendering the keyboard.
- .add(egui::TextEdit::singleline(&mut b.value).id(id).desired_width(66.0).return_key(None).event_filter(egui::EventFilter {
- tab: true,
- horizontal_arrows: true,
- vertical_arrows: true,
- ..Default::default()
- }))
- .on_hover_text(b.label);
- crate::theme::TabAccent::number_focus(ui, &r);
+ egui::Frame::popup(ui.style()).fill(fill).inner_margin(egui::Margin::symmetric(tk.space_3 as i8, 1)).show(ui, |ui| {
+ let r = crate::ui_kit::placement_field(ui, id, &mut b.value, b.label);
// A completion gets first use of forward Tab. Shift+Tab always moves back;
// the box reached by egui's generic traversal must not complete its text.
let changed = (source.is_none() || (source == Some(i) && tab != Some(true))) && crate::params_dialog::complete(ui, &r, &mut b.value);
diff --git a/crates/ui-egui/src/stand_up.rs b/crates/ui-egui/src/stand_up.rs
index 83f24fc859..61f374377f 100644
--- a/crates/ui-egui/src/stand_up.rs
+++ b/crates/ui-egui/src/stand_up.rs
@@ -7,6 +7,7 @@
use serde_json::json;
use crate::SolveApp;
+use crate::ui_kit;
/// The bodies a just-opened file brought (`before`: body names before it opened, none for a
/// new design), and the import's component placement from the command's `result`: offer to
@@ -47,47 +48,36 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
if app.stand_up.is_none() {
return;
}
- let mut act: Option<&str> = None;
- crate::frame::window(ctx, crate::i18n::tr_label("Stand this part up?"), crate::frame::Width::Normal)
- .id(egui::Id::new("sc_stand_up"))
- .collapsible(false)
- .resizable(false)
+ let (closed, action) = ui_kit::Prompt::new(egui::Id::new("sc_stand_up"), "move", crate::i18n::tr_label("Stand this part up?"))
.anchor(egui::Align2::CENTER_TOP, egui::vec2(0.0, 140.0))
- .show(ctx, |ui| {
- ui.label(crate::i18n::tr_label("Files from many CAD programs have Y up, so they open lying on their back here (Z up)."));
- ui.label(crate::i18n::tr_label("Stand it up: a quarter turn about X, as one Move feature you can undo."));
- ui.add_space(6.0);
- ui.horizontal(|ui| {
- let stand = ui.button(crate::i18n::tr_label("Stand it up"));
- crate::scenario::publish_handle("stand_up:stand", stand.rect.center());
- if stand.clicked() {
- act = Some("stand");
- }
- let leave = ui.button(crate::i18n::tr_label("Leave it"));
- crate::scenario::publish_handle("stand_up:leave", leave.rect.center());
- if leave.clicked() {
- act = Some("leave");
- }
- let never = ui
- .button(crate::i18n::tr_label("Don't ask again"))
- .on_hover_text(crate::i18n::tr_label("Preferences › Design turns the offer back on"));
- crate::scenario::publish_handle("stand_up:never", never.rect.center());
- if never.clicked() {
- act = Some("never");
- }
- });
+ .actions("Stand it up", "Leave it", Some("Don't ask again"))
+ .show(ctx, true, |ui| {
+ ui_kit::text_block(
+ ui,
+ "why",
+ crate::i18n::tr_label("Files from many CAD programs have Y up, so they open lying on their back here (Z up)."),
+ false,
+ );
+ ui_kit::text_block(ui, "how", crate::i18n::tr_label("Stand it up: a quarter turn about X, as one Move feature you can undo."), false);
+ ui_kit::note(ui, "never", crate::i18n::tr_label("Preferences › Design turns the offer back on"));
});
- match act {
- Some("stand") => {
+ for (handle, key) in [("stand_up:stand", "dialog:ok"), ("stand_up:never", "dialog:apply"), ("stand_up:leave", "dialog:cancel")] {
+ if let Some(at) = crate::scenario::handle_at(key) {
+ crate::scenario::publish_handle(handle, at);
+ }
+ }
+ match action {
+ ui_kit::Action::Ok => {
if let Err(e) = stand_up(app) {
app.set_status(e, true);
}
}
- Some("leave") => leave(app),
- Some("never") => {
+ ui_kit::Action::Cancel => leave(app),
+ ui_kit::Action::Apply => {
leave(app);
app.preferences.offer_stand_up = false;
}
- _ => {}
+ ui_kit::Action::None if closed => leave(app),
+ ui_kit::Action::None => {}
}
}
diff --git a/crates/ui-egui/src/toolbar_custom.rs b/crates/ui-egui/src/toolbar_custom.rs
index 24be3f9f09..1a853ca8c7 100644
--- a/crates/ui-egui/src/toolbar_custom.rs
+++ b/crates/ui-egui/src/toolbar_custom.rs
@@ -8,14 +8,13 @@
//! and Reset Toolbar; Reset Toolbar restores the tab. Kept with the
//! preferences and exported or imported with the keyboard shortcuts.
-use crate::fonts::RichTextExt as _;
use std::collections::BTreeMap;
use serde_json::{Value, json};
use solidcraft_engine::{CommandSpec, command_specs};
-use crate::SolveApp;
use crate::context_menu::Item;
+use crate::{SolveApp, ui_kit};
/// The only workspace so far.
pub const WORKSPACE: &str = "DESIGN";
@@ -279,48 +278,41 @@ pub fn window(app: &mut SolveApp, ctx: &egui::Context) {
if !app.toolbar_custom.customizing {
return;
}
- let t = crate::theme::Tokens::get();
let tab = app.ui.tab.clone();
- let mut open = true;
let mut changes: Vec<(&'static str, bool)> = Vec::new();
let mut reset_tab = false;
- crate::frame::window(ctx, crate::i18n::tr_label("Customize Toolbar"), crate::frame::Width::Normal)
- .id(egui::Id::new("sc_toolbar_customize"))
- .open(&mut open)
- .default_height(520.0)
- .show(ctx, |ui| {
- ui.label(
- egui::RichText::new(format!(
- "{} tab. Tick a command to give it a toolbar button. You can also drag a row of a panel's drop-down onto the toolbar, drag a button off the toolbar to remove it, or use the pin on a drop-down row.",
- app.tr_label(&tab)
- ))
- .color(t.text_dim),
- );
- ui.separator();
- egui::ScrollArea::vertical().max_height(400.0).show(ui, |ui| {
- for (panel, cmds, n) in panel_lists(&tab) {
- if cmds.is_empty() {
- continue;
- }
- ui.label(egui::RichText::new(app.tr_label(panel)).semibold().color(crate::theme::Tokens::get().text).size(crate::theme::Tokens::get().font_small));
- let shown = buttons(app, &tab, panel, &cmds, n);
- for c in &cmds {
- let mut on = shown.iter().any(|b| b.id == c.id) || pinned_on(app, &tab, c.id).is_some();
- let r = ui.checkbox(&mut on, app.tr_label(c.label));
- crate::scenario::publish_handle(&format!("customize:{}", c.id), r.rect.left_center() + egui::vec2(8.0, 0.0));
- if r.changed() {
- changes.push((c.id, on));
+ let (closed, action) = ui_kit::Prompt::new(egui::Id::new("sc_toolbar_customize"), "settings", crate::i18n::tr_label("Customize Toolbar"))
+ .cards(2.0)
+ .actions("", "Close", None)
+ .show(ctx, true, |ui| {
+ ui_kit::note(ui, "customize", &crate::i18n::format("toolbar.customize_note", &[("tab", app.tr_label(&tab))]));
+ egui::ScrollArea::vertical()
+ .max_height(
+ (ctx.content_rect().height() - crate::theme::Tokens::get().control_height * 8.0)
+ .min(crate::theme::Tokens::get().control_height * 20.0),
+ )
+ .show(ui, |ui| {
+ for (panel, cmds, n) in panel_lists(&tab) {
+ if cmds.is_empty() {
+ continue;
}
+ ui_kit::section(ui, panel, app.tr_label(panel), true, |ui| {
+ let shown = buttons(app, &tab, panel, &cmds, n);
+ for c in &cmds {
+ let mut on = shown.iter().any(|b| b.id == c.id) || pinned_on(app, &tab, c.id).is_some();
+ let r = ui_kit::checkbox(ui, app.tr_label(c.label), &mut on);
+ crate::scenario::publish_handle(&format!("customize:{}", c.id), r.rect.center());
+ if r.changed() {
+ changes.push((c.id, on));
+ }
+ }
+ });
}
- ui.add_space(4.0);
- }
- });
- ui.separator();
- ui.horizontal(|ui| {
- if ui.button(crate::i18n::tr_label("Reset Toolbar")).clicked() {
- reset_tab = true;
- }
- });
+ });
+ let reset = ui_kit::secondary_button(ui, crate::i18n::tr_label("Reset Toolbar"));
+ crate::scenario::publish_rect("customize:reset", reset.rect);
+ crate::scenario::publish_handle("customize:reset", reset.rect.center());
+ reset_tab |= reset.clicked();
});
for (id, on) in changes {
if on {
@@ -334,7 +326,7 @@ pub fn window(app: &mut SolveApp, ctx: &egui::Context) {
if reset_tab {
reset(app, &tab);
}
- app.toolbar_custom.customizing = open;
+ app.toolbar_custom.customizing = !closed && action != ui_kit::Action::Cancel;
}
#[cfg(test)]
diff --git a/crates/ui-egui/src/ui_kit/actions.rs b/crates/ui-egui/src/ui_kit/actions.rs
index 30cac39b10..2995cc2aeb 100644
--- a/crates/ui-egui/src/ui_kit/actions.rs
+++ b/crates/ui-egui/src/ui_kit/actions.rs
@@ -35,7 +35,6 @@ pub fn icon_button_at(ui: &mut Ui, rect: egui::Rect, icon: &str, label: &str) ->
response.on_hover_text(crate::i18n::tr_label(label))
}
-/// Enter applies only when no editor owns it. Editors report their own accepted Enter.
/// Esc cancels; unowned Enter submits only when valid. Tokens: `none`.
pub fn keyboard(ctx: &egui::Context, ok_enabled: bool) -> Action {
if ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
@@ -47,15 +46,26 @@ pub fn keyboard(ctx: &egui::Context, ok_enabled: bool) -> Action {
}
}
-/// Pinned actions; `apply_label` adds Apply without closing. Tokens: form_footer_height,
-/// form_button_height, dialog_footer/rule, control_*, accent, on_accent, font_label, spacing.
/// Pinned OK / optional Apply / Cancel; returns Action. Tokens: `form_footer_height, form_button_height, dialog_footer/rule, radius_lg, control_*, accent, on_accent, font_label, space_6/10/12/16`.
pub fn footer(ui: &mut Ui, ok_label: &str, cancel_label: &str, ok_enabled: bool, apply_label: Option<&str>) -> Action {
- footer_impl(ui, ok_label, cancel_label, ok_enabled, apply_label, None)
+ footer_impl(ui, ok_label, cancel_label, ok_enabled, apply_label, None, None)
+}
+
+/// Footer whose `selected` action is marked (arrow keys move the mark in a prompt); an empty
+/// `ok_label` leaves out the OK action (a close-only card). Tokens: `footer tokens, selected_bg, accent`.
+pub(crate) fn footer_selected(
+ ui: &mut Ui,
+ ok_label: &str,
+ cancel_label: &str,
+ ok_enabled: bool,
+ apply_label: Option<&str>,
+ selected: Option<Action>,
+) -> Action {
+ footer_impl(ui, ok_label, cancel_label, ok_enabled, apply_label, None, selected)
}
/// Footer with stable button IDs and compute text. Tokens: `footer tokens, text_dim, space_4/8`.
-pub fn footer_with_status(
+pub(crate) fn footer_with_status(
ui: &mut Ui,
ok_label: &str,
cancel_label: &str,
@@ -63,12 +73,21 @@ pub fn footer_with_status(
apply_label: Option<&str>,
status: Option<&str>,
) -> Action {
- footer_impl(ui, ok_label, cancel_label, ok_enabled, apply_label, status)
+ footer_impl(ui, ok_label, cancel_label, ok_enabled, apply_label, status, None)
}
/// Shared footer implementation. Tokens: `footer tokens`.
-fn footer_impl(ui: &mut Ui, ok_label: &str, cancel_label: &str, ok_enabled: bool, apply_label: Option<&str>, status: Option<&str>) -> Action {
+fn footer_impl(
+ ui: &mut Ui,
+ ok_label: &str,
+ cancel_label: &str,
+ ok_enabled: bool,
+ apply_label: Option<&str>,
+ status: Option<&str>,
+ selected: Option<Action>,
+) -> Action {
let t = Tokens::get();
+ let ok_enabled = ok_enabled && !ok_label.is_empty();
// The footer is a full-width band (the card has no margin of its own): its own fill, a rule
// on top, and the buttons right-aligned with 6 pt above/below and 10 pt at the sides.
let (band, _) = ui.allocate_exact_size(vec2(dimension(ui.available_width()), t.form_footer_height), egui::Sense::hover());
@@ -78,16 +97,18 @@ fn footer_impl(ui: &mut Ui, ok_label: &str, cancel_label: &str, ok_enabled: bool
scenario::publish_rect("dialog:footer", band);
scenario::publish_count("dialog:ok:enabled", f64::from(ok_enabled && ui.is_enabled()));
let inner = band.shrink2(vec2(t.space_10, t.space_6));
+ scenario::publish_rect("dialog:footer:actions", inner);
let mut action = if ui.is_enabled() { keyboard(ui.ctx(), ok_enabled) } else { Action::None };
let mut actions_left = inner.right();
let row = ui.scope_builder(egui::UiBuilder::new().max_rect(inner).layout(egui::Layout::left_to_right(egui::Align::Center)), |ui| {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ui.spacing_mut().item_spacing.x = t.space_6;
for (label, kind) in [(ok_label, Action::Ok), (apply_label.unwrap_or(""), Action::Apply), (cancel_label, Action::Cancel)] {
- if kind == Action::Apply && apply_label.is_none() {
+ if (kind == Action::Apply && apply_label.is_none()) || (kind == Action::Ok && ok_label.is_empty()) {
continue;
}
- let primary = kind == Action::Ok;
+ let marked = selected == Some(kind);
+ let primary = kind == Action::Ok && selected.is_none_or(|s| s == Action::Ok);
let live = kind == Action::Cancel || ok_enabled;
ui.spacing_mut().button_padding = vec2(if primary { t.space_16 } else { t.space_12 }, 0.0);
let text = RichText::new(crate::i18n::tr_label(label)).size(t.font_label).color(if primary && ok_enabled {
@@ -100,8 +121,18 @@ fn footer_impl(ui: &mut Ui, ok_label: &str, cancel_label: &str, ok_enabled: bool
let response = ui.add_enabled(
live,
egui::Button::new(if primary && ok_enabled { text.bold_face() } else { text })
- .fill(if primary && ok_enabled { t.accent } else { t.control_fill })
- .stroke(egui::Stroke::new(if primary && ok_enabled { 0.0 } else { 1.0 }, t.control_border))
+ .selected(marked && !primary)
+ .fill(if primary && ok_enabled {
+ t.accent
+ } else if marked {
+ t.selected_bg
+ } else {
+ t.control_fill
+ })
+ .stroke(egui::Stroke::new(
+ if primary && ok_enabled { 0.0 } else { 1.0 },
+ if marked && !primary { t.accent } else { t.control_border },
+ ))
.wrap_mode(egui::TextWrapMode::Extend)
.corner_radius(t.control_radius)
.min_size(vec2(0.0, t.form_button_height)),
@@ -139,7 +170,6 @@ pub struct PairButton<'a> {
pub icon: Option<&'a str>,
}
-/// Equal secondary footer actions; Tokens: form_button_height, control_*, selected_bg, hover, font_label, spacing.
/// Equal-width secondary actions with optional icons and selected state. Tokens: `form_button_height, control_*, selected_bg, hover, font_label, text, icon/fill, accent, sketch_footer_icon_size, space_4/6/10`.
pub fn button_pair(ui: &mut egui::Ui, key: &str, states: [bool; 2], buttons: [PairButton<'_>; 2]) -> (bool, bool) {
let t = Tokens::get();
@@ -197,7 +227,6 @@ pub fn button_pair(ui: &mut egui::Ui, key: &str, states: [bool; 2], buttons: [Pa
(clicked.first().copied().unwrap_or(false), clicked.get(1).copied().unwrap_or(false))
}
-/// Ordinary secondary action inheriting `scope`'s control and font tokens; preserves egui sizing.
/// Ordinary secondary action preserving native sizing. Tokens: `scope font/control/spacing tokens`.
pub fn secondary_button(ui: &mut Ui, label: impl Into<egui::WidgetText>) -> Response {
let label = label.into();
@@ -208,7 +237,6 @@ pub fn secondary_button(ui: &mut Ui, label: impl Into<egui::WidgetText>) -> Resp
response
}
-/// Accent action. Tokens: accent, on_accent and the scope's control/font/spacing tokens.
/// Accent action outside the footer. Tokens: `accent, on_accent; scope tokens`.
pub fn primary_button(ui: &mut Ui, label: &str) -> Response {
let t = Tokens::get();
@@ -219,7 +247,6 @@ pub fn primary_button(ui: &mut Ui, label: &str) -> Response {
response
}
-/// Compact inline removal action; Tokens: scope's font and control tokens, egui small padding.
/// Compact inline action preserving native sizing. Tokens: `scope font/control tokens`.
pub fn small_button(ui: &mut Ui, label: &str) -> Response {
let response = ui.small_button(label);
@@ -228,7 +255,6 @@ pub fn small_button(ui: &mut Ui, label: &str) -> Response {
response
}
-/// Allocate a control-height icon action. Tokens: control_height, form_icon_inset, text/dim.
/// Allocated control-height icon action. Tokens: `control_height; icon_button_at tokens`.
pub fn icon_button(ui: &mut Ui, label: &str, icon: &str) -> Response {
let (rect, _) = ui.allocate_exact_size(vec2(row_height(), row_height()), egui::Sense::hover());
@@ -248,3 +274,16 @@ fn publish_button(ui: &Ui, response: &Response, label: &str) {
scenario::publish_handle(&key, response.rect.center());
scenario::publish_rect(&key, response.rect);
}
+
+/// Secondary action with caller-owned enabled state, retaining the native label.
+pub fn enabled_button(ui: &mut Ui, label: &str, enabled: bool) -> Response {
+ ui.add_enabled_ui(enabled, |ui| secondary_button(ui, crate::i18n::tr_label(label))).inner
+}
+
+/// Nested action menu in a dense table. Tokens: scope control/font tokens.
+pub fn action_menu<R>(ui: &mut Ui, label: &str, add: impl FnOnce(&mut Ui) -> R) -> egui::InnerResponse<Option<R>> {
+ let response = ui.menu_button(crate::i18n::tr_label(label), |ui| super::scope(ui, add));
+ scenario::publish_rect(&format!("dialog:menu:{label}"), response.response.rect);
+ scenario::publish_handle(&format!("dialog:menu:{label}"), response.response.rect.center());
+ response
+}
diff --git a/crates/ui-egui/src/ui_kit/choice.rs b/crates/ui-egui/src/ui_kit/choice.rs
index 1ef8bf5b43..eebdda6ca8 100644
--- a/crates/ui-egui/src/ui_kit/choice.rs
+++ b/crates/ui-egui/src/ui_kit/choice.rs
@@ -17,7 +17,7 @@ pub fn segmented(ui: &mut Ui, selected: &mut usize, options: &[&str]) -> bool {
/// Optional per-segment states preserve mixed selections in command-backed controls.
/// Segmented choices with mixed per-choice state. Tokens: `same as segmented`.
-pub fn segmented_states(ui: &mut Ui, selected: &mut usize, options: &[&str], states: &[bool]) -> bool {
+pub(crate) fn segmented_states(ui: &mut Ui, selected: &mut usize, options: &[&str], states: &[bool]) -> bool {
segments(ui, selected, options, states, false)
}
@@ -295,3 +295,104 @@ pub fn toggle_icon(ui: &mut Ui, row: &str, label: &str, selected: &mut bool, ico
#[cfg(test)]
#[path = "choice_tests.rs"]
mod tests;
+
+/// Selectable list item retaining checked state and full text as an accessible label.
+/// Tokens: control_height and scope selection/control/font tokens.
+pub fn list_picker(ui: &mut Ui, key: &str, text: &str, selected: bool) -> egui::Response {
+ let response =
+ ui.add_sized(egui::vec2(super::metrics::dimension(ui.available_width()), super::row_height()), egui::Button::selectable(selected, text));
+ crate::scenario::publish_handle(&format!("dialog:list:{key}"), response.rect.center());
+ crate::scenario::publish_rect(&format!("dialog:list:{key}"), response.rect);
+ response
+}
+
+/// A reusable draggable document-colour sample; caller supplies the existing domain payload.
+/// Tokens: control_height/radius, border, accent, hover.
+pub fn color_swatch<T: Send + Sync + 'static>(
+ ui: &mut Ui,
+ id: egui::Id,
+ color: egui::Color32,
+ selected: bool,
+ tip: &str,
+ payload: T,
+) -> egui::Response {
+ let t = crate::theme::Tokens::get();
+ let response = ui
+ .dnd_drag_source(id, payload, |ui| {
+ let (rect, _) = ui.allocate_exact_size(egui::vec2(t.control_height, t.control_height), egui::Sense::hover());
+ if color.a() < u8::MAX {
+ let half = rect.width() / 2.0;
+ for offset in [egui::Vec2::ZERO, egui::vec2(half, half)] {
+ ui.painter().rect_filled(egui::Rect::from_min_size(rect.min + offset, egui::vec2(half, half)), 0.0, t.hover);
+ }
+ }
+ ui.painter().rect(
+ rect,
+ t.control_radius,
+ color,
+ egui::Stroke::new(if selected { t.space_2 } else { 1.0 }, if selected { t.accent } else { t.border }),
+ egui::StrokeKind::Inside,
+ );
+ })
+ .response;
+ let response = ui.interact(response.rect, id.with("click"), egui::Sense::click()).on_hover_text(tip);
+ if response.hovered() {
+ ui.ctx().set_cursor_icon(egui::CursorIcon::Grab);
+ }
+ response
+}
+
+/// Wrapped samples with common token spacing. Keeps native drag-and-drop payloads intact.
+pub fn swatch_grid<T>(ui: &mut Ui, values: &[T], mut each: impl FnMut(&mut Ui, &T)) {
+ let t = Tokens::get();
+ let columns = ((super::metrics::dimension(ui.available_width()) + t.space_4) / (t.control_height + t.space_4)).floor().clamp(1.0, 64.0) as usize;
+ ui.vertical(|ui| {
+ ui.spacing_mut().item_spacing = vec2(t.space_4, t.space_4);
+ for row in values.chunks(columns.max(1)) {
+ ui.horizontal(|ui| {
+ for value in row {
+ each(ui, value);
+ }
+ });
+ }
+ });
+}
+
+/// A completion/suggestion entry; text and detail are application-supplied data.
+pub struct PopupOption<'a> {
+ pub text: &'a str,
+ pub detail: &'a str,
+ pub color: egui::Color32,
+}
+
+/// Focus-neutral suggestion popup. The owner handles navigation and completion semantics.
+/// Tokens: space_2, form_label_width, control_height, text_dim, scope control/font tokens.
+pub fn popup_list(ctx: &egui::Context, id: egui::Id, anchor: egui::Rect, selected: usize, options: &[PopupOption<'_>], hint: &str) -> Option<usize> {
+ let t = crate::theme::Tokens::get();
+ let mut chosen = None;
+ let area = crate::frame::area(id).order(egui::Order::Tooltip).fixed_pos(anchor.left_bottom() + egui::vec2(0.0, t.space_2)).show(ctx, |ui| {
+ egui::Frame::popup(ui.style()).show(ui, |ui| {
+ super::scope(ui, |ui| {
+ ui.set_width(anchor.width().max(t.form_label_width * 2.0));
+ for (index, option) in options.iter().enumerate() {
+ let response = ui
+ .add_sized(
+ egui::vec2(ui.available_width(), t.control_height),
+ egui::Button::selectable(index == selected, egui::RichText::new(option.text).color(option.color)),
+ )
+ .on_hover_text(option.detail);
+ crate::scenario::publish_handle(&format!("dialog:suggestion:{index}"), response.rect.center());
+ if index == selected {
+ super::note(ui, "completion_detail", option.detail);
+ }
+ if response.clicked() {
+ chosen = Some(index);
+ }
+ }
+ super::note(ui, "completion_hint", hint);
+ })
+ });
+ });
+ crate::scenario::publish_rect("dialog:suggestions", area.response.rect);
+ chosen
+}
diff --git a/crates/ui-egui/src/ui_kit/fields.rs b/crates/ui-egui/src/ui_kit/fields.rs
index 12f830e2ce..c201576ed8 100644
--- a/crates/ui-egui/src/ui_kit/fields.rs
+++ b/crates/ui-egui/src/ui_kit/fields.rs
@@ -34,6 +34,14 @@ pub fn focused_field(ui: &mut Ui, value: &mut String) -> bool {
enter
}
+/// Plain text editor which keeps keyboard focus (a name asked for in a one-field card); returns
+/// accepted Enter. Tokens: `same as field`.
+pub fn focused_text_field(ui: &mut Ui, value: &mut String, hint: &str) -> bool {
+ let (enter, _, response) = editor(ui, value, hint, false);
+ response.request_focus();
+ enter
+}
+
/// Multiline plain text with a stable focus ID. The caller owns Enter/Shift+Enter routing.
/// Tokens: control_height, control_fill, form_inset and font_label.
pub fn multiline_text_field(ui: &mut Ui, label: &str, id: egui::Id, value: &mut String) -> Response {
@@ -165,15 +173,26 @@ fn dropdown_arrow(ui: &Ui, rect: egui::Rect, _visuals: &egui::style::WidgetVisua
pub fn dropdown(ui: &mut Ui, id: &str, selected: &mut usize, options: &[&str]) -> Response {
let text = options.get(*selected).copied().map(crate::i18n::tr_label).unwrap_or("");
let row = label(ui).to_string();
- let response =
- egui::ComboBox::from_id_salt(id).width(dimension(ui.available_width())).selected_text(text).icon(dropdown_arrow).show_ui(ui, |ui| {
- for (index, option) in options.iter().enumerate() {
- let response = ui.selectable_value(selected, index, crate::i18n::tr_label(option));
- scenario::publish_handle(&format!("dialog:{row}:{option}"), response.rect.center());
- }
- });
- publish(ui, &response.response, egui::WidgetType::ComboBox);
- response.response
+ dropdown_menu(ui, id, text, |ui| {
+ for (index, option) in options.iter().enumerate() {
+ let response = ui.selectable_value(selected, index, crate::i18n::tr_label(option));
+ scenario::publish_handle(&format!("dialog:{row}:{option}"), response.rect.center());
+ }
+ })
+}
+
+/// Dropdown with caller-supplied kit choices/actions, including disabled entries and stable
+/// application handles. Tokens: dropdown tokens. Use `dropdown` for a simple indexed list.
+pub fn dropdown_menu(ui: &mut Ui, id: impl egui::AsIdSalt, current: &str, add: impl FnOnce(&mut Ui)) -> Response {
+ let response = egui::ComboBox::from_id_salt(id)
+ .width(dimension(ui.available_width()))
+ .height(Tokens::get().control_height * 14.0)
+ .selected_text(current)
+ .icon(dropdown_arrow)
+ .show_ui(ui, add)
+ .response;
+ publish(ui, &response, egui::WidgetType::ComboBox);
+ response
}
/// Filled point/curve/edge selection target. Tokens: `control_height, control_radius, selected_bg/ink, accent, form_inset, space_24/8, font_label, text_dim`.
@@ -234,15 +253,220 @@ pub fn fraction_field(ui: &mut Ui, value: &mut f64) -> Response {
response
}
-/// How full a surface blend leaves one end (-0.9 to 3, 0 is the plain bridge): a dragged number
-/// with two decimals and the locale's number parser. Tokens: scope's control and font tokens.
-pub fn bulge_field(ui: &mut Ui, value: &mut f64) -> Response {
- let response = ui.add(egui::DragValue::new(value).speed(0.01).range(-0.9..=3.0).fixed_decimals(2).custom_parser(crate::prefs::parse_number));
- scenario::publish_rect(&format!("dialog:bulge:{}", label(ui)), response.rect);
- scenario::publish_handle(&format!("dialog:bulge:{}", label(ui)), response.rect.center());
- response
-}
-
#[cfg(test)]
#[path = "fields_tests.rs"]
mod tests;
+
+/// Stable-ID inline editor for tables. Completion is owned by the caller so Enter can commit
+/// a cell without submitting its panel. Tokens: control_height/fill, form_inset, font_label, text/error.
+pub fn cell_editor(ui: &mut Ui, id: egui::Id, value: &mut String, hint: &str, invalid: bool) -> Response {
+ bounded_cell_editor(ui, id, value, hint, invalid, usize::MAX)
+}
+
+/// Stable-ID cell/name editor with a caller-supplied character cap. Tokens: cell_editor tokens.
+pub fn bounded_cell_editor(ui: &mut Ui, id: egui::Id, value: &mut String, hint: &str, invalid: bool, limit: usize) -> Response {
+ let t = Tokens::get();
+ let response = ui.add_sized(
+ vec2(dimension(ui.available_width()), row_height()),
+ egui::TextEdit::singleline(value)
+ .char_limit(limit)
+ .id(id)
+ .hint_text(crate::i18n::tr_label(hint))
+ .font(egui::FontId::monospace(t.font_label))
+ .background_color(t.control_fill)
+ .text_color(if invalid { t.error } else { t.text })
+ .margin(vec2(t.form_inset, 0.0))
+ .clip_text(true),
+ );
+ publish(ui, &response, egui::WidgetType::TextEdit);
+ response.widget_info(|| {
+ let mut info = egui::WidgetInfo::labeled(egui::WidgetType::TextEdit, ui.is_enabled(), crate::i18n::tr_label(label(ui)));
+ info.current_text_value = Some(value.clone());
+ info
+ });
+ crate::theme::TabAccent::number_focus(ui, &response);
+ response
+}
+
+/// Search input with native accessibility and a stable caller ID. Tokens: cell_editor tokens.
+pub fn search_field(ui: &mut Ui, id: egui::Id, value: &mut String, hint: &str) -> Response {
+ cell_editor(ui, id, value, hint, false)
+}
+
+/// Native colour chooser under the shared form styling. Colour is document data.
+pub fn color_field(ui: &mut Ui, rgb: &mut [u8; 3]) -> Response {
+ let response = ui.color_edit_button_srgb(rgb);
+ scenario::publish_rect(&format!("dialog:color:{}", label(ui)), response.rect);
+ scenario::publish_handle(&format!("dialog:color:{}", label(ui)), response.rect.center());
+ response
+}
+
+/// Continuous scalar control. Formatting never rounds saved values during drawing.
+/// Tokens: control_height, space_24/4, scope control/font tokens.
+pub fn slider(ui: &mut Ui, value: &mut f64, range: std::ops::RangeInclusive<f64>) -> Response {
+ let t = Tokens::get();
+ ui.spacing_mut().slider_width = dimension(ui.available_width() - t.space_24 - t.space_24 - t.space_4);
+ let response = ui.add(egui::Slider::new(value, range).max_decimals_opt(None).custom_formatter(|v, _| format!("{v:.2}")));
+ scenario::publish_rect(&format!("dialog:slider:{}", label(ui)), response.rect);
+ scenario::publish_handle(&format!("dialog:slider:{}", label(ui)), response.rect.center());
+ response
+}
+
+/// Locale-aware bounded scalar field, used for dimensionless material properties.
+pub fn scalar_field(ui: &mut Ui, value: &mut f64, range: std::ops::RangeInclusive<f64>) -> Response {
+ let response = ui.add(egui::DragValue::new(value).range(range).speed(0.01).custom_parser(crate::prefs::parse_number));
+ scenario::publish_rect(&format!("dialog:scalar:{}", label(ui)), response.rect);
+ scenario::publish_handle(&format!("dialog:scalar:{}", label(ui)), response.rect.center());
+ response
+}
+
+/// Length held in millimetres, dragged or typed in the design's units ("0.5 in", "2 cm + 3 mm" parse).
+/// Tokens: control_height, scope control/font tokens.
+pub fn length_field(ui: &mut Ui, value: &mut f64, units: &str, decimals: u8) -> Response {
+ let response = ui.add(length_drag(value, units, decimals));
+ scenario::publish_rect(&format!("dialog:length:{}", label(ui)), response.rect);
+ scenario::publish_handle(&format!("dialog:length:{}", label(ui)), response.rect.center());
+ response
+}
+
+/// Angle in degrees, dragged or typed. Tokens: control_height, scope control/font tokens.
+pub fn angle_field(ui: &mut Ui, value: &mut f64) -> Response {
+ let response = ui.add(egui::DragValue::new(value).speed(1.0).suffix(" deg").custom_parser(crate::prefs::parse_number));
+ scenario::publish_rect(&format!("dialog:angle:{}", label(ui)), response.rect);
+ scenario::publish_handle(&format!("dialog:angle:{}", label(ui)), response.rect.center());
+ response
+}
+
+/// Bounded multiline data input. Caller owns validation and keyboard semantics.
+/// Tokens: control_height/fill, form_inset, font_label.
+pub fn text_area(ui: &mut Ui, label: &str, id: egui::Id, value: &mut String, rows: usize, limit: usize) -> Response {
+ let t = Tokens::get();
+ let response = ui.add_sized(
+ vec2(dimension(ui.available_width()), row_height() * rows.clamp(1, 16) as f32),
+ egui::TextEdit::multiline(value)
+ .id(id)
+ .desired_rows(rows.clamp(1, 16))
+ .char_limit(limit)
+ .font(egui::FontId::monospace(t.font_label))
+ .background_color(t.control_fill)
+ .margin(vec2(t.form_inset, 0.0)),
+ );
+ response.widget_info(|| {
+ let mut info = egui::WidgetInfo::labeled(egui::WidgetType::TextEdit, ui.is_enabled(), label);
+ info.current_text_value = Some(value.clone());
+ info
+ });
+ response
+}
+
+/// Secret input with a stable ID. Never publishes its value in accessibility/scenario metadata.
+/// Tokens: cell_editor tokens.
+pub fn password_field(ui: &mut Ui, id: egui::Id, value: &mut String, hint: &str) -> Response {
+ let t = Tokens::get();
+ let response = ui.add_sized(
+ vec2(dimension(ui.available_width()), row_height()),
+ egui::TextEdit::singleline(value)
+ .id(id)
+ .password(true)
+ .hint_text(hint)
+ .font(egui::FontId::monospace(t.font_label))
+ .background_color(t.control_fill)
+ .margin(vec2(t.form_inset, 0.0)),
+ );
+ publish(ui, &response, egui::WidgetType::TextEdit);
+ response
+}
+
+/// Bounded integer or decimal preference with its original drag step and unit suffix.
+/// Tokens: scope control/font tokens. Values and limits are caller data.
+pub fn number_field<T: egui::emath::Numeric>(ui: &mut Ui, value: &mut T, range: std::ops::RangeInclusive<T>, speed: f64, suffix: &str) -> Response {
+ let response = ui.add(egui::DragValue::new(value).range(range).speed(speed).suffix(suffix).custom_parser(crate::prefs::parse_number));
+ response.widget_info(|| {
+ let mut info = egui::WidgetInfo::drag_value(ui.is_enabled(), value.to_f64());
+ info.label = Some(crate::i18n::tr_label(label(ui)).to_string());
+ info
+ });
+ super::layout::publish_geometry(ui, &response);
+ response
+}
+
+/// Stepped slider retaining caller units/formatting (percent, multiplier, seconds).
+/// Tokens: control_height, space_24/4, scope control/font tokens.
+pub fn formatted_slider<T: egui::emath::Numeric>(
+ ui: &mut Ui,
+ value: &mut T,
+ range: std::ops::RangeInclusive<T>,
+ step: f64,
+ format: impl Fn(f64) -> String + 'static,
+) -> Response {
+ let t = Tokens::get();
+ ui.spacing_mut().slider_width = dimension(ui.available_width() - t.space_24 * 2.0 - t.space_4);
+ let response = ui.add(egui::Slider::new(value, range).step_by(step).custom_formatter(move |v, _| format(v)));
+ response.widget_info(|| egui::WidgetInfo::slider(ui.is_enabled(), value.to_f64(), crate::i18n::tr_label(label(ui))));
+ super::layout::publish_geometry(ui, &response);
+ response
+}
+
+/// Growing plain-text message editor; its parent owns scrolling and Enter routing.
+/// Tokens: control_fill, form_inset, font_label. Use text_area for bounded data input.
+pub fn message_field(ui: &mut Ui, id: egui::Id, value: &mut String, hint: &str) -> Response {
+ let t = Tokens::get();
+ ui.add(
+ egui::TextEdit::multiline(value)
+ .id(id)
+ .hint_text(hint)
+ .desired_rows(2)
+ .desired_width(f32::INFINITY)
+ .font(egui::FontId::proportional(t.font_label))
+ .background_color(t.control_fill)
+ .margin(vec2(t.form_inset, t.space_4)),
+ )
+}
+
+/// Edit a millimetre value through a control expressed in the current design units.
+/// Keep the stored value untouched unless the user actually changes the field.
+pub fn length_drag<'a>(value: &'a mut f64, units: &str, decimals: u8) -> egui::DragValue<'a> {
+ let (scale, unit) = crate::prefs::unit_scale(units);
+ egui::DragValue::new(value)
+ .speed(0.5)
+ .suffix(format!(" {unit}"))
+ .custom_formatter(move |mm, _| crate::prefs::length_number(mm, unit, decimals))
+ .custom_parser(move |text| crate::prefs::parse_length_mm(text, scale))
+}
+
+/// Timeline/drive slider without a numeric editor; the owning surface shows its value.
+/// Whole steps round only while manipulating a timeline. Tokens: control_height, space_4.
+pub fn timeline_slider(ui: &mut Ui, value: &mut f64, range: std::ops::RangeInclusive<f64>, whole_steps: bool) -> Response {
+ ui.spacing_mut().slider_width = dimension(ui.available_width() - Tokens::get().space_4);
+ let slider = egui::Slider::new(value, range).show_value(false);
+ let response = ui.add(if whole_steps { slider.integer() } else { slider });
+ publish(ui, &response, egui::WidgetType::Slider);
+ response.widget_info(|| egui::WidgetInfo::slider(ui.is_enabled(), *value, crate::i18n::tr_label(label(ui))));
+ response
+}
+
+/// Placement editor whose owner routes Enter and Tab (including rejected expressions).
+/// Completion remains with the caller. Tokens: cell_editor tokens.
+pub fn placement_field(ui: &mut Ui, id: egui::Id, value: &mut String, hint: &str) -> Response {
+ let t = Tokens::get();
+ let response = ui.add(
+ egui::TextEdit::singleline(value)
+ .id(id)
+ .desired_width(t.control_height * 3.0 - t.space_6)
+ .return_key(None)
+ .event_filter(egui::EventFilter { tab: true, horizontal_arrows: true, vertical_arrows: true, ..Default::default() })
+ .font(egui::FontId::proportional(t.font_body))
+ .background_color(t.control_fill)
+ .text_color(t.text)
+ .margin(vec2(t.space_4, t.space_2))
+ .clip_text(true),
+ );
+ publish(ui, &response, egui::WidgetType::TextEdit);
+ response.widget_info(|| {
+ let mut info = egui::WidgetInfo::labeled(egui::WidgetType::TextEdit, ui.is_enabled(), crate::i18n::tr_label(hint));
+ info.current_text_value = Some(value.clone());
+ info
+ });
+ crate::theme::TabAccent::number_focus(ui, &response);
+ response.on_hover_text(crate::i18n::tr_label(hint))
+}
diff --git a/crates/ui-egui/src/ui_kit/fields_tests.rs b/crates/ui-egui/src/ui_kit/fields_tests.rs
index 71a45fe3fd..e22650f4e8 100644
--- a/crates/ui-egui/src/ui_kit/fields_tests.rs
+++ b/crates/ui-egui/src/ui_kit/fields_tests.rs
@@ -76,3 +76,122 @@ fn searchable_dropdown_filters_selects_and_accepts_custom_values() {
assert_eq!(chosen.as_deref(), Some(if custom { "/fonts/face.ttf" } else { "two" }));
}
}
+
+#[test]
+fn preference_dropdown_keeps_disabled_choices_inert_and_closes_after_selection() {
+ let ctx = crate::fonts::test_context();
+ let picked = std::cell::Cell::new(1);
+ let mut draw = |ui: &mut Ui| {
+ row(ui, "Samples", |ui| {
+ dropdown_menu(ui, "samples", &picked.get().to_string(), |ui| {
+ for (value, enabled) in [(1, true), (4, false), (8, true)] {
+ let response =
+ ui.add_enabled_ui(enabled, |ui| list_picker(ui, &value.to_string(), &format!("{value}×"), picked.get() == value)).inner;
+ if response.clicked() {
+ picked.set(value);
+ }
+ }
+ });
+ });
+ };
+ frame(&ctx, vec![], &mut draw);
+ let at = scenario::handle_at("dialog:Samples").unwrap();
+ frame(&ctx, pointer(at, true), &mut draw);
+ frame(&ctx, pointer(at, false), &mut draw);
+ let disabled = scenario::handle_at("dialog:list:4").unwrap();
+ frame(&ctx, pointer(disabled, true), &mut draw);
+ frame(&ctx, pointer(disabled, false), &mut draw);
+ frame(&ctx, vec![], &mut draw);
+ assert_eq!(picked.get(), 1, "a disabled choice must not change the value");
+ // Reopen if the native popup closed on the inside click.
+ if scenario::handle_at("dialog:list:8").is_none() {
+ let at = scenario::handle_at("dialog:Samples").unwrap();
+ frame(&ctx, pointer(at, true), &mut draw);
+ frame(&ctx, pointer(at, false), &mut draw);
+ frame(&ctx, vec![], &mut draw);
+ }
+ let enabled = scenario::handle_at("dialog:list:8").unwrap();
+ frame(&ctx, pointer(enabled, true), &mut draw);
+ frame(&ctx, pointer(enabled, false), &mut draw);
+ frame(&ctx, vec![], &mut draw);
+ assert!(scenario::handle_at("dialog:list:8").is_none());
+ assert_eq!(picked.get(), 8);
+}
+
+#[test]
+fn secret_field_retains_focus_and_masks_paint_and_accessibility_events() {
+ let ctx = crate::fonts::test_context();
+ let id = egui::Id::new("secret_test");
+ let mut secret = String::new();
+ let mut draw = |ui: &mut Ui| {
+ row(ui, "API key", |ui| {
+ password_field(ui, id, &mut secret, "Key").request_focus();
+ });
+ };
+ frame(&ctx, vec![], &mut draw);
+ assert!(ctx.memory(|m| m.has_focus(id)));
+ let mut output = ctx
+ .run_ui(egui::RawInput { events: vec![egui::Event::Text("opaque-secret".into())], focused: true, ..Default::default() }, |ui| {
+ scope(ui, &mut draw)
+ });
+ assert!(!format!("{:?}", output.platform_output.events).contains("opaque-secret"));
+ assert!(!format!("{:?}", output.shapes).contains("opaque-secret"));
+ output.textures_delta.clear();
+ assert_eq!(secret, "opaque-secret");
+}
+
+#[test]
+fn growing_message_field_retains_its_id_and_does_not_consume_enter() {
+ let ctx = crate::fonts::test_context();
+ let id = egui::Id::new("message_test");
+ let mut message = String::new();
+ let mut enter = false;
+ let mut draw = |ui: &mut Ui| {
+ let response = message_field(ui, id, &mut message, "Message");
+ response.request_focus();
+ enter = ui.input(|i| i.key_pressed(egui::Key::Enter));
+ };
+ frame(&ctx, vec![], &mut draw);
+ frame(&ctx, vec![egui::Event::Text("First\nSecond".into())], &mut draw);
+ frame(&ctx, key(egui::Key::Enter), &mut draw);
+ assert!(enter && ctx.memory(|m| m.has_focus(id)));
+ assert_eq!(message, "First\nSecond\n");
+}
+
+#[test]
+fn placement_field_keeps_focus_for_owner_validation_on_enter() {
+ let ctx = crate::fonts::test_context();
+ let id = egui::Id::new("placement_enter");
+ let mut value = String::from("invalid expression");
+ let mut draw = |ui: &mut Ui| {
+ row(ui, "Distance", |ui| {
+ placement_field(ui, id, &mut value, "Distance");
+ });
+ };
+ frame(&ctx, vec![], &mut draw);
+ let at = scenario::handle_at("dialog:Distance").unwrap();
+ frame(&ctx, pointer(at, true), &mut draw);
+ frame(&ctx, pointer(at, false), &mut draw);
+ frame(&ctx, key(egui::Key::Enter), &mut draw);
+ assert!(ctx.memory(|m| m.has_focus(id)), "owner can reject Enter without losing the editor");
+ frame(&ctx, vec![egui::Event::Text("x".into())], &mut draw);
+ assert!(value.contains('x'));
+}
+
+#[test]
+fn bounded_name_editor_keeps_unicode_character_cap() {
+ let ctx = crate::fonts::test_context();
+ let id = egui::Id::new("bounded_name");
+ let mut value = String::new();
+ let mut draw = |ui: &mut Ui| {
+ row(ui, "Name", |ui| {
+ bounded_cell_editor(ui, id, &mut value, "", false, 3);
+ });
+ };
+ frame(&ctx, vec![], &mut draw);
+ let at = scenario::handle_at("dialog:Name").unwrap();
+ frame(&ctx, pointer(at, true), &mut draw);
+ frame(&ctx, pointer(at, false), &mut draw);
+ frame(&ctx, vec![egui::Event::Text("åβ界d".into())], &mut draw);
+ assert_eq!(value, "åβ界");
+}
diff --git a/crates/ui-egui/src/ui_kit/gallery.rs b/crates/ui-egui/src/ui_kit/gallery.rs
index e26a4683b7..2604016df7 100644
--- a/crates/ui-egui/src/ui_kit/gallery.rs
+++ b/crates/ui-egui/src/ui_kit/gallery.rs
@@ -4,6 +4,32 @@ use crate::{scenario, theme::Tokens};
use egui::{Ui, vec2};
const ELEMENTS: &[&str] = &[
+ "timeline_slider",
+ "placement_field",
+ "bounded_cell_editor",
+ "password_field",
+ "number_field",
+ "formatted_slider",
+ "dropdown_menu",
+ "message_field",
+ "text_lines",
+ "inline_text",
+ "label_actions",
+ "table",
+ "list_picker",
+ "text_block",
+ "search_field",
+ "cell_editor",
+ "color_field",
+ "slider",
+ "scalar_field",
+ "length_field",
+ "angle_field",
+ "text_area",
+ "color_swatch",
+ "action_menu",
+ "enabled_button",
+ "collapsible_header",
"header",
"row",
"caption",
@@ -15,6 +41,7 @@ const ELEMENTS: &[&str] = &[
"focused_field",
"hint_field",
"text_field",
+ "focused_text_field",
"multiline_text_field",
"searchable_dropdown",
"text_emphasis",
@@ -42,6 +69,7 @@ const ELEMENTS: &[&str] = &[
"value_pair",
"fraction",
"status_header",
+ "progress",
"tool_choices",
"toggle_icon",
];
@@ -53,9 +81,146 @@ fn example(ui: &mut Ui, name: &str) -> (&'static str, Option<&'static str>) {
let mut selected = 0;
let mut checked = true;
match name {
- "header" => {
- header(ui, "fillet", "Fillet", || {});
- ("dialog:header", Some("dialog:close"))
+ "timeline_slider"
+ | "placement_field"
+ | "bounded_cell_editor"
+ | "password_field"
+ | "number_field"
+ | "formatted_slider"
+ | "dropdown_menu"
+ | "message_field"
+ | "text_lines" => {
+ let rect = ui
+ .scope(|ui| match name {
+ "timeline_slider" => {
+ timeline_slider(ui, &mut 12.0, 0.0..=100.0, true);
+ }
+ "placement_field" => {
+ placement_field(ui, ui.id().with("placement"), &mut value, "Distance");
+ }
+ "bounded_cell_editor" => {
+ bounded_cell_editor(ui, ui.id().with("name"), &mut value, "Name", false, 128);
+ }
+ "password_field" => {
+ password_field(ui, ui.id().with("secret"), &mut value, "API key");
+ }
+ "number_field" => {
+ number_field(ui, &mut 3_u32, 1..=200, 1.0, "");
+ }
+ "formatted_slider" => {
+ formatted_slider(ui, &mut 1.0, 0.5..=2.5, 0.05, |v| format!("{:.0} %", v * 100.0));
+ }
+ "dropdown_menu" => {
+ dropdown_menu(ui, "gallery_menu", "Preset", |ui| {
+ list_picker(ui, "preset", "Preset", true);
+ });
+ }
+ "message_field" => {
+ message_field(ui, ui.id().with("message"), &mut value, "Message");
+ }
+ "text_lines" => {
+ text_lines(ui, "gallery", "Licence\nSecond line");
+ }
+ _ => {}
+ })
+ .response
+ .rect;
+ scenario::publish_rect("gallery:forms", rect);
+ ("gallery:forms", None)
+ }
+
+ "table" => {
+ table(ui, "gallery", &[Column { label: "Name", width: 1.0 }, Column { label: "Expression", width: 1.5 }], "No rows", |ui, table| {
+ table.row(ui, "row", true, |row| {
+ row.cell(|ui| {
+ cell_text(ui, "Width");
+ });
+ row.cell(|ui| {
+ cell_editor(ui, ui.id().with("value"), &mut value, "", false);
+ });
+ });
+ });
+ ("dialog:table:gallery:row", None)
+ }
+ "list_picker" => {
+ list_picker(ui, "gallery", "Preset", true);
+ ("dialog:list:gallery", Some("dialog:list:gallery"))
+ }
+ "inline_text" | "label_actions" => {
+ let response = ui
+ .scope(|ui| {
+ if name == "inline_text" {
+ inline_text(ui, "Active");
+ } else {
+ label_actions(ui, "Configuration", |ui| {
+ secondary_button(ui, "Apply");
+ });
+ }
+ })
+ .response;
+ scenario::publish_rect("gallery:inline", response.rect);
+ ("gallery:inline", None)
+ }
+ "text_block" => {
+ text_block(ui, "gallery", "Validation report with retained units: 10 mm", false);
+ ("dialog:report:gallery", None)
+ }
+ "search_field" | "cell_editor" | "color_field" | "slider" | "scalar_field" | "length_field" | "angle_field" | "text_area"
+ | "color_swatch" | "action_menu" | "enabled_button" => {
+ let rect = ui
+ .scope(|ui| match name {
+ "search_field" => {
+ search_field(ui, ui.id().with("search"), &mut value, "Search");
+ }
+ "cell_editor" => {
+ cell_editor(ui, ui.id().with("cell"), &mut value, "Expression", true);
+ }
+ "color_field" => {
+ color_field(ui, &mut [120, 150, 180]);
+ }
+ "slider" => {
+ slider(ui, &mut 0.5, 0.0..=1.0);
+ }
+ "scalar_field" => {
+ scalar_field(ui, &mut 0.5, 0.0..=1.0);
+ }
+ "length_field" => {
+ length_field(ui, &mut 12.7, "in", 2);
+ }
+ "angle_field" => {
+ angle_field(ui, &mut 45.0);
+ }
+ "text_area" => {
+ text_area(ui, "Gallery", ui.id().with("area"), &mut value, 5, 1024);
+ }
+ "color_swatch" => {
+ swatch_grid(ui, &[1], |ui, _| {
+ color_swatch(ui, ui.id().with("swatch"), Tokens::get().accent, true, "Sample", 1);
+ });
+ }
+ "action_menu" => {
+ action_menu(ui, "Actions", |ui| {
+ secondary_button(ui, "Add");
+ });
+ }
+ "enabled_button" => {
+ enabled_button(ui, "Add", true);
+ }
+ _ => {}
+ })
+ .response
+ .rect;
+ scenario::publish_rect("gallery:manage", rect);
+ ("gallery:manage", None)
+ }
+
+ "header" | "collapsible_header" => {
+ if name == "collapsible_header" {
+ collapsible_header(ui, "fillet", "Fillet", &mut false, || {});
+ } else {
+ header(ui, "fillet", "Fillet", || {});
+ }
+ ("dialog:header", Some(if name == "collapsible_header" { "dialog:collapse" } else { "dialog:close" }))
}
"row" => {
row(ui, "Gallery", |ui| {
@@ -113,6 +278,7 @@ fn example(ui: &mut Ui, name: &str) -> (&'static str, Option<&'static str>) {
| "focused_field"
| "hint_field"
| "text_field"
+ | "focused_text_field"
| "fraction"
| "dropdown"
| "selection_field"
@@ -138,6 +304,9 @@ fn example(ui: &mut Ui, name: &str) -> (&'static str, Option<&'static str>) {
"text_field" => {
text_field(ui, &mut value, "Name");
}
+ "focused_text_field" => {
+ focused_text_field(ui, &mut value, "Name");
+ }
"fraction" => {
fraction_field(ui, &mut 0.5);
}
@@ -246,6 +415,10 @@ fn example(ui: &mut Ui, name: &str) -> (&'static str, Option<&'static str>) {
);
("sketch_palette:meter", None)
}
+ "progress" => {
+ progress(ui, "gallery", 0.4);
+ ("dialog:progress:gallery", None)
+ }
_ => panic!("missing gallery example {name}"),
}
}
@@ -430,3 +603,125 @@ fn emphasis_and_compact_modes_keep_independent_actions_in_both_themes() {
assert_eq!(selected, 1);
}
}
+
+#[test]
+fn table_cells_keep_alignment_fixed_rows_editing_and_action_targets() {
+ for dark in [false, true] {
+ let ctx = crate::fonts::test_context();
+ ctx.set_visuals(if dark { egui::Visuals::dark() } else { egui::Visuals::light() });
+ let mut first = "10 mm".to_owned();
+ let mut second = "20 mm".to_owned();
+ let mut removed = false;
+ let mut draw = |ui: &mut Ui| {
+ scope(ui, |ui| {
+ table(
+ ui,
+ "cells",
+ &[Column { label: "Name", width: 1.0 }, Column { label: "Expression", width: 1.5 }, Column { label: "Actions", width: 0.7 }],
+ "Empty",
+ |ui, table| {
+ for (name, value) in [("Width", &mut first), ("Height", &mut second)] {
+ table.row(ui, name, name == "Height", |row| {
+ row.cell(|ui| {
+ cell_text(ui, name);
+ });
+ row.cell(|ui| {
+ let response = cell_editor(ui, ui.id().with("expression"), value, "Expression", false);
+ scenario::publish_handle(&format!("gallery:cell:{name}"), response.rect.center());
+ scenario::publish_rect(&format!("gallery:cell:{name}"), response.rect);
+ });
+ row.cell(|ui| {
+ if small_button(ui, "Delete").clicked() {
+ removed = true;
+ }
+ });
+ });
+ }
+ },
+ );
+ });
+ };
+ for _ in 0..3 {
+ super::test_support::frame(&ctx, vec![], &mut draw);
+ }
+ let first_rect = scenario::rect_of("gallery:cell:Width").unwrap();
+ let second_rect = scenario::rect_of("gallery:cell:Height").unwrap();
+ let header = scenario::rect_of("dialog:column:cells:Expression").unwrap();
+ assert_eq!(first_rect.left(), header.left());
+ assert_eq!(second_rect.left(), header.left());
+ assert_eq!(first_rect.height(), Tokens::get().control_height);
+ assert_eq!(second_rect.height(), Tokens::get().control_height);
+ let at = scenario::handle_at("gallery:cell:Height").unwrap();
+ super::test_support::frame(&ctx, super::test_support::pointer(at, true), &mut draw);
+ super::test_support::frame(&ctx, super::test_support::pointer(at, false), &mut draw);
+ super::test_support::frame(&ctx, vec![egui::Event::Text("x".into())], &mut draw);
+ let delete = scenario::handle_at("dialog:button:Actions:Delete").unwrap();
+ super::test_support::frame(&ctx, super::test_support::pointer(delete, true), &mut draw);
+ super::test_support::frame(&ctx, super::test_support::pointer(delete, false), &mut draw);
+ assert_eq!(first, "10 mm");
+ assert!(second.contains('x'));
+ assert!(removed);
+ }
+}
+
+#[test]
+fn popup_suggestions_and_selectable_lists_keep_click_selection() {
+ for dark in [false, true] {
+ let ctx = crate::fonts::test_context();
+ ctx.set_visuals(if dark { egui::Visuals::dark() } else { egui::Visuals::light() });
+ let mut selected = None;
+ let mut draw = |ui: &mut Ui| {
+ selected = popup_list(
+ ui.ctx(),
+ egui::Id::new("suggestions"),
+ egui::Rect::from_min_size(egui::pos2(10.0, 10.0), vec2(220.0, 24.0)),
+ 0,
+ &[
+ PopupOption { text: "width", detail: "Parameter · 10 mm", color: Tokens::get().text },
+ PopupOption { text: "height", detail: "Parameter · 20 mm", color: Tokens::get().text },
+ ],
+ "Choose",
+ );
+ };
+ for _ in 0..3 {
+ super::test_support::frame(&ctx, vec![], &mut draw);
+ }
+ let at = scenario::handle_at("dialog:suggestion:1").unwrap();
+ super::test_support::frame(&ctx, super::test_support::pointer(at, true), &mut draw);
+ super::test_support::frame(&ctx, super::test_support::pointer(at, false), &mut draw);
+ assert_eq!(selected, Some(1));
+ let mut picked = false;
+ let mut draw = |ui: &mut Ui| {
+ scope(ui, |ui| {
+ if list_picker(ui, "preset", "Preset", picked).clicked() {
+ picked = !picked;
+ }
+ });
+ };
+ super::test_support::frame(&ctx, vec![], &mut draw);
+ let at = scenario::handle_at("dialog:list:preset").unwrap();
+ super::test_support::frame(&ctx, super::test_support::pointer(at, true), &mut draw);
+ super::test_support::frame(&ctx, super::test_support::pointer(at, false), &mut draw);
+ assert!(picked);
+ }
+}
+
+#[test]
+fn many_draggable_samples_wrap_inside_the_available_width() {
+ let ctx = crate::fonts::test_context();
+ let mut rects = Vec::new();
+ let mut bounds = egui::Rect::NOTHING;
+ super::test_support::frame(&ctx, vec![], |ui| {
+ ui.set_width(Tokens::get().form_label_width * 2.0);
+ scope(ui, |ui| {
+ bounds = ui.available_rect_before_wrap();
+ swatch_grid(ui, &(0..20).collect::<Vec<_>>(), |ui, index| {
+ let response = color_swatch(ui, ui.id().with(index), Tokens::get().accent, false, "Sample", *index);
+ rects.push(response.rect);
+ });
+ });
+ });
+ assert_eq!(rects.len(), 20);
+ assert!(rects.iter().all(|rect| rect.right() <= bounds.right() && rect.width() == Tokens::get().control_height));
+ assert!(rects.last().unwrap().top() > rects.first().unwrap().top(), "samples must wrap to additional rows");
+}
diff --git a/crates/ui-egui/src/ui_kit/layout.rs b/crates/ui-egui/src/ui_kit/layout.rs
index e52a096e73..d4e6da4782 100644
--- a/crates/ui-egui/src/ui_kit/layout.rs
+++ b/crates/ui-egui/src/ui_kit/layout.rs
@@ -198,3 +198,37 @@ pub(super) fn publish_geometry(ui: &Ui, response: &Response) {
#[cfg(test)]
#[path = "layout_tests.rs"]
mod tests;
+
+/// Read-only, wrapping report text. Tokens: font_label, text/error, space_4.
+pub fn text_block(ui: &mut Ui, id: &str, text: &str, error: bool) -> Response {
+ let t = Tokens::get();
+ let response = ui
+ .add(egui::Label::new(RichText::new(text).font(egui::FontId::proportional(t.font_label)).color(if error { t.error } else { t.text })).wrap());
+ scenario::publish_rect(&format!("dialog:report:{id}"), response.rect);
+ scenario::publish_handle(&format!("dialog:report:{id}"), response.rect.center());
+ response
+}
+
+/// Inline read-only text beside actions. Tokens: font_label, text.
+pub fn inline_text(ui: &mut Ui, text: &str) -> Response {
+ let response =
+ ui.add(egui::Label::new(RichText::new(text).font(egui::FontId::proportional(Tokens::get().font_label)).color(Tokens::get().text)).truncate());
+ scenario::publish_rect(&format!("dialog:inline:{text}"), response.rect);
+ scenario::publish_handle(&format!("dialog:inline:{text}"), response.rect.center());
+ response
+}
+
+/// Large read-only licence/report with equal-height virtualized lines and horizontal overflow.
+/// Tokens: font_small, text, control_height. Only visible lines are laid out.
+pub fn text_lines(ui: &mut Ui, id: &str, text: &str) {
+ let t = Tokens::get();
+ let lines: Vec<_> = text.lines().collect();
+ let font = egui::FontId::monospace(t.font_small);
+ let height = ui.fonts_mut(|f| f.row_height(&font));
+ let response = egui::ScrollArea::both().id_salt(id).max_height(t.control_height * 15.0).show_rows(ui, height, lines.len(), |ui, rows| {
+ for line in lines.get(rows).unwrap_or_default() {
+ ui.add(egui::Label::new(RichText::new(*line).font(font.clone()).color(t.text)).extend());
+ }
+ });
+ scenario::publish_rect(&format!("dialog:lines:{id}"), response.inner_rect);
+}
diff --git a/crates/ui-egui/src/ui_kit/metrics.rs b/crates/ui-egui/src/ui_kit/metrics.rs
index ef80614b85..69ecb3ec75 100644
--- a/crates/ui-egui/src/ui_kit/metrics.rs
+++ b/crates/ui-egui/src/ui_kit/metrics.rs
@@ -18,6 +18,29 @@ pub(super) fn dimension(value: f32) -> f32 {
if value.is_finite() { value.max(0.0) } else { 0.0 }
}
+/// A table column's header-width basis, as a multiple of `form_label_width`.
+pub(super) const TABLE_COLUMN_BASIS: f32 = 3.2;
+
+/// Share of a row given to the name in `label_actions`.
+pub(super) const LABEL_ACTIONS_SHARE: f32 = 0.45;
+
+/// Widest a label column may grow, as a multiple of `form_label_width`.
+const LABEL_COLUMN_MAX: f32 = 1.6;
+
+/// Measured width of a label in the form label font. Tokens: `font_label, dialog_label`.
+fn natural_label_width(ui: &Ui, text: &str) -> f32 {
+ let t = Tokens::get();
+ ui.painter().layout_no_wrap(crate::i18n::tr_label(text).to_string(), egui::FontId::proportional(t.font_label), t.dialog_label).size().x.ceil()
+}
+
+/// Width of a table header column, measured directly: it never touches the form's shared label-column state.
+/// Tokens: `form_label_width, font_label, dialog_label, space_4`.
+pub(super) fn header_column(ui: &Ui, text: &str) -> f32 {
+ let t = Tokens::get();
+ let base = t.form_label_width;
+ (natural_label_width(ui, text) + t.space_4).clamp(base, base * LABEL_COLUMN_MAX).min(base * TABLE_COLUMN_BASIS * 0.5)
+}
+
/// Allocate exactly one control-height row. Long labels elide; controls cannot widen the card.
/// The design's label column is `form_label_width` wide; a dialog with longer labels widens the
/// column for all of its rows (up to 1.6 times that), so the controls still line up and labels
@@ -27,12 +50,7 @@ pub(super) fn dimension(value: f32) -> f32 {
pub(super) fn label_column(ui: &Ui, text: &str, row_width: f32) -> f32 {
let t = Tokens::get();
let base = t.form_label_width;
- let natural = ui
- .painter()
- .layout_no_wrap(crate::i18n::tr_label(text).to_string(), egui::FontId::proportional(t.font_label), t.dialog_label)
- .size()
- .x
- .ceil();
+ let natural = natural_label_width(ui, text);
let widest = match ui.stack().iter().find(|node| node.tags().contains(FORM)).map(|node| node.id) {
Some(form) => {
let key = form.with("label_column");
@@ -51,7 +69,7 @@ pub(super) fn label_column(ui: &Ui, text: &str, row_width: f32) -> f32 {
}
None => natural,
};
- (widest + t.space_4).clamp(base, base * 1.6).min(row_width * 0.5)
+ (widest + t.space_4).clamp(base, base * LABEL_COLUMN_MAX).min(row_width * 0.5)
}
#[cfg(test)]
diff --git a/crates/ui-egui/src/ui_kit/mod.rs b/crates/ui-egui/src/ui_kit/mod.rs
index 4f415d8282..d8c550bd46 100644
--- a/crates/ui-egui/src/ui_kit/mod.rs
+++ b/crates/ui-egui/src/ui_kit/mod.rs
@@ -8,6 +8,7 @@ pub mod layout;
pub mod metrics;
pub(crate) mod panel;
pub mod status;
+pub mod table;
pub mod text;
pub use actions::*;
@@ -15,9 +16,10 @@ pub use choice::*;
pub use fields::*;
pub use layout::*;
pub use metrics::{header_height, row_height};
-pub use panel::header;
-pub(crate) use panel::{ComputeStatus, FeatureOptions, Panel, Part};
+pub(crate) use panel::{ComputeStatus, FeatureOptions, Panel, Part, Prompt};
+pub use panel::{collapsible_header, header};
pub use status::*;
+pub use table::*;
#[cfg(test)]
mod gallery;
diff --git a/crates/ui-egui/src/ui_kit/panel.rs b/crates/ui-egui/src/ui_kit/panel.rs
index 5a2bf0ab7c..1108e3dfcd 100644
--- a/crates/ui-egui/src/ui_kit/panel.rs
+++ b/crates/ui-egui/src/ui_kit/panel.rs
@@ -5,6 +5,16 @@ use egui::{Ui, vec2};
/// Feature title/icon/close band. Tokens: `form_header_height, form_icon_size, form_close_size, form_inset, font_label, text, dialog_rule, space_8/10; icon_button_at tokens`.
pub fn header(ui: &mut Ui, icon: &str, title: &str, on_close: impl FnOnce()) {
+ header_impl(ui, icon, title, None, on_close);
+}
+
+/// Optional fold action for managers which historically hide their inputs without losing edits.
+/// Tokens: header tokens and space_4; retains the legacy chevron accessibility identities.
+pub fn collapsible_header(ui: &mut Ui, icon: &str, title: &str, collapsed: &mut bool, on_close: impl FnOnce()) {
+ header_impl(ui, icon, title, Some(collapsed), on_close);
+}
+
+fn header_impl(ui: &mut Ui, icon: &str, title: &str, collapsed: Option<&mut bool>, on_close: impl FnOnce()) {
let t = Tokens::get();
let (rect, _) = ui.allocate_exact_size(vec2(dimension(ui.available_width()), header_height()), egui::Sense::hover());
// Design: padding 0 8 0 10, an 18 pt icon, a 7 pt gap, a 22 pt close button.
@@ -22,8 +32,20 @@ pub fn header(ui: &mut Ui, icon: &str, title: &str, on_close: impl FnOnce()) {
if close.clicked() {
on_close();
}
- let left = (icon_rect.right() + t.form_inset).min(close_rect.left());
- let title_rect = egui::Rect::from_min_max(egui::pos2(left, rect.top()), egui::pos2(close_rect.left().max(left), rect.bottom()));
+ let right = if let Some(collapsed) = collapsed {
+ let fold = egui::Rect::from_min_size(egui::pos2(close_rect.left() - t.form_close_size - t.space_4, close_rect.top()), close_rect.size());
+ let response = icon_button_at(ui, fold, if *collapsed { "chevron" } else { "chevron_right" }, if *collapsed { "«" } else { "»" })
+ .on_hover_text(crate::i18n::tr_label(if *collapsed { "Expand" } else { "Collapse" }));
+ scenario::publish_handle("dialog:collapse", response.rect.center());
+ if response.clicked() {
+ *collapsed = !*collapsed;
+ }
+ fold.left()
+ } else {
+ close_rect.left()
+ };
+ let left = (icon_rect.right() + t.form_inset).min(right);
+ let title_rect = egui::Rect::from_min_max(egui::pos2(left, rect.top()), egui::pos2(right.max(left), rect.bottom()));
paint_text(ui, title_rect, title, crate::fonts::semibold(t.font_label), t.text, false);
let title_response = ui.interact(title_rect, ui.make_persistent_id("title_text"), egui::Sense::hover());
title_response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, ui.is_enabled(), title));
@@ -41,6 +63,8 @@ pub(crate) struct Panel<'a> {
side: crate::frame::Side,
frame: egui::Frame,
width: f32,
+ ok: &'a str,
+ cancel: &'a str,
}
pub(crate) struct FeatureOptions<'a> {
@@ -87,7 +111,7 @@ impl<'a> Panel<'a> {
}
pub(crate) fn new(title: &'a str, id: egui::Id, anchor: egui::Pos2, viewport: egui::Rect, side: crate::frame::Side, frame: egui::Frame) -> Self {
- Self { title, id, anchor, viewport, side, frame, width: Tokens::get().form_card_width }
+ Self { title, id, anchor, viewport, side, frame, width: Tokens::get().form_card_width, ok: "OK", cancel: "Cancel" }
}
pub(crate) fn width(mut self, width: f32) -> Self {
@@ -95,6 +119,18 @@ impl<'a> Panel<'a> {
self
}
+ /// The footer's primary and closing actions when they are not OK and Cancel. An empty `ok`
+ /// leaves the primary action out (a card that only closes, e.g. Measure).
+ pub(crate) fn actions(mut self, ok: &'a str, cancel: &'a str) -> Self {
+ (self.ok, self.cancel) = (ok, cancel);
+ self
+ }
+
+ /// Table surface width derives from the same card-width token and remains viewport bounded.
+ pub(crate) fn wide(self) -> Self {
+ self.width(Tokens::get().form_card_width * 3.0)
+ }
+
/// The painted anchor also drives dragging, including the shell's edge clearance.
fn bounded_anchor(&self) -> egui::Pos2 {
let viewport = self.viewport;
@@ -154,6 +190,31 @@ impl<'a> Panel<'a> {
disabled: bool,
valid: bool,
body: impl FnOnce(&mut Ui) -> ComputeStatus,
+ ) -> (bool, super::Action) {
+ self.feature_impl(ui, heading, disabled, valid, None, body)
+ }
+
+ /// Same card with a persistent fold state owned by its caller.
+ pub(crate) fn feature_collapsible(
+ &self,
+ ui: &mut Ui,
+ heading: FeatureOptions<'_>,
+ disabled: bool,
+ valid: bool,
+ collapsed: &mut bool,
+ body: impl FnOnce(&mut Ui) -> ComputeStatus,
+ ) -> (bool, super::Action) {
+ self.feature_impl(ui, heading, disabled, valid, Some(collapsed), body)
+ }
+
+ fn feature_impl(
+ &self,
+ ui: &mut Ui,
+ heading: FeatureOptions<'_>,
+ disabled: bool,
+ valid: bool,
+ mut collapsed: Option<&mut bool>,
+ body: impl FnOnce(&mut Ui) -> ComputeStatus,
) -> (bool, super::Action) {
super::scope(ui, |ui| {
let t = Tokens::get();
@@ -161,13 +222,19 @@ impl<'a> Panel<'a> {
let band = egui::Rect::from_min_size(min, vec2(ui.available_width(), super::header_height()));
crate::frame::drag_dock(ui, band, heading.drag_key, heading.moved, self.bounded_anchor() - heading.docked);
let mut close = false;
- header(ui, heading.icon, heading.title, || close = true);
+ if let Some(collapsed) = collapsed.as_deref_mut() {
+ collapsible_header(ui, heading.icon, heading.title, collapsed, || close = true);
+ } else {
+ header(ui, heading.icon, heading.title, || close = true);
+ }
let bottom = self.viewport.bottom() - crate::shell::SHELL_GAP - self.frame.inner_margin.bottomf() - self.frame.stroke.width;
let footer_height = t.form_footer_height;
let fields_height = (bottom - ui.cursor().top() - footer_height).max(0.0);
let fields_rect = egui::Rect::from_min_size(ui.cursor().min, vec2(ui.available_width(), fields_height));
- let state = ui
- .scope_builder(egui::UiBuilder::new().max_rect(fields_rect), |ui| {
+ let state = if collapsed.as_deref().copied().unwrap_or(false) {
+ ComputeStatus { text: None, busy: disabled, applying: disabled }
+ } else {
+ ui.scope_builder(egui::UiBuilder::new().max_rect(fields_rect), |ui| {
egui::ScrollArea::vertical()
.id_salt("feature_fields")
.min_scrolled_height(0.0)
@@ -188,8 +255,9 @@ impl<'a> Panel<'a> {
})
.inner
})
- .inner;
- let action = super::footer_with_status(ui, "OK", "Cancel", valid && !state.applying, heading.apply_label, state.text.as_deref());
+ .inner
+ };
+ let action = super::footer_with_status(ui, self.ok, self.cancel, valid && !state.applying, heading.apply_label, state.text.as_deref());
if state.busy {
let rect = egui::Rect::from_min_size(
egui::pos2(ui.min_rect().left(), ui.min_rect().bottom() - super::row_height()),
@@ -252,6 +320,140 @@ impl<'a> Panel<'a> {
}
}
+/// A centred prompt or small form card, one and a half card widths wide: the feature header (icon, title, close), a padded body,
+/// and the pinned footer with up to three actions (`apply` is the third, middle action, e.g.
+/// "Don't Save"). Floats over the viewport instead of docking, for confirmations, offers and
+/// short property forms. Tokens: `form_card_width` (x1.5), header/footer tokens, `dialog_body`,
+/// `space_6/8/10`.
+pub(crate) struct Prompt<'a> {
+ id: egui::Id,
+ icon: &'a str,
+ title: &'a str,
+ anchor: Option<(egui::Align2, egui::Vec2)>,
+ placed: Option<(egui::Align2, egui::Pos2)>,
+ ok: &'a str,
+ cancel: &'a str,
+ apply: Option<&'a str>,
+ selected: Option<super::Action>,
+ enter_submits: bool,
+ escape_closes: bool,
+ width: f32,
+}
+
+impl<'a> Prompt<'a> {
+ /// A card with OK and Cancel, centred and movable.
+ pub(crate) fn new(id: egui::Id, icon: &'a str, title: &'a str) -> Self {
+ Self {
+ id,
+ icon,
+ title,
+ anchor: None,
+ placed: None,
+ ok: "OK",
+ cancel: "Cancel",
+ apply: None,
+ selected: None,
+ enter_submits: true,
+ escape_closes: true,
+ width: Tokens::get().form_card_width * 1.5,
+ }
+ }
+
+ /// Pin the card at `align` of the screen, `offset` away (it then no longer moves).
+ pub(crate) fn anchor(mut self, align: egui::Align2, offset: egui::Vec2) -> Self {
+ self.anchor = Some((align, offset));
+ self
+ }
+
+ /// Start with `pivot` of the card at `pos`; the card can then be moved.
+ pub(crate) fn placed(mut self, pivot: egui::Align2, pos: egui::Pos2) -> Self {
+ self.placed = Some((pivot, pos));
+ self
+ }
+
+ /// The primary and closing actions, and an optional third one between them. An empty `ok`
+ /// leaves the primary action out.
+ pub(crate) fn actions(mut self, ok: &'a str, cancel: &'a str, apply: Option<&'a str>) -> Self {
+ (self.ok, self.cancel, self.apply) = (ok, cancel, apply);
+ self
+ }
+
+ /// A card of editable fields: Enter belongs to the fields and never submits (confirmations
+ /// let Enter give the primary action when nothing has focus).
+ pub(crate) fn fields(mut self) -> Self {
+ self.enter_submits = false;
+ self
+ }
+
+ /// Esc does not close the card (the header's close and the closing action still do): for a
+ /// card holding a long text the user is editing, where Esc must not discard the work.
+ pub(crate) fn keep_open_on_escape(mut self) -> Self {
+ self.escape_closes = false;
+ self
+ }
+
+ /// `cards` times the card width instead of one and a half, for wide footers.
+ pub(crate) fn cards(mut self, cards: f32) -> Self {
+ if cards.is_finite() && cards > 0.0 {
+ self.width = Tokens::get().form_card_width * cards;
+ }
+ self
+ }
+
+ /// Mark one action as the one Enter gives.
+ pub(crate) fn selected(mut self, action: super::Action) -> Self {
+ self.selected = Some(action);
+ self
+ }
+
+ /// Draw the card. Returns whether the header's close was pressed and the footer's action.
+ /// `valid` enables the primary action.
+ pub(crate) fn show(self, ctx: &egui::Context, valid: bool, body: impl FnOnce(&mut Ui)) -> (bool, super::Action) {
+ let t = Tokens::get();
+ let frame = crate::frame::shell_card(t.dialog_body).inner_margin(0.0);
+ let inner_width = (self.width - frame.total_margin().sum().x).max(0.0);
+ let window = egui::Window::new(self.title)
+ .enabled(!crate::issue_report::cad_input_blocked())
+ .id(self.id)
+ .title_bar(false)
+ .collapsible(false)
+ .resizable(false)
+ .min_width(inner_width)
+ .max_width(inner_width)
+ .default_width(inner_width)
+ .scroll(false)
+ .frame(frame)
+ .fade_in(false)
+ .fade_out(false);
+ let window = match (self.anchor, self.placed) {
+ (Some((align, offset)), _) => window.anchor(align, offset),
+ (None, Some((pivot, pos))) => window.pivot(pivot).default_pos(pos),
+ (None, None) => window.pivot(egui::Align2::CENTER_CENTER).default_pos(ctx.content_rect().center() - vec2(0.0, row_height() * 2.5)),
+ };
+ let shown = window.show(ctx, |ui| {
+ super::scope(ui, |ui| {
+ let mut close = false;
+ header(ui, self.icon, self.title, || close = true);
+ egui::Frame::NONE
+ .inner_margin(egui::Margin { left: t.space_10 as i8, right: t.space_10 as i8, top: t.space_8 as i8, bottom: t.space_6 as i8 })
+ .show(ui, body);
+ if !self.enter_submits {
+ ui.ctx().input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter));
+ }
+ if !self.escape_closes {
+ ui.ctx().input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape));
+ }
+ let action = super::footer_selected(ui, self.ok, self.cancel, valid, self.apply, self.selected);
+ (close, action)
+ })
+ });
+ if let Some(shown) = &shown {
+ crate::scenario::publish_rect("dialog:window", shown.response.rect);
+ }
+ shown.and_then(|r| r.inner).unwrap_or((false, super::Action::None))
+ }
+}
+
#[cfg(test)]
#[path = "panel_tests.rs"]
mod tests;
diff --git a/crates/ui-egui/src/ui_kit/panel_tests.rs b/crates/ui-egui/src/ui_kit/panel_tests.rs
index 46a7ac7c15..bb14b45bc0 100644
--- a/crates/ui-egui/src/ui_kit/panel_tests.rs
+++ b/crates/ui-egui/src/ui_kit/panel_tests.rs
@@ -192,3 +192,120 @@ fn palette_scrolls_short_views_and_retains_its_status_and_action_handles() {
}
}
}
+
+#[test]
+fn wide_tables_remain_bounded_with_pinned_actions_on_small_viewports() {
+ for layout in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] {
+ for width in [240.0, 640.0, 1200.0] {
+ let ctx = crate::fonts::test_context();
+ let viewport = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, 360.0));
+ for _ in 0..3 {
+ scenario::clear_handles();
+ let mut output = ctx.run_ui(egui::RawInput { screen_rect: Some(viewport), ..Default::default() }, |_| {
+ let side = crate::frame::Side::Right;
+ let anchor = viewport.right_top();
+ let panel = Panel::new("Table", egui::Id::new("wide"), anchor, viewport, side, Panel::feature_frame(&ctx, layout, side)).wide();
+ panel.window().show(&ctx, |ui| {
+ panel.feature(
+ ui,
+ FeatureOptions {
+ icon: "fillet",
+ title: "Table",
+ drag_key: "wide",
+ moved: egui::Vec2::ZERO,
+ docked: anchor,
+ apply_label: None,
+ },
+ false,
+ true,
+ |ui| {
+ for _ in 0..30 {
+ note(ui, "row", "Table body");
+ }
+ ComputeStatus { text: None, busy: false, applying: false }
+ },
+ );
+ });
+ });
+ output.textures_delta.clear();
+ }
+ let header = scenario::rect_of("dialog:header").unwrap();
+ let footer = scenario::rect_of("dialog:footer").unwrap();
+ assert!(viewport.expand(1.0).contains_rect(header), "{width}: {header:?}");
+ assert!(viewport.expand(1.0).contains_rect(footer), "{width}: {footer:?}");
+ }
+ }
+}
+
+#[test]
+fn prompt_is_one_and_a_half_cards_wide_with_its_actions_in_both_themes() {
+ let previous = crate::theme::is_dark();
+ for dark in [false, true] {
+ crate::theme::set_dark(dark);
+ let ctx = crate::fonts::test_context();
+ let t = Tokens::get();
+ let mut action = Action::None;
+ for _ in 0..3 {
+ scenario::clear_handles();
+ let mut output = ctx.run_ui(
+ egui::RawInput {
+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))),
+ focused: true,
+ ..Default::default()
+ },
+ |ui| {
+ action = Prompt::new(egui::Id::new("prompt_test"), "delete", "Delete")
+ .actions("Delete", "Cancel", Some("Keep"))
+ .selected(Action::Apply)
+ .show(ui.ctx(), true, |ui| {
+ text_block(ui, "body", "Three features go with it.", false);
+ })
+ .1;
+ },
+ );
+ output.textures_delta.clear();
+ }
+ assert_eq!(action, Action::None);
+ let header = scenario::rect_of("dialog:header").unwrap();
+ let footer = scenario::rect_of("dialog:footer").unwrap();
+ assert!((header.width() - (t.form_card_width * 1.5 - 2.0)).abs() <= 3.0, "{dark}: {header:?}");
+ assert_eq!(header.width(), footer.width());
+ assert!(footer.top() > header.bottom());
+ let (ok, apply, cancel) =
+ (scenario::rect_of("dialog:ok").unwrap(), scenario::rect_of("dialog:apply").unwrap(), scenario::rect_of("dialog:cancel").unwrap());
+ assert!(cancel.right() < apply.left() && apply.right() < ok.left(), "Cancel, the third action, then the primary one");
+ assert!(footer.contains_rect(ok) && footer.contains_rect(cancel));
+ assert!(scenario::handle_at("dialog:Keep").is_some() && scenario::handle_at("dialog:close").is_some());
+ }
+ crate::theme::set_dark(previous);
+}
+
+#[test]
+fn escape_closes_a_prompt_unless_it_keeps_the_card_open() {
+ for keep in [false, true] {
+ let ctx = crate::fonts::test_context();
+ let mut action = Action::None;
+ for frame in 0..3 {
+ let events = if frame == 2 { crate::ui_kit::test_support::key(egui::Key::Escape) } else { Vec::new() };
+ let mut output = ctx.run_ui(
+ egui::RawInput {
+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))),
+ focused: true,
+ events,
+ ..Default::default()
+ },
+ |ui| {
+ let prompt = Prompt::new(egui::Id::new(("prompt_escape", keep)), "settings", "Report").actions("Open", "Close", None);
+ let prompt = if keep { prompt.keep_open_on_escape() } else { prompt };
+ action = prompt
+ .show(ui.ctx(), true, |ui| {
+ text_block(ui, "body", "A long text the user is editing.", false);
+ })
+ .1;
+ },
+ );
+ output.textures_delta.clear();
+ }
+ assert_eq!(action, if keep { Action::None } else { Action::Cancel }, "keep_open_on_escape={keep}");
+ }
+}
diff --git a/crates/ui-egui/src/ui_kit/status.rs b/crates/ui-egui/src/ui_kit/status.rs
index fd5fdc6cd0..c23490e007 100644
--- a/crates/ui-egui/src/ui_kit/status.rs
+++ b/crates/ui-egui/src/ui_kit/status.rs
@@ -45,3 +45,19 @@ pub fn status_header(ui: &mut egui::Ui, key: &str, name: &str, status: StatusHea
crate::scenario::publish_handle(&format!("{key}:status_header"), response.rect.center());
response
}
+
+/// Determinate progress bar for a running operation (a download, a file load), full width and
+/// `space_6` tall; `fraction` is clamped (non-finite counts as zero). Pair it with a `text_block`
+/// that names the step. Tokens: `space_3/6, dialog_rule, accent`.
+pub fn progress(ui: &mut egui::Ui, key: &str, fraction: f32) -> egui::Response {
+ let t = Tokens::get();
+ let fraction = if fraction.is_finite() { fraction.clamp(0.0, 1.0) } else { 0.0 };
+ let (bar, response) = ui.allocate_exact_size(vec2(ui.available_width().max(0.0), t.space_6), egui::Sense::hover());
+ ui.painter().rect_filled(bar, t.space_3, t.dialog_rule);
+ if fraction > 0.0 {
+ ui.painter().rect_filled(egui::Rect::from_min_size(bar.min, vec2(bar.width() * fraction, bar.height())), t.space_3, t.accent);
+ }
+ response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::ProgressIndicator, ui.is_enabled(), format!("{:.0}%", fraction * 100.0)));
+ crate::scenario::publish_rect(&format!("dialog:progress:{key}"), bar);
+ response
+}
diff --git a/crates/ui-egui/src/ui_kit/table.rs b/crates/ui-egui/src/ui_kit/table.rs
new file mode 100644
index 0000000000..6a8052ab06
--- /dev/null
+++ b/crates/ui-egui/src/ui_kit/table.rs
@@ -0,0 +1,131 @@
+//! Dense editable tables. Geometry and typography share the form label-column tokens.
+use super::{metrics::*, text::paint_text};
+use crate::{scenario, theme::Tokens};
+use egui::{Response, Ui, vec2};
+
+/// A column's minimum width is a multiple of the measured form label column.
+pub struct Column<'a> {
+ pub label: &'a str,
+ pub width: f32,
+}
+
+pub struct Table<'a> {
+ columns: &'a [Column<'a>],
+ widths: Vec<f32>,
+ id: String,
+ rows: usize,
+}
+
+/// Header, horizontally scrolling body and empty state. Rows are exactly control_height.
+/// Tokens: form_label_width, font_label, dialog_label, space_4/8, dialog_rule, text/dim, selected_bg.
+pub fn table<R>(ui: &mut Ui, id: &str, columns: &[Column<'_>], empty: &str, add: impl FnOnce(&mut Ui, &mut Table<'_>) -> R) -> R {
+ let t = Tokens::get();
+ let widths: Vec<_> = columns.iter().map(|c| header_column(ui, c.label) * dimension(c.width)).collect();
+ let mut table = Table { columns, widths, id: id.to_owned(), rows: 0 };
+ egui::ScrollArea::horizontal()
+ .id_salt(id)
+ .auto_shrink([false, true])
+ .show(ui, |ui| {
+ let width = table.width();
+ let (rect, _) = ui.allocate_exact_size(vec2(width, row_height()), egui::Sense::hover());
+ let mut left = rect.left();
+ for (column, width) in table.columns.iter().zip(&table.widths) {
+ let cell = egui::Rect::from_min_size(egui::pos2(left, rect.top()), vec2(*width, rect.height()));
+ let response = ui.put(cell, egui::Label::new(egui::RichText::new(crate::i18n::tr_label(column.label)).color(t.text_dim)).truncate());
+ response.on_hover_text(crate::i18n::tr_label(column.label));
+ scenario::publish_rect(&format!("dialog:column:{id}:{}", column.label), cell);
+ left = cell.right() + t.space_8;
+ }
+ ui.painter().hline(rect.x_range(), rect.bottom(), egui::Stroke::new(1.0, t.dialog_rule));
+ let result = add(ui, &mut table);
+ if table.rows == 0 {
+ super::note(ui, id, empty);
+ }
+ result
+ })
+ .inner
+}
+
+impl Table<'_> {
+ fn width(&self) -> f32 {
+ self.widths.iter().sum::<f32>() + Tokens::get().space_8 * self.widths.len().saturating_sub(1) as f32
+ }
+
+ /// A selectable row with independently interactive cells and actions.
+ pub fn row(&mut self, ui: &mut Ui, key: &str, selected: bool, add: impl FnOnce(&mut TableRow<'_>)) -> Response {
+ self.row_visible(ui, key, selected, true, add)
+ }
+
+ /// Keep off-screen rows' space without building their cells. Force active drafts to stay live.
+ pub fn row_visible(&mut self, ui: &mut Ui, key: &str, selected: bool, force: bool, add: impl FnOnce(&mut TableRow<'_>)) -> Response {
+ let t = Tokens::get();
+ let (rect, response) = ui.allocate_exact_size(vec2(self.width(), row_height()), egui::Sense::click());
+ self.rows += 1;
+ if !force && !ui.is_rect_visible(rect) {
+ return response;
+ }
+ if selected || response.hovered() {
+ ui.painter().rect_filled(rect, t.control_radius, if selected { t.selected_bg } else { t.hover });
+ }
+ response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, ui.is_enabled(), selected, key));
+ scenario::publish_rect(&format!("dialog:table:{}:{key}", self.id), rect);
+ ui.push_id((&self.id, key), |ui| {
+ add(&mut TableRow { ui, widths: &self.widths, columns: self.columns, rect, column: 0, left: rect.left() });
+ });
+ response
+ }
+}
+
+pub struct TableRow<'a> {
+ ui: &'a mut Ui,
+ widths: &'a [f32],
+ columns: &'a [Column<'a>],
+ rect: egui::Rect,
+ column: usize,
+ left: f32,
+}
+
+impl TableRow<'_> {
+ /// Place an inline field, text, choice or row actions in the next clipped cell.
+ pub fn cell<R>(&mut self, add: impl FnOnce(&mut Ui) -> R) -> R {
+ let width = self.widths.get(self.column).copied().unwrap_or(0.0);
+ let label = self.columns.get(self.column).map_or("", |c| c.label);
+ let rect = egui::Rect::from_min_size(egui::pos2(self.left, self.rect.top()), vec2(width, self.rect.height()));
+ self.column += 1;
+ self.left += width + Tokens::get().space_8;
+ self.ui
+ .scope_builder(
+ egui::UiBuilder::new()
+ .id_salt(self.column)
+ .max_rect(rect)
+ .layout(egui::Layout::left_to_right(egui::Align::Center))
+ .ui_stack_info(egui::UiStackInfo::default().with_tag_value(super::layout::LABEL, label.to_owned())),
+ |ui| {
+ ui.set_clip_rect(ui.clip_rect().intersect(rect));
+ ui.spacing_mut().text_edit_width = width;
+ add(ui)
+ },
+ )
+ .inner
+ }
+}
+
+/// Read-only clipped cell retaining a full tooltip and accessible label. Tokens: font_label, text.
+pub fn cell_text(ui: &mut Ui, text: &str) -> Response {
+ let t = Tokens::get();
+ let (rect, response) = ui.allocate_exact_size(vec2(dimension(ui.available_width()), row_height()), egui::Sense::click());
+ paint_text(ui, rect, text, egui::FontId::proportional(t.font_label), t.text, false);
+ response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, ui.is_enabled(), text));
+ scenario::publish_rect(&format!("dialog:cell:{text}"), rect);
+ scenario::publish_handle(&format!("dialog:cell:{text}"), rect.center());
+ response.on_hover_text(text)
+}
+
+/// Clipped row name beside compact actions. Tokens: control_height and scope font/spacing.
+pub fn label_actions(ui: &mut Ui, text: &str, add: impl FnOnce(&mut Ui)) {
+ let width = dimension(ui.available_width());
+ ui.allocate_ui_with_layout(vec2(width * LABEL_ACTIONS_SHARE, row_height()), egui::Layout::left_to_right(egui::Align::Center), |ui| {
+ cell_text(ui, text);
+ });
+ add(ui);
+}
diff --git a/crates/ui-egui/src/ui_kit_guard_tests.rs b/crates/ui-egui/src/ui_kit_guard_tests.rs
index e4e41865fa..8c0da5799e 100644
--- a/crates/ui-egui/src/ui_kit_guard_tests.rs
+++ b/crates/ui-egui/src/ui_kit_guard_tests.rs
@@ -3,12 +3,7 @@ use std::path::Path;
use syn::visit::{self, Visit};
/// Counts may shrink; additions need a specific reason. Dense-only files have no allowance.
-const ALLOWED: &[(&str, usize, &str)] = &[
- ("dialogs.rs", 13, "retired non-dense window and explicitly guarded legacy selection/field helpers"),
- ("dialogs_assembly.rs", 6, "non-dense Drive Joint slider, Motion Study compute and joint browser actions"),
- ("dialogs_plastic.rs", 1, "non-dense Manage Rules active-rule checkbox"),
- ("dialogs_sheet.rs", 4, "non-dense Manage Rules and flat-pattern export actions"),
-];
+const ALLOWED: &[(&str, usize, &str)] = &[];
#[derive(Default)]
struct Guard {
diff --git a/crates/ui-egui/src/update.rs b/crates/ui-egui/src/update.rs
index 6b958de4f8..c87bcd38b6 100644
--- a/crates/ui-egui/src/update.rs
+++ b/crates/ui-egui/src/update.rs
@@ -12,7 +12,6 @@
//! The host provides the HTTP client (`Services::http_get`), so this crate stays portable and
//! the browser build never checks (it updates itself through its service worker).
-use crate::fonts::RichTextExt as _;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::mpsc::{Receiver, TryRecvError};
@@ -23,6 +22,7 @@ use serde_json::Value;
use crate::SolveApp;
use crate::theme::Tokens;
+use crate::ui_kit;
/// The repository releases come from.
pub const REPO: &str = "bherbruck/solidcraft";
@@ -54,9 +54,6 @@ const MAX_NOTES: usize = 64 * 1024;
const MAX_ASSETS: usize = 400;
/// The room the Update pill's long label leaves for the document tabs.
const TAB_ROOM: f32 = 300.0;
-/// The Update window's width, and its release notes' wrap width.
-const WINDOW_W: f32 = 460.0;
-const NOTES_W: f32 = WINDOW_W - 30.0;
/// The Linux app ID (Flatpak, desktop files).
pub const APP_ID: &str = "ai.storyteller.solidcraft";
@@ -782,7 +779,7 @@ pub fn button(app: &mut SolveApp, ui: &mut egui::Ui, span: egui::Rect, labeled:
Some(rect)
}
-/// The Update window.
+/// The Update card.
pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
if !app.updater.open {
return;
@@ -795,140 +792,106 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
let install = install_method(app);
let arch = std::env::consts::ARCH;
let t = Tokens::get();
- let mut open = true;
- let mut action = None;
- let shown = crate::frame::window(ctx, crate::i18n::tr("update.title"), crate::frame::Width::Wide)
- .id(egui::Id::new("sc_update"))
- .open(&mut open)
- .resizable(false)
- .show(ctx, |ui| {
- ui.set_width(WINDOW_W);
- ui.set_max_width(WINDOW_W);
- ui.label(
- RichText::new(crate::i18n::format("update.available", &[("version", release.version())]))
- .semibold()
- .color(crate::theme::Tokens::get().text)
- .size(crate::theme::Tokens::get().font_subtitle),
- );
- ui.label(RichText::new(crate::i18n::format("update.you_have", &[("version", current_version())])).color(t.text_dim));
- ui.add_space(6.0);
+ let one_click = install.is_some() && !matches!(app.updater.installed, Some(Err(_)));
+ let downloading = app.updater.job.is_some();
+ let state = match &app.updater.installed {
+ _ if downloading => State::Downloading,
+ Some(Ok(install::Outcome::Restart(_))) => State::Restart,
+ Some(Ok(install::Outcome::Installer(..) | install::Outcome::Opened(_))) => State::Started,
+ _ => State::Offer,
+ };
+ let primary = match (&install, one_click) {
+ (Some(install::Method::Msi), true) => crate::i18n::tr("update.install_msi"),
+ (Some(install::Method::Dmg), true) => crate::i18n::tr("update.download_open"),
+ (Some(_), true) => crate::i18n::tr("update.update_now"),
+ _ if kind.system_managed() => crate::i18n::tr("update.release_page"),
+ _ => crate::i18n::tr("update.download"),
+ };
+ let download = if kind.system_managed() { crate::i18n::tr("update.release_page") } else { crate::i18n::tr("update.download") };
+ let (ok, cancel, apply) = match state {
+ State::Downloading => ("", crate::i18n::tr("ui.cancel"), None),
+ State::Restart => (crate::i18n::tr("update.restart"), crate::i18n::tr("update.restart_later"), None),
+ State::Started => ("", crate::i18n::tr("ui.close"), None),
+ State::Offer => (primary, crate::i18n::tr("update.later"), Some(crate::i18n::tr("update.skip"))),
+ };
+ let id = egui::Id::new("sc_update");
+ let mut also_download = false;
+ let (closed, answer) =
+ ui_kit::Prompt::new(id, "update", crate::i18n::tr("update.title")).cards(1.7).actions(ok, cancel, apply).show(ctx, true, |ui| {
+ ui_kit::text_block(ui, "available", &crate::i18n::format("update.available", &[("version", release.version())]), false);
+ ui_kit::note(ui, "have", &crate::i18n::format("update.you_have", &[("version", current_version())]));
egui::Frame::group(ui.style()).show(ui, |ui| {
ui.set_width(ui.available_width());
- ui.set_max_width(NOTES_W + 12.0);
egui::ScrollArea::vertical().max_height(260.0).auto_shrink([false, true]).show(ui, |ui| {
if release.notes.trim().is_empty() {
- ui.label(RichText::new(crate::i18n::tr("update.no_notes")).color(t.text_dim));
+ ui_kit::note(ui, "no_notes", crate::i18n::tr("update.no_notes"));
} else {
markdown(ui, &release.notes, &t);
}
});
});
- ui.add_space(6.0);
let asset = release.asset_for(&kind, arch).map(|a| a.name.clone());
if let Some(cmd) = kind.update_command(asset.as_deref()) {
let how = match kind {
InstallKind::Deb | InstallKind::Rpm | InstallKind::Snap { store: false } => "update.package_hint",
_ => "update.system_hint",
};
- ui.add(egui::Label::new(crate::i18n::format(how, &[("kind", kind.label())])).wrap());
- ui.horizontal(|ui| {
- ui.add(egui::Label::new(RichText::new(&cmd).monospace()).selectable(true));
- if ui.small_button(crate::i18n::tr("update.copy")).clicked() {
+ ui_kit::text_block(ui, "how", &crate::i18n::format(how, &[("kind", kind.label())]), false);
+ ui_kit::label_actions(ui, &cmd, |ui| {
+ if ui_kit::small_button(ui, crate::i18n::tr("update.copy")).clicked() {
ui.ctx().copy_text(cmd.clone());
}
});
- ui.add_space(4.0);
} else if let Some(name) = asset.as_ref().filter(|_| app.updater.installed.as_ref().is_none_or(|r| r.is_err())) {
- ui.label(
- RichText::new(crate::i18n::format("update.file", &[("file", name)]))
- .size(crate::theme::Tokens::get().font_small)
- .color(t.text_dim),
- );
+ ui_kit::note(ui, "file", &crate::i18n::format("update.file", &[("file", name)]));
}
- if let Some((_, progress)) = &app.updater.job {
- let done = progress.done.load(std::sync::atomic::Ordering::Relaxed);
- let total = progress.total.load(std::sync::atomic::Ordering::Relaxed).max(1);
- let mb = |b: u64| format!("{:.1}", b as f64 / 1_048_576.0);
- ui.add(
- egui::ProgressBar::new((done as f32 / total as f32).clamp(0.0, 1.0))
- .text(crate::i18n::format("update.downloading", &[("done", &mb(done)), ("total", &mb(total))])),
- );
- if ui.button(crate::i18n::tr("ui.cancel")).clicked() {
- progress.cancel.store(true, std::sync::atomic::Ordering::Relaxed);
- }
- ui.ctx().request_repaint_after(std::time::Duration::from_millis(100));
- return;
- }
- match &app.updater.installed {
- Some(Ok(install::Outcome::Restart(_))) => {
- ui.label(
- RichText::new(crate::i18n::format("update.installed", &[("version", release.version())]))
- .semibold()
- .color(crate::theme::Tokens::get().text),
+ match (&state, &app.updater.installed, &app.updater.job) {
+ (State::Downloading, _, Some((_, progress))) => {
+ let done = progress.done.load(std::sync::atomic::Ordering::Relaxed);
+ let total = progress.total.load(std::sync::atomic::Ordering::Relaxed).max(1);
+ let mb = |b: u64| format!("{:.1}", b as f64 / 1_048_576.0);
+ ui_kit::text_block(
+ ui,
+ "downloading",
+ &crate::i18n::format("update.downloading", &[("done", &mb(done)), ("total", &mb(total))]),
+ false,
);
- ui.horizontal(|ui| {
- let r = ui.add(
- egui::Button::new(RichText::new(crate::i18n::tr("update.restart")).semibold().color(crate::theme::Tokens::get().text))
- .fill(t.accent),
- );
- crate::scenario::publish_rect("update:restart", r.rect);
- if r.clicked() {
- action = Some("restart");
- }
- if ui.button(crate::i18n::tr("update.restart_later")).clicked() {
- action = Some("close");
- }
- });
- return;
- }
- Some(Ok(install::Outcome::Installer(..))) => {
- ui.label(crate::i18n::tr("update.installer_started"));
- return;
- }
- Some(Ok(install::Outcome::Opened(_))) => {
- ui.add(egui::Label::new(crate::i18n::tr("update.dmg_opened")).wrap());
- return;
+ ui_kit::progress(ui, "download", done as f32 / total as f32);
+ ui.ctx().request_repaint_after(std::time::Duration::from_millis(100));
}
- Some(Err(e)) => {
- ui.add(egui::Label::new(RichText::new(crate::i18n::format("update.install_failed", &[("error", e)])).color(t.error)).wrap());
+ (State::Restart, ..) => {
+ ui_kit::text_block(ui, "installed", &crate::i18n::format("update.installed", &[("version", release.version())]), false);
}
- None => {}
- }
- ui.horizontal(|ui| {
- let one_click = install.is_some() && !matches!(app.updater.installed, Some(Err(_)));
- if let Some(m) = install.as_ref().filter(|_| one_click) {
- let label = match m {
- install::Method::Msi => crate::i18n::tr("update.install_msi"),
- install::Method::Dmg => crate::i18n::tr("update.download_open"),
- _ => crate::i18n::tr("update.update_now"),
- };
- let r = ui.add(egui::Button::new(RichText::new(label).semibold().color(crate::theme::Tokens::get().text)).fill(t.accent));
- crate::scenario::publish_rect("update:install", r.rect);
- if r.clicked() {
- action = Some("install");
- }
+ (_, Some(Ok(install::Outcome::Installer(..))), _) => {
+ ui_kit::text_block(ui, "installer", crate::i18n::tr("update.installer_started"), false);
}
- let download = if kind.system_managed() { crate::i18n::tr("update.release_page") } else { crate::i18n::tr("update.download") };
- let r = if one_click {
- ui.button(download)
- } else {
- ui.add(egui::Button::new(RichText::new(download).semibold().color(crate::theme::Tokens::get().text)).fill(t.accent))
- };
- crate::scenario::publish_rect("update:download", r.rect);
- if r.clicked() {
- action = Some("download");
+ (_, Some(Ok(install::Outcome::Opened(_))), _) => {
+ ui_kit::text_block(ui, "dmg", crate::i18n::tr("update.dmg_opened"), false);
}
- if ui.button(crate::i18n::tr("update.skip")).clicked() {
- action = Some("skip");
+ (_, Some(Err(e)), _) => {
+ ui_kit::text_block(ui, "failed", &crate::i18n::format("update.install_failed", &[("error", e)]), true);
}
- if ui.button(crate::i18n::tr("update.later")).clicked() {
- action = Some("later");
- }
- });
+ _ => {}
+ }
+ // With a one-click install the footer's main action installs; the download stays one click away.
+ if state == State::Offer && one_click {
+ also_download = ui_kit::secondary_button(ui, download).clicked();
+ }
});
- if let Some(w) = &shown {
- crate::scenario::publish_rect("update:window", w.response.rect);
+ if let Some(area) = ctx.memory(|m| m.area_rect(id)) {
+ crate::scenario::publish_rect("update:window", area);
}
+ let action = match (&state, answer) {
+ (State::Offer, ui_kit::Action::Ok) if one_click => Some("install"),
+ (State::Offer, ui_kit::Action::Ok) => Some("download"),
+ (State::Offer, ui_kit::Action::Apply) => Some("skip"),
+ (State::Offer, ui_kit::Action::Cancel) => Some("later"),
+ (State::Offer, _) if also_download => Some("download"),
+ (State::Restart, ui_kit::Action::Ok) => Some("restart"),
+ (State::Restart | State::Started, ui_kit::Action::Cancel) => Some("close"),
+ (State::Downloading, ui_kit::Action::Cancel) => Some("cancel_download"),
+ _ => None,
+ };
let now = unix_now();
match action {
Some("download") => {
@@ -947,22 +910,39 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
Some("install") => start_install(app, ctx),
Some("restart") => restart(app),
Some("close") => app.updater.open = false,
- _ if !open => app.updater.open = false,
+ Some("cancel_download") => {
+ if let Some((_, progress)) = &app.updater.job {
+ progress.cancel.store(true, std::sync::atomic::Ordering::Relaxed);
+ }
+ }
+ _ if closed => app.updater.open = false,
_ => {}
}
}
+/// What the Update card shows below the notes.
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum State {
+ /// A newer release: install or download it, skip it or be reminded.
+ Offer,
+ /// The package is downloading.
+ Downloading,
+ /// The update is installed and waits for a restart.
+ Restart,
+ /// An installer or disk image was started; nothing is left to do here.
+ Started,
+}
+
/// Preferences ▸ General: the automatic check and Check now.
-pub fn prefs_rows(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) {
+pub fn prefs_rows(app: &mut SolveApp, ui: &mut egui::Ui) {
let can = available(app);
let kind = app.updater.kind().clone();
- ui.label(crate::i18n::tr("update.prefs_label"));
- ui.add_enabled(can, egui::Checkbox::new(&mut app.preferences.check_updates, crate::i18n::tr("update.check_automatically")));
- ui.end_row();
- ui.label("");
+ ui_kit::row(ui, crate::i18n::tr("update.prefs_label"), |ui| {
+ ui.add_enabled_ui(can, |ui| ui_kit::checkbox(ui, crate::i18n::tr("update.check_automatically"), &mut app.preferences.check_updates));
+ });
ui.horizontal(|ui| {
let busy = app.updater.status == Status::Checking;
- let r = ui.add_enabled(can && !busy, egui::Button::new(crate::i18n::tr("update.check_now")));
+ let r = ui_kit::enabled_button(ui, crate::i18n::tr("update.check_now"), can && !busy);
crate::scenario::publish_rect("prefs:check_now", r.rect);
if r.clicked() {
let ctx = ui.ctx().clone();
@@ -977,11 +957,9 @@ pub fn prefs_rows(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) {
(Status::Idle, None) => String::new(),
};
if !status.is_empty() {
- ui.label(RichText::new(status).color(t.text_dim));
+ ui_kit::inline_text(ui, &status);
}
});
- ui.end_row();
- ui.label("");
let note = if can {
crate::i18n::format("update.prefs_note", &[("version", current_version()), ("kind", kind.label())])
} else if let InstallKind::Flatpak(id) = &kind {
@@ -989,11 +967,10 @@ pub fn prefs_rows(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) {
} else {
crate::i18n::format("update.prefs_dev", &[("version", current_version())])
};
- ui.add(egui::Label::new(RichText::new(note).size(crate::theme::Tokens::get().font_small).color(t.text_dim)).wrap());
- ui.end_row();
+ ui_kit::note(ui, "updates", &note);
if let Some(v) = offered_or_newer(app)
&& offered(app).is_none()
- && ui.link(crate::i18n::format("update.show", &[("version", &v)])).clicked()
+ && ui_kit::secondary_button(ui, crate::i18n::format("update.show", &[("version", &v)])).clicked()
{
app.updater.open = true;
}
@@ -1180,8 +1157,8 @@ fn markdown(ui: &mut egui::Ui, src: &str, t: &Tokens) {
}
});
};
- // Fixed widths: the notes never widen the window, whatever their lines.
- let width = NOTES_W;
+ // The notes wrap to the card; they never widen it, whatever their lines.
+ let width = (ui.available_width() - 2.0 * t.space_8).max(60.0);
for block in parse_markdown(src) {
match block {
Block::Heading(spans) => {
diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs
index 5fe8c208c8..2c243e2ee3 100644
--- a/crates/ui-egui/src/viewport.rs
+++ b/crates/ui-egui/src/viewport.rs
@@ -6008,11 +6008,17 @@ mod tests {
.expect("the list's popup");
let dialog = h.app.viewport.dialog_rect.expect("the dialog");
let vp = h.app.viewport.rect.expect("the viewport");
+ // The dense header, hint and footer change which item first hangs beyond
+ // the card. Keep the original reproduction over the exposed model.
+ let (item, first) = crate::scenario::handles("dialog:Material:")
+ .into_iter()
+ .find(|(_, point)| !dialog.contains(*point) && list.shrink(2.0).contains(*point) && vp.contains(*point))
+ .expect("a visible list item over the model");
assert!(!dialog.contains(first) && vp.contains(first), "the list must hang over the model: {first:?} {dialog:?}");
// The wheel scrolls the list and only the list, in its middle and by its edges.
assert!(!wheel(&mut h, pos2(list.center().x, first.y), -60.0), "smooth {smooth}: the wheel over the list zoomed the model");
- let moved = handle_at(item).expect("the list stays open");
+ let moved = handle_at(&item).expect("the list stays open");
assert!(moved.y < first.y - 1.0, "the wheel must scroll the list: {first:?} -> {moved:?}");
for p in [pos2(list.left() + 2.0, list.center().y), pos2(list.right() - 2.0, list.center().y), pos2(list.center().x, list.bottom() - 2.0)]
{
@@ -6025,7 +6031,7 @@ mod tests {
// next to the model.
h.call("ui.move", field.clone());
h.call("ui.click", field);
- assert!(handle_at(item).is_none(), "the list must close");
+ assert!(handle_at(&item).is_none(), "the list must close");
// Floating cards sit inside the full viewport. Probe their actual edges; the
// content anchor also reserves gaps and space below the short browser card.
// Docked panels end at the viewport boundary instead.
diff --git a/crates/ui-egui/tests/scenarios/s10_parameters_drive_model.json b/crates/ui-egui/tests/scenarios/s10_parameters_drive_model.json
index 65f227b403..1d5d0211de 100644
--- a/crates/ui-egui/tests/scenarios/s10_parameters_drive_model.json
+++ b/crates/ui-egui/tests/scenarios/s10_parameters_drive_model.json
@@ -99,7 +99,7 @@
}
},
{
- "widget": "Close window"
+ "click": {"handle": "params:close"}
},
{
"expect": {
diff --git a/crates/ui-egui/tests/scenarios/s15_start_page_sample_save_reopen.json b/crates/ui-egui/tests/scenarios/s15_start_page_sample_save_reopen.json
index d0950e537e..07150df4c4 100644
--- a/crates/ui-egui/tests/scenarios/s15_start_page_sample_save_reopen.json
+++ b/crates/ui-egui/tests/scenarios/s15_start_page_sample_save_reopen.json
@@ -10,7 +10,7 @@
{"key": "A", "cmd": true},
{"text": "100 mm"},
{"key": "Enter"},
- {"widget": "Close window"},
+ {"click": {"handle": "params:close"}},
{"expect": {"param": {"width": 100}, "errors": 0}},
{"click": {"handle": "titlebar:save"}},
{"expect": {"file": "Sample Plate.solidcraft"}},
diff --git a/crates/ui-egui/tests/scenarios/s23_configurations.json b/crates/ui-egui/tests/scenarios/s23_configurations.json
index 3d097ae4eb..df923be53d 100644
--- a/crates/ui-egui/tests/scenarios/s23_configurations.json
+++ b/crates/ui-egui/tests/scenarios/s23_configurations.json
@@ -43,7 +43,14 @@
]
}
},
- {"click": {"sketch": [20, -8]}},
+ {
+ "click": {
+ "sketch": [
+ 20,
+ -8
+ ]
+ }
+ },
{
"text": "40"
},
@@ -97,8 +104,9 @@
"key": "Enter"
},
{
- "widget": "Activate",
- "near": "Configuration2"
+ "click": {
+ "handle": "config:activate:Configuration2"
+ }
},
{
"expect": {
@@ -110,8 +118,9 @@
}
},
{
- "widget": "Activate",
- "near": "Default"
+ "click": {
+ "handle": "config:activate:Default"
+ }
},
{
"expect": {
@@ -124,4 +133,4 @@
{
"shot": "s23_configs"
}
-]
\ No newline at end of file
+]
diff --git a/crates/ui-egui/tests/scenarios/s24_motion_study.json b/crates/ui-egui/tests/scenarios/s24_motion_study.json
index 913ed90fe2..d41fbd10bb 100644
--- a/crates/ui-egui/tests/scenarios/s24_motion_study.json
+++ b/crates/ui-egui/tests/scenarios/s24_motion_study.json
@@ -166,6 +166,10 @@
{
"widget": "OK"
},
+ {
+ "call": "ui.resize",
+ "params": {"width": 1600, "height": 1200}
+ },
{
"start": "motion.study"
},
@@ -173,8 +177,7 @@
"widget": "Add Key"
},
{
- "widget": "0 deg",
- "near": "Value"
+ "click": {"handle": "dialog:Value"}
},
{
"key": "A",
diff --git a/crates/ui-egui/tests/scenarios/s36_sketch_palette_visible.json b/crates/ui-egui/tests/scenarios/s36_sketch_palette_visible.json
index 6531a36fd7..a13497ccec 100644
--- a/crates/ui-egui/tests/scenarios/s36_sketch_palette_visible.json
+++ b/crates/ui-egui/tests/scenarios/s36_sketch_palette_visible.json
@@ -64,7 +64,7 @@
"start": "parameters.change"
},
{
- "widget": "Close window"
+ "click": {"handle": "params:close"}
},
{"click": {"handle": "tab:SKETCH"}},
{
diff --git a/crates/ui-egui/tests/scenarios/s43_quit_asks_to_save.json b/crates/ui-egui/tests/scenarios/s43_quit_asks_to_save.json
index e3c7c0f32f..20166e6086 100644
--- a/crates/ui-egui/tests/scenarios/s43_quit_asks_to_save.json
+++ b/crates/ui-egui/tests/scenarios/s43_quit_asks_to_save.json
@@ -10,17 +10,17 @@
{"expect": {"shown": "Don't Save", "quit_requested": false}},
{"key": "Escape"},
{"expect": {"not_shown": "Don't Save", "quitting": false, "quit_requested": false}},
- {"note": "Left and Right pick a button (Save first, stopping at the ends) and Enter gives it."},
+ {"note": "Left and Right pick a button as laid out (Cancel, Don't Save, Save from the left; Save first, stopping at the ends) and Enter gives it."},
{"call": "app.quit"},
- {"key": "ArrowRight"},
- {"key": "ArrowRight"},
- {"key": "ArrowRight"},
+ {"key": "ArrowLeft"},
+ {"key": "ArrowLeft"},
+ {"key": "ArrowLeft"},
{"key": "Enter"},
{"expect": {"not_shown": "Don't Save", "quitting": false, "quit_requested": false, "bodies": 1}},
{"call": "app.quit"},
- {"key": "ArrowRight"},
- {"key": "ArrowRight"},
{"key": "ArrowLeft"},
+ {"key": "ArrowLeft"},
+ {"key": "ArrowRight"},
{"key": "Enter"},
{"expect": {"quit_requested": true}}
]
diff --git a/crates/ui-egui/tests/scenarios/s46_preferences_fixed_size.json b/crates/ui-egui/tests/scenarios/s46_preferences_fixed_size.json
index bd37acc6f8..88914283e5 100644
--- a/crates/ui-egui/tests/scenarios/s46_preferences_fixed_size.json
+++ b/crates/ui-egui/tests/scenarios/s46_preferences_fixed_size.json
@@ -1,24 +1,24 @@
[
- {"note": "#290: Preferences keeps one size on every page; descriptions wrap inside it, and OK / Cancel / Apply sit flush right in the bottom bar."},
+ {"note": "#290: Preferences keeps one size on every page; descriptions wrap inside it, and the kit footer keeps Cancel / Apply / OK flush right inside its action inset."},
{"click": {"handle": "titlebar:preferences"}},
- {"expect": {"prefs": {"dialog": "General"}, "same_width": "prefs:window", "right_edge": {"inner": "prefs:apply", "outer": "prefs:footer", "tol": 1}, "spans": {"inner": "prefs:footer", "outer": "prefs:window", "axis": "x", "tol": 12}}},
+ {"expect": {"prefs": {"dialog": "General"}, "same_width": "prefs:window", "right_edge": {"inner": "prefs:ok", "outer": "prefs:actions", "tol": 1}, "spans": {"inner": "prefs:footer", "outer": "prefs:window", "axis": "x", "tol": 12}}},
{"widget": "Navigation"},
- {"expect": {"prefs": {"dialog": "Navigation"}, "same_width": "prefs:window", "right_edge": {"inner": "prefs:apply", "outer": "prefs:footer", "tol": 1}}},
+ {"expect": {"prefs": {"dialog": "Navigation"}, "same_width": "prefs:window", "right_edge": {"inner": "prefs:ok", "outer": "prefs:actions", "tol": 1}}},
{"widget": "Fusion"},
{"widget": "SolidWorks"},
{"expect": {"prefs": {"nav": "solidworks"}, "same_width": "prefs:window"}},
{"widget": "Keyboard Shortcuts"},
- {"expect": {"prefs": {"dialog": "Keyboard Shortcuts"}, "same_width": "prefs:window", "right_edge": {"inner": "prefs:apply", "outer": "prefs:footer", "tol": 1}}},
+ {"expect": {"prefs": {"dialog": "Keyboard Shortcuts"}, "same_width": "prefs:window", "right_edge": {"inner": "prefs:ok", "outer": "prefs:actions", "tol": 1}}},
{"widget": "Design"},
- {"expect": {"prefs": {"dialog": "Design"}, "same_width": "prefs:window", "right_edge": {"inner": "prefs:apply", "outer": "prefs:footer", "tol": 1}}},
+ {"expect": {"prefs": {"dialog": "Design"}, "same_width": "prefs:window", "right_edge": {"inner": "prefs:ok", "outer": "prefs:actions", "tol": 1}}},
{"widget": "Graphics"},
- {"expect": {"prefs": {"dialog": "Graphics"}, "same_width": "prefs:window", "right_edge": {"inner": "prefs:apply", "outer": "prefs:footer", "tol": 1}}},
+ {"expect": {"prefs": {"dialog": "Graphics"}, "same_width": "prefs:window", "right_edge": {"inner": "prefs:ok", "outer": "prefs:actions", "tol": 1}}},
{"widget": "Sketch"},
- {"expect": {"prefs": {"dialog": "Sketch"}, "same_width": "prefs:window", "right_edge": {"inner": "prefs:apply", "outer": "prefs:footer", "tol": 1}}},
+ {"expect": {"prefs": {"dialog": "Sketch"}, "same_width": "prefs:window", "right_edge": {"inner": "prefs:ok", "outer": "prefs:actions", "tol": 1}}},
{"widget": "Selection"},
- {"expect": {"prefs": {"dialog": "Selection"}, "same_width": "prefs:window", "right_edge": {"inner": "prefs:apply", "outer": "prefs:footer", "tol": 1}}},
+ {"expect": {"prefs": {"dialog": "Selection"}, "same_width": "prefs:window", "right_edge": {"inner": "prefs:ok", "outer": "prefs:actions", "tol": 1}}},
{"widget": "General"},
- {"expect": {"prefs": {"dialog": "General"}, "same_width": "prefs:window", "right_edge": {"inner": "prefs:apply", "outer": "prefs:footer", "tol": 1}}},
+ {"expect": {"prefs": {"dialog": "General"}, "same_width": "prefs:window", "right_edge": {"inner": "prefs:ok", "outer": "prefs:actions", "tol": 1}}},
{"widget": "Cancel"},
{"expect": {"prefs": {"dialog": null}}}
]
diff --git a/crates/ui-egui/tests/ui_layout.rs b/crates/ui-egui/tests/ui_layout.rs
index 0b1b423627..678e4db683 100644
--- a/crates/ui-egui/tests/ui_layout.rs
+++ b/crates/ui-egui/tests/ui_layout.rs
@@ -33,10 +33,16 @@ fn every_dialog_opens_docked_within_its_width_limits() {
h.frames(4);
if h.app.dialog.is_some() {
seen += 1;
- // Command dialogs are 260–380 px (plus their 1 px border), the few with tables
- // (motion study, configurations) 480–560.
+ // Wide cards use the kit's bounded table/timeline width.
let w = rect_of("dialog:outer").map_or(0.0, |r| r.width());
- let limits = if w > 400.0 { json!({"min": 480, "max": 562}) } else { json!({"min": 260, "max": 382}) };
+ let limits = if matches!(spec.id, "config.table" | "config.configure" | "motion.study") {
+ let width = solidcraft_ui_egui::theme::Tokens::get().form_card_width * 3.0;
+ json!({"min":width - 4.0,"max":width + 2.0})
+ } else if w > 400.0 {
+ json!({"min":480,"max":562})
+ } else {
+ json!({"min":260,"max":382})
+ };
if let Err(e) = check(&mut h, &json!({ "dialog_docked": limits })) {
bad.push(format!("{}: {e}", spec.id));
}
diff --git a/crates/ui-egui/tests/window_widths.rs b/crates/ui-egui/tests/window_widths.rs
index ef624db767..1bb3731b8d 100644
--- a/crates/ui-egui/tests/window_widths.rs
+++ b/crates/ui-egui/tests/window_widths.rs
@@ -5,18 +5,31 @@ use serde_json::json;
use solidcraft_ui_egui::frame::{DIALOG_MAX_W, DIALOG_MIN_W, DIALOG_WIDE_MAX_W, WINDOW_WIDE_MAX_W};
use solidcraft_ui_egui::scenario::Harness;
-/// Widths of dialogs and windows on screen; the browser card is workspace chrome.
-fn window_widths(h: &Harness) -> Vec<(String, f32)> {
+/// Widths of the windows on screen (their areas in the middle layer).
+fn window_widths(h: &Harness) -> Vec<(egui::Id, f32)> {
h.ctx.memory(|m| {
m.areas()
.visible_layer_ids()
.into_iter()
.filter(|l| l.order == egui::Order::Middle && l.id != egui::Id::new("sc_browser_card"))
- .filter_map(|l| m.area_rect(l.id).map(|r| (format!("{:?}", l.id), r.width())))
+ .filter_map(|l| m.area_rect(l.id).map(|r| (l.id, r.width())))
.collect()
})
}
+fn kit_table_limit(id: egui::Id) -> Option<f32> {
+ [
+ egui::Id::new("sc_prefs"),
+ egui::Id::new("sc_params_dialog"),
+ egui::Id::new("sc_material_card_review"),
+ egui::Id::new(("sc_dialog", "CONFIGURATIONS")),
+ egui::Id::new(("sc_dialog", "MOTION STUDY")),
+ egui::Id::new(("sc_dialog", "EDIT MOTION STUDY")),
+ ]
+ .contains(&id)
+ .then(|| solidcraft_ui_egui::theme::Tokens::get().form_card_width * 3.0)
+}
+
fn fresh() -> Harness {
let mut h = Harness::new();
h.call("engine.execute", json!({"command": "solid.box", "params": {"length": 40, "width": 30, "height": 20}}));
@@ -37,9 +50,9 @@ fn command_dialogs_shrink_to_their_content_within_limits() {
let max = if wide { DIALOG_WIDE_MAX_W } else { DIALOG_MAX_W };
for (layer, w) in window_widths(&h) {
// Floating windows a command opened (Parameters…) have their own limit.
- let limit = if h.app.dialog.is_some() { max } else { WINDOW_WIDE_MAX_W };
+ let limit = kit_table_limit(layer).unwrap_or(if h.app.dialog.is_some() { max } else { WINDOW_WIDE_MAX_W });
if w > limit + slack {
- bad.push(format!("{} ({layer}): {w} px", spec.id));
+ bad.push(format!("{} ({layer:?}): {w} px", spec.id));
}
}
// The docked dialog shrinks to its content: most dialogs stay well under the maximum.
@@ -54,6 +67,9 @@ fn command_dialogs_shrink_to_their_content_within_limits() {
h.app.params = None;
h.app.design_properties = None;
h.app.bom = None;
+ if spec.id == "material.properties.validate" {
+ h.step(&json!({"click":{"handle":"dialog:close"}})).unwrap();
+ }
h.app.tool = None;
if h.app.session.active_sketch.is_some() {
h.app.finish_sketch();
@@ -91,6 +107,7 @@ fn floating_windows_stay_within_limits() {
// Keyboard Shortcuts is a page of Preferences (one window, #36).
assert!(ws.len() >= 3, "windows on screen: {ws:?}");
for (layer, w) in ws {
- assert!(w <= WINDOW_WIDE_MAX_W + 4.0, "{layer} is {w} px wide");
+ let limit = kit_table_limit(layer).unwrap_or(WINDOW_WIDE_MAX_W);
+ assert!(w <= limit + 4.0, "{layer:?} is {w} px wide");
}
}
diff --git a/docs/manage-ui-kit-audit.md b/docs/manage-ui-kit-audit.md
new file mode 100644
index 0000000000..96cf2e0a22
--- /dev/null
+++ b/docs/manage-ui-kit-audit.md
@@ -0,0 +1,153 @@
+# Manage popup audit
+
+Source inventory for `ui/shared-ui-kit`, before the Manage port. No native application
+was launched. Control recipes below are source-derived; screenshots need owner verification.
+Send each start as `{"id":1,"method":"ui.start","params":{"command":"COMMAND"}}`
+with the launch token on the connection's first request. Engine setup calls use
+`{"method":"engine.execute","params":{"command":"COMMAND","params":{...}}}`.
+
+| Manage entry | Before: source and surface | Existing fields, actions and nested surfaces | Recipe/setup |
+| --- | --- | --- | --- |
+| `parameters.change` | `params_dialog.rs`, custom PARAMETERS window, not kit | Filter; Import; Export CSV/JSON; Favorites, User Parameters, grouped Model Parameters. Columns: favorite/order, name (double-click rename), unit, expression, evaluated value/error, comment, delete. Add name/unit/expression/comment. Unit dropdowns; expression completion. Native import/save sheets; validation errors inline. | Start directly; optionally `parameters.add {"name":"width","expression":"10 mm"}` first. |
+| `parameters.graph` | `lib.rs::start` falls through to engine, **no popup** | Returns dependency graph JSON. | `ui.start` opens nothing; `engine.execute parameters.graph {}` returns the graph JSON. |
+| `parameters.move` | Same, **no popup** | Missing arguments report an error. Ordering UI is the Parameters window's arrows. | Open `parameters.change`; click `param:before:NAME` or `param:after:NAME`. |
+| `parameters.import`, `parameters.export` | Same, **no popup** from ribbon | Actual UI is Parameters window buttons and host-native file picker (`file_picker.rs`). No import/export option panel or additional egui confirmation exists. | Open `parameters.change`; Import… / Export CSV… / Export JSON…. |
+| `config.table`, `config.configure` | `dialogs_motion.rs`, legacy CONFIGURATIONS Dialog | Horizontal table: Configuration, dynamic parameter/suppression/material/appearance columns, remove column, active/Activate/Apply, inline cell fields, Delete row. New configuration, Add Row, Add Column menu with Face Appearance → Faces on BODY submenus; per-cell Library menu. Structured rule editor and preview below table. | Start either; optionally `parameters.add {"name":"width","expression":"10 mm"}`, then `config.configure {"params":["width"]}`. |
+| `config.rules`, `config.preview` | `lib.rs::start` falls through, **no dedicated popup** | Rules returns data; preview requires a row. Existing UI lives below configuration table: ordered enabled rules, Edit/up/down/Delete, Add or edit rule disclosure (name, units, recursive condition, effect, Save Rule), row dropdown/Preview Row and report disclosure. | Open `config.table`; Add or edit rule / Preview Row. |
+| `material.assign` | `dialogs.rs`, legacy PHYSICAL MATERIAL Dialog | Bodies selection, Material dropdown, OK/Cancel; includes document-created materials. | `solid.box {"length":10,"width":10,"height":10}`, then start; select Body1 in viewport/browser. |
+| `appearance.assign` | `dialogs_appearance.rs`, legacy APPEARANCE Dialog | Objects selection; Apply To bodies/faces/component; Colour popup; Opacity; PBR toggle and metallic/roughness/IOR; Apply to selection/Remove override; local library path/open/load/search/select/apply/export and overwrite checkbox; In This Design swatches; Library category/search/swatches; drag/drop. Inline status. | Same box setup, then start. |
+| `material.properties.validate` | `material_card_review.rs`, independent legacy review window | JSON multiline input, Review, validation error, card properties/conditions/sources/derived moduli disclosures and read-only report, Close. | Start directly, paste a supported candidate card. |
+| `library.inspect`, `library.export`, `library.apply` | `lib.rs::start` falls through, **no dedicated popup** | Require arguments. Existing local-library UI is inside Appearance (`dialogs_library.rs`); native Open/Save sheets; overwrite is explicit checkbox, errors inline. | Start `appearance.assign`; use library:path/load/search/entry:N/apply/export handles. |
+| `sheet.manage_rules` | `dialogs_sheet.rs`, legacy MANAGE RULES Dialog | Rule dropdown including New rule; conditional name; thickness, K factor, bend radius, relief width/depth, corner relief shape/size, hem gap/gap; Active rule; Delete rule; OK/Cancel. No separate deletion confirmation. | Start directly. |
+| `plastic.manage_rules` | `dialogs_plastic.rs`, legacy MANAGE PLASTIC RULES Dialog | Rule dropdown including New rule; conditional name; material and rule expression fields; Active rule; OK/Cancel. | Start directly. |
+| `plastic.assign_rule` | `dialogs_plastic.rs`, **already kit** | Bodies selection, Rule dropdown, OK/Cancel. | Box setup above, then start. |
+| `document.units` | `lib.rs::start` falls through, **no popup** | Missing units argument reports an error. Existing unit choices are browser context menu commands. | `engine.execute` with `{"units":"in"}` changes units directly. |
+| `timeline.compute_all`, `edit.checkpoint` | `lib.rs::start`, **immediate commands** | Recompute / create checkpoint, no dialog. | Start directly. |
+| `edit.restore_checkpoint` | `lib.rs::start` falls through, **no popup** | Requires checkpoint id; no checkpoint picker exists. | `edit.checkpoint {}` returns id; `edit.restore_checkpoint {"checkpoint":ID}` restores directly. |
+
+Native Open/Save boundaries need separate acceptance decisions if “all
+popups on the library” includes OS-provided windows. The existing file-picking continuation
+and platform behavior must remain intact; replacing those is not a paint-only port.
+
+## Other surfaces still outside the kit (source inventory)
+
+This list includes windows, floating panels and menus; it does not claim runtime screenshot verification.
+
+| Surface | Source |
+| --- | --- |
+| Home page (full-page start surface: painted tiles, thumbnail cards, links; no kit element fits) | `home.rs` |
+| Assistant transcript/composer layout, image gallery and docking chrome (specialised conversation/media surfaces; matching controls use the kit) | `agent_chat/panel.rs` |
+| Host-native file/program pickers (no egui surface; the load/progress card is ported) | `file_picker.rs`; host services in `apps/solidcraft/src/main.rs` and `apps/solidcraft-web/src/main.rs` |
+| Help action menu and shortcut command-result list/pin painting (menus/search results, not property forms; the search field uses the kit) | `help.rs`, `shortcut_box.rs` |
+| Ribbon overflow/recent/family menus and context menus | `toolbar.rs`, `context_menu.rs`, `timeline_left.rs` |
+| Motion transport controls, key strips and analysis chart; generated part thumbnails | `dialogs_motion.rs`, `dialogs_motion_plot.rs`, `dialogs_parts.rs` (matching form controls are ported) |
+| Joint-browser/timeline rows and glyphs; flat-pattern canvas | `dialogs_assembly.rs`, `dialogs_sheet.rs` (dialogs and export actions are ported) |
+| Slicer program icons and painted popup entries; native program picking | `dialogs_save_mesh.rs` (format, checkbox and dropdown shell are ported) |
+| Canvas/decal insertion and dimension placement/geometry painting | `dim_view.rs`, `sketch_dims.rs`, `canvas.rs` (dimension text editors are ported) |
+| Select Other popup and viewport display controls | `select_other.rs`, `viewport.rs` |
+| Tab-strip painting and popup placement; render canvas | `documents.rs`, `render_workspace.rs` (overflow choices and matching settings controls are ported) |
+
+## Port implementation and boundaries
+
+The port replaces the renderers listed above; it does not add a new interaction for
+ribbon entries that currently execute immediately. No command id or engine implementation
+is changed. Existing import/export callbacks, overwrite handling, local-library identity
+checks, parameter validation/undo/order, appearance selection/drag payloads, opacity/PBR
+precision, configuration rule ordering and non-mutating preview are retained.
+
+Kit additions are documented in `docs/ui-kit.md`: table columns/rows/cells and empty state,
+wide bounded Panel and optional manager folding, stable cell/search editors, multiline data input, read-only reports,
+selectable lists, colour/scalar controls, swatches, dense nested action menus and suggestion
+popup rendering. Existing expression-completion keyboard routing stays in its original
+module; drawing now goes through the kit. Native file sheets are unchanged. The colour
+chooser is owned by the kit's `color_field`, which still delegates its internal HSV/RGB
+popover to egui. No tabs/progress row was added because these Manage surfaces do not use one.
+
+User-visible layout changes: standard kit header/hint/footer; fixed 24 pt table rows;
+horizontal overflow for wide tables; the Add Parameter form uses labelled rows below the
+user table; model groups use kit disclosures; review closes via standard OK/Cancel or ×.
+Closing Parameters/Configurations still leaves edits already applied by their per-row
+commands, as before. New catalog entries exist in every locale; new helper text currently
+uses English fallback values in non-English catalogs and needs translation review.
+
+Family 4 removes the remaining raw-widget allowances for legacy window chrome/selection controls,
+Drive Joint and flat-pattern exports. Appearance RGB data and library swatch
+colours retain the pre-existing colour-data exemptions; no new allowance is added.
+
+## Ready-to-send starts for the ported cards
+
+A small common setup (run once in a fresh design) gives assignment targets and one
+configuration column. Repeat the `select.set` line before each assignment card; opening a selection card consumes the preselection.
+Close each card through `dialog:close` (Parameters also retains `params:close`) before
+opening the next one. Library actions are inside Appearance; configuration rules/preview
+are inside Config Table. The host must authenticate the first request as described above.
+
+```json
+{"id":10,"method":"engine.execute","params":{"command":"solid.box","params":{"length":10,"width":10,"height":10}}}
+{"id":11,"method":"engine.execute","params":{"command":"parameters.add","params":{"name":"width","expression":"10 mm"}}}
+{"id":12,"method":"engine.execute","params":{"command":"config.configure","params":{"params":["width"]}}}
+{"id":13,"method":"engine.execute","params":{"command":"select.set","params":{"items":[{"type":"body","name":"Body1"}]}}}
+{"id":20,"method":"ui.start","params":{"command":"parameters.change"}}
+{"id":21,"method":"ui.start","params":{"command":"config.table"}}
+{"id":22,"method":"ui.start","params":{"command":"config.configure"}}
+{"id":23,"method":"ui.start","params":{"command":"material.assign"}}
+{"id":24,"method":"ui.start","params":{"command":"appearance.assign"}}
+{"id":25,"method":"ui.start","params":{"command":"material.properties.validate"}}
+{"id":26,"method":"ui.start","params":{"command":"sheet.manage_rules"}}
+{"id":27,"method":"ui.start","params":{"command":"plastic.manage_rules"}}
+{"id":28,"method":"ui.start","params":{"command":"plastic.assign_rule"}}
+```
+
+Useful nested handles: `dialog:Unit:cm` after `param:new:unit`; `dialog:section:Add or edit rule`;
+`dialog:When:Parameter` / `dialog:Then:Range` after their dropdowns; `dialog:section:Local library`;
+`library:path`, `library:load`, `library:search`, `library:entry:0`, `library:apply`, `library:export`;
+`appearance:pbr`, `appearance:metallic`, `appearance:roughness`, `appearance:ior`; `review:input`.
+Use `ui.at {"handle":"HANDLE"}` to resolve these into coordinates for `ui.click`/`ui.text`.
+
+Manager cards retain their fold/unfold behavior through the kit header (`dialog:collapse`), preserving drafts and picked inputs. Rule actions also publish `config:save_rule`, `config:preview_row`, `config:rule:ID:up` and `config:preview:param:NAME` for scrolling and automation.
+
+Wide manager cards reserve the active Sketch Palette’s space when both panels fit; tables scroll horizontally within that width.
+
+## Family 3: settings, help and customisation
+
+Source inventory before porting:
+
+| Surface | Inventory and disposition | Open it |
+| --- | --- | --- |
+| AI settings | Master/toolbar toggles; installed/added agent cards, Test/Default/Remove, global/per-agent permissions, remembered grants, side and turn limit. Ported to kit rows, disclosures, choices, notes and actions. | Preferences → AI (`ui.prefs {"open":"AI"}`); enable AI features. |
+| Add agent | Installed/custom/API choices, discovery/preset dropdowns, name/command/URL/model/key, connection test/error, Add and close. Ported to Prompt; secret remains masked and disabled without a keychain. | AI settings → Add agent, or Assistant agent selector → Add agent. |
+| Assistant controls | Agent/mode/model selectors, connection/authentication, new-conversation confirmation, approval actions, attachments and queue actions use matching kit elements. Transcript, growing bottom composer container, docking/drag chrome and image gallery keep their specialised layouts. No generic property card replaces them. | Enable AI, then View → Assistant or Cmd/Ctrl+Shift+A (`ui.agent_chat {"features":true,"open":true}`). |
+| About | Build identity, diagnostic copy, attribution/font/licence disclosures and virtualized third-party text. Ported to close-only Prompt. Help's action menu is a menu, not a form card. | Help (?) → About SolidCraft (`ui.help {"item":"about"}`). |
+| Shortcut search | Search editor ported, retaining its focus ID and one-time focus request. Result ranking, JSON execution, keyboard selection, pins, row context menus and painted command list remain their specialised search layout. | S, or the application-bar search button. |
+| Keyboard Shortcuts | Search, reset/import/export, conflict actions, command/key table, capture/clear/reset. Ported to kit table/fields/actions. Read-only Help entry remains read-only. | Preferences → Keyboard Shortcuts, File/Help → Keyboard Shortcuts (`ui.prefs {"open":"Keyboard Shortcuts"}`). |
+| Toolbar customisation | Tab guidance, panel command checkboxes and Reset Toolbar. Ported to close-only Prompt. Drag/reorder menus remain in their existing toolbar surfaces. | Right-click toolbar → Customize Toolbar… (menu item `ui.toolbarCustomize`; this is a UI menu action, not an engine command). |
+| Preferences | All eight page selectors and form controls use the kit. Theme/font discovery and native import/export callbacks, Cancel/Apply snapshots, scale drag deferral, unsupported MSAA choices and command-backed auto-projection are retained. Colour-vision sample is a painted preview, not a form control. Update/cursor preference controls use kit drawing through their existing helpers. | File → Preferences, gear, Cmd/Ctrl+, (`ui.prefs {"open":"General"}`). |
+
+No guard allowance was added. Deleted the legacy settings section/note painters, About window/licence renderer, toolbar window and keymap grid, and Preferences window/grid/footers. Kit additions are documented in `ui-kit.md` and exercised in the light/dark gallery. New catalogue messages have English placeholders in other locales.
+
+## Family 4: remaining dialogs and matching inline controls
+
+Inventory and disposition, in port order:
+
+| Surface | Result and retained boundary | Open it |
+| --- | --- | --- |
+| Contact sets | Kit Panel, name, enable checkbox, set actions and collision report. Commands and preselection remain unchanged. | `ui.start {"command":"contact.create"}`; create components with bodies to populate sets. |
+| Motion Study / analysis | Kit wide Panel, study/name/steps, loop/speed, step slider, joint/key controls, plot/quantity/duration and collision actions. Transport icons, key strips and the interactive chart retain their specialised painting. Preview moves, playback, collision navigation, GIF export and restoration remain owned by the existing code. | `ui.start {"command":"motion.study"}`; create a movable joint first. To edit: include `"params":{"study":"NAME"}`. Plot and collision controls are inside this card. |
+| Exploded View | Kit name and continuous scale slider; preview and cancel restoration retained. | `ui.start {"command":"explode.create"}` with assembly components. |
+| Standard parts / Insert Part | Kit Panel, family/size/length/name and table-value controls. The generated part thumbnail remains an image, with its existing cache. | `ui.start {"command":"parts.insert"}` or `parts.fastener`; optionally preselect a hole wall/rim. |
+| Legacy dispatcher | Deleted the independent window, grid, header, footer, width measurements and raw field/combo/selection fallbacks. Every Dialog kind now composes the kit. Save/Send and Export DXF labels and aliases are retained. | All command dialogs. |
+| Drive Joint / Interference | Kit Panel, joint selector, stable focus expression editor, continuous slider, range/stopped text and compute actions. Browser/timeline joint rows, glyphs and context-menu containers retain their existing specialised rendering. | `ui.start {"command":"joint.drive"}` after creating a movable joint; `inspect.interference` for analysis. Browser → Joints → double-click edits a joint; its menu offers Drive Joint. |
+| Save as mesh | Kit Panel, format, Send checkbox and slicer dropdown shell. Installed-program icons and popup rows remain painter-based; Delete/custom-program picking and host-native file continuations are retained. | Preselect bodies, then `ui.start {"command":"file.save_mesh"}`. Slicer controls require native program-picker services. |
+| Current View as DXF | Kit choices, tolerance and projection/help text; remembered options and asynchronous native save retained. | `ui.start {"command":"file.export_view_dxf"}` with visible bodies. |
+| Flat Pattern controls | Kit Panel, dimensions/bends and DXF/bend-table export actions. The flat-pattern canvas and navigation remain specialised. | `ui.start {"command":"sheet.flat_pattern"}` after making sheet metal. |
+| Dimension editor | Kit stable-ID editor, heading and validation report. Reference insertion, selection ranges, completion and draft commit/cancel remain in their owner. | Sketch → Dimension; place a dimension, or double-click an existing driving dimension. |
+| Placement fields | Kit placement editor retains drawing-tool Enter/Tab/completion ownership. Floating field positioning and canvas geometry remain specialised. | Start a sketch shape (line, circle, rectangle, etc.); type into its live dimension fields. |
+| Select Other | Skipped: the entire popup is painter-based, including entity icons, hover highlighting and hit targets; there is no separate form control to replace cleanly. | Hold left-click over overlapping geometry, viewport menu → Select Other, or `ui.selectOther {"x":X,"y":Y}`. |
+| Document-tab overflow | Kit selectable entries; tab-strip painting and popup placement/outside-click handling retained. | Open enough designs to overflow the tab strip, then click `tab:overflow`. |
+| Render setup selector | Kit dropdown and capped name editor; the remaining matching buttons, checkboxes, dimensions, colour and progress controls also use the kit so the file needs no raw-control allowance. Render canvas and navigation remain specialised. | Enter the Render workspace (`ui.workspace {"workspace":"render"}`); setup selector is at the top of its settings panel. |
+
+The raw-control allowance table is empty (previously 10 in `dialogs.rs`, 6 in
+`dialogs_assembly.rs`, 2 in `dialogs_sheet.rs`). Native file sheets, context menus,
+canvases, browser rows and painter-based controls above are retained. Kit additions
+are listed under “Inline placement and motion controls” in `ui-kit.md` and in the
+light/dark gallery. No command IDs or engine behavior are changed.
diff --git a/docs/ui-kit.md b/docs/ui-kit.md
index 489a5012e0..ccb52d9d14 100644
--- a/docs/ui-kit.md
+++ b/docs/ui-kit.md
@@ -1,6 +1,6 @@
# SolidCraft UI kit
-`crates/ui-egui/src/ui_kit/` is the tokenised library used to assemble dense feature dialogs and the sketch palette. This extraction preserves their existing layout, painting, focus, accessibility labels and scenario identities. Sketch tool panels use the same composition and elements.
+`crates/ui-egui/src/ui_kit/` is the tokenised library used to assemble dense feature dialogs, preferences, property/prompt cards and the sketch palette. This extraction preserves their existing layout, painting, focus, accessibility labels and scenario identities. Sketch tool panels use the same composition and elements.
## Module tree
@@ -8,13 +8,14 @@
ui_kit/
mod.rs overview and the one caller import path
metrics.rs row/header dimensions, sanitising and label-column maths
+ table.rs measured columns, headers, fixed-height selectable rows and cells
text.rs weighted, clipped, pixel-snapped text
- layout.rs form scope, aligned rows, captions, hints, sections, dividers, picked lists
+ layout.rs form scope, aligned rows, captions, hints, notes, sections, dividers, picked lists, text_block, inline_text
panel.rs bounded windows, surfaces, feature/palette composition and compute status
- fields.rs expressions, plain text, units, dropdowns, selections and paired values
- choice.rs text/icon segments, checkboxes, wrapped modes and icon toggles
+ fields.rs expressions, plain text, cell/search editors, dropdowns, selections, paired values, colour/scalar/slider
+ choice.rs text/icon segments, checkboxes, wrapped modes, icon toggles, popup_list, swatches and list_picker
actions.rs buttons, equal secondary pairs, keyboard and OK/Apply/Cancel footers
- status.rs supplied name/status/icon and constraint meter
+ status.rs supplied name/status/icon, constraint meter and progress bar
gallery.rs test-only light/dark element examples and geometry/interaction checks
*_tests.rs moved concern tests, Panel regressions and shared test input helpers
```
@@ -27,7 +28,7 @@ ui_kit/
- Build cards with `Panel`. Right-hand feature cards keep `space_8` clearance from the viewport edge. It owns the bounded window, feature header/drag target, scrolling body padding, pinned actions, compute status and keyboard routing. Its palette composition retains the existing palette padding and whole-card scrolling on short viewports. Supply `FeatureOptions::apply_label` for a tool card that also needs Apply. Use `feature_frame` or `palette_frame` for the existing docked/floating surfaces.
- Panels use kit elements instead of raw egui controls. Application logic supplies values, command metadata and enabled state; it receives responses/actions and runs the existing commands.
- Arguments put `ui` first, then the label/key (when not inherited from `row`), then the value and options. Buttons/targets return `Response`; choices report clicks; expression editors report accepted Enter (`text_field` additionally returns changed). Containers return their closure result. Existing Enter semantics intentionally distinguish completion from submission.
-- Scenario names and accessibility labels are API: preserve them. New elements publish geometry without overwriting the native accessible label or checked state.
+- Scenario names and accessibility labels are API: preserve them. New elements publish geometry without overwriting the native accessible label or checked state. `Prompt` publishes `dialog:window`; the footer also publishes `dialog:footer:actions` for its padded action bounds. Callers may publish stable surface aliases for those rectangles.
- `footer(..., None)` retains the original OK/Cancel layout. `Some("Apply")` adds the third action and returns `Action::Apply`; the panel decides whether to keep the operation open.
## Elements
@@ -39,26 +40,33 @@ All calls below use `crate::ui_kit::`; snippets assume local values and normal e
| `metrics::row_height` | Row height for controls | `control_height` | `row_height()` |
| `metrics::header_height` | Feature heading height | `form_header_height` | `header_height()` |
| `layout::scope` | Inherited form styling and label-column identity | `space_4/8, form_gap_y, control_height, font_label, accent, selected_bg, dialog_rule, control_fill/border/radius, text` | `scope(ui, \|ui\| { /* elements */ })` |
-| `layout::row` | Aligned label/control row, 24 pt today | `control_height, form_label_width, font_label, dialog_label, space_8` | `row(ui, "Radius", \|ui\| number_field(ui, &mut radius, "mm"))` |
+| `layout::row` | Aligned label/control row, 24 pt today | `control_height, form_label_width, font_label, dialog_label, space_8` | `row(ui, "Radius", \|ui\| field(ui, &mut radius))` |
| `layout::caption` | Dim helper beneath a row control | `form_icon_size, font_small, text_dim, space_8; label-column tokens` | `caption(ui, "Line Type", "Construction")` |
| `layout::section` | Persisted disclosure with a rule and uppercase title | `control_height, space_2, radius_sm, hover, dialog_rule, form_section_icon_size, form_gap_y, font_caption, font_section_tracking, text_dim` | `section(ui, "advanced", "Advanced", false, \|ui\| {})` |
| `layout::hint` | Helper text below a card header | `control_height, font_small, text_dim` | `hint(ui, "pick", "Pick a point")` |
| `layout::note` | Wrapping explanatory text in a card body, for rules or caveats too long for a hint | `font_small, text_dim, space_4` | `note(ui, "pattern", "Counts include the original.")` |
| `layout::list_row` | Picked-item row with a remove action | `control_height, space_8, font_label, text; icon-button tokens` | `list_row(ui, "point-1", "Point 1").clicked()` |
| `layout::divider` | Full-width rule without extra padding | `dialog_rule` | `divider(ui, "group")` |
+| `collapsible_header`, `Panel::feature_collapsible` | Optional manager fold action retaining inputs, the common header/footer and legacy chevron labels | header tokens, `space_4` | `collapsible_header(ui, icon, title, &mut collapsed, close)` |
| `panel::header` | Feature title/icon/close band | `form_header_height, form_icon_size, form_close_size, form_inset, font_label, text, dialog_rule, space_8/10; icon_button_at tokens` | `header(ui, "fillet", "Fillet", || {})` |
| `fields::field` | Expression editor; the value carries its unit text ("20 mm", "45 deg"), there is no unit suffix; returns accepted Enter | `control_height, control_fill, form_inset, font_label, text_dim, space_4; scope tokens` | `field(ui, &mut expression)` |
| `fields::focused_field` | Single-value expression popup retaining keyboard focus | `field tokens` | `focused_field(ui, &mut expression)` |
| `fields::hint_field` | Expression editor with empty-value hint | `same as field` | `hint_field(ui, &mut depth, "To the next face")` |
+| `dropdown_menu` | Dropdown with caller-supplied kit choices/actions, disabled entries and stable aliases; use `dropdown` for indexed lists | dropdown tokens | `dropdown_menu(ui, "msaa", current, \|ui\| { /* enabled list_picker choices */ })` |
+| `password_field` | Stable-ID secret input; never publishes the secret in scenario/accessibility metadata | `control_height/fill`, `form_inset`, `font_label` | `password_field(ui, id, &mut key, hint)` |
+| `number_field` | Integer/decimal field retaining the caller's range, drag step and unit suffix | scope control/font tokens | `number_field(ui, &mut minutes, 0.0..=120.0, 0.5, " min")` |
+| `formatted_slider` | Stepped preference slider retaining percent/multiplier formatting and numeric accessibility value | `control_height`, `space_24/4`, scope control/font tokens | `formatted_slider(ui, &mut scale, 0.5..=2.5, 0.05, \|v\| format!("{:.0} %", v * 100.0))` |
+| `message_field` | Growing plain-text message editor; parent retains scroll container and Enter routing | `control_fill`, `form_inset`, `font_label`, `space_4` | `message_field(ui, id, &mut message, hint)` |
+| `text_lines` | Virtualized read-only licence/report lines with horizontal overflow; only visible lines are laid out | `font_small`, `text`, `control_height` | `text_lines(ui, "licences", report)` |
| `fields::text_field` | Plain text editor without expression completion; returns (Enter, changed) | `same as field` | `text_field(ui, &mut name, "Name")` |
| `fields::multiline_text_field` | Three-line plain-text row with stable focus ID; caller routes Enter | `control_height, control_fill, form_inset, font_label; row tokens` | `multiline_text_field(ui, "Text", id, &mut text)` |
| `fields::searchable_dropdown`, `SearchOption` | Search/list dropdown with optional custom-value action and loading message | `control_height, space_24, font_label; scope control tokens` | `searchable_dropdown(ui, "font", current, &mut filter, &choices, custom, pending)` |
-| `fields::value_pair_named` | Paired X/Y captions retaining independent accessible/scenario names | `value_pair tokens` | `value_pair_named(ui, "Position", [x, y], ["X", "Y"], ["Distance X", "Distance Y"], "mm")` |
+| `fields::value_pair_named` | Paired X/Y captions retaining independent accessible/scenario names | `value_pair tokens` | `value_pair_named(ui, "Position", [&mut x, &mut y], ["X", "Y"], ["Distance X", "Distance Y"])` |
| `choice::text_emphasis` | Compact bold/italic toggles with localized accessible names | `scope font/control tokens` | `text_emphasis(ui, &mut bold, &mut italic)` |
| `fields::dropdown` | Native dropdown with kit arrow and scenario option handles | `text_dim; scope control/font tokens` | `dropdown(ui, "operation", &mut operation, &["Join", "Cut"])` |
| `fields::selection_field` | Filled point/curve/edge selection target | `control_height, control_radius, selected_bg/ink, accent, form_inset, space_24/8, font_label, text_dim` | `selection_field(ui, "Point 1", active)` |
| `fields::selection_field_state` | Selection target with explicit filled state | `same as selection_field` | `selection_field_state(ui, "Select", active, false)` |
-| `fields::value_pair` | Two labelled numeric fields in one row; returns accepted Enter | `row/field tokens, space_8, dialog_label` | `value_pair(ui, "Position", [&mut x, &mut y], ["X", "Y"], "mm")` |
+| `fields::value_pair` | Two labelled numeric fields in one row; returns accepted Enter | `row/field tokens, space_8, dialog_label` | `value_pair(ui, "Position", [&mut x, &mut y], ["X", "Y"])` |
| `fields::fraction_field` | Locale-aware variable-radius position editor | `scope control/font tokens` | `fraction_field(ui, &mut position)` |
| `choice::segmented` | Equal text choices, falling back to dropdown when labels cannot fit | `control_height, control_fill/border/radius, font_label, selected_bg/ink, hover, text, space_8` | `segmented(ui, &mut mode, &["One", "Two"])` |
| `choice::segmented_compact` | Always-visible short choices; long translations clip and retain tooltips and per-choice handles | `segmented tokens, space_4` | `segmented_compact(ui, &mut alignment, &labels)` |
@@ -79,7 +87,28 @@ All calls below use `crate::ui_kit::`; snippets assume local values and normal e
| `actions::small_button` | Compact inline action preserving native sizing | `scope font/control tokens` | `small_button(ui, "×")` |
| `actions::icon_button` | Allocated control-height icon action | `control_height; icon_button_at tokens` | `icon_button(ui, "Remove", "close")` |
| `status::status_header` | Name, status dot/text and meter for a card | `font_label, text/dim, accent, dialog_rule, sketch_accent, form_icon_size, space_3/4/6/8/10` | `status_header(ui, "card", "Sketch 1", status)` |
-| `panel::Panel` | Docked/floating window and both card compositions | `form_card_width`, frame/header/body/footer tokens above | `Panel::new(title, id, anchor, viewport, side, frame).window()` |
+| `table`, `Column`, `Table::row`, `TableRow::cell` | Horizontal table with measured column widths, header, 24 pt selectable body rows, inline controls/actions and empty state; compose an Add action after it | `form_label_width`, label-column maths, `control_height`, `font_label`, `dialog_label/rule`, `space_4/8`, `text/dim`, `selected_bg`, `hover` | `table(ui, "parameters", &columns, empty, \|ui, table\| table.row(ui, "width", false, \|row\| row.cell(\|ui\| field(ui, &mut value))))` |
+| `inline_text` | Read-only text beside compact actions | `font_label, text` | `inline_text(ui, "Active")` |
+| `label_actions` | Clipped row name beside compact actions | `control_height`, scope font/spacing tokens | `label_actions(ui, name, \|ui\| {})` |
+| `PopupOption`, `popup_list` | Focus-neutral completion/suggestion popup; owner retains keyboard routing | `space_2, form_label_width, control_height, text_dim`, scope tokens | `popup_list(ctx, id, anchor, selected, &items, hint)` |
+| `cell_text` | Read-only clipped table value with full tooltip/accessibility label | `control_height, font_label, text` | `cell_text(ui, name)` |
+| `cell_editor` | Stable-ID inline editor; caller owns completion and commit/blur semantics | `control_height/fill, form_inset, font_label, text/error` | `cell_editor(ui, id, &mut value, "Expression", invalid)` |
+| `search_field` | Stable-ID search input | `cell_editor` tokens | `search_field(ui, id, &mut query, "Filter")` |
+| `text_area` | Bounded multiline JSON/data input, caller owns keyboard and validation | `control_height/fill, form_inset, font_label` | `text_area(ui, label, id, &mut json, 5, 262144)` |
+| `text_block` | Wrapping read-only report or validation error; values include their units | `font_label, text/error` | `text_block(ui, "validation", report, invalid)` |
+| `list_picker` | Selectable list row with native checked state and caller identity | `control_height`, scope control/font/selection tokens | `list_picker(ui, id, name, selected)` |
+| `color_field` | Document RGB chooser under form styling (the internal native egui chooser remains) | scope colour/font tokens; RGB is document data | `color_field(ui, &mut rgb)` |
+| `slider`, `scalar_field` | Continuous (display only, two decimals; the stored value is never rounded) / locale-aware bounded dimensionless values | `control_height`, scope control/font tokens | `slider(ui, &mut opacity, 0.0..=1.0)` |
+| `color_swatch`, `swatch_grid` | Wrapped draggable document-colour samples retaining caller payload | `control_height/radius, border, accent, hover, space_4` | `color_swatch(ui, id, color, picked, tip, payload)` |
+| `enabled_button`, `action_menu` | Enabled secondary action (`label`, then `enabled`) and nested dense action menu | scope control/font tokens | `enabled_button(ui, "Add", valid)`, `action_menu(ui, "Add Column", \|ui\| {})` |
+| `panel::Prompt` | Floating card (1.5 card widths) for confirmations, offers, notices and short property forms: header, padded body, pinned footer with up to three actions (`actions(ok, cancel, apply)`; an empty `ok` leaves the primary one out), `anchor` / `placed` position, `selected` mark for the action Enter gives, `fields()` when Enter belongs to editable fields; returns (close pressed, `Action`) | `form_card_width` (x1.5, `cards(n)` for other widths), `dialog_body`, header/footer tokens, `space_6/8/10` | `Prompt::new(id, "delete", title).actions("Delete", "Cancel", None).show(ctx, true, \|ui\| text_block(ui, "why", text, false))` |
+| `status::progress` | Determinate progress bar (a download, a file load), full width, `space_6` tall; fraction clamped; pair with a `text_block` naming the step | `space_3/6, dialog_rule, accent` | `progress(ui, "download", 0.4)` |
+| `panel::Panel::actions` | Footer primary/closing labels of a docked card when they are not OK/Cancel ("Delete"/"Cancel"; `"", "Close"` for a card that only closes) | footer tokens | `Panel::new(..).actions("", "Close")` |
+| `panel::Prompt::keep_open_on_escape` | Esc does not close the card (header close and the closing action still do): for a card holding a long text being edited (issue report) | footer tokens | `Prompt::new(..).fields().keep_open_on_escape()` |
+| `actions::footer_selected` | Footer marking one action as the one Enter gives (used by `Prompt`) | footer tokens, `selected_bg`, `accent` | `footer_selected(ui, "Save", "Cancel", true, Some("Don't Save"), Some(Action::Apply))` |
+| `fields::focused_text_field` | Plain text editor keeping keyboard focus, for a one-name card (Rename); returns accepted Enter | `field` tokens | `focused_text_field(ui, &mut name, "")` |
+| `fields::length_field`, `fields::angle_field` | Draggable/typeable length held in millimetres (shown in the design's units) and angle in degrees | `control_height`, scope control/font tokens | `length_field(ui, &mut x, "in", 2)`, `angle_field(ui, &mut deg)` |
+| `panel::Panel` | Docked/floating window and both card compositions | `form_card_width` (`wide()` uses three card widths), frame/header/body/footer tokens above | `Panel::new(title, id, anchor, viewport, side, frame).window()` |
| `choice::toggle_icon` | Independent pattern direction/centering icon | `control_height`, `space_3/4/24`, `icon/fill`, `accent`, scope tokens | `toggle_icon(ui, "Alignment", "Center", &mut on, "pattern_center")` |
| `choice::IconSegment`, `ToolChoice` | Supplied icon/command-choice metadata | Read by their drawing element | `IconSegment { key, icon, tip }` |
| `actions::Action`, `PairButton` | Footer result and equal-action metadata | Read by their drawing element | `Action::Apply` |
@@ -98,13 +127,33 @@ The bounded allowances in `ui_kit_guard_tests.rs` cover:
| Source | Maximum calls | Reason |
| --- | ---: | --- |
-| `dialogs.rs` | 13 | Retired window controls, legacy selection chips, the legacy combo and its choices, guarded legacy checkboxes and parameter-table Add. Dense error actions and pattern toggles now use kit elements. |
+| `dialogs.rs` | 10 | Retired window controls, legacy selection chips, the legacy combo and its choices, and guarded legacy checkboxes. Dense error actions and pattern toggles now use kit elements; Measure, Section Analysis, Rename and the feature deletion dialog are dense cards. |
| `dialogs_assembly.rs` | 6 | Non-dense Drive Joint slider, Motion Study compute action and joint-browser actions. |
-| `dialogs_plastic.rs` | 1 | Non-dense Manage Rules active-rule checkbox. |
-| `dialogs_sheet.rs` | 4 | Non-dense Manage Rules checkbox/delete and flat-pattern exports. |
+| `dialogs_sheet.rs` | 2 | Flat-pattern exports remain outside this Manage port. |
Other retired non-sketch dialog sources keep their existing raw controls; they are outside this dense-panel port. Sketch modify, text, text move and attachment panels have no raw-control allowance. Dense adapters, the sketch palette and future sources using the kit are scanned recursively. Kit implementations themselves own the raw widgets and require no allowances. Guarded legacy text editors in `dialogs.rs` and `dialogs_plastic.rs` also remain for the old path.
## Verification and legacy boundaries
`ui_kit::gallery` renders every element in light and dark without a native window. Moved tests cover geometry, labels, field focus/completion, disclosures and actions. Panel tests cover both card layouts and short-height scrolling. `ui_kit_guard_tests` rejects raw controls in dense sources; the small allowance table names the remaining retired dialog paths. Standard font/colour guards, clippy, wasm, assets and layers still apply.
+
+## Manage cards
+
+Parameters, configurations (including rules and preview), physical material, appearance
+(including local library), sheet/plastic rule managers and material-card review compose
+these elements through `Panel`. Editable tables use `wide()` and horizontal scrolling
+when columns exceed the bounded viewport. No tabs or progress rows are needed by these
+existing workflows. Read [the Manage audit](manage-ui-kit-audit.md) for command recipes,
+the initial inventory, immediate command entries and the remaining application surfaces.
+
+Host-native Open/Save sheets remain in the host service. Expression completion and the
+colour chooser retain their shared popup behavior; the latter is owned by `color_field`
+but its internal HSV/RGB controls still use egui's built-in picker.
+
+## Inline placement and motion controls
+
+- `timeline_slider(ui, value, range, whole_steps)` draws a slider without a numeric editor. Motion timelines supply `true` for integer steps; Drive Joint supplies `false` and retains its expression editor and range caption. Tokens: `control_height`, `space_4`. Values are rounded only by manipulation, never just by rendering.
+- `placement_field(ui, id, value, hint)` retains the caller's focus ID and leaves Enter and Tab with the drawing tool, so rejecting an expression keeps the field available for correction. Completion stays with the caller. Tokens: `control_fill`, `text`, `font_body`, `control_height`, `space_2/4/6`. The floating canvas container and placement calculation remain outside the kit.
+- `bounded_cell_editor(ui, id, value, hint, invalid, limit)` is the stable cell editor with a Unicode character cap, used for render setup names (128 characters). Tokens: `cell_editor` tokens. `cell_editor` uses the same implementation without an additional cap.
+
+All three have light/dark gallery examples; keyboard and character-cap checks cover the two editors.