Merge branch 'main' into schema-plastic-rules-12313
This commit is contained in:
132 files changed
+40694
-1665
No files matched your search
@@ -828,6 +828,18 @@ Original SolidCraft drawings, Open for owner review; no runtime assignments.
|
||||
| docs/book/src/media/sketching/offset.mp4 | SolidCraft contributors | original screen recording of the actual SolidCraft 0.29.0 English desktop UI (default dark theme, software renderer) offsetting a sketch outline, with the original drawn pointer of examples/demo/overlay.py and labels set in DejaVu Sans Bold, captured with examples/demo/doc_shots.py | MIT OR Apache-2.0 |
|
||||
| docs/book/src/media/sketching/trim.mp4 | SolidCraft contributors | original screen recording of the actual SolidCraft 0.29.0 English desktop UI (default dark theme, software renderer) trimming a notch in a sketch, with the original drawn pointer of examples/demo/overlay.py and labels set in DejaVu Sans Bold, captured with examples/demo/doc_shots.py | MIT OR Apache-2.0 |
|
||||
| assets/locales/ca.json | carlymx | Catalan translation of the English catalog, contributed upstream | MIT OR Apache-2.0 |
|
||||
| assets/locales/pending/sketch-mirror-auto-line.json | SolidCraft contributors | Original Mirror preference label and translations | MIT OR Apache-2.0 |
|
||||
| docs/screenshots/7452/demo-01-extrude5-edge-frame.png | SamD98 | screenshot of the actual SolidCraft desktop UI showing the revolve axis pick on the Cat Post Topper repro design (docs/screenshots/7452/revolve-edge-frame.solidcraft), for #7452 | MIT OR Apache-2.0 |
|
||||
| docs/screenshots/7452/demo-04-preview-outer-l11.png | SamD98 | screenshot of the actual SolidCraft desktop UI showing the revolve axis pick on the Cat Post Topper repro design (docs/screenshots/7452/revolve-edge-frame.solidcraft), for #7452 | MIT OR Apache-2.0 |
|
||||
| docs/screenshots/7452/demo-05-preview-inner-l8.png | SamD98 | screenshot of the actual SolidCraft desktop UI showing the revolve axis pick on the Cat Post Topper repro design (docs/screenshots/7452/revolve-edge-frame.solidcraft), for #7452 | MIT OR Apache-2.0 |
|
||||
| docs/screenshots/7452/demo-06-result-outer-120.png | SamD98 | screenshot of the actual SolidCraft desktop UI showing the revolve axis pick on the Cat Post Topper repro design (docs/screenshots/7452/revolve-edge-frame.solidcraft), for #7452 | MIT OR Apache-2.0 |
|
||||
| docs/screenshots/7452/demo-07-preview-360.png | SamD98 | screenshot of the actual SolidCraft desktop UI showing the revolve axis pick on the Cat Post Topper repro design (docs/screenshots/7452/revolve-edge-frame.solidcraft), for #7452 | MIT OR Apache-2.0 |
|
||||
| docs/screenshots/7452/demo-08-cancelled.png | SamD98 | screenshot of the actual SolidCraft desktop UI showing the revolve axis pick on the Cat Post Topper repro design (docs/screenshots/7452/revolve-edge-frame.solidcraft), for #7452 | MIT OR Apache-2.0 |
|
||||
| docs/screenshots/7452/demo-13-colliding-id.png | SamD98 | screenshot of the actual SolidCraft desktop UI showing the revolve axis pick on the Cat Post Topper repro design (docs/screenshots/7452/revolve-edge-frame.solidcraft), for #7452 | MIT OR Apache-2.0 |
|
||||
| docs/screenshots/7452/demo-14-surface-l1.png | SamD98 | screenshot of the actual SolidCraft desktop UI showing the revolve axis pick on the Cat Post Topper repro design (docs/screenshots/7452/revolve-edge-frame.solidcraft), for #7452 | MIT OR Apache-2.0 |
|
||||
| docs/screenshots/7452/demo-15-surface-result.png | SamD98 | screenshot of the actual SolidCraft desktop UI showing the revolve axis pick on the Cat Post Topper repro design (docs/screenshots/7452/revolve-edge-frame.solidcraft), for #7452 | MIT OR Apache-2.0 |
|
||||
| docs/screenshots/7452/revolve-selected-edge.mp4 | SamD98 | screen recording of the actual SolidCraft desktop UI showing the revolve axis pick on the Cat Post Topper repro design (docs/screenshots/7452/revolve-edge-frame.solidcraft), for #7452 | MIT OR Apache-2.0 |
|
||||
| assets/locales/bg.json | Yasen-55 | Original translation | MIT OR Apache-2.0 |
|
||||
|
||||
## Code adapted from sibling projects
|
||||
|
||||
|
||||
@@ -828,7 +828,9 @@ mod web {
|
||||
self.files.panel.set(false);
|
||||
}
|
||||
"insert" => {
|
||||
self.app.insert_path(&path);
|
||||
if !solidcraft_ui_egui::mesh_units::ask(&mut self.app, &path, true) {
|
||||
self.app.insert_path(&path);
|
||||
}
|
||||
self.files.panel.set(false);
|
||||
}
|
||||
"download" => match vfs::read(&path, solidcraft_engine::io::MAX_DESIGN_BYTES) {
|
||||
|
||||
@@ -1044,6 +1044,7 @@
|
||||
"cmd.occurrence_move": "تحريك النسخة",
|
||||
"cmd.occurrence_properties": "الخصائص الفيزيائية للنسخة",
|
||||
"cmd.occurrence_reparent": "نقل إلى مكوّن",
|
||||
"cmd.panel.action": "تشغيل إجراء رأس اللوحة",
|
||||
"cmd.panel.activate": "تنشيط علامة تبويب اللوحة",
|
||||
"cmd.panel.close": "إغلاق اللوحة",
|
||||
"cmd.panel.collapse": "طي قسم اللوحة",
|
||||
@@ -2384,6 +2385,8 @@
|
||||
"prefs.edges": "الحواف والتظليل",
|
||||
"prefs.extend": "توسيع",
|
||||
"prefs.extra_navigation": "Ctrl مع السحب بالزر الأيسر في مساحة فارغة يدوّر العرض، واضغط مطولًا على Space للإزاحة.",
|
||||
"prefs.extrude_arrow_face_stops": "يتوقف سهم البثق عند الأوجه",
|
||||
"prefs.extrude_arrow_face_stops_note": "عند سحب سهم مسافة البثق يتوقف عند الأوجه المستوية الموازية للمقطع، مثل الجانب البعيد من كتلة يجري قطعها، ويحدد الوجه. عند الإيقاف: يتحرك السهم بخطوات مستديرة فقط.",
|
||||
"prefs.extrude_view_isometric": "التحويل إلى العرض المتساوي القياس عند فتح البثق",
|
||||
"prefs.extrude_view_return": "العودة إلى العرض السابق عند إغلاق البثق",
|
||||
"prefs.follows_os": "يتبع النظام",
|
||||
@@ -2546,6 +2549,22 @@
|
||||
"prefs.persistent_ribbon_pressed": "تمييز أوامر الشريط النشطة",
|
||||
"prefs.persistent_ribbon_pressed_help": "تمييز أوامر الشريط أثناء تفعيل تأثيراتها. أوقف هذا الخيار للاحتفاظ بالمظهر المحايد السابق ومساعدة الأوامر.",
|
||||
"prefs.perspective_fov": "مجال الرؤية",
|
||||
"prefs.picker.carousel": "عرض دوّار",
|
||||
"prefs.picker.change": "تغيير",
|
||||
"prefs.picker.clear": "مسح عوامل التصفية",
|
||||
"prefs.picker.day": "سمة النهار",
|
||||
"prefs.picker.empty": "لا توجد سمة تطابق عوامل التصفية هذه.",
|
||||
"prefs.picker.follow": "اتباع النظام",
|
||||
"prefs.picker.grid": "شبكة",
|
||||
"prefs.picker.high": "تباين عالٍ",
|
||||
"prefs.picker.high_note": "{source} · تباين عالٍ",
|
||||
"prefs.picker.hint": "تتغير تلقائيًا مع نظام التشغيل.",
|
||||
"prefs.picker.import": "استيراد ملف سمة…",
|
||||
"prefs.picker.imported": "مستوردة",
|
||||
"prefs.picker.night": "سمة الليل",
|
||||
"prefs.picker.one": "سمة واحدة",
|
||||
"prefs.picker.pick": "اختيار من الأسفل",
|
||||
"prefs.picker.standard": "قياسي",
|
||||
"prefs.placement": "الموضع",
|
||||
"prefs.plugins_enabled": "مفعّل",
|
||||
"prefs.plugins_installed": "المثبّتة",
|
||||
@@ -2665,6 +2684,7 @@
|
||||
"prefs.sketch_exit_view_note": "أين ينتقل العرض بعد إنهاء الرسم أو الإلغاء أو الضغط على Esc مرتين.",
|
||||
"prefs.sketch_face_activates_part": "الرسم على وجه جزء يجعل ذلك الجزء نشطًا",
|
||||
"prefs.sketch_face_activates_part_note": "الرسم الذي يبدأ على وجه جسم في مكوّن آخر ينشّط ذلك المكوّن أولًا، فينتمي الرسم إليه ويبقى مع ذلك الجزء في المستعرض. ويبقى الجزء نشطًا بعد ذلك. عند الإيقاف: ينتمي الرسم إلى المكوّن النشط.",
|
||||
"prefs.sketch_mirror_auto_line": "استخدام الخط الإنشائي المحدد مسبقًا كمحور للانعكاس",
|
||||
"prefs.sketch_open_look_at": "توجيه العرض نحو الرسم عند فتحه",
|
||||
"prefs.sketch_open_look_at_note": "عند الإيقاف: إنشاء الرسم أو تحريره يُبقي العرض كما هو. يوجّه «النظر إلى» العرض نحو الرسم عند الحاجة.",
|
||||
"prefs.sketch_recent_snap": "الالتقاط التلقائي إلى المراكز ونقاط المنتصف الأخيرة",
|
||||
@@ -5340,6 +5360,65 @@
|
||||
"ui.palette_sketch_options": "خيارات الرسم",
|
||||
"ui.pan": "إزاحة العرض",
|
||||
"ui.pan_zoom_orbit": "إزاحة، تكبير، تدوير",
|
||||
"ui.panel_fixture.apply": "تطبيق",
|
||||
"ui.panel_fixture.cancel": "إلغاء",
|
||||
"ui.panel_fixture.caption": "نموذج لوحة تجريبي",
|
||||
"ui.panel_fixture.draft": "مسودة محفوظة",
|
||||
"ui.panel_fixture.editor": "محرر تجريبي",
|
||||
"ui.panel_fixture.explanation": "يحتفظ هذا المحتوى التجريبي بمسودته عند إخفائه أو نقله.",
|
||||
"ui.panel_fixture.fill": "نموذج ملء الارتفاع",
|
||||
"ui.panel_fixture.finish": "إنهاء",
|
||||
"ui.panel_fixture.finished": "انتهت المعاملة التجريبية",
|
||||
"ui.panel_fixture.footer": "تترك الإجراءات التجريبية التصميم دون تغيير.",
|
||||
"ui.panel_fixture.guard": "رفض الإلغاء أثناء نشاط المعاملة",
|
||||
"ui.panel_fixture.inline": "نموذج بسطر واحد",
|
||||
"ui.panel_fixture.live": "المعاملة التجريبية نشطة",
|
||||
"ui.panel_fixture.log": "سجل تجريبي",
|
||||
"ui.panel_fixture.pin": "نموذج تجريبي مثبت",
|
||||
"ui.panel_fixture.title": "{title} · {id}",
|
||||
"ui.panel_fixture.updates": "تحديثات الخدمة: {count}",
|
||||
"ui.panel_host.attention": "يحتاج إلى انتباه",
|
||||
"ui.panel_host.bottom": "أسفل",
|
||||
"ui.panel_host.close": "إغلاق اللوحة",
|
||||
"ui.panel_host.collapse": "طي اللوحة",
|
||||
"ui.panel_host.expand": "توسيع اللوحة",
|
||||
"ui.panel_host.floating": "عائم",
|
||||
"ui.panel_host.focus": "تركيز اللوحة",
|
||||
"ui.panel_host.focus_target": "التركيز على {title}",
|
||||
"ui.panel_host.header": "رأس اللوحة",
|
||||
"ui.panel_host.join": "ضم علامات التبويب",
|
||||
"ui.panel_host.join_target": "ضم علامات التبويب مع {title}",
|
||||
"ui.panel_host.left": "يسار",
|
||||
"ui.panel_host.menu": "إجراءات اللوحة",
|
||||
"ui.panel_host.move": "نقل إلى",
|
||||
"ui.panel_host.overflow": "المزيد من اللوحات",
|
||||
"ui.panel_host.popout": "فتح في نافذة",
|
||||
"ui.panel_host.resize": "تغيير حجم اللوحة",
|
||||
"ui.panel_host.right": "يمين",
|
||||
"ui.panel_host.rule.availability": "هذه اللوحة غير متاحة.",
|
||||
"ui.panel_host.rule.bounds": "لا تتسع اللوحات ضمن حدود أحجامها.",
|
||||
"ui.panel_host.rule.capability": "لا يدعم هذا المضيف هذا الإجراء.",
|
||||
"ui.panel_host.rule.collection_limit": "بلغ تخطيط اللوحات حده الأقصى.",
|
||||
"ui.panel_host.rule.duplicate_id": "هوية هذه اللوحة مستخدمة بالفعل.",
|
||||
"ui.panel_host.rule.exactly_once": "يجب أن تظهر كل لوحة مرة واحدة.",
|
||||
"ui.panel_host.rule.feature_disabled": "هذا الإجراء معطل لهذه اللوحة.",
|
||||
"ui.panel_host.rule.id": "هوية اللوحة غير صالحة.",
|
||||
"ui.panel_host.rule.incompatible_tabs": "لا يمكن لهذه اللوحات مشاركة مجموعة علامات تبويب.",
|
||||
"ui.panel_host.rule.lifecycle": "تعذر على اللوحة إكمال هذا الإجراء.",
|
||||
"ui.panel_host.rule.missing_target": "لم يعد هدف اللوحة هذا متاحا.",
|
||||
"ui.panel_host.rule.no_space": "لا توجد مساحة كافية لتخطيط اللوحات هذا.",
|
||||
"ui.panel_host.rule.pin_conflict": "هناك لوحة أخرى مثبتة بالفعل على هذه الحافة.",
|
||||
"ui.panel_host.rule.pin_order": "يجب أن تبقى اللوحة المثبتة أولا على حافتها.",
|
||||
"ui.panel_host.rule.placement": "لا يمكن نقل هذه اللوحة إلى ذلك الموضع.",
|
||||
"ui.panel_host.rule.revision": "تغير التخطيط. حاول الإجراء مجددا.",
|
||||
"ui.panel_host.rule.schema": "طلب اللوحة غير صالح.",
|
||||
"ui.panel_host.rule.version": "إصدار تخطيط اللوحات هذا غير مدعوم.",
|
||||
"ui.panel_host.sash": "تغيير حجم اللوحات المتجاورة",
|
||||
"ui.panel_host.scroll_horizontal": "تمرير أعمدة اللوحات",
|
||||
"ui.panel_host.scroll_vertical": "تمرير مجموعات اللوحات",
|
||||
"ui.panel_host.surface": "لوحة",
|
||||
"ui.panel_host.tab": "علامة تبويب لوحة",
|
||||
"ui.panel_host.tabs": "كل علامات التبويب",
|
||||
"ui.parallel": "متوازي",
|
||||
"ui.parameters": "المعاملات",
|
||||
"ui.part_size_needs_a_part": "حدد قطعة قياسية مُدرجة (برغي أو صامولة أو حلقة مسطحة أو مسمار) لتغيير مقاسها. لتكبير جسم أو تصغيره، استخدم «تحجيم».",
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1035,6 +1035,7 @@
|
||||
"cmd.occurrence_move": "Instanz verschieben",
|
||||
"cmd.occurrence_properties": "Physikalische Eigenschaften der Instanz",
|
||||
"cmd.occurrence_reparent": "In andere Komponente verschieben",
|
||||
"cmd.panel.action": "Panelaktion ausführen",
|
||||
"cmd.panel.activate": "Panel-Registerkarte aktivieren",
|
||||
"cmd.panel.close": "Panel schließen",
|
||||
"cmd.panel.collapse": "Panel-Bereich einklappen",
|
||||
@@ -2353,6 +2354,8 @@
|
||||
"prefs.edges": "Kanten und Schattierung",
|
||||
"prefs.extend": "Erweitern",
|
||||
"prefs.extra_navigation": "Mit Strg und gedrückter linker Maustaste auf einer freien Fläche drehen. Leertaste gedrückt halten, um die Ansicht zu verschieben.",
|
||||
"prefs.extrude_arrow_face_stops": "Extrusionspfeil hält an Flächen",
|
||||
"prefs.extrude_arrow_face_stops_note": "Beim Ziehen des Abstandspfeils von Extrusion hält er an ebenen Flächen parallel zum Profil, etwa an der Rückseite eines Blocks, in den geschnitten wird, und hebt die Fläche hervor. Aus: Der Pfeil bewegt sich nur in runden Schritten.",
|
||||
"prefs.extrude_view_isometric": "Beim Öffnen von Extrudieren isometrisch ausrichten",
|
||||
"prefs.extrude_view_return": "Beim Schließen von Extrudieren zur vorigen Ansicht zurück",
|
||||
"prefs.follows_os": "Wie im Betriebssystem",
|
||||
@@ -2623,6 +2626,7 @@
|
||||
"prefs.sketch_exit_view_note": "Legt fest, zu welcher Ansicht nach „Skizze beenden“, „Abbrechen“ oder zweimaligem Drücken der Esc-Taste gewechselt wird.",
|
||||
"prefs.sketch_face_activates_part": "Skizzieren auf der Fläche eines Teils aktiviert dieses Teil",
|
||||
"prefs.sketch_face_activates_part_note": "Eine Skizze, die auf einer Fläche am Körper einer anderen Komponente begonnen wird, aktiviert zuerst diese Komponente, sodass die Skizze zu ihr gehört und im Browser bei diesem Teil bleibt. Das Teil bleibt danach aktiv. Aus: Die Skizze gehört zur aktiven Komponente.",
|
||||
"prefs.sketch_mirror_auto_line": "Vorausgewählte Konstruktionslinie zum Spiegeln verwenden",
|
||||
"prefs.sketch_open_look_at": "Beim Öffnen einer Skizze auf sie ausrichten",
|
||||
"prefs.sketch_open_look_at_note": "Aus: Beim Erstellen oder Bearbeiten einer Skizze bleibt die Ansicht, wie sie ist. „Ansehen“ richtet die Ansicht bei Bedarf auf die Skizze aus.",
|
||||
"prefs.sketch_recent_snap": "Automatisch an zuletzt verwendete Mittelpunkte fangen",
|
||||
@@ -5256,6 +5260,65 @@
|
||||
"ui.palette_sketch_options": "Skizzenoptionen",
|
||||
"ui.pan": "Verschieben",
|
||||
"ui.pan_zoom_orbit": "Verschieben, zoomen, umkreisen",
|
||||
"ui.panel_fixture.apply": "Anwenden",
|
||||
"ui.panel_fixture.cancel": "Abbrechen",
|
||||
"ui.panel_fixture.caption": "Synthetisches Panelmuster",
|
||||
"ui.panel_fixture.draft": "Beibehaltener Entwurf",
|
||||
"ui.panel_fixture.editor": "Mustereditor",
|
||||
"ui.panel_fixture.explanation": "Dieser synthetische Inhalt behält seinen Entwurf beim Ausblenden oder Verschieben.",
|
||||
"ui.panel_fixture.fill": "Füllendes Muster",
|
||||
"ui.panel_fixture.finish": "Abschließen",
|
||||
"ui.panel_fixture.finished": "Synthetische Transaktion beendet",
|
||||
"ui.panel_fixture.footer": "Musteraktionen lassen den Entwurf unverändert.",
|
||||
"ui.panel_fixture.guard": "Abbruch bei laufender Transaktion verweigern",
|
||||
"ui.panel_fixture.inline": "Einzeiliges Muster",
|
||||
"ui.panel_fixture.live": "Synthetische Transaktion läuft",
|
||||
"ui.panel_fixture.log": "Musterprotokoll",
|
||||
"ui.panel_fixture.pin": "Angeheftetes Muster",
|
||||
"ui.panel_fixture.title": "{title} · {id}",
|
||||
"ui.panel_fixture.updates": "Dienstaktualisierungen: {count}",
|
||||
"ui.panel_host.attention": "Aufmerksamkeit erforderlich",
|
||||
"ui.panel_host.bottom": "Unten",
|
||||
"ui.panel_host.close": "Panel schließen",
|
||||
"ui.panel_host.collapse": "Panel einklappen",
|
||||
"ui.panel_host.expand": "Panel ausklappen",
|
||||
"ui.panel_host.floating": "Schwebend",
|
||||
"ui.panel_host.focus": "Panel fokussieren",
|
||||
"ui.panel_host.focus_target": "{title} fokussieren",
|
||||
"ui.panel_host.header": "Panelkopf",
|
||||
"ui.panel_host.join": "Tabs verbinden",
|
||||
"ui.panel_host.join_target": "Tabs mit {title} verbinden",
|
||||
"ui.panel_host.left": "Links",
|
||||
"ui.panel_host.menu": "Panelaktionen",
|
||||
"ui.panel_host.move": "Verschieben nach",
|
||||
"ui.panel_host.overflow": "Weitere Panels",
|
||||
"ui.panel_host.popout": "In einem Fenster öffnen",
|
||||
"ui.panel_host.resize": "Panelgröße ändern",
|
||||
"ui.panel_host.right": "Rechts",
|
||||
"ui.panel_host.rule.availability": "Dieses Panel ist nicht verfügbar.",
|
||||
"ui.panel_host.rule.bounds": "Die Panels passen nicht in ihre Größenbegrenzungen.",
|
||||
"ui.panel_host.rule.capability": "Dieser Host unterstützt diese Aktion nicht.",
|
||||
"ui.panel_host.rule.collection_limit": "Das Panellayout hat seine Grenze erreicht.",
|
||||
"ui.panel_host.rule.duplicate_id": "Diese Panelkennung wird bereits verwendet.",
|
||||
"ui.panel_host.rule.exactly_once": "Jedes Panel muss einmal erscheinen.",
|
||||
"ui.panel_host.rule.feature_disabled": "Diese Aktion ist für dieses Panel deaktiviert.",
|
||||
"ui.panel_host.rule.id": "Die Panelkennung ist ungültig.",
|
||||
"ui.panel_host.rule.incompatible_tabs": "Diese Panels können keine Tabgruppe teilen.",
|
||||
"ui.panel_host.rule.lifecycle": "Das Panel konnte diese Aktion nicht abschließen.",
|
||||
"ui.panel_host.rule.missing_target": "Dieses Panelziel ist nicht mehr verfügbar.",
|
||||
"ui.panel_host.rule.no_space": "Für dieses Panellayout ist kein Platz.",
|
||||
"ui.panel_host.rule.pin_conflict": "An dieser Kante ist bereits ein anderes Panel angeheftet.",
|
||||
"ui.panel_host.rule.pin_order": "Ein angeheftetes Panel muss an seiner Kante zuerst bleiben.",
|
||||
"ui.panel_host.rule.placement": "Dieses Panel kann nicht an diese Position verschoben werden.",
|
||||
"ui.panel_host.rule.revision": "Das Layout wurde geändert. Versuchen Sie die Aktion erneut.",
|
||||
"ui.panel_host.rule.schema": "Die Panelanfrage ist ungültig.",
|
||||
"ui.panel_host.rule.version": "Diese Panellayoutversion wird nicht unterstützt.",
|
||||
"ui.panel_host.sash": "Benachbarte Panels skalieren",
|
||||
"ui.panel_host.scroll_horizontal": "Panelspalten scrollen",
|
||||
"ui.panel_host.scroll_vertical": "Panelstapel scrollen",
|
||||
"ui.panel_host.surface": "Panel",
|
||||
"ui.panel_host.tab": "Paneltab",
|
||||
"ui.panel_host.tabs": "Alle Tabs",
|
||||
"ui.parallel": "Parallel",
|
||||
"ui.parameters": "Parameter",
|
||||
"ui.part_size_needs_a_part": "Wählen Sie ein eingefügtes Standardbauteil (Schraube, Mutter, Scheibe oder Stift) aus, um seine Größe zu ändern. Einen Körper vergrößern oder verkleinern Sie mit Skalieren.",
|
||||
|
||||
@@ -1044,6 +1044,7 @@
|
||||
"cmd.occurrence_move": "Move Occurrence",
|
||||
"cmd.occurrence_properties": "Occurrence Physical Properties",
|
||||
"cmd.occurrence_reparent": "Move to Component",
|
||||
"cmd.panel.action": "Run Panel Header Action",
|
||||
"cmd.panel.activate": "Activate Panel Tab",
|
||||
"cmd.panel.close": "Close Panel",
|
||||
"cmd.panel.collapse": "Collapse Panel Section",
|
||||
@@ -2384,6 +2385,8 @@
|
||||
"prefs.edges": "Edges and shading",
|
||||
"prefs.extend": "Extend",
|
||||
"prefs.extra_navigation": "Ctrl+left drag on empty space orbits; hold Space to pan.",
|
||||
"prefs.extrude_arrow_face_stops": "Extrude arrow stops at faces",
|
||||
"prefs.extrude_arrow_face_stops_note": "Dragging Extrude's distance arrow stops at flat faces parallel to the profile, such as the far side of a block being cut, and outlines the face. Off: the arrow moves in round steps only.",
|
||||
"prefs.extrude_view_isometric": "Turn the view to isometric when Extrude opens",
|
||||
"prefs.extrude_view_return": "Go back to the earlier view when Extrude closes",
|
||||
"prefs.follows_os": "Follows the OS",
|
||||
@@ -2546,6 +2549,22 @@
|
||||
"prefs.persistent_ribbon_pressed": "Highlight active ribbon commands",
|
||||
"prefs.persistent_ribbon_pressed_help": "Highlight ribbon commands while their effects are on. Turn off to keep the previous neutral appearance and command help.",
|
||||
"prefs.perspective_fov": "Field of view",
|
||||
"prefs.picker.carousel": "Carousel",
|
||||
"prefs.picker.change": "Change",
|
||||
"prefs.picker.clear": "Clear filters",
|
||||
"prefs.picker.day": "Day theme",
|
||||
"prefs.picker.empty": "No theme matches these filters.",
|
||||
"prefs.picker.follow": "Follow system",
|
||||
"prefs.picker.grid": "Grid",
|
||||
"prefs.picker.high": "High contrast",
|
||||
"prefs.picker.high_note": "{source} · High contrast",
|
||||
"prefs.picker.hint": "Switches with your operating system.",
|
||||
"prefs.picker.import": "Import theme file…",
|
||||
"prefs.picker.imported": "Imported",
|
||||
"prefs.picker.night": "Night theme",
|
||||
"prefs.picker.one": "One theme",
|
||||
"prefs.picker.pick": "Pick from below",
|
||||
"prefs.picker.standard": "Standard",
|
||||
"prefs.placement": "Placement",
|
||||
"prefs.plugins_enabled": "Enabled",
|
||||
"prefs.plugins_installed": "Installed",
|
||||
@@ -2665,6 +2684,7 @@
|
||||
"prefs.sketch_exit_view_note": "Where the view goes after Finish Sketch, Cancel or a double Esc.",
|
||||
"prefs.sketch_face_activates_part": "Sketching on a part's face makes that part active",
|
||||
"prefs.sketch_face_activates_part_note": "A sketch started on a face of another component's body activates that component first, so the sketch belongs to it and stays with that part in the browser. The part stays active afterwards. Off: the sketch belongs to the active component.",
|
||||
"prefs.sketch_mirror_auto_line": "Use the preselected construction line for Mirror",
|
||||
"prefs.sketch_open_look_at": "Turn to face a sketch when it opens",
|
||||
"prefs.sketch_open_look_at_note": "Off: creating or editing a sketch leaves the view as it is. Look At faces the sketch when you want it.",
|
||||
"prefs.sketch_recent_snap": "Auto snap to recent centers and midpoints",
|
||||
@@ -5340,6 +5360,65 @@
|
||||
"ui.palette_sketch_options": "Sketch options",
|
||||
"ui.pan": "Pan",
|
||||
"ui.pan_zoom_orbit": "Pan, zoom, orbit",
|
||||
"ui.panel_fixture.apply": "Apply",
|
||||
"ui.panel_fixture.cancel": "Cancel",
|
||||
"ui.panel_fixture.caption": "Synthetic panel specimen",
|
||||
"ui.panel_fixture.draft": "Retained draft",
|
||||
"ui.panel_fixture.editor": "Specimen editor",
|
||||
"ui.panel_fixture.explanation": "This synthetic content retains its draft while hidden or moved.",
|
||||
"ui.panel_fixture.fill": "Fill specimen",
|
||||
"ui.panel_fixture.finish": "Finish",
|
||||
"ui.panel_fixture.finished": "Synthetic transaction ended",
|
||||
"ui.panel_fixture.footer": "Synthetic actions leave the design unchanged.",
|
||||
"ui.panel_fixture.guard": "Refuse cancellation while the transaction is live",
|
||||
"ui.panel_fixture.inline": "Inline specimen",
|
||||
"ui.panel_fixture.live": "Synthetic transaction live",
|
||||
"ui.panel_fixture.log": "Specimen log",
|
||||
"ui.panel_fixture.pin": "Pinned specimen",
|
||||
"ui.panel_fixture.title": "{title} · {id}",
|
||||
"ui.panel_fixture.updates": "Service updates: {count}",
|
||||
"ui.panel_host.attention": "Needs attention",
|
||||
"ui.panel_host.bottom": "Bottom",
|
||||
"ui.panel_host.close": "Close panel",
|
||||
"ui.panel_host.collapse": "Collapse panel",
|
||||
"ui.panel_host.expand": "Expand panel",
|
||||
"ui.panel_host.floating": "Floating",
|
||||
"ui.panel_host.focus": "Focus panel",
|
||||
"ui.panel_host.focus_target": "Focus {title}",
|
||||
"ui.panel_host.header": "Panel header",
|
||||
"ui.panel_host.join": "Join tabs",
|
||||
"ui.panel_host.join_target": "Join tabs with {title}",
|
||||
"ui.panel_host.left": "Left",
|
||||
"ui.panel_host.menu": "Panel actions",
|
||||
"ui.panel_host.move": "Move to",
|
||||
"ui.panel_host.overflow": "More panels",
|
||||
"ui.panel_host.popout": "Open in a window",
|
||||
"ui.panel_host.resize": "Resize panel",
|
||||
"ui.panel_host.right": "Right",
|
||||
"ui.panel_host.rule.availability": "This panel is unavailable.",
|
||||
"ui.panel_host.rule.bounds": "The panels do not fit within their size limits.",
|
||||
"ui.panel_host.rule.capability": "This host does not support that action.",
|
||||
"ui.panel_host.rule.collection_limit": "The panel layout has reached its limit.",
|
||||
"ui.panel_host.rule.duplicate_id": "This panel identity is already in use.",
|
||||
"ui.panel_host.rule.exactly_once": "Each panel must appear once.",
|
||||
"ui.panel_host.rule.feature_disabled": "This action is disabled for this panel.",
|
||||
"ui.panel_host.rule.id": "The panel identity is invalid.",
|
||||
"ui.panel_host.rule.incompatible_tabs": "These panels cannot share a tab group.",
|
||||
"ui.panel_host.rule.lifecycle": "The panel could not complete this action.",
|
||||
"ui.panel_host.rule.missing_target": "This panel target is no longer available.",
|
||||
"ui.panel_host.rule.no_space": "There is no space for this panel layout.",
|
||||
"ui.panel_host.rule.pin_conflict": "Another panel is already pinned to this edge.",
|
||||
"ui.panel_host.rule.pin_order": "A pinned panel must remain first on its edge.",
|
||||
"ui.panel_host.rule.placement": "This panel cannot move to that location.",
|
||||
"ui.panel_host.rule.revision": "The layout changed. Try the action again.",
|
||||
"ui.panel_host.rule.schema": "The panel request is invalid.",
|
||||
"ui.panel_host.rule.version": "This panel layout version is unsupported.",
|
||||
"ui.panel_host.sash": "Resize neighbouring panels",
|
||||
"ui.panel_host.scroll_horizontal": "Scroll panel columns",
|
||||
"ui.panel_host.scroll_vertical": "Scroll panel stacks",
|
||||
"ui.panel_host.surface": "Panel",
|
||||
"ui.panel_host.tab": "Panel tab",
|
||||
"ui.panel_host.tabs": "All tabs",
|
||||
"ui.parallel": "Parallel",
|
||||
"ui.parameters": "Parameters",
|
||||
"ui.part_size_needs_a_part": "Select an inserted standard part (a screw, nut, washer or pin) to change its size. To make a body larger or smaller, use Scale.",
|
||||
|
||||
@@ -2349,6 +2349,8 @@
|
||||
"prefs.edges": "Aristas y sombreado",
|
||||
"prefs.extend": "Extensiones",
|
||||
"prefs.extra_navigation": "Ctrl + arrastrar con el botón izquierdo sobre un espacio vacío orbita; mantén Espacio para desplazar.",
|
||||
"prefs.extrude_arrow_face_stops": "La flecha de Extruir se detiene en las caras",
|
||||
"prefs.extrude_arrow_face_stops_note": "Al arrastrar la flecha de distancia de Extruir, se detiene en las caras planas paralelas al perfil, como el lado opuesto de un bloque que se corta, y resalta la cara. Desactivado: la flecha solo avanza en pasos redondos.",
|
||||
"prefs.extrude_view_isometric": "Girar la vista a isométrica al abrir Extrusión",
|
||||
"prefs.extrude_view_return": "Volver a la vista anterior al cerrar Extrusión",
|
||||
"prefs.follows_os": "Sigue al sistema operativo",
|
||||
|
||||
@@ -2201,6 +2201,8 @@
|
||||
"prefs.edges": "Arêtes et ombrage",
|
||||
"prefs.extend": "Étendre",
|
||||
"prefs.extra_navigation": "Ctrl+glisser gauche dans le vide fait orbiter ; maintenir Espace pour un panoramique.",
|
||||
"prefs.extrude_arrow_face_stops": "La flèche d'extrusion s'arrête aux faces",
|
||||
"prefs.extrude_arrow_face_stops_note": "En faisant glisser la flèche de distance d'Extrusion, elle s'arrête aux faces planes parallèles au profil, comme l'autre côté d'un bloc qu'on découpe, et souligne la face. Désactivé : la flèche avance seulement par pas ronds.",
|
||||
"prefs.extrude_view_isometric": "Passer la vue en isométrique à l'ouverture de l'extrusion",
|
||||
"prefs.extrude_view_return": "Revenir à la vue précédente à la fermeture de l'extrusion",
|
||||
"prefs.follows_os": "Suit le système",
|
||||
|
||||
@@ -1044,6 +1044,7 @@
|
||||
"cmd.occurrence_move": "הזזת מופע",
|
||||
"cmd.occurrence_properties": "תכונות פיזיקליות של מופע",
|
||||
"cmd.occurrence_reparent": "העברה לרכיב",
|
||||
"cmd.panel.action": "הפעלת פעולה בכותרת הלוח",
|
||||
"cmd.panel.activate": "הפעלת לשונית חלונית",
|
||||
"cmd.panel.close": "סגירת חלונית",
|
||||
"cmd.panel.collapse": "כיווץ מקטע חלונית",
|
||||
@@ -2384,6 +2385,8 @@
|
||||
"prefs.edges": "מקצועות והצללה",
|
||||
"prefs.extend": "הרחבה",
|
||||
"prefs.extra_navigation": "Ctrl עם גרירה שמאלית במקום ריק מסובב את המבט; החזקת Space מזיזה אותו.",
|
||||
"prefs.extrude_arrow_face_stops": "חץ השליפה נעצר בפאות",
|
||||
"prefs.extrude_arrow_face_stops_note": "גרירת חץ המרחק של השליפה נעצרת בפאות שטוחות המקבילות לפרופיל, כמו הצד הרחוק של גוש שנחתך, ומדגישה את קו המתאר של הפאה. כבוי: החץ זז בצעדים עגולים בלבד.",
|
||||
"prefs.extrude_view_isometric": "סיבוב התצוגה לאיזומטרית בפתיחת שליפה",
|
||||
"prefs.extrude_view_return": "חזרה לתצוגה הקודמת בסגירת שליפה",
|
||||
"prefs.follows_os": "לפי מערכת ההפעלה",
|
||||
@@ -2546,6 +2549,22 @@
|
||||
"prefs.persistent_ribbon_pressed": "הדגשת פקודות פעילות ברצועת הכלים",
|
||||
"prefs.persistent_ribbon_pressed_help": "הדגשת פקודות ברצועת הכלים כל עוד ההשפעות שלהן פעילות. כבו אפשרות זו כדי לשמור על המראה הניטרלי הקודם ועל עזרת הפקודות.",
|
||||
"prefs.perspective_fov": "שדה ראייה",
|
||||
"prefs.picker.carousel": "קרוסלה",
|
||||
"prefs.picker.change": "שינוי",
|
||||
"prefs.picker.clear": "ניקוי מסננים",
|
||||
"prefs.picker.day": "ערכת נושא ליום",
|
||||
"prefs.picker.empty": "אין ערכת נושא שתואמת למסננים האלה.",
|
||||
"prefs.picker.follow": "לפי המערכת",
|
||||
"prefs.picker.grid": "רשת",
|
||||
"prefs.picker.high": "ניגודיות גבוהה",
|
||||
"prefs.picker.high_note": "{source} · ניגודיות גבוהה",
|
||||
"prefs.picker.hint": "מתחלפת בהתאם למערכת ההפעלה.",
|
||||
"prefs.picker.import": "ייבוא קובץ ערכת נושא…",
|
||||
"prefs.picker.imported": "מיובאות",
|
||||
"prefs.picker.night": "ערכת נושא ללילה",
|
||||
"prefs.picker.one": "ערכת נושא אחת",
|
||||
"prefs.picker.pick": "בחירה מהרשימה למטה",
|
||||
"prefs.picker.standard": "רגילה",
|
||||
"prefs.placement": "מיקום",
|
||||
"prefs.plugins_enabled": "מופעל",
|
||||
"prefs.plugins_installed": "מותקנים",
|
||||
@@ -2665,6 +2684,7 @@
|
||||
"prefs.sketch_exit_view_note": "לאן התצוגה עוברת אחרי סיום סקיצה, ביטול או Esc כפול.",
|
||||
"prefs.sketch_face_activates_part": "שרטוט על פאה של חלק הופך את החלק לפעיל",
|
||||
"prefs.sketch_face_activates_part_note": "שרטוט שמתחיל על פאה של גוף ברכיב אחר מפעיל קודם את הרכיב הזה, כך שהשרטוט שייך לו ונשאר עם החלק בסייר. החלק נשאר פעיל אחר כך. כבוי: השרטוט שייך לרכיב הפעיל.",
|
||||
"prefs.sketch_mirror_auto_line": "שימוש בישר העזר שנבחר מראש כציר שיקוף",
|
||||
"prefs.sketch_open_look_at": "הפניית התצוגה אל הסקיצה בפתיחתה",
|
||||
"prefs.sketch_open_look_at_note": "כבוי: יצירה או עריכה של סקיצה משאירות את התצוגה כפי שהיא. «מבט אל» מפנה את התצוגה אל הסקיצה כשרוצים.",
|
||||
"prefs.sketch_recent_snap": "הצמדה אוטומטית למרכזים ולנקודות אמצע אחרונים",
|
||||
@@ -5340,6 +5360,65 @@
|
||||
"ui.palette_sketch_options": "אפשרויות סקיצה",
|
||||
"ui.pan": "הזזת מבט",
|
||||
"ui.pan_zoom_orbit": "הזזה, זום, סיבוב מבט",
|
||||
"ui.panel_fixture.apply": "החלה",
|
||||
"ui.panel_fixture.cancel": "ביטול",
|
||||
"ui.panel_fixture.caption": "דוגמת לוח סינתטית",
|
||||
"ui.panel_fixture.draft": "טיוטה שמורה",
|
||||
"ui.panel_fixture.editor": "עורך לדוגמה",
|
||||
"ui.panel_fixture.explanation": "תוכן סינתטי זה שומר את הטיוטה כשהוא מוסתר או מועבר.",
|
||||
"ui.panel_fixture.fill": "דוגמה למילוי הגובה",
|
||||
"ui.panel_fixture.finish": "סיום",
|
||||
"ui.panel_fixture.finished": "הפעולה הסינתטית הסתיימה",
|
||||
"ui.panel_fixture.footer": "פעולות הדוגמה משאירות את התכנון ללא שינוי.",
|
||||
"ui.panel_fixture.guard": "סירוב לביטול כל עוד הפעולה פעילה",
|
||||
"ui.panel_fixture.inline": "דוגמה בשורה אחת",
|
||||
"ui.panel_fixture.live": "הפעולה הסינתטית פעילה",
|
||||
"ui.panel_fixture.log": "יומן לדוגמה",
|
||||
"ui.panel_fixture.pin": "דוגמה מוצמדת",
|
||||
"ui.panel_fixture.title": "{title} · {id}",
|
||||
"ui.panel_fixture.updates": "עדכוני שירות: {count}",
|
||||
"ui.panel_host.attention": "נדרשת תשומת לב",
|
||||
"ui.panel_host.bottom": "למטה",
|
||||
"ui.panel_host.close": "סגירת לוח",
|
||||
"ui.panel_host.collapse": "כיווץ לוח",
|
||||
"ui.panel_host.expand": "הרחבת הלוח",
|
||||
"ui.panel_host.floating": "צף",
|
||||
"ui.panel_host.focus": "מיקוד בלוח",
|
||||
"ui.panel_host.focus_target": "מיקוד ב־{title}",
|
||||
"ui.panel_host.header": "כותרת לוח",
|
||||
"ui.panel_host.join": "צירוף לשוניות",
|
||||
"ui.panel_host.join_target": "צירוף לשוניות עם {title}",
|
||||
"ui.panel_host.left": "שמאל",
|
||||
"ui.panel_host.menu": "פעולות לוח",
|
||||
"ui.panel_host.move": "העברה אל",
|
||||
"ui.panel_host.overflow": "לוחות נוספים",
|
||||
"ui.panel_host.popout": "פתיחה בחלון",
|
||||
"ui.panel_host.resize": "שינוי גודל לוח",
|
||||
"ui.panel_host.right": "ימין",
|
||||
"ui.panel_host.rule.availability": "לוח זה אינו זמין.",
|
||||
"ui.panel_host.rule.bounds": "הלוחות אינם מתאימים למגבלות הגודל שלהם.",
|
||||
"ui.panel_host.rule.capability": "מארח זה אינו תומך בפעולה זו.",
|
||||
"ui.panel_host.rule.collection_limit": "פריסת הלוחות הגיעה למגבלה.",
|
||||
"ui.panel_host.rule.duplicate_id": "מזהה לוח זה כבר בשימוש.",
|
||||
"ui.panel_host.rule.exactly_once": "כל לוח חייב להופיע פעם אחת.",
|
||||
"ui.panel_host.rule.feature_disabled": "פעולה זו מושבתת בלוח זה.",
|
||||
"ui.panel_host.rule.id": "מזהה הלוח אינו תקין.",
|
||||
"ui.panel_host.rule.incompatible_tabs": "לוחות אלה אינם יכולים להשתייך לאותה קבוצת לשוניות.",
|
||||
"ui.panel_host.rule.lifecycle": "הלוח לא הצליח להשלים פעולה זו.",
|
||||
"ui.panel_host.rule.missing_target": "יעד לוח זה אינו זמין עוד.",
|
||||
"ui.panel_host.rule.no_space": "אין מספיק מקום לפריסת הלוחות הזו.",
|
||||
"ui.panel_host.rule.pin_conflict": "לוח אחר כבר מוצמד לקצה זה.",
|
||||
"ui.panel_host.rule.pin_order": "לוח מוצמד חייב להישאר ראשון בקצה שלו.",
|
||||
"ui.panel_host.rule.placement": "לא ניתן להעביר לוח זה למיקום זה.",
|
||||
"ui.panel_host.rule.revision": "הפריסה השתנתה. יש לנסות שוב.",
|
||||
"ui.panel_host.rule.schema": "בקשת הלוח אינה תקינה.",
|
||||
"ui.panel_host.rule.version": "גרסת פריסת לוחות זו אינה נתמכת.",
|
||||
"ui.panel_host.sash": "שינוי גודל לוחות סמוכים",
|
||||
"ui.panel_host.scroll_horizontal": "גלילת עמודות הלוחות",
|
||||
"ui.panel_host.scroll_vertical": "גלילת ערימות הלוחות",
|
||||
"ui.panel_host.surface": "לוח",
|
||||
"ui.panel_host.tab": "לשונית לוח",
|
||||
"ui.panel_host.tabs": "כל הלשוניות",
|
||||
"ui.parallel": "מקביל",
|
||||
"ui.parameters": "פרמטרים",
|
||||
"ui.part_size_needs_a_part": "בחרו חלק סטנדרטי שהוכנס (בורג, אום, דסקית או פין) כדי לשנות את גודלו. כדי להגדיל או להקטין גוף, השתמשו בשינוי קנה מידה.",
|
||||
|
||||
@@ -1044,6 +1044,7 @@
|
||||
"cmd.occurrence_move": "オカレンスを移動",
|
||||
"cmd.occurrence_properties": "オカレンスの物理的プロパティ",
|
||||
"cmd.occurrence_reparent": "コンポーネントへ移動",
|
||||
"cmd.panel.action": "パネル操作を実行",
|
||||
"cmd.panel.activate": "パネルのタブをアクティブ化",
|
||||
"cmd.panel.close": "パネルを閉じる",
|
||||
"cmd.panel.collapse": "パネルのセクションを折りたたむ",
|
||||
@@ -2384,6 +2385,8 @@
|
||||
"prefs.edges": "エッジと陰影",
|
||||
"prefs.extend": "拡張",
|
||||
"prefs.extra_navigation": "何もない場所でCtrl+左ドラッグすると回転し、Spaceを押しながらドラッグすると移動します。",
|
||||
"prefs.extrude_arrow_face_stops": "押し出し矢印を面で止める",
|
||||
"prefs.extrude_arrow_face_stops_note": "押し出しの距離矢印をドラッグすると、プロファイルに平行な平らな面(カットするブロックの反対側など)で止まり、その面の輪郭を表示します。オフ: 矢印はきりのよい刻みでのみ動きます。",
|
||||
"prefs.extrude_view_isometric": "押し出しを開いたときに等角ビューにする",
|
||||
"prefs.extrude_view_return": "押し出しを閉じたときに元のビューに戻す",
|
||||
"prefs.follows_os": "OS の設定に従う",
|
||||
@@ -2546,6 +2549,22 @@
|
||||
"prefs.persistent_ribbon_pressed": "有効なリボンコマンドを強調表示",
|
||||
"prefs.persistent_ribbon_pressed_help": "効果が有効な間、リボンのコマンドを強調表示します。無効にすると、従来の中立的な表示とコマンドのヘルプを保持します。",
|
||||
"prefs.perspective_fov": "画角",
|
||||
"prefs.picker.carousel": "カルーセル",
|
||||
"prefs.picker.change": "変更",
|
||||
"prefs.picker.clear": "フィルターをクリア",
|
||||
"prefs.picker.day": "日中のテーマ",
|
||||
"prefs.picker.empty": "このフィルターに一致するテーマはありません。",
|
||||
"prefs.picker.follow": "システムに合わせる",
|
||||
"prefs.picker.grid": "グリッド",
|
||||
"prefs.picker.high": "ハイコントラスト",
|
||||
"prefs.picker.high_note": "{source} · ハイコントラスト",
|
||||
"prefs.picker.hint": "OSの設定に合わせて切り替わります。",
|
||||
"prefs.picker.import": "テーマファイルをインポート…",
|
||||
"prefs.picker.imported": "インポート済み",
|
||||
"prefs.picker.night": "夜間のテーマ",
|
||||
"prefs.picker.one": "単一のテーマ",
|
||||
"prefs.picker.pick": "下から選択",
|
||||
"prefs.picker.standard": "標準",
|
||||
"prefs.placement": "配置",
|
||||
"prefs.plugins_enabled": "有効",
|
||||
"prefs.plugins_installed": "インストール済み",
|
||||
@@ -2665,6 +2684,7 @@
|
||||
"prefs.sketch_exit_view_note": "「スケッチを終了」、キャンセル、Esc の 2 回押しの後にビューが移る先です。",
|
||||
"prefs.sketch_face_activates_part": "部品の面にスケッチするとその部品をアクティブにする",
|
||||
"prefs.sketch_face_activates_part_note": "別のコンポーネントのボディの面で始めたスケッチは、先にそのコンポーネントをアクティブにし、スケッチはそのコンポーネントに属してブラウザでその部品の下に表示されます。部品はその後もアクティブのままです。オフ:スケッチはアクティブなコンポーネントに属します。",
|
||||
"prefs.sketch_mirror_auto_line": "事前に選択した補助直線をミラー線に使用する",
|
||||
"prefs.sketch_open_look_at": "スケッチを開いたときに正対させる",
|
||||
"prefs.sketch_open_look_at_note": "オフ: スケッチの作成や編集でビューを動かしません。必要なときは「正面視」でスケッチに正対します。",
|
||||
"prefs.sketch_recent_snap": "最近使った中心と中点へ自動スナップ",
|
||||
@@ -5340,6 +5360,65 @@
|
||||
"ui.palette_sketch_options": "スケッチオプション",
|
||||
"ui.pan": "パン",
|
||||
"ui.pan_zoom_orbit": "パン、ズーム、オービット",
|
||||
"ui.panel_fixture.apply": "適用",
|
||||
"ui.panel_fixture.cancel": "キャンセル",
|
||||
"ui.panel_fixture.caption": "合成パネル標本",
|
||||
"ui.panel_fixture.draft": "保持された下書き",
|
||||
"ui.panel_fixture.editor": "標本エディター",
|
||||
"ui.panel_fixture.explanation": "この合成コンテンツは非表示や移動後も下書きを保持します。",
|
||||
"ui.panel_fixture.fill": "高さを埋める標本",
|
||||
"ui.panel_fixture.finish": "完了",
|
||||
"ui.panel_fixture.finished": "合成トランザクション終了",
|
||||
"ui.panel_fixture.footer": "標本の操作は設計を変更しません。",
|
||||
"ui.panel_fixture.guard": "トランザクション中のキャンセルを拒否",
|
||||
"ui.panel_fixture.inline": "一行の標本",
|
||||
"ui.panel_fixture.live": "合成トランザクション実行中",
|
||||
"ui.panel_fixture.log": "標本ログ",
|
||||
"ui.panel_fixture.pin": "固定標本",
|
||||
"ui.panel_fixture.title": "{title} · {id}",
|
||||
"ui.panel_fixture.updates": "サービス更新: {count}",
|
||||
"ui.panel_host.attention": "確認が必要",
|
||||
"ui.panel_host.bottom": "下",
|
||||
"ui.panel_host.close": "パネルを閉じる",
|
||||
"ui.panel_host.collapse": "パネルを折りたたむ",
|
||||
"ui.panel_host.expand": "パネルを展開",
|
||||
"ui.panel_host.floating": "フローティング",
|
||||
"ui.panel_host.focus": "パネルにフォーカス",
|
||||
"ui.panel_host.focus_target": "{title}にフォーカス",
|
||||
"ui.panel_host.header": "パネルヘッダー",
|
||||
"ui.panel_host.join": "タブを結合",
|
||||
"ui.panel_host.join_target": "{title}とタブを結合",
|
||||
"ui.panel_host.left": "左",
|
||||
"ui.panel_host.menu": "パネル操作",
|
||||
"ui.panel_host.move": "移動先",
|
||||
"ui.panel_host.overflow": "その他のパネル",
|
||||
"ui.panel_host.popout": "ウィンドウで開く",
|
||||
"ui.panel_host.resize": "パネルのサイズ変更",
|
||||
"ui.panel_host.right": "右",
|
||||
"ui.panel_host.rule.availability": "このパネルは使用できません。",
|
||||
"ui.panel_host.rule.bounds": "パネルがサイズ制限内に収まりません。",
|
||||
"ui.panel_host.rule.capability": "このホストはその操作に対応していません。",
|
||||
"ui.panel_host.rule.collection_limit": "パネルレイアウトが上限に達しました。",
|
||||
"ui.panel_host.rule.duplicate_id": "このパネルIDは既に使用されています。",
|
||||
"ui.panel_host.rule.exactly_once": "各パネルは1回表示する必要があります。",
|
||||
"ui.panel_host.rule.feature_disabled": "このパネルではこの操作は無効です。",
|
||||
"ui.panel_host.rule.id": "パネルIDが無効です。",
|
||||
"ui.panel_host.rule.incompatible_tabs": "これらのパネルはタブグループを共有できません。",
|
||||
"ui.panel_host.rule.lifecycle": "パネルはこの操作を完了できませんでした。",
|
||||
"ui.panel_host.rule.missing_target": "このパネルの対象は使用できなくなりました。",
|
||||
"ui.panel_host.rule.no_space": "このパネル配置に必要な空間がありません。",
|
||||
"ui.panel_host.rule.pin_conflict": "この端には別のパネルが既に固定されています。",
|
||||
"ui.panel_host.rule.pin_order": "固定パネルは端の先頭に置く必要があります。",
|
||||
"ui.panel_host.rule.placement": "このパネルはその位置に移動できません。",
|
||||
"ui.panel_host.rule.revision": "レイアウトが変更されました。操作をやり直してください。",
|
||||
"ui.panel_host.rule.schema": "パネルのリクエストが無効です。",
|
||||
"ui.panel_host.rule.version": "このパネルレイアウトのバージョンには対応していません。",
|
||||
"ui.panel_host.sash": "隣接パネルのサイズ変更",
|
||||
"ui.panel_host.scroll_horizontal": "パネル列をスクロール",
|
||||
"ui.panel_host.scroll_vertical": "パネルの積み重ねをスクロール",
|
||||
"ui.panel_host.surface": "パネル",
|
||||
"ui.panel_host.tab": "パネルタブ",
|
||||
"ui.panel_host.tabs": "すべてのタブ",
|
||||
"ui.parallel": "平行",
|
||||
"ui.parameters": "パラメータ",
|
||||
"ui.part_size_needs_a_part": "サイズを変更する挿入済みの標準パーツ(ねじ、ナット、座金、ピン)を選択してください。ボディを拡大・縮小するには尺度を使います。",
|
||||
|
||||
@@ -982,6 +982,7 @@
|
||||
"cmd.occurrence_ground": "고정",
|
||||
"cmd.occurrence_move": "인스턴스 이동",
|
||||
"cmd.occurrence_properties": "인스턴스 물리 속성",
|
||||
"cmd.panel.action": "패널 동작 실행",
|
||||
"cmd.panel.activate": "패널 탭 활성화",
|
||||
"cmd.panel.close": "패널 닫기",
|
||||
"cmd.panel.collapse": "패널 구역 접기",
|
||||
@@ -2160,6 +2161,7 @@
|
||||
"prefs.sketch_conflict_colour": "충돌하는 기하를 충돌 색상으로 표시",
|
||||
"prefs.sketch_conflict_colour_note": "스케치의 구속 조건이 충돌하는 동안 실패한 구속 조건의 글리프나 치수뿐 아니라 그 구속 조건이 잡고 있는 곡선과 점도 충돌 색상으로 그립니다. 끄기: 평소 색상을 유지합니다.",
|
||||
"prefs.sketch_construction_lines": "확장 보조 직선 도구",
|
||||
"prefs.sketch_mirror_auto_line": "미리 선택한 보조 직선을 미러 선으로 사용",
|
||||
"prefs.sketch_open_look_at": "스케치를 열 때 정면으로 돌리기",
|
||||
"prefs.sketch_open_look_at_note": "끄기: 스케치를 만들거나 편집해도 뷰가 그대로입니다. 필요할 때 '바라보기'로 스케치를 정면으로 봅니다.",
|
||||
"prefs.sketch_recent_snap": "최근 중심과 중점에 자동 스냅",
|
||||
@@ -4728,6 +4730,65 @@
|
||||
"ui.palette_sketch_options": "스케치 옵션",
|
||||
"ui.pan": "이동",
|
||||
"ui.pan_zoom_orbit": "이동, 확대/축소, 궤도 회전",
|
||||
"ui.panel_fixture.apply": "적용",
|
||||
"ui.panel_fixture.cancel": "취소",
|
||||
"ui.panel_fixture.caption": "합성 패널 견본",
|
||||
"ui.panel_fixture.draft": "유지된 초안",
|
||||
"ui.panel_fixture.editor": "견본 편집기",
|
||||
"ui.panel_fixture.explanation": "이 합성 콘텐츠는 숨기거나 이동해도 초안을 유지합니다.",
|
||||
"ui.panel_fixture.fill": "높이 채우기 견본",
|
||||
"ui.panel_fixture.finish": "완료",
|
||||
"ui.panel_fixture.finished": "합성 트랜잭션 종료됨",
|
||||
"ui.panel_fixture.footer": "견본 동작은 설계를 변경하지 않습니다.",
|
||||
"ui.panel_fixture.guard": "트랜잭션이 활성 상태일 때 취소 거부",
|
||||
"ui.panel_fixture.inline": "한 줄 견본",
|
||||
"ui.panel_fixture.live": "합성 트랜잭션 활성 상태",
|
||||
"ui.panel_fixture.log": "견본 로그",
|
||||
"ui.panel_fixture.pin": "고정된 견본",
|
||||
"ui.panel_fixture.title": "{title} · {id}",
|
||||
"ui.panel_fixture.updates": "서비스 업데이트: {count}",
|
||||
"ui.panel_host.attention": "주의 필요",
|
||||
"ui.panel_host.bottom": "아래쪽",
|
||||
"ui.panel_host.close": "패널 닫기",
|
||||
"ui.panel_host.collapse": "패널 접기",
|
||||
"ui.panel_host.expand": "패널 펼치기",
|
||||
"ui.panel_host.floating": "플로팅",
|
||||
"ui.panel_host.focus": "패널에 초점",
|
||||
"ui.panel_host.focus_target": "{title}에 초점",
|
||||
"ui.panel_host.header": "패널 머리글",
|
||||
"ui.panel_host.join": "탭 결합",
|
||||
"ui.panel_host.join_target": "{title}와 탭 결합",
|
||||
"ui.panel_host.left": "왼쪽",
|
||||
"ui.panel_host.menu": "패널 동작",
|
||||
"ui.panel_host.move": "이동 위치",
|
||||
"ui.panel_host.overflow": "더 많은 패널",
|
||||
"ui.panel_host.popout": "창에서 열기",
|
||||
"ui.panel_host.resize": "패널 크기 조정",
|
||||
"ui.panel_host.right": "오른쪽",
|
||||
"ui.panel_host.rule.availability": "이 패널을 사용할 수 없습니다.",
|
||||
"ui.panel_host.rule.bounds": "패널이 크기 제한에 맞지 않습니다.",
|
||||
"ui.panel_host.rule.capability": "이 호스트는 해당 동작을 지원하지 않습니다.",
|
||||
"ui.panel_host.rule.collection_limit": "패널 배치가 한도에 도달했습니다.",
|
||||
"ui.panel_host.rule.duplicate_id": "이 패널 식별자는 이미 사용 중입니다.",
|
||||
"ui.panel_host.rule.exactly_once": "각 패널은 한 번 나타나야 합니다.",
|
||||
"ui.panel_host.rule.feature_disabled": "이 패널에서 해당 동작이 비활성화되어 있습니다.",
|
||||
"ui.panel_host.rule.id": "패널 식별자가 유효하지 않습니다.",
|
||||
"ui.panel_host.rule.incompatible_tabs": "이 패널들은 탭 그룹을 공유할 수 없습니다.",
|
||||
"ui.panel_host.rule.lifecycle": "패널이 이 동작을 완료하지 못했습니다.",
|
||||
"ui.panel_host.rule.missing_target": "이 패널 대상은 더 이상 사용할 수 없습니다.",
|
||||
"ui.panel_host.rule.no_space": "이 패널 배치를 위한 공간이 없습니다.",
|
||||
"ui.panel_host.rule.pin_conflict": "이 가장자리에는 다른 패널이 이미 고정되어 있습니다.",
|
||||
"ui.panel_host.rule.pin_order": "고정된 패널은 가장자리의 첫 위치를 유지해야 합니다.",
|
||||
"ui.panel_host.rule.placement": "이 패널은 해당 위치로 이동할 수 없습니다.",
|
||||
"ui.panel_host.rule.revision": "배치가 변경되었습니다. 동작을 다시 시도하세요.",
|
||||
"ui.panel_host.rule.schema": "패널 요청이 유효하지 않습니다.",
|
||||
"ui.panel_host.rule.version": "이 패널 배치 버전은 지원되지 않습니다.",
|
||||
"ui.panel_host.sash": "인접한 패널 크기 조정",
|
||||
"ui.panel_host.scroll_horizontal": "패널 열 스크롤",
|
||||
"ui.panel_host.scroll_vertical": "패널 스택 스크롤",
|
||||
"ui.panel_host.surface": "패널",
|
||||
"ui.panel_host.tab": "패널 탭",
|
||||
"ui.panel_host.tabs": "모든 탭",
|
||||
"ui.parallel": "평행",
|
||||
"ui.parameters": "매개변수",
|
||||
"ui.part_size_needs_a_part": "크기를 바꿀 삽입된 표준 부품(나사, 너트, 와셔 또는 핀)을 선택하십시오. 바디를 키우거나 줄이려면 축척을 사용하십시오.",
|
||||
|
||||
@@ -1044,6 +1044,7 @@
|
||||
"cmd.occurrence_move": "Di chuyển đối tượng",
|
||||
"cmd.occurrence_properties": "Thuộc tính cơ lý của bản thể (Occurrence)",
|
||||
"cmd.occurrence_reparent": "Chuyển sang Cụm chi tiết",
|
||||
"cmd.panel.action": "Chạy thao tác trên tiêu đề bảng",
|
||||
"cmd.panel.activate": "Kích hoạt thẻ bảng",
|
||||
"cmd.panel.close": "Đóng bảng",
|
||||
"cmd.panel.collapse": "Thu gọn vùng bảng",
|
||||
@@ -2384,6 +2385,8 @@
|
||||
"prefs.edges": "Cạnh và đổ bóng",
|
||||
"prefs.extend": "Kéo dài",
|
||||
"prefs.extra_navigation": "Ctrl + kéo chuột trái trên vùng trống để xoay; giữ phím Cách (Space) để trượt góc nhìn.",
|
||||
"prefs.extrude_arrow_face_stops": "Mũi tên đùn dừng tại các mặt",
|
||||
"prefs.extrude_arrow_face_stops_note": "Khi kéo mũi tên khoảng cách của Đùn, nó dừng tại các mặt phẳng song song với biên dạng, chẳng hạn mặt bên kia của khối đang cắt, và tô viền mặt đó. Tắt: mũi tên chỉ di chuyển theo các bước tròn.",
|
||||
"prefs.extrude_view_isometric": "Xoay sang góc nhìn trục đo khi mở Đùn khối",
|
||||
"prefs.extrude_view_return": "Trở lại góc nhìn trước khi đóng Đùn khối",
|
||||
"prefs.follows_os": "Theo hệ điều hành",
|
||||
@@ -2546,6 +2549,22 @@
|
||||
"prefs.persistent_ribbon_pressed": "Tô sáng lệnh đang bật trên dải băng",
|
||||
"prefs.persistent_ribbon_pressed_help": "Tô sáng các lệnh trên dải băng khi hiệu ứng của chúng đang bật. Tắt tùy chọn này để giữ giao diện trung tính và trợ giúp lệnh như trước.",
|
||||
"prefs.perspective_fov": "Trường nhìn",
|
||||
"prefs.picker.carousel": "Băng chuyền",
|
||||
"prefs.picker.change": "Thay đổi",
|
||||
"prefs.picker.clear": "Xóa bộ lọc",
|
||||
"prefs.picker.day": "Giao diện ban ngày",
|
||||
"prefs.picker.empty": "Không có giao diện nào khớp với các bộ lọc này.",
|
||||
"prefs.picker.follow": "Theo hệ thống",
|
||||
"prefs.picker.grid": "Lưới",
|
||||
"prefs.picker.high": "Tương phản cao",
|
||||
"prefs.picker.high_note": "{source} · Tương phản cao",
|
||||
"prefs.picker.hint": "Tự động chuyển theo hệ điều hành.",
|
||||
"prefs.picker.import": "Nhập tệp giao diện…",
|
||||
"prefs.picker.imported": "Đã nhập",
|
||||
"prefs.picker.night": "Giao diện ban đêm",
|
||||
"prefs.picker.one": "Một giao diện",
|
||||
"prefs.picker.pick": "Chọn bên dưới",
|
||||
"prefs.picker.standard": "Tiêu chuẩn",
|
||||
"prefs.placement": "Vị trí đặt",
|
||||
"prefs.plugins_enabled": "Đã bật",
|
||||
"prefs.plugins_installed": "Đã cài đặt",
|
||||
@@ -2665,6 +2684,7 @@
|
||||
"prefs.sketch_exit_view_note": "Góc nhìn sẽ chuyển đến đâu sau khi bấm Hoàn tất phác thảo, Hủy bỏ hoặc bấm phím Esc hai lần.",
|
||||
"prefs.sketch_face_activates_part": "Phác thảo trên mặt của một chi tiết sẽ kích hoạt chi tiết đó",
|
||||
"prefs.sketch_face_activates_part_note": "Bản phác thảo bắt đầu trên mặt của một khối thuộc thành phần khác sẽ kích hoạt thành phần đó trước, nên bản phác thảo thuộc về nó và nằm cùng chi tiết đó trong trình duyệt. Chi tiết vẫn được kích hoạt sau đó. Tắt: bản phác thảo thuộc thành phần đang hoạt động.",
|
||||
"prefs.sketch_mirror_auto_line": "Dùng đường dựng hình đã chọn làm đường đối xứng",
|
||||
"prefs.sketch_open_look_at": "Xoay góc nhìn trực diện phác thảo khi mở",
|
||||
"prefs.sketch_open_look_at_note": "Tắt: tạo hoặc chỉnh sửa phác thảo sẽ giữ nguyên góc nhìn. Dùng Nhìn trực diện để nhìn thẳng vào phác thảo khi cần.",
|
||||
"prefs.sketch_recent_snap": "Tự động bắt điểm vào tâm và trung điểm gần đây",
|
||||
@@ -5340,6 +5360,65 @@
|
||||
"ui.palette_sketch_options": "Tùy chọn phác thảo",
|
||||
"ui.pan": "Dời góc nhìn (Pan)",
|
||||
"ui.pan_zoom_orbit": "Dời góc nhìn, thu phóng, xoay quanh tâm",
|
||||
"ui.panel_fixture.apply": "Áp dụng",
|
||||
"ui.panel_fixture.cancel": "Hủy bỏ",
|
||||
"ui.panel_fixture.caption": "Mẫu bảng tổng hợp",
|
||||
"ui.panel_fixture.draft": "Bản nháp được giữ lại",
|
||||
"ui.panel_fixture.editor": "Trình sửa mẫu",
|
||||
"ui.panel_fixture.explanation": "Nội dung tổng hợp này giữ bản nháp khi bị ẩn hoặc di chuyển.",
|
||||
"ui.panel_fixture.fill": "Mẫu lấp đầy chiều cao",
|
||||
"ui.panel_fixture.finish": "Hoàn tất",
|
||||
"ui.panel_fixture.finished": "Giao dịch tổng hợp đã kết thúc",
|
||||
"ui.panel_fixture.footer": "Các thao tác mẫu giữ nguyên thiết kế.",
|
||||
"ui.panel_fixture.guard": "Từ chối hủy khi giao dịch đang hoạt động",
|
||||
"ui.panel_fixture.inline": "Mẫu một hàng",
|
||||
"ui.panel_fixture.live": "Giao dịch tổng hợp đang hoạt động",
|
||||
"ui.panel_fixture.log": "Nhật ký mẫu",
|
||||
"ui.panel_fixture.pin": "Mẫu đã ghim",
|
||||
"ui.panel_fixture.title": "{title} · {id}",
|
||||
"ui.panel_fixture.updates": "Số lần cập nhật dịch vụ: {count}",
|
||||
"ui.panel_host.attention": "Cần chú ý",
|
||||
"ui.panel_host.bottom": "Dưới",
|
||||
"ui.panel_host.close": "Đóng bảng",
|
||||
"ui.panel_host.collapse": "Thu gọn bảng",
|
||||
"ui.panel_host.expand": "Mở rộng bảng",
|
||||
"ui.panel_host.floating": "Nổi",
|
||||
"ui.panel_host.focus": "Đặt tiêu điểm vào bảng",
|
||||
"ui.panel_host.focus_target": "Đặt tiêu điểm vào {title}",
|
||||
"ui.panel_host.header": "Tiêu đề bảng",
|
||||
"ui.panel_host.join": "Ghép thẻ",
|
||||
"ui.panel_host.join_target": "Ghép thẻ với {title}",
|
||||
"ui.panel_host.left": "Trái",
|
||||
"ui.panel_host.menu": "Thao tác bảng",
|
||||
"ui.panel_host.move": "Chuyển đến",
|
||||
"ui.panel_host.overflow": "Thêm bảng",
|
||||
"ui.panel_host.popout": "Mở trong cửa sổ",
|
||||
"ui.panel_host.resize": "Đổi kích thước bảng",
|
||||
"ui.panel_host.right": "Phải",
|
||||
"ui.panel_host.rule.availability": "Bảng này không khả dụng.",
|
||||
"ui.panel_host.rule.bounds": "Các bảng không vừa trong giới hạn kích thước.",
|
||||
"ui.panel_host.rule.capability": "Máy chủ này không hỗ trợ thao tác đó.",
|
||||
"ui.panel_host.rule.collection_limit": "Bố cục bảng đã đạt giới hạn.",
|
||||
"ui.panel_host.rule.duplicate_id": "Định danh bảng này đã được sử dụng.",
|
||||
"ui.panel_host.rule.exactly_once": "Mỗi bảng phải xuất hiện một lần.",
|
||||
"ui.panel_host.rule.feature_disabled": "Thao tác này bị tắt cho bảng này.",
|
||||
"ui.panel_host.rule.id": "Định danh bảng không hợp lệ.",
|
||||
"ui.panel_host.rule.incompatible_tabs": "Các bảng này không thể dùng chung nhóm thẻ.",
|
||||
"ui.panel_host.rule.lifecycle": "Bảng không thể hoàn thành thao tác này.",
|
||||
"ui.panel_host.rule.missing_target": "Đích bảng này không còn khả dụng.",
|
||||
"ui.panel_host.rule.no_space": "Không đủ chỗ cho bố cục bảng này.",
|
||||
"ui.panel_host.rule.pin_conflict": "Một bảng khác đã được ghim vào cạnh này.",
|
||||
"ui.panel_host.rule.pin_order": "Bảng đã ghim phải luôn đứng đầu cạnh của nó.",
|
||||
"ui.panel_host.rule.placement": "Không thể chuyển bảng này đến vị trí đó.",
|
||||
"ui.panel_host.rule.revision": "Bố cục đã thay đổi. Hãy thử lại thao tác.",
|
||||
"ui.panel_host.rule.schema": "Yêu cầu bảng không hợp lệ.",
|
||||
"ui.panel_host.rule.version": "Phiên bản bố cục bảng này không được hỗ trợ.",
|
||||
"ui.panel_host.sash": "Đổi kích thước các bảng liền kề",
|
||||
"ui.panel_host.scroll_horizontal": "Cuộn các cột bảng",
|
||||
"ui.panel_host.scroll_vertical": "Cuộn các chồng bảng",
|
||||
"ui.panel_host.surface": "Bảng",
|
||||
"ui.panel_host.tab": "Thẻ bảng",
|
||||
"ui.panel_host.tabs": "Tất cả thẻ",
|
||||
"ui.parallel": "Song song",
|
||||
"ui.parameters": "Bảng tham số",
|
||||
"ui.part_size_needs_a_part": "Hãy chọn một chi tiết tiêu chuẩn đã chèn (vít, đai ốc, vòng đệm hoặc chốt) để đổi kích thước. Để phóng to hoặc thu nhỏ một thân khối, hãy dùng Thay đổi tỷ lệ.",
|
||||
|
||||
@@ -1044,6 +1044,7 @@
|
||||
"cmd.occurrence_move": "移动实例",
|
||||
"cmd.occurrence_properties": "实例物理属性",
|
||||
"cmd.occurrence_reparent": "移动到组件",
|
||||
"cmd.panel.action": "执行面板操作",
|
||||
"cmd.panel.activate": "激活面板选项卡",
|
||||
"cmd.panel.close": "关闭面板",
|
||||
"cmd.panel.collapse": "折叠面板分区",
|
||||
@@ -2384,6 +2385,8 @@
|
||||
"prefs.edges": "边缘与着色",
|
||||
"prefs.extend": "扩展",
|
||||
"prefs.extra_navigation": "在空白处按住Ctrl并用鼠标左键拖动可旋转;按住空格键可平移。",
|
||||
"prefs.extrude_arrow_face_stops": "拉伸箭头停在面上",
|
||||
"prefs.extrude_arrow_face_stops_note": "拖动拉伸的距离箭头时,它会停在与轮廓平行的平面上(例如正在切除的块的另一侧),并勾勒出该面。关闭:箭头只按整数步长移动。",
|
||||
"prefs.extrude_view_isometric": "打开拉伸时转到等轴测视图",
|
||||
"prefs.extrude_view_return": "关闭拉伸时回到之前的视图",
|
||||
"prefs.follows_os": "跟随操作系统",
|
||||
@@ -2546,6 +2549,22 @@
|
||||
"prefs.persistent_ribbon_pressed": "突出显示已启用的功能区命令",
|
||||
"prefs.persistent_ribbon_pressed_help": "在效果启用时突出显示相应的功能区命令。关闭此选项可保留原来的中性外观和命令帮助。",
|
||||
"prefs.perspective_fov": "视场角",
|
||||
"prefs.picker.carousel": "轮播",
|
||||
"prefs.picker.change": "更改",
|
||||
"prefs.picker.clear": "清除筛选条件",
|
||||
"prefs.picker.day": "日间主题",
|
||||
"prefs.picker.empty": "没有符合这些筛选条件的主题。",
|
||||
"prefs.picker.follow": "跟随系统",
|
||||
"prefs.picker.grid": "网格",
|
||||
"prefs.picker.high": "高对比度",
|
||||
"prefs.picker.high_note": "{source} · 高对比度",
|
||||
"prefs.picker.hint": "随操作系统设置自动切换。",
|
||||
"prefs.picker.import": "导入主题文件…",
|
||||
"prefs.picker.imported": "已导入",
|
||||
"prefs.picker.night": "夜间主题",
|
||||
"prefs.picker.one": "单一主题",
|
||||
"prefs.picker.pick": "从下方选择",
|
||||
"prefs.picker.standard": "标准",
|
||||
"prefs.placement": "放置",
|
||||
"prefs.plugins_enabled": "已启用",
|
||||
"prefs.plugins_installed": "已安装",
|
||||
@@ -2665,6 +2684,7 @@
|
||||
"prefs.sketch_exit_view_note": "“完成草图”、取消或连按两次 Esc 后视图的去向。",
|
||||
"prefs.sketch_face_activates_part": "在零件的面上绘制草图时激活该零件",
|
||||
"prefs.sketch_face_activates_part_note": "在另一个组件的实体面上开始的草图会先激活该组件,因此草图属于它,并在浏览器中留在该零件下。之后该零件保持激活。关闭时:草图属于当前激活的组件。",
|
||||
"prefs.sketch_mirror_auto_line": "将预选的构造直线用作镜像线",
|
||||
"prefs.sketch_open_look_at": "打开草图时转向正对草图",
|
||||
"prefs.sketch_open_look_at_note": "关闭:创建或编辑草图时视图保持不变。需要时用“朝向”正对草图。",
|
||||
"prefs.sketch_recent_snap": "自动吸附到最近的圆心和中点",
|
||||
@@ -5340,6 +5360,65 @@
|
||||
"ui.palette_sketch_options": "草图选项",
|
||||
"ui.pan": "平移",
|
||||
"ui.pan_zoom_orbit": "平移、缩放、环绕",
|
||||
"ui.panel_fixture.apply": "应用",
|
||||
"ui.panel_fixture.cancel": "取消",
|
||||
"ui.panel_fixture.caption": "合成面板示例",
|
||||
"ui.panel_fixture.draft": "保留的草稿",
|
||||
"ui.panel_fixture.editor": "示例编辑器",
|
||||
"ui.panel_fixture.explanation": "此合成内容在隐藏或移动时保留草稿。",
|
||||
"ui.panel_fixture.fill": "填充高度示例",
|
||||
"ui.panel_fixture.finish": "完成",
|
||||
"ui.panel_fixture.finished": "合成事务已结束",
|
||||
"ui.panel_fixture.footer": "示例操作不会更改设计。",
|
||||
"ui.panel_fixture.guard": "事务活动期间拒绝取消",
|
||||
"ui.panel_fixture.inline": "单行示例",
|
||||
"ui.panel_fixture.live": "合成事务活动中",
|
||||
"ui.panel_fixture.log": "示例日志",
|
||||
"ui.panel_fixture.pin": "固定示例",
|
||||
"ui.panel_fixture.title": "{title} · {id}",
|
||||
"ui.panel_fixture.updates": "服务更新:{count}",
|
||||
"ui.panel_host.attention": "需要注意",
|
||||
"ui.panel_host.bottom": "底部",
|
||||
"ui.panel_host.close": "关闭面板",
|
||||
"ui.panel_host.collapse": "折叠面板",
|
||||
"ui.panel_host.expand": "展开面板",
|
||||
"ui.panel_host.floating": "浮动",
|
||||
"ui.panel_host.focus": "聚焦面板",
|
||||
"ui.panel_host.focus_target": "聚焦{title}",
|
||||
"ui.panel_host.header": "面板标题栏",
|
||||
"ui.panel_host.join": "合并标签页",
|
||||
"ui.panel_host.join_target": "与{title}合并标签页",
|
||||
"ui.panel_host.left": "左侧",
|
||||
"ui.panel_host.menu": "面板操作",
|
||||
"ui.panel_host.move": "移动到",
|
||||
"ui.panel_host.overflow": "更多面板",
|
||||
"ui.panel_host.popout": "在窗口中打开",
|
||||
"ui.panel_host.resize": "调整面板大小",
|
||||
"ui.panel_host.right": "右侧",
|
||||
"ui.panel_host.rule.availability": "此面板不可用。",
|
||||
"ui.panel_host.rule.bounds": "面板不符合尺寸限制。",
|
||||
"ui.panel_host.rule.capability": "此宿主不支持该操作。",
|
||||
"ui.panel_host.rule.collection_limit": "面板布局已达到上限。",
|
||||
"ui.panel_host.rule.duplicate_id": "此面板标识已被使用。",
|
||||
"ui.panel_host.rule.exactly_once": "每个面板必须出现一次。",
|
||||
"ui.panel_host.rule.feature_disabled": "此面板已禁用该操作。",
|
||||
"ui.panel_host.rule.id": "面板标识无效。",
|
||||
"ui.panel_host.rule.incompatible_tabs": "这些面板无法共享标签组。",
|
||||
"ui.panel_host.rule.lifecycle": "面板无法完成此操作。",
|
||||
"ui.panel_host.rule.missing_target": "此面板目标已不可用。",
|
||||
"ui.panel_host.rule.no_space": "没有足够的空间容纳此面板布局。",
|
||||
"ui.panel_host.rule.pin_conflict": "此边缘已固定另一个面板。",
|
||||
"ui.panel_host.rule.pin_order": "固定面板必须保持在其边缘的首位。",
|
||||
"ui.panel_host.rule.placement": "此面板无法移至该位置。",
|
||||
"ui.panel_host.rule.revision": "布局已更改。请重试该操作。",
|
||||
"ui.panel_host.rule.schema": "面板请求无效。",
|
||||
"ui.panel_host.rule.version": "不支持此面板布局版本。",
|
||||
"ui.panel_host.sash": "调整相邻面板大小",
|
||||
"ui.panel_host.scroll_horizontal": "滚动面板列",
|
||||
"ui.panel_host.scroll_vertical": "滚动面板堆栈",
|
||||
"ui.panel_host.surface": "面板",
|
||||
"ui.panel_host.tab": "面板标签页",
|
||||
"ui.panel_host.tabs": "所有标签页",
|
||||
"ui.parallel": "平行",
|
||||
"ui.parameters": "参数",
|
||||
"ui.part_size_needs_a_part": "请选择已插入的标准零件(螺钉、螺母、垫圈或销)以更改其尺寸。要放大或缩小实体,请使用缩放。",
|
||||
|
||||
@@ -321,6 +321,12 @@ pub struct Extent {
|
||||
/// Through all bodies in the direction(s) instead of `distance`.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub through_all: bool,
|
||||
/// Two Sides as older builds read it: `distance2` goes the other way from wherever the
|
||||
/// first side went, so a negative entered distance sends it back along the normal. Saved
|
||||
/// designs from before entered distances kept their sides carry it, so they rebuild as
|
||||
/// they did whatever their expressions evaluate to; new and edited extrudes leave it off.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub second_follows_first: bool,
|
||||
/// Taper angle (expression; positive grows the profile).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[walk(angle = "Taper angle")]
|
||||
|
||||
+18
-5
@@ -6083,15 +6083,28 @@ fn from_profile_on_closed_path(segs: Vec<solidcore_record::Seg2>, path: &Plane,
|
||||
/// Where an extrude of distance `d` starts and ends along the sketch normal, before any start
|
||||
/// offset: one side, the other, both (symmetric), or a second distance on the other side.
|
||||
///
|
||||
/// A second distance (`distance2`) goes the other way from the first side, wherever that went:
|
||||
/// against the normal for `direction: negative` (#2700), and back along it when a negative
|
||||
/// distance or a To Object below the sketch sends the first side down.
|
||||
/// A second distance (`distance2`) goes the other way from the first side: against the normal,
|
||||
/// or along it for `direction: negative` (#2700). Entered distances keep those sides whatever
|
||||
/// their signs; a To Object below the sketch or a Through All that reaches down sends the first
|
||||
/// side down and the second back along the normal.
|
||||
pub(crate) fn extent_sides(vals: &BTreeMap<String, Value>, extent: &crate::Extent, d: f64, direction: crate::Direction) -> Result<(f64, f64)> {
|
||||
Ok(match (&extent.distance2, direction) {
|
||||
(Some(d2), _) => {
|
||||
let first = if direction == crate::Direction::Negative { -d } else { d };
|
||||
let negative = direction == crate::Direction::Negative;
|
||||
let first = if negative { -d } else { d };
|
||||
let d2 = val(vals, d2, Kind::Length)?;
|
||||
(if first < 0.0 { d2 } else { -d2 }, first)
|
||||
// An entered distance keeps its side whatever its sign: Direction fixes the sides,
|
||||
// and a sign only turns its own side over. A reach computed from the model (To
|
||||
// Object, Through All) has the sign of where the object is, so the other side
|
||||
// follows it.
|
||||
let second = if extent.second_follows_first || extent.to.is_some() || extent.through_all {
|
||||
if first < 0.0 { d2 } else { -d2 }
|
||||
} else if negative {
|
||||
d2
|
||||
} else {
|
||||
-d2
|
||||
};
|
||||
(second, first)
|
||||
}
|
||||
(None, crate::Direction::Positive) => (0.0, d),
|
||||
(None, crate::Direction::Negative) => (-d, 0.0),
|
||||
|
||||
@@ -1914,6 +1914,7 @@ mod tests {
|
||||
distance2: None,
|
||||
start_offset: None,
|
||||
through_all: false,
|
||||
second_follows_first: false,
|
||||
taper: Some("0 deg".into()),
|
||||
corner: Default::default(),
|
||||
to: Some(crate::FacePick(solidcore_record::Vec3::new(0.0, 0.0, 10.0))),
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
//! In a two-sided extrude (`distance2`) with entered distances, Direction fixes the sides and the
|
||||
//! sign of a distance only turns its own side over; `distance2` no longer follows the first
|
||||
//! side across the sketch plane. Older builds sent `distance2` to the other side of a negative
|
||||
//! first distance, so this step marks every saved two-sided extrude with entered distances
|
||||
//! `second_follows_first`, which keeps that reading. The distances themselves are left as they
|
||||
//! were, so an expression keeps the old sides whatever it evaluates to and a feature's named
|
||||
//! inputs keep their values for the expressions that use them. An extent that reaches to an
|
||||
//! object or through all already lets the second side follow the first, and a symmetric one has
|
||||
//! no second side. The last release asks for an update instead of opening a design that carries
|
||||
//! this change.
|
||||
use serde_json::Value;
|
||||
|
||||
pub fn step(v: &mut Value) -> crate::Result<()> {
|
||||
let Some(Value::Array(features)) = v.get_mut("features") else {
|
||||
return Ok(());
|
||||
};
|
||||
for feature in features {
|
||||
if !matches!(feature.get("type").and_then(Value::as_str), Some("extrude" | "surface_extrude")) {
|
||||
continue;
|
||||
}
|
||||
let Some(extent) = feature.get_mut("extent").and_then(Value::as_object_mut) else { continue };
|
||||
let plain = extent.get("distance2").is_some_and(|d| !d.is_null())
|
||||
&& extent.get("to").is_none_or(Value::is_null)
|
||||
&& !extent.get("through_all").and_then(Value::as_bool).unwrap_or(false)
|
||||
&& extent.get("direction").and_then(Value::as_str) != Some("symmetric");
|
||||
if plain {
|
||||
extent.insert("second_follows_first".into(), Value::Bool(true));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn saved_two_sided_extrudes_keep_their_sides_and_distances() {
|
||||
let mut v = json!({"features": [
|
||||
{"type": "extrude", "extent": {"distance": "-10 mm", "distance2": "5 mm"}},
|
||||
{"type": "extrude", "extent": {"distance": "-10 mm", "direction": "negative", "distance2": "5 mm"}},
|
||||
{"type": "extrude", "extent": {"distance": "-0 mm", "distance2": "5 mm"}},
|
||||
{"type": "extrude", "extent": {"distance": "-width", "distance2": "10 mm"}},
|
||||
{"type": "extrude", "extent": {"distance": "-10 mm"}},
|
||||
{"type": "extrude", "extent": {"distance": "-10 mm", "through_all": true, "distance2": "5 mm"}},
|
||||
{"type": "extrude", "extent": {"distance": "-10 mm", "to": [0.0, 0.0, 1.0], "distance2": "5 mm"}},
|
||||
{"type": "sketch"}
|
||||
]});
|
||||
let before = v.clone();
|
||||
super::step(&mut v).unwrap();
|
||||
let features = v["features"].as_array().unwrap();
|
||||
let marked: Vec<bool> = features.iter().map(|f| f["extent"]["second_follows_first"] == json!(true)).collect();
|
||||
assert_eq!(marked, [true, true, true, true, false, false, false, false]);
|
||||
for (f, b) in features.iter().zip(before["features"].as_array().unwrap()) {
|
||||
assert_eq!((&f["extent"]["distance"], &f["extent"]["direction"]), (&b["extent"]["distance"], &b["extent"]["direction"]));
|
||||
}
|
||||
let mut empty = json!({"name": "Untitled"});
|
||||
super::step(&mut empty).unwrap();
|
||||
assert_eq!(empty, json!({"name": "Untitled"}));
|
||||
}
|
||||
}
|
||||
@@ -463,6 +463,7 @@ mod tests {
|
||||
distance2: None,
|
||||
start_offset: None,
|
||||
through_all: false,
|
||||
second_follows_first: false,
|
||||
taper: None,
|
||||
corner: Default::default(),
|
||||
to: None,
|
||||
|
||||
@@ -106,6 +106,7 @@ pub(super) fn local_geometry(f: &Feature, components: &std::collections::HashMap
|
||||
distance2: _,
|
||||
start_offset: _,
|
||||
through_all,
|
||||
second_follows_first: _,
|
||||
taper: _,
|
||||
to,
|
||||
to_offset: _,
|
||||
|
||||
@@ -453,6 +453,7 @@ mod tests {
|
||||
distance2: None,
|
||||
start_offset: None,
|
||||
through_all: false,
|
||||
second_follows_first: false,
|
||||
taper: None,
|
||||
corner: Default::default(),
|
||||
to: None,
|
||||
@@ -637,6 +638,7 @@ mod tests {
|
||||
distance2: None,
|
||||
start_offset: None,
|
||||
through_all: false,
|
||||
second_follows_first: false,
|
||||
taper: None,
|
||||
corner: Default::default(),
|
||||
to: None,
|
||||
|
||||
@@ -39,6 +39,7 @@ fn plate_doc() -> (Document, u64) {
|
||||
distance2: None,
|
||||
start_offset: None,
|
||||
through_all: false,
|
||||
second_follows_first: false,
|
||||
taper: None,
|
||||
corner: Default::default(),
|
||||
to: None,
|
||||
@@ -345,6 +346,7 @@ fn box_fillet_cut_timeline() {
|
||||
distance2: None,
|
||||
start_offset: None,
|
||||
through_all: false,
|
||||
second_follows_first: false,
|
||||
taper: None,
|
||||
corner: Default::default(),
|
||||
to: None,
|
||||
@@ -1130,6 +1132,7 @@ fn an_extruded_ellipse_or_spline_is_one_wall_named_by_its_curve() {
|
||||
distance2: None,
|
||||
start_offset: None,
|
||||
through_all: false,
|
||||
second_follows_first: false,
|
||||
taper: None,
|
||||
corner: Default::default(),
|
||||
to: None,
|
||||
|
||||
@@ -200,7 +200,10 @@ fn a_second_distance_goes_the_other_way_from_the_first_side() {
|
||||
for (settings, lo, hi) in [
|
||||
(json!({"direction":"positive","distance":"10 mm","distance2":"4 mm"}), -4.0, 10.0),
|
||||
(json!({"direction":"negative","distance":"10 mm","distance2":"4 mm"}), -10.0, 4.0),
|
||||
(json!({"direction":"positive","distance":"-10 mm","distance2":"4 mm"}), -10.0, 4.0),
|
||||
// A sign only turns its own side over: Distance 2 stays where Direction puts it, so a
|
||||
// negative Distance 1 leaves the span between the two ends.
|
||||
(json!({"direction":"positive","distance":"-10 mm","distance2":"4 mm"}), -10.0, -4.0),
|
||||
(json!({"direction":"negative","distance":"-10 mm","distance2":"4 mm"}), 4.0, 10.0),
|
||||
] {
|
||||
let s = fixture(settings.clone());
|
||||
check(&s, lo, hi);
|
||||
@@ -249,3 +252,34 @@ fn an_older_reversed_two_sided_extrude_keeps_its_shape() {
|
||||
let FeatureKind::Extrude { extent, .. } = &s.doc.find_feature("Depth").unwrap().kind else { panic!("extrude") };
|
||||
assert_eq!(extent.direction, solidcraft_doc::Direction::Positive);
|
||||
}
|
||||
|
||||
/// Designs saved before entered distances kept their sides sent Distance 2 to the other side of
|
||||
/// a negative first distance. Opening one keeps that, for an expression too and after its
|
||||
/// parameter changes, and leaves the distance and its named input as they were.
|
||||
#[test]
|
||||
fn an_older_two_sided_extrude_with_a_negative_distance_keeps_its_sides() {
|
||||
let mut base = fixture(json!({"direction":"positive","distance":"10 mm","distance2":"10 mm"}));
|
||||
run(&mut base, "parameters.add", json!({"name":"width","expression":"20 mm"}));
|
||||
let mut saved: Value = serde_json::from_str(&base.doc.to_json()).unwrap();
|
||||
// As the last release saved it: the format before this build's pending changes.
|
||||
let version: u32 = saved["format"].as_str().unwrap().trim_start_matches("solidcraft/").parse().unwrap();
|
||||
saved["format"] = json!(format!("solidcraft/{}", version - 1));
|
||||
saved.as_object_mut().unwrap().remove("format_pending");
|
||||
for (distance, lo, hi) in [("-width", -20.0, 10.0), ("-0 mm", -10.0, 0.0), ("-10 mm", -10.0, 10.0)] {
|
||||
let mut file = saved.clone();
|
||||
for f in file["features"].as_array_mut().unwrap() {
|
||||
if f["type"] == "extrude" {
|
||||
f["extent"]["distance"] = json!(distance);
|
||||
}
|
||||
}
|
||||
let mut opened = Session::new(Document::from_json(&file.to_string()).unwrap());
|
||||
check(&opened, lo, hi);
|
||||
let FeatureKind::Extrude { extent, .. } = &opened.doc.find_feature("Depth").unwrap().kind else { panic!("extrude") };
|
||||
assert_eq!(extent.distance, distance);
|
||||
if distance == "-width" {
|
||||
run(&mut opened, "parameters.change", json!({"name":"width","expression":"15 mm"}));
|
||||
check(&opened, -15.0, 10.0);
|
||||
}
|
||||
check(&Session::new(Document::from_json(&opened.doc.to_json()).unwrap()), if distance == "-width" { -15.0 } else { lo }, hi);
|
||||
}
|
||||
}
|
||||
@@ -39,7 +39,7 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.key("E")
|
||||
.contract(&EXTRUDE_CONTRACT)
|
||||
.output(output_schema_for::<FeatureResult>)
|
||||
.params("distance: expr (or through_all: true); taper?: angle expr (positive: outward, so the far end is larger along the extrusion direction; negative: inward, so the far end is smaller); corner?: preserve_curvature|tangent|round (how a taper closes a sharp corner its offset opens: each wall continues as itself, a line's plane or an arc's cone, until it meets its neighbour; each continues straight along its end tangent; or an arc about the corner. Without it, each profile preserves curvature where every curve is a line or an arc and takes tangent where another curve has a corner, and the feature's warning says so; a corner rule given is kept, and refused where the kernel cannot build it); sketch?: id|name (default: active or last sketch); profiles?: all | [index] | [{curves: [ids]}] (the profile whose outer loop is made of exactly these curves, or pieces of them; found again on every recompute, so it follows parameter changes; islands inside are its holes; an error when no profile or several match) | [{point:[x,y]}] (index and point picks are stored by their curves when that finds the same profile; a pick on a drawn profile that reference geometry, such as the projected outline of the face the sketch is on, cuts into regions takes the whole drawn profile); exact_regions?: bool (each index or point pick is exactly the region it names, as the dialogs send); default: every drawn profile, except that a loop inside another is its hole and a loop inside that hole is material again; face?: [x,y,z] (extrude a planar body face instead of a sketch profile); faces?: [[x,y,z],…] (coplanar faces of one body); face_body?: name (whose face, where faces of several bodies meet at the point); direction?: positive|negative|symmetric (distance is total thickness, split evenly around the start plane); convention?: total_distance|legacy_per_side (how a symmetric distance is read; default total_distance, split evenly around the start plane; legacy_per_side: the distance on each side, as older symmetric extrudes keep); distance2?: expr (Two Sides: a second distance the other way from the first side, which may be through_all or to; with direction: negative the first side goes against the normal and distance2 along it); start_offset?: expr (along the sketch normal, also with direction: negative); to?: [x,y,z] (To Object: a face, vertex or point; to_offset?: expr past it); from?: [x,y,z] (From Object: start at that face or point); operation?: new|join|cut|intersect|auto (cut into a body, otherwise join existing solids; new in an empty component); touching?: separate|one_body (what a join makes of pieces that share no face: separate, the default, makes each piece that touches another only along an edge or at a point a body of its own and keeps pieces that touch nothing in one body; one_body keeps every piece in one body); targets?: [body] (Join from a face, or from a sketch on a body's face, defaults to that face's body; explicit targets or participants override); name?; body_name?; thin?: true (Thin: a wall along sketch curves instead of the profiles) with curves?: [curve ids] (open chains and closed loops, joined where they meet end to end; default: every drawn curve of the sketch), thickness: expr, side?: center|inside|outside|two_sides (a closed loop's inside is the area it encloses, an open chain's the side it bends toward, a straight line's the left of its first curve as drawn; default center), thickness2?: expr (two_sides: the thickness outside); corners are mitred, crossing walls are one"),
|
||||
.params("distance: expr (or through_all: true); taper?: angle expr (positive: outward, so the far end is larger along the extrusion direction; negative: inward, so the far end is smaller); corner?: preserve_curvature|tangent|round (how a taper closes a sharp corner its offset opens: each wall continues as itself, a line's plane or an arc's cone, until it meets its neighbour; each continues straight along its end tangent; or an arc about the corner. Without it, each profile preserves curvature where every curve is a line or an arc and takes tangent where another curve has a corner, and the feature's warning says so; a corner rule given is kept, and refused where the kernel cannot build it); sketch?: id|name (default: active or last sketch); profiles?: all | [index] | [{curves: [ids]}] (the profile whose outer loop is made of exactly these curves, or pieces of them; found again on every recompute, so it follows parameter changes; islands inside are its holes; an error when no profile or several match) | [{point:[x,y]}] (index and point picks are stored by their curves when that finds the same profile; a pick on a drawn profile that reference geometry, such as the projected outline of the face the sketch is on, cuts into regions takes the whole drawn profile); exact_regions?: bool (each index or point pick is exactly the region it names, as the dialogs send); default: every drawn profile, except that a loop inside another is its hole and a loop inside that hole is material again; face?: [x,y,z] (extrude a planar body face instead of a sketch profile); faces?: [[x,y,z],…] (coplanar faces of one body); face_body?: name (whose face, where faces of several bodies meet at the point); direction?: positive|negative|symmetric (distance is total thickness, split evenly around the start plane); convention?: total_distance|legacy_per_side (how a symmetric distance is read; default total_distance, split evenly around the start plane; legacy_per_side: the distance on each side, as older symmetric extrudes keep); distance2?: expr (Two Sides: a second distance on the side direction leaves free, the first side may be through_all or to; with direction: negative the first side goes against the normal and distance2 along it; a negative distance only turns its own side over); start_offset?: expr (along the sketch normal, also with direction: negative); to?: [x,y,z] (To Object: a face, vertex or point; to_offset?: expr past it); from?: [x,y,z] (From Object: start at that face or point); operation?: new|join|cut|intersect|auto (cut into a body, otherwise join existing solids; new in an empty component); touching?: separate|one_body (what a join makes of pieces that share no face: separate, the default, makes each piece that touches another only along an edge or at a point a body of its own and keeps pieces that touch nothing in one body; one_body keeps every piece in one body); targets?: [body] (Join from a face, or from a sketch on a body's face, defaults to that face's body; explicit targets or participants override); name?; body_name?; thin?: true (Thin: a wall along sketch curves instead of the profiles) with curves?: [curve ids] (open chains and closed loops, joined where they meet end to end; default: every drawn curve of the sketch), thickness: expr, side?: center|inside|outside|two_sides (a closed loop's inside is the area it encloses, an open chain's the side it bends toward, a straight line's the left of its first curve as drawn; default center), thickness2?: expr (two_sides: the thickness outside); corners are mitred, crossing walls are one"),
|
||||
CommandSpec::new("solid.revolve", "Revolve", revolve)
|
||||
.at("SOLID", "CREATE")
|
||||
.icon("revolve")
|
||||
@@ -1269,6 +1269,7 @@ pub(super) fn extent_param(s: &Session, p: &Value, cmd: &str) -> Result<Extent>
|
||||
distance2,
|
||||
start_offset,
|
||||
through_all,
|
||||
second_follows_first: false,
|
||||
taper,
|
||||
corner,
|
||||
to: p.get("to").and_then(vec3).map(FacePick),
|
||||
|
||||
@@ -31,7 +31,7 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.icon("open")
|
||||
.key("Ctrl+O")
|
||||
.noundo()
|
||||
.params("path: .sc design (or a .solidcraft design from an earlier release), .dxf/.svg drawing (opens as a new, unsaved design with an XY sketch, using sketch.insert_dxf/sketch.insert_svg units and defaults), or a .step/.stp/.igs/.fcstd/.3dm/.3mf/.stl/.obj/.glb/.gltf file (STEP, IGES, FreeCAD, Rhino, 3MF, STL, OBJ or glTF; opens as a new design holding the file as a component named after it, as file.insert_step and file.insert_mesh make), or a .ply/.xyz/.pts point cloud (opens as a new design holding it, as pointcloud.insert makes; its `units` and `max_points` as there); up?: z|y for a STEP, IGES, FreeCAD, Rhino or glTF file (see file.insert_step and file.insert_mesh); names?: auto|solid|product|instance for a STEP, IGES, FreeCAD or Rhino file (see file.insert_step); read_only?: bool (a design: saving to its own file is refused, file.save_as keeps the changes elsewhere) → open_elsewhere: {host, user, app, opened} when another SolidCraft has the design open (its lock file is fresh); newer_file: {format, reads_up_to, unknown_changes, not_understood, notice} and warnings when a newer SolidCraft saved it: it opens all the same, and what this version can't read is named there and kept by saving"),
|
||||
.params("path: .sc design (or a .solidcraft design from an earlier release), .dxf/.svg drawing (opens as a new, unsaved design with an XY sketch, using sketch.insert_dxf/sketch.insert_svg units and defaults), or a .step/.stp/.igs/.fcstd/.3dm/.3mf/.stl/.obj/.glb/.gltf file (STEP, IGES, FreeCAD, Rhino, 3MF, STL, OBJ or glTF; opens as a new design holding the file as a component named after it, as file.insert_step and file.insert_mesh make), or a .ply/.xyz/.pts point cloud (opens as a new design holding it, as pointcloud.insert makes; its `units` and `max_points` as there); up?: z|y for a STEP, IGES, FreeCAD, Rhino or glTF file (see file.insert_step and file.insert_mesh); names?: auto|solid|product|instance for a STEP, IGES, FreeCAD or Rhino file (see file.insert_step); units?: for an STL or OBJ file (see file.insert_mesh); read_only?: bool (a design: saving to its own file is refused, file.save_as keeps the changes elsewhere) → open_elsewhere: {host, user, app, opened} when another SolidCraft has the design open (its lock file is fresh); newer_file: {format, reads_up_to, unknown_changes, not_understood, notice} and warnings when a newer SolidCraft saved it: it opens all the same, and what this version can't read is named there and kept by saving"),
|
||||
CommandSpec::new("file.insert_step", "Insert STEP", insert_step)
|
||||
.at("SOLID", "INSERT")
|
||||
.icon("import")
|
||||
@@ -39,7 +39,7 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("file.insert_mesh", "Insert Mesh", insert_mesh)
|
||||
.at("SOLID", "INSERT")
|
||||
.icon("import")
|
||||
.params("path: .3mf, .stl, .obj, .ply (with faces), .glb or .gltf file (its meshes join the design as mesh bodies in a new component named after the file → component, component_name, occurrence; a glTF file's node tree becomes nested components held as one rigid group until component.unlock, a mesh placed again another occurrence, its materials the bodies' appearances, and its metres millimetres); name?; up?: z|y for a glTF file (default y: glTF has Y up, so the import's component is turned a quarter turn about X, Y becoming Z → stand_up: its occurrence; z: the file's axes are kept)"),
|
||||
.params("path: .3mf, .stl, .obj, .ply (with faces), .glb or .gltf file (its meshes join the design as mesh bodies in a new component named after the file → component, component_name, occurrence; a glTF file's node tree becomes nested components held as one rigid group until component.unlock, a mesh placed again another occurrence, its materials the bodies' appearances, and its metres millimetres); name?; up?: z|y for a glTF file (default y: glTF has Y up, so the import's component is turned a quarter turn about X, Y becoming Z → stand_up: its occurrence; z: the file's axes are kept); units?: mm|cm|m|in|ft for an STL or OBJ file, or a PLY file with faces (default mm): the unit its coordinates are in, scaled to millimetres as the file is read (a 3MF or glTF file states its own). The design keeps the millimetre mesh and not the unit, so insert the file again to try another"),
|
||||
CommandSpec::new("file.save", "Save", save)
|
||||
.icon("save")
|
||||
.key("Ctrl+S")
|
||||
@@ -225,7 +225,7 @@ fn created_bodies(s: &Session, feature: u64) -> Vec<String> {
|
||||
/// Add a MeshImport feature for a 3MF, STL, OBJ or glTF file, in a new component named after the
|
||||
/// file. A glTF file's nodes become components in it, and its materials the bodies' looks; it is
|
||||
/// in metres with Y up, so unless `y_up` is false its component is turned to Z up (#1505).
|
||||
fn add_mesh(s: &mut Session, path: &str, name: Option<&str>, y_up: Option<bool>) -> Result<Value> {
|
||||
fn add_mesh(s: &mut Session, path: &str, name: Option<&str>, y_up: Option<bool>, unit: Option<(&'static str, f64)>) -> Result<Value> {
|
||||
let err = |e: solidcraft_io::IoError| EngineError::Other(format!("{path}: {e}"));
|
||||
let bytes = solidcraft_io::vfs::read(path, solidcraft_io::MAX_3MF_BYTES).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
|
||||
let gltf = solidcraft_io::is_gltf_path(path);
|
||||
@@ -239,7 +239,7 @@ fn add_mesh(s: &mut Session, path: &str, name: Option<&str>, y_up: Option<bool>)
|
||||
}
|
||||
(g.feature, Some(g.plan), g.looks)
|
||||
} else {
|
||||
(solidcraft_io::mesh_import_feature(&bytes, path).map_err(err)?, None, Vec::new())
|
||||
(solidcraft_io::mesh_import_feature_in(&bytes, path, unit.map_or(1.0, |(_, mm)| mm)).map_err(err)?, None, Vec::new())
|
||||
};
|
||||
let fname = name.filter(|n| !n.trim().is_empty()).unwrap_or(&mf.name).to_string();
|
||||
let cname = import::component_name(path, name);
|
||||
@@ -262,6 +262,9 @@ fn add_mesh(s: &mut Session, path: &str, name: Option<&str>, y_up: Option<bool>)
|
||||
let fname = s.doc.feature(id).map(|f| f.name.clone()).unwrap_or_default();
|
||||
let mut out = json!({"path": path, "feature": id, "name": fname, "bodies": bodies, "created_bodies": bodies, "warnings": mf.warnings});
|
||||
placed.report(&mut out);
|
||||
if let Some((name, _)) = unit {
|
||||
out["units"] = json!(name);
|
||||
}
|
||||
if let Some(turned) = turned {
|
||||
out["stand_up"] = json!(turned);
|
||||
}
|
||||
@@ -291,6 +294,27 @@ fn mesh_up(p: &Value, path: &str, cmd: &str) -> Result<Option<bool>> {
|
||||
Ok(Some(step_options(p, cmd)?.y_up))
|
||||
}
|
||||
|
||||
/// `units` for an STL, OBJ or PLY file: the unit its coordinates are in (one of
|
||||
/// `solidcraft_doc::point_cloud::UNITS`, the same as a point cloud's), which they are scaled from
|
||||
/// to millimetres as the file is read. The design keeps the millimetre mesh and not the unit, so
|
||||
/// importing again is how a different unit is tried. A 3MF or glTF file states its own.
|
||||
fn mesh_units(p: &Value, path: &str, cmd: &str) -> Result<Option<(&'static str, f64)>> {
|
||||
let names = || solidcraft_doc::point_cloud::UNITS.iter().map(|(n, _)| *n).collect::<Vec<_>>().join(", ");
|
||||
let unit = match p.get("units") {
|
||||
None | Some(Value::Null) => return Ok(None),
|
||||
Some(Value::String(u)) => solidcraft_doc::point_cloud::UNITS
|
||||
.iter()
|
||||
.find(|(name, _)| name.eq_ignore_ascii_case(u))
|
||||
.map(|(name, mm)| (*name, *mm))
|
||||
.ok_or_else(|| bad(cmd, format!("`units` must be one of {} (not `{u}`)", names())))?,
|
||||
Some(_) => return Err(bad(cmd, format!("`units` must be one of {}", names()))),
|
||||
};
|
||||
if solidcraft_io::is_gltf_path(path) || path.to_ascii_lowercase().ends_with(".3mf") {
|
||||
return Err(bad(cmd, "`units` applies to STL, OBJ and PLY files only: a 3MF or glTF file states its own"));
|
||||
}
|
||||
Ok(Some(unit))
|
||||
}
|
||||
|
||||
fn insert_mesh(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cmd = "file.insert_mesh";
|
||||
let path = path_arg(p, cmd)?;
|
||||
@@ -298,7 +322,8 @@ fn insert_mesh(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(cmd, "only 3MF, STL, OBJ, PLY and glTF files (.3mf, .stl, .obj, .ply, .glb, .gltf) can be inserted as meshes"));
|
||||
}
|
||||
let up = mesh_up(p, path, cmd)?;
|
||||
add_mesh(s, path, str_(p, "name"), up)
|
||||
let unit = mesh_units(p, path, cmd)?;
|
||||
add_mesh(s, path, str_(p, "name"), up, unit)
|
||||
}
|
||||
|
||||
fn insert_step(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -375,7 +400,7 @@ fn open(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let r = if solidcraft_io::is_step_path(path) {
|
||||
add_step(&mut fresh, path, None, &step_options(p, "doc.open")?)?
|
||||
} else {
|
||||
add_mesh(&mut fresh, path, None, mesh_up(p, path, "doc.open")?)?
|
||||
add_mesh(&mut fresh, path, None, mesh_up(p, path, "doc.open")?, mesh_units(p, path, "doc.open")?)?
|
||||
};
|
||||
// The design is the file: its component is the one being worked in.
|
||||
if let Some(c) = r["component"].as_u64() {
|
||||
|
||||
@@ -895,11 +895,27 @@ fn kind_param(p: &Value, cmd: &str) -> Result<JointKind> {
|
||||
.ok_or_else(|| bad(cmd, "`type` must be rigid, revolute, slider, cylindrical, pin_slot, planar, ball, parallel, perpendicular, angle, point_on_plane, point_on_line or line_on_plane"))
|
||||
}
|
||||
|
||||
fn new_joint_name(s: &Session, p: &Value) -> String {
|
||||
str_(p, "name").map(str::to_string).unwrap_or_else(|| {
|
||||
fn new_joint_name(s: &Session, p: &Value, kind: JointKind) -> String {
|
||||
str_(p, "name").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string).unwrap_or_else(|| {
|
||||
let label = match kind {
|
||||
JointKind::Rigid => "Rigid",
|
||||
JointKind::Revolute => "Revolute",
|
||||
JointKind::Slider => "Slider",
|
||||
JointKind::Cylindrical => "Cylindrical",
|
||||
JointKind::PinSlot => "Pin_slot",
|
||||
JointKind::Planar => "Planar",
|
||||
JointKind::Ball => "Ball",
|
||||
JointKind::Parallel => "Parallel",
|
||||
JointKind::Perpendicular => "Perpendicular",
|
||||
JointKind::Angle => "Angle",
|
||||
JointKind::PointOnPlane => "Point_on_plane",
|
||||
JointKind::PointOnLine => "Point_on_line",
|
||||
JointKind::LineOnPlane => "Line_on_plane",
|
||||
};
|
||||
let prefix = format!("{label} Joint");
|
||||
let names: std::collections::BTreeSet<_> = s.doc.assembly.joints.iter().map(|j| j.name.as_str()).collect();
|
||||
let number = (1..=s.doc.assembly.joints.len().saturating_add(1)).find(|n| !names.contains(format!("Joint{n}").as_str())).unwrap_or(1);
|
||||
format!("Joint{number}")
|
||||
let number = (1..=s.doc.assembly.joints.len().saturating_add(1)).find(|n| !names.contains(format!("{prefix}{n}").as_str())).unwrap_or(1);
|
||||
format!("{prefix}{number}")
|
||||
})
|
||||
}
|
||||
|
||||
@@ -909,7 +925,7 @@ fn joint(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let a = origin_param(s, p.get("a"), cmd)?;
|
||||
let b = origin_param(s, p.get("b"), cmd)?;
|
||||
let id = s.doc_mut().allocate_id()?;
|
||||
let name = new_joint_name(s, p);
|
||||
let name = new_joint_name(s, p, kind);
|
||||
let offset = match p.get("offset") {
|
||||
Some(v) => value(s, v, false, cmd)?,
|
||||
None => 0.0,
|
||||
@@ -961,7 +977,7 @@ fn as_built(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let fa = side(oa)?;
|
||||
let fb = side(ob)?;
|
||||
let id = s.doc_mut().allocate_id()?;
|
||||
let name = new_joint_name(s, p);
|
||||
let name = new_joint_name(s, p, kind);
|
||||
let n = kind.dofs().len();
|
||||
let j = Joint {
|
||||
id,
|
||||
|
||||
@@ -2719,3 +2719,46 @@ fn driving_an_angle_reports_the_number_a_person_would_read() {
|
||||
let j = s.doc.assembly.joints.iter().find(|j| j.name == "Turn").unwrap();
|
||||
assert_ne!(j.values[0].to_degrees(), 30.0, "the stored angle keeps its bits");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_joints_generate_type_prefixed_names_or_keep_custom_name() {
|
||||
let mut s = two_cubes();
|
||||
let (a, b) = (occ(&s, "A"), occ(&s, "B"));
|
||||
|
||||
// 1. Without name: revolute joint defaults to "Revolute Joint1"
|
||||
let r1 = run(
|
||||
&mut s,
|
||||
"joint.create",
|
||||
json!({
|
||||
"type": "revolute",
|
||||
"a": {"occurrence": a, "face": [5, 5, 10]},
|
||||
"b": {"occurrence": b, "face": [25, 5, 0]}
|
||||
}),
|
||||
);
|
||||
assert_eq!(r1["name"], "Revolute Joint1");
|
||||
|
||||
// 2. Without name: slider joint defaults to "Slider Joint1"
|
||||
let r2 = run(
|
||||
&mut s,
|
||||
"joint.as_built",
|
||||
json!({
|
||||
"type": "slider",
|
||||
"a": "A",
|
||||
"b": "B"
|
||||
}),
|
||||
);
|
||||
assert_eq!(r2["name"], "Slider Joint1");
|
||||
|
||||
// 3. With custom name: preserves custom name exactly
|
||||
let r3 = run(
|
||||
&mut s,
|
||||
"joint.create",
|
||||
json!({
|
||||
"type": "rigid",
|
||||
"name": "CustomRigid",
|
||||
"a": {"occurrence": a, "face": [5, 5, 10]},
|
||||
"b": {"occurrence": b, "face": [25, 5, 0]}
|
||||
}),
|
||||
);
|
||||
assert_eq!(r3["name"], "CustomRigid");
|
||||
}
|
||||
@@ -377,6 +377,7 @@ pub(crate) fn refresh(s: &mut Session) {
|
||||
}
|
||||
if changed {
|
||||
s.model.evaluate(&s.doc);
|
||||
s.evaluations = s.evaluations.saturating_add(1);
|
||||
s.revision += 1;
|
||||
}
|
||||
for t in &traces {
|
||||
|
||||
@@ -52,6 +52,14 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
wire::WorkspaceReply,
|
||||
"workspace, expected_revision?: atomically remember outgoing and replace with destination"
|
||||
),
|
||||
command!(
|
||||
"panel.action",
|
||||
"activate",
|
||||
"Run Panel Header Action",
|
||||
wire::HeaderAction,
|
||||
crate::panels::LayoutReply,
|
||||
"target or legacy id, action, expected_revision?: invoke a registered owning-controller action"
|
||||
),
|
||||
command!(
|
||||
"panel.activate",
|
||||
"activate",
|
||||
@@ -114,7 +122,7 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
"Move Panel",
|
||||
wire::Move,
|
||||
crate::panels::LayoutReply,
|
||||
"target or legacy id, destination: new_section or join_tab, expected_revision?"
|
||||
"target or legacy id, destination: new_section, join_tab or relative, activate?: false, expected_revision?"
|
||||
),
|
||||
command!(
|
||||
"panel.native_close",
|
||||
@@ -162,7 +170,7 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
"Resize Panel Section",
|
||||
wire::Resize,
|
||||
crate::panels::LayoutReply,
|
||||
"target or legacy id, size: {width,height}, expected_revision?"
|
||||
"target or legacy id, size: {width,height}, thickness_only?: false by default; true changes Bottom height or side column width and ignores the other valid size component, expected_revision?"
|
||||
),
|
||||
command!(
|
||||
"panel.resize_pair",
|
||||
|
||||
@@ -401,6 +401,48 @@ fn construction_axis_moved_behind_its_revolve_and_back() {
|
||||
assert!((solidcraft_kernel::measure(&s.model.state().bodies[0].body).unwrap().volume - 60.0 * PI).abs() < 0.05);
|
||||
}
|
||||
|
||||
/// The two vertical sides of one rectangle are different axes. A two-point rectangle numbers
|
||||
/// the max-x side and the min-x side separately; a 120° revolve about each must contain a point
|
||||
/// swept about that side and not the point swept about the other (#7452).
|
||||
#[test]
|
||||
fn rectangle_revolve_about_its_right_edge_differs_from_its_left() {
|
||||
for (axis_x, sample_x) in [(30.0, 10.5), (10.0, 29.5)] {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "sketch.create", json!({"name": "Profile", "plane": "XY"}));
|
||||
run(&mut s, "sketch.rectangle.two_point", json!({"p0": [10, 0], "p1": [30, 10]}));
|
||||
let id = vertical_line(&s, axis_x);
|
||||
run(&mut s, "sketch.finish", json!({}));
|
||||
run(&mut s, "solid.revolve", json!({"sketch": "Profile", "axis": id, "angle": "120 deg", "operation": "new"}));
|
||||
let body = &s.model.state().bodies[0].body;
|
||||
let on_edge = lift_xy(axis_x, sample_x);
|
||||
let on_other = lift_xy(if axis_x > 20.0 { 10.0 } else { 30.0 }, if sample_x < 20.0 { 29.5 } else { 10.5 });
|
||||
assert!(body.classify_point(on_edge).unwrap() == solidcraft_kernel::PointClass::Inside, "axis x={axis_x} ({id}) should contain {on_edge:?}");
|
||||
assert!(
|
||||
body.classify_point(on_other).unwrap() != solidcraft_kernel::PointClass::Inside,
|
||||
"axis x={axis_x} ({id}) should not contain the other edge's probe {on_other:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn vertical_line(s: &Session, x: f64) -> String {
|
||||
let sk = s.doc.sketch(s.active_sketch.expect("sketch")).expect("sketch");
|
||||
sk.curves
|
||||
.iter()
|
||||
.find_map(|c| {
|
||||
let solidcraft_sketch::CurveKind::Line { a, b } = c.kind else { return None };
|
||||
let (pa, pb) = (sk.point(a)?, sk.point(b)?);
|
||||
((pa.x - x).abs() < 1e-9 && (pb.x - x).abs() < 1e-9).then(|| c.id.clone())
|
||||
})
|
||||
.unwrap_or_else(|| panic!("no vertical line at x={x}"))
|
||||
}
|
||||
|
||||
/// `(point_x, 5, 0)` rotated 80° about `x = axis_x` toward +Z, the sketch-normal sense on XY.
|
||||
fn lift_xy(axis_x: f64, point_x: f64) -> Vec3 {
|
||||
let dx = point_x - axis_x;
|
||||
let t = 80.0_f64.to_radians();
|
||||
Vec3::new(axis_x + dx * t.cos(), 5.0, dx.abs() * t.sin())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn construction_axis_revolve_rejects_invalid_axes_atomically() {
|
||||
for (a, b, message) in [
|
||||
|
||||
@@ -16,17 +16,32 @@ use super::sketch::edit;
|
||||
use super::sketch_store;
|
||||
use super::{CommandSpec, in_sketch};
|
||||
use crate::params::{bad, string_list, vec2};
|
||||
use crate::schema::sketch_clipboard::{Copied, CopyParams, CutParams, PasteParams, Pasted};
|
||||
use crate::schema::{TypedContract, output_schema_for};
|
||||
use crate::{Result, Sel, Session};
|
||||
|
||||
const COPY_CONTRACT: TypedContract<CopyParams> = TypedContract::new();
|
||||
const CUT_CONTRACT: TypedContract<CutParams> = TypedContract::new();
|
||||
const PASTE_CONTRACT: TypedContract<PasteParams> = TypedContract::new();
|
||||
|
||||
pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("sketch.copy", "Copy Sketch Entities", copy).icon("copy")
|
||||
CommandSpec::new("sketch.copy", "Copy Sketch Entities", crate::checked!("sketch.copy", copy)).icon("copy")
|
||||
.noundo()
|
||||
.enabled(in_sketch)
|
||||
.contract(©_CONTRACT)
|
||||
.output(output_schema_for::<Copied>)
|
||||
.params("entities?: [curve or point ids] (default: the selected sketch geometry); the constraints and dimensions among them come along"),
|
||||
CommandSpec::new("sketch.cut", "Cut Sketch Entities", cut).icon("cut")
|
||||
CommandSpec::new("sketch.cut", "Cut Sketch Entities", crate::checked!("sketch.cut", cut)).icon("cut")
|
||||
.enabled(in_sketch)
|
||||
.contract(&CUT_CONTRACT)
|
||||
.output(output_schema_for::<Copied>)
|
||||
.params("entities?: [curve or point ids] (default: the selected sketch geometry): copies them as sketch.copy does, then deletes them (one undo step)"),
|
||||
CommandSpec::new("sketch.paste", "Paste Sketch Entities", paste).icon("paste").enabled(in_sketch).params(
|
||||
CommandSpec::new("sketch.paste", "Paste Sketch Entities", crate::checked!("sketch.paste", paste))
|
||||
.icon("paste")
|
||||
.enabled(in_sketch)
|
||||
.contract(&PASTE_CONTRACT)
|
||||
.output(output_schema_for::<Pasted>)
|
||||
.params(
|
||||
"at?: [x, y] (sketch point the copy's centre goes to) | translate?: [x, y]; without either, offset from the original in its own sketch and at the same coordinates in another; sketch?: target (default: the active sketch)",
|
||||
),
|
||||
];
|
||||
@@ -229,15 +244,20 @@ fn copy(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
clip.center = bounds.center();
|
||||
let size = bounds.size();
|
||||
clip.extent = size.x.max(size.y);
|
||||
let out = json!({
|
||||
"curves": clip.curves.len() + texts.iter().map(|t| sk.link_curves(t).len()).sum::<usize>(),
|
||||
"points": clip.lone.len(),
|
||||
"texts": texts.len(),
|
||||
"constraints": clip.constraints.len(),
|
||||
"center": [clip.center.x, clip.center.y],
|
||||
});
|
||||
let out = Copied {
|
||||
curves: clip.curves.len() + texts.iter().map(|t| sk.link_curves(t).len()).sum::<usize>(),
|
||||
points: clip.lone.len(),
|
||||
texts: texts.len(),
|
||||
constraints: clip.constraints.len(),
|
||||
center: [clip.center.x, clip.center.y],
|
||||
param_warnings: Vec::new(),
|
||||
};
|
||||
s.sketch_clipboard = Some(clip);
|
||||
Ok(out)
|
||||
reply(cmd, out)
|
||||
}
|
||||
|
||||
fn reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {
|
||||
serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))
|
||||
}
|
||||
|
||||
fn cut(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -361,7 +381,7 @@ fn paste(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.chain(lone.iter().map(|id| Sel::SketchPoint { id: id.clone() }))
|
||||
.collect();
|
||||
}
|
||||
Ok(json!({"curves": curves, "points": lone, "constraints": constraints, "translate": [t.x, t.y], "sketch": info}))
|
||||
reply(cmd, Pasted { curves, points: lone, constraints, translate: [t.x, t.y], sketch: info, param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
+11
-12
@@ -633,8 +633,7 @@ pub struct Session {
|
||||
/// Record this session's top-level commands in the crash journal (the app's own design;
|
||||
/// never previews or other scratch sessions). See [`crash`].
|
||||
pub crash_journal: bool,
|
||||
/// Full model evaluations (`refresh`), for tests.
|
||||
#[cfg(test)]
|
||||
/// Live-model evaluations after this session's initialization; never serialized.
|
||||
pub(crate) evaluations: usize,
|
||||
/// Resolved associative trace inputs, independent of the document revision and view state.
|
||||
pub(crate) motion_traces: cmd::motion::associative::Cache,
|
||||
@@ -870,7 +869,6 @@ impl Session {
|
||||
camera: None,
|
||||
render_viewport: None,
|
||||
render_jobs: Default::default(),
|
||||
#[cfg(test)]
|
||||
evaluations: 0,
|
||||
motion_traces: Default::default(),
|
||||
command_check: None,
|
||||
@@ -1276,12 +1274,17 @@ impl Session {
|
||||
self.doc.find_component(key).or_else(|| self.doc.occurrences.iter().find(|o| o.name == key).map(|o| o.component)).filter(|id| *id != 0)
|
||||
}
|
||||
|
||||
/// Number of live-model evaluations after this session's initialization.
|
||||
/// Construction, other sessions and trial evaluations of cloned models are
|
||||
/// excluded. This is not a count of all geometry work. Reading the counter
|
||||
/// never evaluates geometry or warms display meshes.
|
||||
pub fn evaluation_count(&self) -> usize {
|
||||
self.evaluations
|
||||
}
|
||||
|
||||
pub fn refresh(&mut self) {
|
||||
if self.model.evaluate_shared(&self.doc) {
|
||||
#[cfg(test)]
|
||||
{
|
||||
self.evaluations += 1;
|
||||
}
|
||||
self.evaluations = self.evaluations.saturating_add(1);
|
||||
}
|
||||
self.revision += 1;
|
||||
self.prune_occurrence_state();
|
||||
@@ -1306,10 +1309,7 @@ impl Session {
|
||||
break;
|
||||
}
|
||||
self.model.evaluate(&self.doc);
|
||||
#[cfg(test)]
|
||||
{
|
||||
self.evaluations += 1;
|
||||
}
|
||||
self.evaluations = self.evaluations.saturating_add(1);
|
||||
}
|
||||
}
|
||||
cmd::motion::associative::refresh(self);
|
||||
@@ -1977,7 +1977,6 @@ impl Session {
|
||||
render_viewport: self.render_viewport.clone(),
|
||||
render_jobs: self.render_jobs.scratch(),
|
||||
saved_visibility: self.saved_visibility.clone(),
|
||||
#[cfg(test)]
|
||||
evaluations: 0,
|
||||
motion_traces: self.motion_traces.clone(),
|
||||
command_check: self.command_check.clone(),
|
||||
|
||||
@@ -245,6 +245,7 @@ pub const IDS: &[&str] = &[
|
||||
"layout.reset",
|
||||
"layout.save",
|
||||
"layout.workspace.select",
|
||||
"panel.action",
|
||||
"panel.activate",
|
||||
"panel.close",
|
||||
"panel.collapse",
|
||||
@@ -267,6 +268,7 @@ pub enum PanelCommand {
|
||||
List,
|
||||
Get,
|
||||
Open(wire::Open),
|
||||
HeaderAction(wire::HeaderAction),
|
||||
Select { operation: &'static str, params: wire::Select },
|
||||
Move { operation: &'static str, params: wire::Move },
|
||||
Resize(wire::Resize),
|
||||
@@ -316,6 +318,7 @@ pub fn parse_command(id: &str, params: &Value) -> PanelResult<PanelCommand> {
|
||||
PanelCommand::Get
|
||||
}
|
||||
"panel.open" => PanelCommand::Open(read(params)?),
|
||||
"panel.action" => PanelCommand::HeaderAction(read(params)?),
|
||||
"panel.close" | "panel.activate" | "panel.focus" | "panel.peek" | "panel.native_close" => {
|
||||
PanelCommand::Select { operation: id, params: read(params)? }
|
||||
}
|
||||
@@ -341,6 +344,7 @@ fn validate_selector(target: &Option<wire::Target>, id: &Option<String>) -> Pane
|
||||
(Some(target), None) => match target {
|
||||
wire::Target::Instance(id) => valid_id(&id.0),
|
||||
wire::Target::Section(id) => valid_id(&id.0),
|
||||
wire::Target::Column(id) => valid_id(&id.0),
|
||||
wire::Target::Workspace(id) => valid_id(&id.0),
|
||||
wire::Target::NativeHost(id) => valid_id(&id.0),
|
||||
},
|
||||
@@ -364,6 +368,18 @@ fn validate_destination(destination: Destination) -> PanelResult<()> {
|
||||
return Err(error(Rule::Bounds, "tab index cap"));
|
||||
}
|
||||
}
|
||||
Destination::Relative { section, placement, new_section, new_column, size } => {
|
||||
valid_id(§ion.0)?;
|
||||
valid_id(&new_section.0)?;
|
||||
size.validate()?;
|
||||
if let Some(column) = &new_column {
|
||||
valid_id(&column.0)?;
|
||||
}
|
||||
let split_column = matches!(placement, RelativePlacement::BeforeColumn | RelativePlacement::AfterColumn);
|
||||
if split_column != new_column.is_some() {
|
||||
return Err(error(Rule::Placement, "new_column required only for relative column placement"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -377,6 +393,10 @@ fn validate_command(command: &PanelCommand) -> PanelResult<()> {
|
||||
}
|
||||
}
|
||||
PanelCommand::Select { params, .. } => validate_selector(¶ms.target, ¶ms.id)?,
|
||||
PanelCommand::HeaderAction(p) => {
|
||||
validate_selector(&p.target, &p.id)?;
|
||||
valid_id(&p.action.0)?;
|
||||
}
|
||||
PanelCommand::Move { params, .. } => {
|
||||
validate_selector(¶ms.target, ¶ms.id)?;
|
||||
validate_destination(params.destination.clone().into())?;
|
||||
@@ -515,7 +535,29 @@ fn lower(command: PanelCommand, state: &LayoutReply, registry: &PanelRegistry, w
|
||||
}
|
||||
PanelCommand::Resize(p) => {
|
||||
revision(p.expected_revision, state)?;
|
||||
Mutation::SetSize { section: section(target(p.target, p.id, layout, registry)?, layout)?, size: p.size.into() }
|
||||
match target(p.target, p.id, layout, registry)? {
|
||||
LayoutTarget::Column(column) => Mutation::SetColumnWidth { column, width: p.size.width },
|
||||
selected => {
|
||||
let section = section(selected, layout)?;
|
||||
if p.thickness_only {
|
||||
let group = layout.section(§ion)?;
|
||||
match &group.location {
|
||||
SectionLocation::Dock { zone: Zone::Bottom } => Mutation::SetBottomHeight { section, height: p.size.height },
|
||||
SectionLocation::Dock { zone: Zone::Left | Zone::Right } => Mutation::SetColumnWidth {
|
||||
column: group.column.clone().ok_or_else(|| error(Rule::Placement, "side section requires a column"))?,
|
||||
width: p.size.width,
|
||||
},
|
||||
_ => return Err(error(Rule::Placement, "thickness-only resize requires a dock target")),
|
||||
}
|
||||
} else {
|
||||
Mutation::SetSize { section, size: p.size.into() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
PanelCommand::HeaderAction(p) => {
|
||||
revision(p.expected_revision, state)?;
|
||||
Mutation::HeaderAction { instance: instance(target(p.target, p.id, layout, registry)?, layout)?, action: p.action }
|
||||
}
|
||||
PanelCommand::Collapse(p) => {
|
||||
revision(p.expected_revision, state)?;
|
||||
@@ -547,9 +589,26 @@ fn current_envelope(catalogue: &CatalogueState, state: &LayoutReply, registry: &
|
||||
}
|
||||
}
|
||||
|
||||
/// Read-only retained projection for reservation capture. Do not force expanded
|
||||
/// v1 writes merely to inspect identities; callers union current live IDs too.
|
||||
pub fn current_envelope_snapshot(catalogue: &dyn LayoutCatalogue, state: &LayoutReply, registry: &PanelRegistry) -> PanelResult<LayoutEnvelope> {
|
||||
match catalogue.state().remembered(&state.layout.workspace) {
|
||||
Some(stored) => stored.project_envelope(registry, &state.layout.workspace),
|
||||
None => Ok(LayoutEnvelope::new(state.layout.clone())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Preserve all opaque sidecars. Reusing an identity with different opaque intent
|
||||
/// is an error, never silently resolved by choosing one preset's value.
|
||||
fn merge_envelopes(current: &LayoutEnvelope, mut next: LayoutEnvelope, registry: &PanelRegistry) -> PanelResult<LayoutEnvelope> {
|
||||
let current_priorities = preparation_context(current)?.extent_priorities;
|
||||
let incoming_priorities = preparation_context(&next)?.extent_priorities;
|
||||
if let Some(raw) = ¤t.recovery_wire {
|
||||
if next.recovery_wire.as_ref().is_some_and(|other| other != raw) {
|
||||
return Err(error(Rule::DuplicateId, "opaque envelope recovery intent collision"));
|
||||
}
|
||||
next.recovery_wire = Some(raw.clone());
|
||||
}
|
||||
next.layout.workspace = current.layout.workspace.clone();
|
||||
for item in ¤t.quarantine {
|
||||
if next.layout.instances.iter().any(|known| known.id == item.instance) {
|
||||
@@ -588,23 +647,51 @@ fn merge_envelopes(current: &LayoutEnvelope, mut next: LayoutEnvelope, registry:
|
||||
}
|
||||
}
|
||||
next.section_order = order;
|
||||
super::persistence::merge_retained_priority_context(&mut next, ¤t_priorities, &incoming_priorities)?;
|
||||
let layout = next.layout.clone();
|
||||
with_live_layout(&next, layout, registry)
|
||||
}
|
||||
|
||||
fn stage_current(
|
||||
context: &mut PanelCommandContext<'_>,
|
||||
state: &LayoutReply,
|
||||
action: &LayoutAction,
|
||||
envelope: &LayoutEnvelope,
|
||||
recovery: Option<Arc<[u8]>>,
|
||||
next: CatalogueState,
|
||||
) -> PanelResult<LayoutReply> {
|
||||
let preparation = preparation_context(envelope)?;
|
||||
stage_current_prepared(context, state, action, envelope, recovery, next, &preparation)
|
||||
}
|
||||
|
||||
fn stage_current_prepared(
|
||||
context: &mut PanelCommandContext<'_>,
|
||||
state: &LayoutReply,
|
||||
action: &LayoutAction,
|
||||
envelope: &LayoutEnvelope,
|
||||
recovery: Option<Arc<[u8]>>,
|
||||
mut next: CatalogueState,
|
||||
) -> PanelResult<(LayoutReply, CatalogueState)> {
|
||||
let projected = context.sink.project(action.clone())?;
|
||||
preparation: &LayoutPreparationContext,
|
||||
) -> PanelResult<LayoutReply> {
|
||||
let source_catalogue = context.catalogue.state().clone();
|
||||
let projected = context.sink.project_in_context(action.clone(), preparation)?;
|
||||
let workspace = match action {
|
||||
LayoutAction::Replace { layout, .. } => &layout.workspace,
|
||||
_ => &state.layout.workspace,
|
||||
};
|
||||
if &projected.workspace != workspace {
|
||||
return Err(error(Rule::Revision, "projected layout changed requested workspace"));
|
||||
}
|
||||
let envelope = with_live_layout(envelope, projected, context.registry)?;
|
||||
let stored = StoredEnvelope::new(&envelope, recovery.as_deref(), context.registry)?;
|
||||
next.remembered.insert(envelope.layout.workspace.clone(), stored);
|
||||
if context.catalogue.state() != &source_catalogue {
|
||||
return Err(error(Rule::Revision, "catalogue changed during layout projection"));
|
||||
}
|
||||
let prepared = context.catalogue.prepare(next)?;
|
||||
if context.catalogue.state() != &source_catalogue {
|
||||
return Err(error(Rule::Revision, "catalogue changed during storage staging"));
|
||||
}
|
||||
// Inspect can change through external adapters between planning and dispatch.
|
||||
// Every action below includes the inspected revision; no stale catalogue publishes.
|
||||
if context.sink.inspect().revision != state.revision {
|
||||
@@ -615,10 +702,45 @@ fn stage_current(
|
||||
revision(Some(state.revision), ¤t)?;
|
||||
current
|
||||
} else {
|
||||
context.sink.dispatch(action.clone())?
|
||||
context.sink.dispatch_in_context(action.clone(), preparation)?
|
||||
};
|
||||
context.catalogue.publish(prepared);
|
||||
Ok((committed, context.catalogue.state().clone()))
|
||||
Ok(committed)
|
||||
}
|
||||
|
||||
/// Current-workspace GUI actions share the command catalogue preflight. The sink
|
||||
/// owns the exact private proposal returned by project and consumed by dispatch.
|
||||
pub fn execute_layout_action(action: LayoutAction, context: &mut PanelCommandContext<'_>) -> PanelResult<LayoutReply> {
|
||||
if let LayoutAction::Apply { mutations, .. } = &action {
|
||||
if mutations.is_empty() || mutations.len() > MAX_MUTATIONS {
|
||||
return Err(error(Rule::CollectionLimit, "transaction requires 1..64 mutations"));
|
||||
}
|
||||
validate_lifecycle_intents(mutations)?;
|
||||
validate_header_action_transaction(mutations)?;
|
||||
if matches!(mutations.first(), Some(Mutation::HeaderAction { .. })) {
|
||||
// Registration, revision, presentation, availability and controller
|
||||
// permission remain authoritative sink responsibilities.
|
||||
return context.sink.dispatch(action);
|
||||
}
|
||||
}
|
||||
let state = context.sink.inspect();
|
||||
let action = match action {
|
||||
LayoutAction::Apply { expected_revision, mutations } => {
|
||||
revision(expected_revision, &state)?;
|
||||
LayoutAction::Apply { expected_revision: Some(state.revision), mutations }
|
||||
}
|
||||
LayoutAction::Replace { expected_revision, layout } => {
|
||||
revision(expected_revision, &state)?;
|
||||
if layout.workspace != state.layout.workspace {
|
||||
return Err(error(Rule::Capability, "workspace replacement requires workspace command"));
|
||||
}
|
||||
LayoutAction::Replace { expected_revision: Some(state.revision), layout }
|
||||
}
|
||||
LayoutAction::Inspect => LayoutAction::Inspect,
|
||||
};
|
||||
let next = context.catalogue.state().clone();
|
||||
let (current, recovery) = current_envelope(&next, &state, context.registry)?;
|
||||
stage_current(context, &state, &action, ¤t, recovery, next)
|
||||
}
|
||||
|
||||
pub fn execute_command(command: PanelCommand, context: &mut PanelCommandContext<'_>) -> PanelResult<Value> {
|
||||
@@ -627,6 +749,13 @@ pub fn execute_command(command: PanelCommand, context: &mut PanelCommandContext<
|
||||
match command {
|
||||
PanelCommand::List => return value(wire::ListReply { state, kinds: context.registry.specs().cloned().collect() }),
|
||||
PanelCommand::Get => return value(wire::GetReply { state, workspaces: context.catalogue.state().summaries() }),
|
||||
command @ PanelCommand::HeaderAction(_) => {
|
||||
let mutation = lower(command, &state, context.registry, context.web)?;
|
||||
return value(execute_layout_action(
|
||||
LayoutAction::Apply { expected_revision: Some(state.revision), mutations: vec![mutation] },
|
||||
context,
|
||||
)?);
|
||||
}
|
||||
PanelCommand::Workspace(ref p) if p.workspace == state.layout.workspace => {
|
||||
revision(p.expected_revision, &state)?;
|
||||
return value(wire::WorkspaceReply {
|
||||
@@ -655,7 +784,7 @@ pub fn execute_command(command: PanelCommand, context: &mut PanelCommandContext<
|
||||
}
|
||||
next.users.insert(name.clone(), StoredEnvelope::new(¤t, recovery.as_deref(), context.registry)?);
|
||||
let action = LayoutAction::Inspect;
|
||||
let (state, _) = stage_current(context, &state, &action, ¤t, recovery, next)?;
|
||||
let state = stage_current(context, &state, &action, ¤t, recovery, next)?;
|
||||
value(wire::SaveReply { name, overwritten, state })
|
||||
}
|
||||
PanelCommand::Apply(p) => {
|
||||
@@ -669,7 +798,7 @@ pub fn execute_command(command: PanelCommand, context: &mut PanelCommandContext<
|
||||
restore_quarantine(&mut envelope, context.registry)?;
|
||||
let recovery = merge_recovery(recovery, stored.rejected.clone())?;
|
||||
let action = LayoutAction::Replace { expected_revision: Some(state.revision), layout: envelope.layout.clone() };
|
||||
value(stage_current(context, &state, &action, &envelope, recovery, next)?.0)
|
||||
value(stage_current(context, &state, &action, &envelope, recovery, next)?)
|
||||
}
|
||||
PanelCommand::Reset(p) => {
|
||||
revision(p.expected_revision, &state)?;
|
||||
@@ -683,7 +812,7 @@ pub fn execute_command(command: PanelCommand, context: &mut PanelCommandContext<
|
||||
restore_quarantine(&mut envelope, context.registry)?;
|
||||
let recovery = merge_recovery(recovery, stored.rejected.clone())?;
|
||||
let action = LayoutAction::Replace { expected_revision: Some(state.revision), layout: envelope.layout.clone() };
|
||||
value(stage_current(context, &state, &action, &envelope, recovery, next)?.0)
|
||||
value(stage_current(context, &state, &action, &envelope, recovery, next)?)
|
||||
}
|
||||
PanelCommand::Workspace(p) => {
|
||||
revision(p.expected_revision, &state)?;
|
||||
@@ -703,13 +832,24 @@ pub fn execute_command(command: PanelCommand, context: &mut PanelCommandContext<
|
||||
let incoming_recovery = stored.rejected.clone();
|
||||
next.remembered.insert(previous_workspace.clone(), StoredEnvelope::new(¤t, recovery.as_deref(), context.registry)?);
|
||||
let action = LayoutAction::Replace { expected_revision: Some(state.revision), layout: envelope.layout.clone() };
|
||||
let (state, _) = stage_current(context, &state, &action, &envelope, incoming_recovery, next)?;
|
||||
let state = stage_current(context, &state, &action, &envelope, incoming_recovery, next)?;
|
||||
value(wire::WorkspaceReply { previous_workspace, source, state })
|
||||
}
|
||||
command => {
|
||||
let activate = matches!(&command, PanelCommand::Move { params, .. } if params.activate);
|
||||
let mutation = lower(command, &state, context.registry, context.web)?;
|
||||
let action = LayoutAction::Apply { expected_revision: Some(state.revision), mutations: vec![mutation] };
|
||||
value(stage_current(context, &state, &action, ¤t, recovery, next)?.0)
|
||||
let activation = if activate {
|
||||
match &mutation {
|
||||
Mutation::Move { instance, .. } => Some(Mutation::Activate { instance: instance.clone() }),
|
||||
_ => None,
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut mutations = vec![mutation];
|
||||
mutations.extend(activation);
|
||||
let action = LayoutAction::Apply { expected_revision: Some(state.revision), mutations };
|
||||
value(stage_current(context, &state, &action, ¤t, recovery, next)?)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -734,6 +874,7 @@ struct PlanningSink<'a> {
|
||||
state: LayoutReply,
|
||||
mutations: Vec<Mutation>,
|
||||
replaced: bool,
|
||||
preparation: LayoutPreparationContext,
|
||||
}
|
||||
impl ActionSink for PlanningSink<'_> {
|
||||
fn inspect(&self) -> LayoutReply {
|
||||
@@ -782,6 +923,44 @@ impl ActionSink for PlanningSink<'_> {
|
||||
self.state.layout = layout;
|
||||
Ok(self.state.clone())
|
||||
}
|
||||
fn project_in_context(&self, action: LayoutAction, context: &LayoutPreparationContext) -> PanelResult<Layout> {
|
||||
match action {
|
||||
LayoutAction::Apply { expected_revision, mutations } => {
|
||||
revision(expected_revision, &self.state)?;
|
||||
if self.replaced {
|
||||
return Err(error(Rule::Capability, "cannot combine replacement and mutations"));
|
||||
}
|
||||
if self.mutations.len().saturating_add(mutations.len()) > MAX_MUTATIONS {
|
||||
return Err(error(Rule::CollectionLimit, "layout batch mutation cap"));
|
||||
}
|
||||
let mut combined = self.mutations.clone();
|
||||
combined.extend(mutations);
|
||||
self.authoritative
|
||||
.project_in_context(LayoutAction::Apply { expected_revision: Some(self.state.revision), mutations: combined }, &self.preparation)
|
||||
}
|
||||
LayoutAction::Replace { expected_revision, layout } => {
|
||||
revision(expected_revision, &self.state)?;
|
||||
if !self.mutations.is_empty() {
|
||||
return Err(error(Rule::Capability, "cannot combine replacement and mutations"));
|
||||
}
|
||||
self.authoritative.project_in_context(LayoutAction::Replace { expected_revision: Some(self.state.revision), layout }, context)
|
||||
}
|
||||
LayoutAction::Inspect => Ok(self.state.layout.clone()),
|
||||
}
|
||||
}
|
||||
fn dispatch_in_context(&mut self, action: LayoutAction, context: &LayoutPreparationContext) -> PanelResult<LayoutReply> {
|
||||
let layout = self.project_in_context(action.clone(), context)?;
|
||||
match action {
|
||||
LayoutAction::Apply { mutations, .. } => self.mutations.extend(mutations),
|
||||
LayoutAction::Replace { .. } => {
|
||||
self.replaced = true;
|
||||
self.state.interaction = InteractionState::default();
|
||||
}
|
||||
LayoutAction::Inspect => {}
|
||||
}
|
||||
self.state.layout = layout;
|
||||
Ok(self.state.clone())
|
||||
}
|
||||
}
|
||||
|
||||
/// Pure structural preflight, usable before application context publication.
|
||||
@@ -793,12 +972,14 @@ pub fn preflight_batch(steps: &[Value], workspace: &WorkspaceId) -> PanelResult<
|
||||
let mut selected = workspace.clone();
|
||||
let mut replacement = false;
|
||||
let mut mutation = false;
|
||||
let mut header_action = false;
|
||||
for step in steps {
|
||||
let id =
|
||||
step.get("command").or_else(|| step.get("id")).and_then(Value::as_str).ok_or_else(|| error(Rule::Schema, "batch command required"))?;
|
||||
let empty = json!({});
|
||||
match parse_command(id, step.get("params").unwrap_or(&empty))? {
|
||||
PanelCommand::List | PanelCommand::Get | PanelCommand::Save(_) => {}
|
||||
PanelCommand::HeaderAction(_) => header_action = true,
|
||||
PanelCommand::Apply(_) | PanelCommand::Reset(_) => replacement = true,
|
||||
PanelCommand::Workspace(params) => {
|
||||
replacement |= params.workspace != selected;
|
||||
@@ -807,6 +988,9 @@ pub fn preflight_batch(steps: &[Value], workspace: &WorkspaceId) -> PanelResult<
|
||||
_ => mutation = true,
|
||||
}
|
||||
}
|
||||
if header_action && steps.len() != 1 {
|
||||
return Err(error(Rule::Capability, "header actions require a standalone transaction"));
|
||||
}
|
||||
if replacement && mutation {
|
||||
return Err(error(Rule::Capability, "atomic batches cannot combine snapshot replacement and explicit panel mutations; use rollback:false"));
|
||||
}
|
||||
@@ -821,8 +1005,25 @@ pub fn execute_batch(steps: &[Value], context: &mut PanelCommandContext<'_>) ->
|
||||
}
|
||||
let state = context.sink.inspect();
|
||||
preflight_batch(steps, &state.layout.workspace)?;
|
||||
if let Some(step) = steps.first() {
|
||||
let id =
|
||||
step.get("command").or_else(|| step.get("id")).and_then(Value::as_str).ok_or_else(|| error(Rule::Schema, "batch command required"))?;
|
||||
let empty = json!({});
|
||||
let command = parse_command(id, step.get("params").unwrap_or(&empty))?;
|
||||
if matches!(&command, PanelCommand::HeaderAction(_)) {
|
||||
let result = execute_command(command, context)?;
|
||||
return Ok(json!({"completed":1,"results":[result],"undone":0}));
|
||||
}
|
||||
}
|
||||
let mut planned = InMemoryCatalogue { state: context.catalogue.state().clone(), fail_stage: false };
|
||||
let mut sink = PlanningSink { authoritative: &*context.sink, state: state.clone(), mutations: Vec::new(), replaced: false };
|
||||
let preparation = preparation_context(¤t_envelope_snapshot(&*context.catalogue, &state, context.registry)?)?;
|
||||
let mut sink = PlanningSink {
|
||||
authoritative: &*context.sink,
|
||||
state: state.clone(),
|
||||
mutations: Vec::new(),
|
||||
replaced: false,
|
||||
preparation: preparation.clone(),
|
||||
};
|
||||
let mut rows = Vec::new();
|
||||
for step in steps {
|
||||
let id =
|
||||
@@ -849,7 +1050,8 @@ pub fn execute_batch(steps: &[Value], context: &mut PanelCommandContext<'_>) ->
|
||||
drop(sink);
|
||||
let committed = if changed {
|
||||
let (envelope, recovery) = current_envelope(&planned.state, &planned_state, context.registry)?;
|
||||
stage_current(context, &state, &action, &envelope, recovery, planned.state)?.0
|
||||
let final_context = if matches!(&action, LayoutAction::Apply { .. }) { preparation } else { preparation_context(&envelope)? };
|
||||
stage_current_prepared(context, &state, &action, &envelope, recovery, planned.state, &final_context)?
|
||||
} else {
|
||||
context.sink.inspect()
|
||||
};
|
||||
@@ -897,6 +1099,33 @@ pub struct InMemoryPanelBackend {
|
||||
/// native flags cannot make this adapter claim that it opened an OS window.
|
||||
struct HeadlessSink<'a>(&'a mut LayoutService);
|
||||
impl ActionSink for HeadlessSink<'_> {
|
||||
fn project_in_context(&self, action: LayoutAction, context: &LayoutPreparationContext) -> PanelResult<Layout> {
|
||||
let availability = if matches!(&action, LayoutAction::Replace { .. }) { AvailabilityMap::new() } else { self.0.inspect().availability };
|
||||
let prepared = self.0.prepare_with_context(action, &availability, context)?;
|
||||
if prepared
|
||||
.effects()
|
||||
.iter()
|
||||
.any(|effect| matches!(effect, HostEffect::CreateNative { .. } | HostEffect::RebindNative { .. } | HostEffect::HeaderAction { .. }))
|
||||
{
|
||||
return Err(error(Rule::Capability, "headless cannot realize native or controller actions"));
|
||||
}
|
||||
Ok(prepared.layout().clone())
|
||||
}
|
||||
fn dispatch_in_context(&mut self, action: LayoutAction, context: &LayoutPreparationContext) -> PanelResult<LayoutReply> {
|
||||
let availability = if matches!(&action, LayoutAction::Replace { .. }) { AvailabilityMap::new() } else { self.0.inspect().availability };
|
||||
let prepared = self.0.prepare_with_context(action, &availability, context)?;
|
||||
if prepared
|
||||
.effects()
|
||||
.iter()
|
||||
.any(|effect| matches!(effect, HostEffect::CreateNative { .. } | HostEffect::RebindNative { .. } | HostEffect::HeaderAction { .. }))
|
||||
{
|
||||
return Err(error(Rule::Capability, "headless cannot realize native or controller actions"));
|
||||
}
|
||||
let mut reply = self.0.commit(prepared)?;
|
||||
reply.capabilities.native_windows = false;
|
||||
reply.capabilities.max_native_hosts = 0;
|
||||
Ok(reply)
|
||||
}
|
||||
fn inspect(&self) -> LayoutReply {
|
||||
let mut state = self.0.inspect();
|
||||
state.capabilities.native_windows = false;
|
||||
@@ -908,6 +1137,9 @@ impl ActionSink for HeadlessSink<'_> {
|
||||
if prepared.effects().iter().any(|effect| matches!(effect, HostEffect::CreateNative { .. } | HostEffect::RebindNative { .. })) {
|
||||
return Err(error(Rule::Capability, "headless has no native host adapter"));
|
||||
}
|
||||
if prepared.effects().iter().any(|effect| matches!(effect, HostEffect::HeaderAction { .. })) {
|
||||
return Err(error(Rule::Capability, "headless has no owning panel action controller"));
|
||||
}
|
||||
Ok(prepared.layout().clone())
|
||||
}
|
||||
fn dispatch(&mut self, action: LayoutAction) -> PanelResult<LayoutReply> {
|
||||
|
||||
@@ -19,7 +19,7 @@ pub fn synthetic_registry() -> PanelResult<PanelRegistry> {
|
||||
registry.register(PanelSpec {
|
||||
kind: PanelKind::new(kind)?,
|
||||
title_key: "ui.panel".into(),
|
||||
icon: "panel".into(),
|
||||
icon: "list".into(),
|
||||
allowed_zones,
|
||||
default_zone: Zone::Left,
|
||||
min_size: Size { width: 160.0, height: 120.0 },
|
||||
@@ -28,6 +28,9 @@ pub fn synthetic_registry() -> PanelResult<PanelRegistry> {
|
||||
edge_rule: if pinned { EdgeRule::PinOuter } else { EdgeRule::None },
|
||||
surface: PanelSurface::FollowZone,
|
||||
features: PanelFeatures { multi_instance: multi, ..PanelFeatures::default() },
|
||||
side_height_policy: SideHeightPolicy::Content,
|
||||
header_actions: Vec::new(),
|
||||
text_heavy: false,
|
||||
})?;
|
||||
}
|
||||
Ok(registry)
|
||||
|
||||
@@ -78,20 +78,21 @@ impl Direction {
|
||||
}
|
||||
|
||||
/// Usable logical units: egui applies scale exactly once, outside this contract.
|
||||
/// Free/native flow starts at aspect 1, switches Tall->Wide above 1.1, Wide->Tall
|
||||
/// below 0.9, and retains the previous flow inside that band.
|
||||
pub fn responsive(zone: Zone, usable: Size, previous: Option<Flow>) -> PanelResult<(Flow, SizeClass)> {
|
||||
/// Free/native flow follows the assigned logical aspect. The previous argument
|
||||
/// remains for source compatibility; a stretched parent never determines flow.
|
||||
pub fn responsive(zone: Zone, usable: Size, _previous: Option<Flow>) -> PanelResult<(Flow, SizeClass)> {
|
||||
usable.validate()?;
|
||||
let aspect = usable.width / usable.height;
|
||||
let flow = match zone {
|
||||
Zone::Left | Zone::Right => Flow::Tall,
|
||||
Zone::Bottom => Flow::Wide,
|
||||
Zone::Floating | Zone::Window => match previous {
|
||||
Some(Flow::Tall) if aspect <= 1.1 => Flow::Tall,
|
||||
Some(Flow::Wide) if aspect >= 0.9 => Flow::Wide,
|
||||
_ if aspect >= 1.0 => Flow::Wide,
|
||||
_ => Flow::Tall,
|
||||
},
|
||||
Zone::Floating | Zone::Window => {
|
||||
if aspect >= 1.0 {
|
||||
Flow::Wide
|
||||
} else {
|
||||
Flow::Tall
|
||||
}
|
||||
}
|
||||
};
|
||||
let shorter = usable.width.min(usable.height);
|
||||
let class = if shorter < 240.0 {
|
||||
@@ -144,7 +145,7 @@ pub struct ResolvedPanel {
|
||||
pub section: SectionId,
|
||||
pub zone: Zone,
|
||||
pub outer: LogicalRect,
|
||||
pub body: LogicalRect,
|
||||
pub body: Option<LogicalRect>,
|
||||
pub painted: Vec<LogicalRect>,
|
||||
pub input: Vec<InputRegion>,
|
||||
}
|
||||
@@ -153,11 +154,13 @@ impl ResolvedPanel {
|
||||
valid_id(&self.instance.0)?;
|
||||
valid_id(&self.section.0)?;
|
||||
self.outer.validate()?;
|
||||
self.body.validate()?;
|
||||
if !self.outer.contains_rect(self.body) {
|
||||
return Err(error(Rule::Bounds, "usable body outside outer host"));
|
||||
if let Some(body) = self.body {
|
||||
body.validate()?;
|
||||
if !self.outer.contains_rect(body) {
|
||||
return Err(error(Rule::Bounds, "usable body outside outer host"));
|
||||
}
|
||||
}
|
||||
if self.painted.is_empty() || self.painted.len() > MAX_TABS || self.input.len() > MAX_INSTANCES {
|
||||
if self.painted.len() > MAX_TABS || self.input.len() > MAX_INSTANCES {
|
||||
return Err(error(Rule::CollectionLimit, "resolved region count"));
|
||||
}
|
||||
for rect in &self.painted {
|
||||
@@ -235,134 +238,632 @@ impl ResolvedLayout {
|
||||
}
|
||||
}
|
||||
|
||||
/// Reference geometry for synthetic mounts. Production docking owns its richer
|
||||
/// resolver; both return the same meaningful geometry contract. No layout writes.
|
||||
/// Width-dependent, side-effect-free measurement request. Heights include all
|
||||
/// shared chrome, body, footer, padding and spacing at this exact assigned width.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ContentMeasureRequest {
|
||||
pub instance: InstanceId,
|
||||
pub width: f32,
|
||||
pub chrome_height: f32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct SideContentMeasure {
|
||||
pub request: ContentMeasureRequest,
|
||||
pub needed_height: f32,
|
||||
pub policy: SideHeightPolicy,
|
||||
}
|
||||
|
||||
/// Immutable input to the allocator. Availability and measurements are captured
|
||||
/// by the adapter; allocation never calls content or changes layout preferences.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct AllocationEnvironment {
|
||||
pub capacity: LogicalRect,
|
||||
pub direction: Direction,
|
||||
pub header_height: f32,
|
||||
pub footer_height: f32,
|
||||
pub gap: f32,
|
||||
pub inline_max_height: f32,
|
||||
pub min_viewport: Size,
|
||||
pub scroll: Point,
|
||||
pub available: Vec<InstanceId>,
|
||||
pub content: Vec<SideContentMeasure>,
|
||||
pub content_revision: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct AllocatedSection {
|
||||
pub section: SectionId,
|
||||
pub instance: InstanceId,
|
||||
pub outer: LogicalRect,
|
||||
pub collapsed: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct AllocatedGeometry {
|
||||
pub sections: Vec<AllocatedSection>,
|
||||
pub extent: Size,
|
||||
pub scroll: Point,
|
||||
}
|
||||
|
||||
impl AllocationEnvironment {
|
||||
pub fn validate(&self) -> PanelResult<()> {
|
||||
validate_allocation_capacity(self.capacity)?;
|
||||
self.scroll.validate()?;
|
||||
self.min_viewport.validate()?;
|
||||
if self.scroll.x < 0.0 || self.scroll.y < 0.0 {
|
||||
return Err(error(Rule::Bounds, "negative panel scroll"));
|
||||
}
|
||||
for value in [self.header_height, self.footer_height, self.gap] {
|
||||
if !value.is_finite() || !(0.0..=256.0).contains(&value) {
|
||||
return Err(error(Rule::Bounds, "invalid allocation chrome"));
|
||||
}
|
||||
}
|
||||
if self.header_height <= 0.0 {
|
||||
return Err(error(Rule::Bounds, "header height must be positive"));
|
||||
}
|
||||
if self.available.len() > MAX_INSTANCES || self.content.len() > MAX_INSTANCES {
|
||||
return Err(error(Rule::CollectionLimit, "allocation environment bound"));
|
||||
}
|
||||
if !self.inline_max_height.is_finite() || !(0.0..=88.0).contains(&self.inline_max_height) {
|
||||
return Err(error(Rule::Bounds, "invalid inline allocation threshold"));
|
||||
}
|
||||
let mut available = std::collections::BTreeSet::new();
|
||||
for id in &self.available {
|
||||
valid_id(&id.0)?;
|
||||
if !available.insert(id) {
|
||||
return Err(error(Rule::DuplicateId, "duplicate availability"));
|
||||
}
|
||||
}
|
||||
let mut measures = std::collections::BTreeSet::new();
|
||||
for measure in &self.content {
|
||||
valid_id(&measure.request.instance.0)?;
|
||||
if !measure.request.width.is_finite()
|
||||
|| measure.request.width <= 0.0
|
||||
|| measure.request.width > MAX_LOGICAL
|
||||
|| !measure.request.chrome_height.is_finite()
|
||||
|| measure.request.chrome_height < 0.0
|
||||
|| !measure.needed_height.is_finite()
|
||||
|| measure.needed_height < measure.request.chrome_height
|
||||
|| measure.needed_height > MAX_LOGICAL
|
||||
{
|
||||
return Err(error(Rule::Bounds, "invalid intrinsic content measure"));
|
||||
}
|
||||
if !measures.insert((&measure.request.instance, measure.request.width.to_bits(), measure.request.chrome_height.to_bits())) {
|
||||
return Err(error(Rule::DuplicateId, "duplicate content measure"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Capacity may be empty, unlike a positive panel/body rectangle.
|
||||
pub fn validate_allocation_capacity(bounds: LogicalRect) -> PanelResult<()> {
|
||||
bounds.origin.validate()?;
|
||||
if !bounds.size.width.is_finite()
|
||||
|| !bounds.size.height.is_finite()
|
||||
|| bounds.size.width < 0.0
|
||||
|| bounds.size.height < 0.0
|
||||
|| bounds.size.width > MAX_LOGICAL
|
||||
|| bounds.size.height > MAX_LOGICAL
|
||||
|| (bounds.origin.x + bounds.size.width).abs() > MAX_LOGICAL
|
||||
|| (bounds.origin.y + bounds.size.height).abs() > MAX_LOGICAL
|
||||
{
|
||||
return Err(error(Rule::Bounds, "invalid allocation capacity"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct AxisLimit {
|
||||
min: f32,
|
||||
max: f32,
|
||||
weight: f32,
|
||||
preferred: Option<f32>,
|
||||
priority: u16,
|
||||
}
|
||||
|
||||
/// Bounded water filling starts at minima, redistributes only available surplus,
|
||||
/// and leaves a real gap when every member reaches its maximum.
|
||||
fn distribute(items: &[AxisLimit], available: f32) -> Vec<f32> {
|
||||
let mut sizes: Vec<_> = items.iter().map(|item| item.min).collect();
|
||||
let mut remaining = (f64::from(available) - sizes.iter().map(|v| f64::from(*v)).sum::<f64>()).max(0.0);
|
||||
let tiers: std::collections::BTreeSet<_> = items.iter().filter(|item| item.preferred.is_some()).map(|item| item.priority).collect();
|
||||
for tier in tiers.iter().rev() {
|
||||
let requested: f64 = items
|
||||
.iter()
|
||||
.filter(|item| item.priority == *tier)
|
||||
.map(|item| item.preferred.map_or(0.0, |wanted| f64::from(wanted.clamp(item.min, item.max)) - f64::from(item.min)))
|
||||
.sum();
|
||||
let factor = if requested > 0.0 { (remaining / requested).min(1.0) } else { 0.0 };
|
||||
for (item, size) in items.iter().zip(&mut sizes) {
|
||||
if item.priority == *tier
|
||||
&& let Some(wanted) = item.preferred
|
||||
{
|
||||
let increment = (f64::from(wanted.clamp(item.min, item.max)) - f64::from(item.min)) * factor;
|
||||
let mut next = (f64::from(*size) + increment) as f32;
|
||||
if f64::from(next) > f64::from(*size) + increment {
|
||||
next = f32::from_bits(next.to_bits().saturating_sub(1));
|
||||
}
|
||||
remaining = (remaining - (f64::from(next) - f64::from(*size))).max(0.0);
|
||||
*size = next;
|
||||
}
|
||||
}
|
||||
// This tier exhausted the mathematical budget. Inward f32 rounding
|
||||
// leaves real uncovered space, never priority for a lower tier/weight.
|
||||
if factor < 1.0 && requested > 0.0 {
|
||||
return sizes;
|
||||
}
|
||||
}
|
||||
for _ in 0..items.len() {
|
||||
let total: f64 = items
|
||||
.iter()
|
||||
.zip(&sizes)
|
||||
.filter(|(item, size)| item.preferred.is_none() && item.max > **size && item.weight > 0.0)
|
||||
.map(|(item, _)| f64::from(item.weight))
|
||||
.sum();
|
||||
if remaining <= 0.0 || total <= 0.0 {
|
||||
break;
|
||||
}
|
||||
let mut consumed = 0.0;
|
||||
for (item, size) in items.iter().zip(&mut sizes) {
|
||||
if item.preferred.is_none() && item.max > *size && item.weight > 0.0 {
|
||||
let increment = (remaining * f64::from(item.weight) / total).min(f64::from(item.max) - f64::from(*size));
|
||||
let mut next = (f64::from(*size) + increment) as f32;
|
||||
// Round surplus inward: a collection of f32 round-ups must not
|
||||
// advertise a capacity fit which actually crosses its boundary.
|
||||
if f64::from(next) > f64::from(*size) + increment {
|
||||
next = f32::from_bits(next.to_bits().saturating_sub(1));
|
||||
}
|
||||
consumed += f64::from(next) - f64::from(*size);
|
||||
*size = next.min(item.max);
|
||||
}
|
||||
}
|
||||
if consumed <= 0.0 {
|
||||
break;
|
||||
}
|
||||
remaining = (remaining - consumed).max(0.0);
|
||||
}
|
||||
sizes
|
||||
}
|
||||
|
||||
/// Deterministic presentation identity, without changing remembered activation.
|
||||
pub fn presented_instance<'a>(section: &'a Section, available: &[InstanceId]) -> Option<&'a InstanceId> {
|
||||
if section.tabs.is_empty() || section.tabs.len() > MAX_TABS || available.len() > MAX_INSTANCES {
|
||||
return None;
|
||||
}
|
||||
if section.tabs.contains(§ion.active) && available.contains(§ion.active) {
|
||||
Some(§ion.active)
|
||||
} else {
|
||||
section.tabs.iter().find(|id| available.contains(id))
|
||||
}
|
||||
}
|
||||
|
||||
fn presented<'a>(section: &'a Section, env: &AllocationEnvironment) -> Option<&'a InstanceId> {
|
||||
presented_instance(section, &env.available)
|
||||
}
|
||||
|
||||
struct AllocationColumn<'a> {
|
||||
column: &'a Column,
|
||||
members: Vec<&'a Section>,
|
||||
width: f32,
|
||||
}
|
||||
|
||||
fn allocation_columns<'a>(layout: &'a Layout, registry: &PanelRegistry, env: &AllocationEnvironment) -> PanelResult<Vec<AllocationColumn<'a>>> {
|
||||
let mut columns = Vec::new();
|
||||
let mut limits = Vec::new();
|
||||
for zone in [Zone::Left, Zone::Right] {
|
||||
for column in layout.columns.iter().filter(|column| column.zone == zone) {
|
||||
let members: Vec<_> =
|
||||
layout.sections.iter().filter(|section| section.column.as_ref() == Some(&column.id) && presented(section, env).is_some()).collect();
|
||||
if members.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// Unavailable members still constrain widths, just like inactive tabs.
|
||||
let (min, max) = column_bounds(layout, registry, &column.id)?;
|
||||
let preferred = column.width.clamp(min, max);
|
||||
limits.push(AxisLimit { min, max: preferred, weight: (preferred - min).max(0.001), preferred: None, priority: 0 });
|
||||
columns.push(AllocationColumn { column, members, width: 0.0 });
|
||||
}
|
||||
}
|
||||
let gaps = env.gap * columns.len().saturating_sub(1) as f32;
|
||||
for (column, width) in columns.iter_mut().zip(distribute(&limits, (env.capacity.size.width - gaps).max(0.0))) {
|
||||
column.width = width;
|
||||
}
|
||||
Ok(columns)
|
||||
}
|
||||
|
||||
pub fn allocation_measure_requests(
|
||||
layout: &Layout,
|
||||
registry: &PanelRegistry,
|
||||
env: &AllocationEnvironment,
|
||||
) -> PanelResult<Vec<ContentMeasureRequest>> {
|
||||
validate(layout, registry)?;
|
||||
env.validate()?;
|
||||
let mut requests = Vec::new();
|
||||
for column in allocation_columns(layout, registry, env)? {
|
||||
if let Some(section) = column.members.first().filter(|_| column.members.len() == 1)
|
||||
&& !section.collapsed
|
||||
&& let Some(instance) = presented(section, env)
|
||||
{
|
||||
requests.push(ContentMeasureRequest {
|
||||
instance: instance.clone(),
|
||||
width: column.width,
|
||||
chrome_height: env.header_height + env.footer_height,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(requests)
|
||||
}
|
||||
|
||||
fn section_height_limit(layout: &Layout, registry: &PanelRegistry, section: &Section, env: &AllocationEnvironment) -> PanelResult<AxisLimit> {
|
||||
if section.collapsed {
|
||||
return Ok(AxisLimit { min: env.header_height, max: env.header_height, weight: 0.0, preferred: None, priority: 0 });
|
||||
}
|
||||
let (min, max) = tab_bounds(layout, registry, section)?;
|
||||
let free_width = section.size.width.min(env.capacity.size.width).clamp(min.width, max.width);
|
||||
let free_height = section.size.height.min(env.capacity.size.height).clamp(min.height, max.height);
|
||||
let inline = (section.location.zone() == Zone::Bottom && section.size.height <= env.inline_max_height)
|
||||
|| (matches!(section.location.zone(), Zone::Floating | Zone::Window) && free_height <= env.inline_max_height && free_width >= free_height);
|
||||
let chrome = if inline { env.header_height } else { env.header_height + env.footer_height };
|
||||
let min = min.height.max(chrome);
|
||||
if min > max.height {
|
||||
return Err(error(Rule::IncompatibleTabs, "chrome exceeds composite height"));
|
||||
}
|
||||
Ok(AxisLimit {
|
||||
min,
|
||||
max: max.height,
|
||||
weight: section.weight,
|
||||
preferred: if section.location.zone().side() { section.preferred_extent } else { None },
|
||||
priority: section.extent_priority,
|
||||
})
|
||||
}
|
||||
|
||||
fn measure_for<'a>(env: &'a AllocationEnvironment, request: &ContentMeasureRequest) -> PanelResult<&'a SideContentMeasure> {
|
||||
env.content
|
||||
.iter()
|
||||
.find(|measure| measure.request == *request)
|
||||
.ok_or_else(|| error(Rule::Revision, "missing or stale assigned-width content metrics"))
|
||||
}
|
||||
|
||||
/// The exact bounds used for allocation and host command/gesture admission.
|
||||
pub fn effective_allocation_bounds(
|
||||
layout: &Layout,
|
||||
registry: &PanelRegistry,
|
||||
section: &Section,
|
||||
env: &AllocationEnvironment,
|
||||
) -> PanelResult<(Size, Size)> {
|
||||
env.validate()?;
|
||||
if layout.section(§ion.id)? != section {
|
||||
return Err(error(Rule::Revision, "allocation section became stale"));
|
||||
}
|
||||
let (mut min, mut max) = tab_bounds(layout, registry, section)?;
|
||||
if let Some(column) = §ion.column {
|
||||
let (low, high) = column_bounds(layout, registry, column)?;
|
||||
min.width = low;
|
||||
max.width = high;
|
||||
}
|
||||
let height = section_height_limit(layout, registry, section, env)?;
|
||||
min.height = height.min;
|
||||
max.height = height.max;
|
||||
if section.location.zone().side() && !section.collapsed {
|
||||
let count = layout.sections.iter().filter(|member| member.column == section.column && presented(member, env).is_some()).count();
|
||||
if count == 1
|
||||
&& let Some(instance) = presented(section, env)
|
||||
{
|
||||
let width = allocation_columns(layout, registry, env)?
|
||||
.iter()
|
||||
.find(|column| Some(&column.column.id) == section.column.as_ref())
|
||||
.map(|column| column.width)
|
||||
.ok_or_else(|| error(Rule::MissingTarget, "presented column missing"))?;
|
||||
let request = ContentMeasureRequest { instance: instance.clone(), width, chrome_height: env.header_height + env.footer_height };
|
||||
let measure = measure_for(env, &request)?;
|
||||
if measure.policy == SideHeightPolicy::Content {
|
||||
max.height = measure.needed_height.clamp(min.height, max.height);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok((min, max))
|
||||
}
|
||||
|
||||
/// Closest feasible shared Bottom thickness using proposed presentation bounds.
|
||||
/// Both regimes delegate chrome/composite constraints to the same allocator.
|
||||
pub fn bottom_resize_height(layout: &Layout, registry: &PanelRegistry, env: &AllocationEnvironment, requested: f32) -> PanelResult<f32> {
|
||||
validate(layout, registry)?;
|
||||
env.validate()?;
|
||||
if !requested.is_finite() {
|
||||
return Err(error(Rule::Bounds, "nonfinite Bottom thickness"));
|
||||
}
|
||||
let (registered_min, registered_max) = bottom_height_bounds(layout, registry)?;
|
||||
let expanded_min = f32::from_bits(env.inline_max_height.to_bits().saturating_add(1));
|
||||
let regions = [(registered_min, registered_max.min(env.inline_max_height)), (registered_min.max(expanded_min), registered_max)];
|
||||
let mut proposed = layout.clone();
|
||||
let mut best: Option<f32> = None;
|
||||
for (mut low, mut high) in regions {
|
||||
if low > high {
|
||||
continue;
|
||||
}
|
||||
let probe = requested.clamp(low, high);
|
||||
for section in &mut proposed.sections {
|
||||
if section.location.zone() == Zone::Bottom {
|
||||
section.size.height = probe;
|
||||
}
|
||||
}
|
||||
let mut compatible = true;
|
||||
for section in proposed
|
||||
.sections
|
||||
.iter()
|
||||
.filter(|section| section.location.zone() == Zone::Bottom && !section.collapsed && presented(section, env).is_some())
|
||||
{
|
||||
match effective_allocation_bounds(&proposed, registry, section, env) {
|
||||
Ok((min, max)) => {
|
||||
low = low.max(min.height);
|
||||
high = high.min(max.height);
|
||||
}
|
||||
Err(failure) if failure.rule == Rule::IncompatibleTabs => {
|
||||
compatible = false;
|
||||
break;
|
||||
}
|
||||
Err(failure) => return Err(failure),
|
||||
}
|
||||
}
|
||||
if !compatible || low > high {
|
||||
continue;
|
||||
}
|
||||
let next = requested.clamp(low, high);
|
||||
if best.is_none_or(|old| (f64::from(next) - f64::from(requested)).abs() < (f64::from(old) - f64::from(requested)).abs()) {
|
||||
best = Some(next);
|
||||
}
|
||||
}
|
||||
best.ok_or_else(|| error(Rule::IncompatibleTabs, "Bottom row has no feasible proposed thickness"))
|
||||
}
|
||||
|
||||
/// Authoritative allocation for committed presentation and every proposal.
|
||||
/// Extent is independent of clipping. Right and Bottom anchor to that extent,
|
||||
/// so minima remain nonoverlapping even in an empty/tiny visible capacity.
|
||||
pub fn allocate_layout(layout: &Layout, registry: &PanelRegistry, env: &AllocationEnvironment) -> PanelResult<AllocatedGeometry> {
|
||||
validate(layout, registry)?;
|
||||
env.validate()?;
|
||||
let columns = allocation_columns(layout, registry, env)?;
|
||||
let bottoms: Vec<_> =
|
||||
layout.sections.iter().filter(|section| section.location.zone() == Zone::Bottom && presented(section, env).is_some()).collect();
|
||||
let mut bottom_height = 0.0_f32;
|
||||
let mut bottom_limits = Vec::new();
|
||||
for section in &bottoms {
|
||||
let (min, max) = tab_bounds(layout, registry, section)?;
|
||||
let h = section_height_limit(layout, registry, section, env)?;
|
||||
bottom_height = bottom_height.max(section.size.height.clamp(h.min, h.max));
|
||||
bottom_limits.push(AxisLimit {
|
||||
min: min.width,
|
||||
max: max.width,
|
||||
weight: section.weight,
|
||||
preferred: if section.collapsed { None } else { section.preferred_extent },
|
||||
priority: section.extent_priority,
|
||||
});
|
||||
}
|
||||
let bottom_gap = if bottoms.is_empty() || columns.is_empty() { 0.0 } else { env.gap };
|
||||
let side_available = (env.capacity.size.height - bottom_height - bottom_gap).max(0.0);
|
||||
let mut heights = Vec::new();
|
||||
let mut side_height = 0.0_f32;
|
||||
for column in &columns {
|
||||
let mut limits = Vec::new();
|
||||
for section in &column.members {
|
||||
limits.push(section_height_limit(layout, registry, section, env)?);
|
||||
}
|
||||
if column.members.len() == 1
|
||||
&& let (Some(section), Some(limit)) = (column.members.first(), limits.first_mut())
|
||||
&& !section.collapsed
|
||||
&& let Some(instance) = presented(section, env)
|
||||
{
|
||||
let request =
|
||||
ContentMeasureRequest { instance: instance.clone(), width: column.width, chrome_height: env.header_height + env.footer_height };
|
||||
let measure = measure_for(env, &request)?;
|
||||
// Sole presentation follows actual content/declared Fill, retaining
|
||||
// an explicit stack preference only for a later multi-section state.
|
||||
limit.preferred = None;
|
||||
limit.weight = 1.0;
|
||||
if measure.policy == SideHeightPolicy::Content {
|
||||
limit.max = measure.needed_height.clamp(limit.min, limit.max);
|
||||
}
|
||||
}
|
||||
let gaps = env.gap * column.members.len().saturating_sub(1) as f32;
|
||||
let sizes = distribute(&limits, (side_available - gaps).max(0.0));
|
||||
side_height = side_height.max((sizes.iter().map(|size| f64::from(*size)).sum::<f64>() + f64::from(gaps)) as f32);
|
||||
heights.push(sizes);
|
||||
}
|
||||
let widths: Vec<_> = distribute(&bottom_limits, (env.capacity.size.width - env.gap * bottoms.len().saturating_sub(1) as f32).max(0.0));
|
||||
let columns_width =
|
||||
(columns.iter().map(|column| f64::from(column.width)).sum::<f64>() + f64::from(env.gap) * columns.len().saturating_sub(1) as f64) as f32;
|
||||
let bottom_width =
|
||||
(widths.iter().map(|width| f64::from(*width)).sum::<f64>() + f64::from(env.gap) * bottoms.len().saturating_sub(1) as f64) as f32;
|
||||
let mut free_min = Size { width: 0.0, height: 0.0 };
|
||||
for section in &layout.sections {
|
||||
if section.location.zone() == Zone::Floating && presented(section, env).is_some() {
|
||||
let (min, _) = tab_bounds(layout, registry, section)?;
|
||||
free_min.width = free_min.width.max(min.width);
|
||||
free_min.height = free_min.height.max(section_height_limit(layout, registry, section, env)?.min);
|
||||
}
|
||||
}
|
||||
let extent = Size {
|
||||
width: env.capacity.size.width.max(columns_width).max(bottom_width).max(free_min.width),
|
||||
height: env.capacity.size.height.max(side_height + bottom_height + bottom_gap).max(free_min.height),
|
||||
};
|
||||
if !extent.width.is_finite() || !extent.height.is_finite() || extent.width > MAX_LOGICAL || extent.height > MAX_LOGICAL {
|
||||
return Err(error(Rule::Bounds, "panel scroll extent exceeds bound"));
|
||||
}
|
||||
let scroll = Point {
|
||||
x: env.scroll.x.min((extent.width - env.capacity.size.width).max(0.0)),
|
||||
y: env.scroll.y.min((extent.height - env.capacity.size.height).max(0.0)),
|
||||
};
|
||||
let origin = Point { x: env.capacity.origin.x - scroll.x, y: env.capacity.origin.y - scroll.y };
|
||||
let mut result = AllocatedGeometry { sections: Vec::new(), extent, scroll };
|
||||
let mut offsets = [0.0_f64; 2];
|
||||
for (column, sizes) in columns.iter().zip(heights) {
|
||||
let side = usize::from(column.column.zone == Zone::Right);
|
||||
let offset = offsets.get(side).copied().unwrap_or(0.0);
|
||||
let x = (if env.direction.edge(column.column.zone)? == PhysicalEdge::Left {
|
||||
f64::from(origin.x) + offset
|
||||
} else {
|
||||
f64::from(origin.x) + f64::from(extent.width) - offset - f64::from(column.width)
|
||||
}) as f32;
|
||||
let mut y = f64::from(origin.y);
|
||||
for (section, height) in column.members.iter().zip(sizes) {
|
||||
if let Some(instance) = presented(section, env) {
|
||||
push_allocation(&mut result, section, instance, x, y as f32, column.width, height)?;
|
||||
y += f64::from(height) + f64::from(env.gap);
|
||||
}
|
||||
}
|
||||
if let Some(offset) = offsets.get_mut(side) {
|
||||
*offset += f64::from(column.width) + f64::from(env.gap);
|
||||
}
|
||||
}
|
||||
let mut cursor = 0.0_f64;
|
||||
for (section, width) in bottoms.iter().zip(widths) {
|
||||
let height_limit = section_height_limit(layout, registry, section, env)?;
|
||||
let height = bottom_height.clamp(height_limit.min, height_limit.max);
|
||||
let x = (if env.direction == Direction::Ltr {
|
||||
f64::from(origin.x) + cursor
|
||||
} else {
|
||||
f64::from(origin.x) + f64::from(extent.width) - cursor - f64::from(width)
|
||||
}) as f32;
|
||||
if let Some(instance) = presented(section, env) {
|
||||
push_allocation(&mut result, section, instance, x, origin.y + extent.height - height, width, height)?;
|
||||
}
|
||||
cursor += f64::from(width) + f64::from(env.gap);
|
||||
}
|
||||
for section in &layout.sections {
|
||||
if let SectionLocation::Floating { origin } = §ion.location
|
||||
&& let Some(instance) = presented(section, env)
|
||||
{
|
||||
let (min, max) = tab_bounds(layout, registry, section)?;
|
||||
let width = section.size.width.min(env.capacity.size.width).clamp(min.width, max.width);
|
||||
let height_limit = section_height_limit(layout, registry, section, env)?;
|
||||
let height = section.size.height.min(env.capacity.size.height).clamp(height_limit.min, height_limit.max);
|
||||
let x = origin.x.clamp(env.capacity.origin.x, (env.capacity.origin.x + env.capacity.size.width - width).max(env.capacity.origin.x))
|
||||
- scroll.x;
|
||||
let y = origin.y.clamp(env.capacity.origin.y, (env.capacity.origin.y + env.capacity.size.height - height).max(env.capacity.origin.y))
|
||||
- scroll.y;
|
||||
push_allocation(&mut result, section, instance, x, y, width, height)?;
|
||||
}
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn push_allocation(
|
||||
result: &mut AllocatedGeometry,
|
||||
section: &Section,
|
||||
instance: &InstanceId,
|
||||
x: f32,
|
||||
y: f32,
|
||||
width: f32,
|
||||
height: f32,
|
||||
) -> PanelResult<()> {
|
||||
let outer = LogicalRect { origin: Point { x, y }, size: Size { width, height } };
|
||||
outer.validate()?;
|
||||
result.sections.push(AllocatedSection { section: section.id.clone(), instance: instance.clone(), outer, collapsed: section.collapsed });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Synthetic/reference convenience adapter. Product hosts capture real intrinsic
|
||||
/// metrics through allocation_measure_requests, rather than using preferred size.
|
||||
pub fn resolve_geometry(service: &LayoutService, capacity: LogicalRect, direction: Direction, chrome: f32) -> PanelResult<ResolvedLayout> {
|
||||
capacity.validate()?;
|
||||
if !chrome.is_finite() || chrome < 0.0 || chrome > 256.0 {
|
||||
return Err(error(Rule::Bounds, "invalid header/footer chrome extent"));
|
||||
if !chrome.is_finite() || chrome <= 0.0 || chrome > 256.0 {
|
||||
return Err(error(Rule::Bounds, "invalid shared chrome height"));
|
||||
}
|
||||
let mut env = AllocationEnvironment {
|
||||
capacity,
|
||||
direction,
|
||||
header_height: chrome / 2.0,
|
||||
footer_height: chrome / 2.0,
|
||||
gap: 0.0,
|
||||
inline_max_height: 0.0,
|
||||
min_viewport: Size { width: 1.0, height: 1.0 },
|
||||
scroll: Point { x: 0.0, y: 0.0 },
|
||||
available: service
|
||||
.layout()
|
||||
.instances
|
||||
.iter()
|
||||
.filter(|instance| service.availability(&instance.id) == Availability::Available)
|
||||
.map(|instance| instance.id.clone())
|
||||
.collect(),
|
||||
content: Vec::new(),
|
||||
content_revision: service.inspect().revision,
|
||||
};
|
||||
for request in allocation_measure_requests(service.layout(), service.registry(), &env)? {
|
||||
let section = service.layout().containing(&request.instance)?;
|
||||
env.content.push(SideContentMeasure {
|
||||
needed_height: section.size.height.max(request.chrome_height),
|
||||
policy: service.registry().get(&service.layout().instance(&request.instance)?.kind)?.side_height_policy,
|
||||
request,
|
||||
});
|
||||
}
|
||||
let mut allocation = allocate_layout(service.layout(), service.registry(), &env)?;
|
||||
// The reference adapter may model explicit native hosts. They have their
|
||||
// own viewport and never consume the in-app allocator's capacity.
|
||||
if service.capabilities().native_windows {
|
||||
for section in &service.layout().sections {
|
||||
if let SectionLocation::Window { origin, .. } = §ion.location
|
||||
&& let Some(instance) = presented(section, &env)
|
||||
{
|
||||
let height = if section.collapsed { env.header_height } else { section.size.height };
|
||||
push_allocation(&mut allocation, section, instance, origin.x, origin.y, section.size.width, height)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut result = ResolvedLayout::default();
|
||||
let mut left = capacity.origin.x;
|
||||
let mut right = capacity.origin.x + capacity.size.width;
|
||||
let mut bottom = capacity.origin.y + capacity.size.height;
|
||||
let mut left_y = capacity.origin.y;
|
||||
let mut right_y = capacity.origin.y;
|
||||
let mut bottom_x = capacity.origin.x;
|
||||
let mut rail_y = capacity.origin.y;
|
||||
let mut occupied: Vec<LogicalRect> = Vec::new();
|
||||
for section in &service.layout().sections {
|
||||
let id = §ion.active;
|
||||
let zone = section.location.zone();
|
||||
let peek = &service.interaction().peek;
|
||||
let active = peek.as_ref().filter(|p| section.tabs.contains(p)).unwrap_or(id);
|
||||
let available = service.availability(active) == Availability::Available;
|
||||
let reason = if !available {
|
||||
Some(UnpresentedReason::Unavailable)
|
||||
} else if zone == Zone::Window && !service.capabilities().native_windows {
|
||||
Some(UnpresentedReason::NativeUnsupported)
|
||||
} else if section.collapsed && peek.as_ref() != Some(active) {
|
||||
Some(UnpresentedReason::Collapsed)
|
||||
} else {
|
||||
for card in allocation.sections {
|
||||
let body_height = card.outer.size.height - chrome;
|
||||
let body = if card.collapsed || body_height <= 0.0 {
|
||||
None
|
||||
} else {
|
||||
Some(LogicalRect {
|
||||
origin: Point { x: card.outer.origin.x, y: card.outer.origin.y + chrome / 2.0 },
|
||||
size: Size { width: card.outer.size.width, height: body_height },
|
||||
})
|
||||
};
|
||||
if let Some(reason) = reason {
|
||||
result.unpresented.push(UnpresentedSection { section: section.id.clone(), reason: reason.clone() });
|
||||
if reason == UnpresentedReason::Collapsed {
|
||||
append_rail(&mut result, service, active, capacity, direction, zone, &mut rail_y)?;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let size = section.size;
|
||||
let origin = match §ion.location {
|
||||
SectionLocation::Floating { origin } | SectionLocation::Window { origin, .. } => *origin,
|
||||
SectionLocation::Dock { zone } => match direction.edge(*zone)? {
|
||||
PhysicalEdge::Left => Point { x: left, y: left_y },
|
||||
PhysicalEdge::Right => Point { x: right - size.width, y: right_y },
|
||||
PhysicalEdge::Bottom => Point { x: bottom_x, y: bottom - size.height },
|
||||
},
|
||||
};
|
||||
let outer = LogicalRect { origin, size };
|
||||
let overlaps_dock = zone.docked()
|
||||
&& !section.collapsed
|
||||
&& occupied.iter().any(|r| {
|
||||
r.origin.x < origin.x + size.width
|
||||
&& origin.x < r.origin.x + r.size.width
|
||||
&& r.origin.y < origin.y + size.height
|
||||
&& origin.y < r.origin.y + r.size.height
|
||||
});
|
||||
if !capacity.contains_rect(outer) || size.height <= chrome || overlaps_dock {
|
||||
result.unpresented.push(UnpresentedSection { section: section.id.clone(), reason: UnpresentedReason::MinimumOverflow });
|
||||
append_rail(&mut result, service, active, capacity, direction, zone, &mut rail_y)?;
|
||||
continue;
|
||||
}
|
||||
if zone.docked() && !section.collapsed {
|
||||
occupied.push(outer);
|
||||
match direction.edge(zone)? {
|
||||
PhysicalEdge::Left => {
|
||||
left_y += size.height;
|
||||
left = left.max(origin.x);
|
||||
}
|
||||
PhysicalEdge::Right => {
|
||||
right_y += size.height;
|
||||
right = right.min(origin.x + size.width);
|
||||
}
|
||||
PhysicalEdge::Bottom => {
|
||||
bottom_x += size.width;
|
||||
bottom = bottom.min(origin.y + size.height);
|
||||
}
|
||||
}
|
||||
}
|
||||
let body =
|
||||
LogicalRect { origin: Point { x: origin.x, y: origin.y + chrome / 2.0 }, size: Size { width: size.width, height: size.height - chrome } };
|
||||
let panel = ResolvedPanel {
|
||||
instance: active.clone(),
|
||||
section: section.id.clone(),
|
||||
zone,
|
||||
outer,
|
||||
body,
|
||||
painted: vec![outer],
|
||||
input: vec![InputRegion {
|
||||
control: ControlId::new(format!("host.{}", section.id.0).chars().take(MAX_ID_BYTES).collect::<String>())?,
|
||||
let zone = service.layout().section(&card.section)?.location.zone();
|
||||
let painted = if zone == Zone::Window { vec![card.outer] } else { intersect_rect(card.outer, capacity).into_iter().collect::<Vec<_>>() };
|
||||
let title_key = service.registry().get(&service.layout().instance(&card.instance)?.kind)?.title_key.clone();
|
||||
let input = painted
|
||||
.iter()
|
||||
.map(|bounds| InputRegion {
|
||||
control: ControlId(card.instance.0.clone()),
|
||||
role: InputRole::Surface,
|
||||
bounds: outer,
|
||||
bounds: *bounds,
|
||||
keyboard_focusable: true,
|
||||
accessible_name: service.registry().get(&service.layout().instance(active)?.kind)?.title_key.clone(),
|
||||
}],
|
||||
};
|
||||
panel.validate()?;
|
||||
result.panels.push(panel);
|
||||
accessible_name: title_key.clone(),
|
||||
})
|
||||
.collect();
|
||||
result.panels.push(ResolvedPanel { instance: card.instance, section: card.section, zone, outer: card.outer, body, painted, input });
|
||||
}
|
||||
for section in &service.layout().sections {
|
||||
if !result.panels.iter().any(|panel| panel.section == section.id) {
|
||||
result.unpresented.push(UnpresentedSection {
|
||||
section: section.id.clone(),
|
||||
reason: if section.location.zone() == Zone::Window {
|
||||
if service.capabilities().native_windows { UnpresentedReason::Unavailable } else { UnpresentedReason::NativeUnsupported }
|
||||
} else {
|
||||
UnpresentedReason::Unavailable
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
result.validate()?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn append_rail(
|
||||
result: &mut ResolvedLayout,
|
||||
service: &LayoutService,
|
||||
active: &InstanceId,
|
||||
capacity: LogicalRect,
|
||||
direction: Direction,
|
||||
zone: Zone,
|
||||
rail_y: &mut f32,
|
||||
) -> PanelResult<()> {
|
||||
// Rails are bounded chrome, not below-minimum content bodies. If every entry
|
||||
// cannot fit, the complete unpresented list remains available to a host's rail.
|
||||
let width = 32.0_f32.min(capacity.size.width);
|
||||
let height = 32.0_f32.min(capacity.size.height);
|
||||
if *rail_y + height <= capacity.origin.y + capacity.size.height {
|
||||
let right = direction.edge(if zone.docked() { zone } else { Zone::Left })? == PhysicalEdge::Right;
|
||||
let x = if right { capacity.origin.x + capacity.size.width - width } else { capacity.origin.x };
|
||||
result.rails.push(InputRegion {
|
||||
control: ControlId::new(format!("rail.{}", result.rails.len()))?,
|
||||
role: InputRole::Rail,
|
||||
bounds: LogicalRect { origin: Point { x, y: *rail_y }, size: Size { width, height } },
|
||||
keyboard_focusable: true,
|
||||
accessible_name: service.registry().get(&service.layout().instance(active)?.kind)?.title_key.clone(),
|
||||
});
|
||||
*rail_y += height;
|
||||
pub fn intersect_rect(a: LogicalRect, b: LogicalRect) -> Option<LogicalRect> {
|
||||
if validate_allocation_capacity(a).is_err() || validate_allocation_capacity(b).is_err() {
|
||||
return None;
|
||||
}
|
||||
Ok(())
|
||||
let x = a.origin.x.max(b.origin.x);
|
||||
let y = a.origin.y.max(b.origin.y);
|
||||
let width = (a.origin.x + a.size.width).min(b.origin.x + b.size.width) - x;
|
||||
let height = (a.origin.y + a.size.height).min(b.origin.y + b.size.height) - y;
|
||||
if width <= 0.0 || height <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
Some(LogicalRect { origin: Point { x, y }, size: Size { width, height } })
|
||||
}
|
||||
|
||||
/// Surfaces child resolves theme tokens. Invalid authored pairs retain raw import
|
||||
@@ -400,11 +901,21 @@ impl ContrastOutcome {
|
||||
/// default (bottom/native opaque, sides/free translucent). No colour implementation.
|
||||
pub fn group_surface<'a>(zone: Zone, specs: impl IntoIterator<Item = &'a PanelSpec>) -> PanelSurface {
|
||||
let mut translucent = false;
|
||||
let mut text_heavy = false;
|
||||
let mut count = 0;
|
||||
for spec in specs {
|
||||
count += 1;
|
||||
text_heavy |= spec.text_heavy;
|
||||
if spec.surface == PanelSurface::Opaque {
|
||||
return PanelSurface::Opaque;
|
||||
}
|
||||
translucent |= spec.surface == PanelSurface::Translucent;
|
||||
}
|
||||
if translucent || !matches!(zone, Zone::Bottom | Zone::Window) { PanelSurface::Translucent } else { PanelSurface::Opaque }
|
||||
if translucent {
|
||||
PanelSurface::Translucent
|
||||
} else if matches!(zone, Zone::Bottom | Zone::Window) || (count > 1 && text_heavy) {
|
||||
PanelSurface::Opaque
|
||||
} else {
|
||||
PanelSurface::Translucent
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,9 @@ use super::geometry::Point;
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub const LAYOUT_VERSION: u32 = 1;
|
||||
pub const PANEL_API_VERSION: u32 = 1;
|
||||
pub const LAYOUT_VERSION: u32 = 2;
|
||||
pub const PANEL_API_VERSION: u32 = 2;
|
||||
pub const MAX_HEADER_ACTIONS: usize = 16;
|
||||
pub const MAX_ID_BYTES: usize = 64;
|
||||
pub const MAX_INSTANCES: usize = 128;
|
||||
pub const MAX_SECTIONS: usize = 64;
|
||||
@@ -37,6 +38,7 @@ pub enum Rule {
|
||||
IncompatibleTabs,
|
||||
Lifecycle,
|
||||
MissingTarget,
|
||||
NoSpace,
|
||||
PinConflict,
|
||||
PinOrder,
|
||||
Placement,
|
||||
@@ -80,7 +82,7 @@ macro_rules! identity {
|
||||
}
|
||||
)+};
|
||||
}
|
||||
identity!(PanelKind, InstanceId, SectionId, WorkspaceId, DocumentId, ViewportId, HostId, ControlId);
|
||||
identity!(PanelKind, InstanceId, SectionId, ColumnId, WorkspaceId, DocumentId, ViewportId, HostId, ControlId);
|
||||
|
||||
/// Leading/trailing logical sides, mirrored by a host for RTL. There is no Top zone.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema)]
|
||||
@@ -94,11 +96,18 @@ pub enum Zone {
|
||||
}
|
||||
|
||||
impl Zone {
|
||||
pub fn side(self) -> bool {
|
||||
matches!(self, Self::Left | Self::Right)
|
||||
}
|
||||
pub fn docked(self) -> bool {
|
||||
matches!(self, Self::Left | Self::Right | Self::Bottom)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn all_zones() -> BTreeSet<Zone> {
|
||||
[Zone::Left, Zone::Right, Zone::Bottom, Zone::Floating, Zone::Window].into_iter().collect()
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum EdgeRule {
|
||||
@@ -142,6 +151,8 @@ impl Size {
|
||||
pub struct PanelFeatures {
|
||||
pub collapsible: bool,
|
||||
pub closable: bool,
|
||||
#[serde(default)]
|
||||
pub hot_closable: bool,
|
||||
pub popout: bool,
|
||||
pub tabbable: bool,
|
||||
pub multi_instance: bool,
|
||||
@@ -149,16 +160,32 @@ pub struct PanelFeatures {
|
||||
|
||||
impl Default for PanelFeatures {
|
||||
fn default() -> Self {
|
||||
Self { collapsible: true, closable: true, popout: true, tabbable: true, multi_instance: false }
|
||||
Self { collapsible: true, closable: true, hot_closable: false, popout: true, tabbable: true, multi_instance: false }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum SideHeightPolicy {
|
||||
#[default]
|
||||
Content,
|
||||
Fill,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct HeaderActionSpec {
|
||||
pub id: ControlId,
|
||||
pub label_key: String,
|
||||
pub icon: String,
|
||||
}
|
||||
|
||||
/// Immutable registration metadata. No callbacks, content state or model references.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct PanelSpec {
|
||||
pub kind: PanelKind,
|
||||
pub title_key: String,
|
||||
pub icon: String,
|
||||
#[serde(default = "all_zones")]
|
||||
pub allowed_zones: BTreeSet<Zone>,
|
||||
pub default_zone: Zone,
|
||||
pub min_size: Size,
|
||||
@@ -166,7 +193,14 @@ pub struct PanelSpec {
|
||||
pub max_size: Size,
|
||||
pub edge_rule: EdgeRule,
|
||||
pub surface: PanelSurface,
|
||||
#[serde(default)]
|
||||
pub features: PanelFeatures,
|
||||
#[serde(default)]
|
||||
pub side_height_policy: SideHeightPolicy,
|
||||
#[serde(default)]
|
||||
pub header_actions: Vec<HeaderActionSpec>,
|
||||
#[serde(default)]
|
||||
pub text_heavy: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
@@ -179,6 +213,18 @@ impl PanelRegistry {
|
||||
valid_id(&spec.kind.0)?;
|
||||
valid_id(&spec.title_key)?;
|
||||
valid_id(&spec.icon)?;
|
||||
if spec.header_actions.len() > MAX_HEADER_ACTIONS {
|
||||
return Err(error(Rule::CollectionLimit, "header action cap"));
|
||||
}
|
||||
let mut actions = BTreeSet::new();
|
||||
for action in &spec.header_actions {
|
||||
valid_id(&action.id.0)?;
|
||||
valid_id(&action.label_key)?;
|
||||
valid_id(&action.icon)?;
|
||||
if !actions.insert(&action.id) {
|
||||
return Err(error(Rule::DuplicateId, "duplicate header action"));
|
||||
}
|
||||
}
|
||||
spec.min_size.validate()?;
|
||||
spec.max_size.validate()?;
|
||||
spec.default_size.validate()?;
|
||||
@@ -245,6 +291,20 @@ pub struct DockReturn {
|
||||
pub index: usize,
|
||||
pub size: Size,
|
||||
pub collapsed: bool,
|
||||
#[serde(default)]
|
||||
pub section: Option<SectionId>,
|
||||
#[serde(default)]
|
||||
pub column: Option<ColumnId>,
|
||||
#[serde(default)]
|
||||
pub column_index: usize,
|
||||
#[serde(default)]
|
||||
pub column_width: Option<f32>,
|
||||
#[serde(default = "default_weight")]
|
||||
pub weight: f32,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub preferred_extent: Option<f32>,
|
||||
#[serde(default, skip_serializing_if = "is_zero_extent_priority")]
|
||||
pub extent_priority: u16,
|
||||
/// Restore a former tab group when it still occupies the recorded dock.
|
||||
/// Missing/reparented groups use the nonrecursive dock fallback above.
|
||||
#[serde(default)]
|
||||
@@ -261,6 +321,11 @@ impl DockReturn {
|
||||
return Err(error(Rule::Placement, "invalid native return destination"));
|
||||
}
|
||||
self.size.validate()?;
|
||||
validate_extent_priority(self.preferred_extent, self.extent_priority)?;
|
||||
validate_column_memory(self.zone, &self.column, self.column_index, self.column_width, self.weight)?;
|
||||
if let Some(section) = &self.section {
|
||||
valid_id(§ion.0)?;
|
||||
}
|
||||
if let Some(join) = &self.join {
|
||||
valid_id(&join.section.0)?;
|
||||
if join.index >= MAX_TABS {
|
||||
@@ -280,6 +345,16 @@ pub struct Section {
|
||||
/// Desired outer dimensions; overflow resolution never modifies these.
|
||||
pub size: Size,
|
||||
pub collapsed: bool,
|
||||
#[serde(default)]
|
||||
pub column: Option<ColumnId>,
|
||||
/// Saved expansion proportion. Collapse and transient allocation retain it.
|
||||
#[serde(default = "default_weight")]
|
||||
pub weight: f32,
|
||||
/// Explicit dock stack-axis request, independent of surplus proportions.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub preferred_extent: Option<f32>,
|
||||
#[serde(default, skip_serializing_if = "is_zero_extent_priority")]
|
||||
pub extent_priority: u16,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
|
||||
@@ -290,6 +365,80 @@ pub struct PlacementMemory {
|
||||
pub tab_index: usize,
|
||||
pub size: Size,
|
||||
pub collapsed: bool,
|
||||
#[serde(default)]
|
||||
pub column: Option<ColumnId>,
|
||||
#[serde(default)]
|
||||
pub column_index: usize,
|
||||
#[serde(default)]
|
||||
pub column_width: Option<f32>,
|
||||
#[serde(default = "default_weight")]
|
||||
pub weight: f32,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub preferred_extent: Option<f32>,
|
||||
#[serde(default, skip_serializing_if = "is_zero_extent_priority")]
|
||||
pub extent_priority: u16,
|
||||
}
|
||||
|
||||
pub fn dock_stack_extent(zone: Zone, size: Size) -> Option<f32> {
|
||||
match zone {
|
||||
Zone::Left | Zone::Right => Some(size.height),
|
||||
Zone::Bottom => Some(size.width),
|
||||
Zone::Floating | Zone::Window => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn validate_preferred_extent(value: Option<f32>) -> PanelResult<()> {
|
||||
if value.is_some_and(|value| !value.is_finite() || value <= 0.0 || value > MAX_LOGICAL) {
|
||||
return Err(error(Rule::Bounds, "preferred extent must be finite and in (0, 32768]"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn is_zero_extent_priority(value: &u16) -> bool {
|
||||
*value == 0
|
||||
}
|
||||
|
||||
pub fn validate_extent_priority(preferred_extent: Option<f32>, extent_priority: u16) -> PanelResult<()> {
|
||||
validate_preferred_extent(preferred_extent)?;
|
||||
if extent_priority > 0 && preferred_extent.is_none() {
|
||||
return Err(error(Rule::Bounds, "positive extent priority requires an explicit extent"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn default_weight() -> f32 {
|
||||
1.0
|
||||
}
|
||||
|
||||
pub fn validate_weight(weight: f32) -> PanelResult<()> {
|
||||
if !weight.is_finite() || weight < 0.0 || weight > MAX_LOGICAL {
|
||||
return Err(error(Rule::Bounds, "weight must be finite and in [0, 32768]"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn validate_column_memory(zone: Zone, column: &Option<ColumnId>, index: usize, width: Option<f32>, weight: f32) -> PanelResult<()> {
|
||||
validate_weight(weight)?;
|
||||
if index > MAX_SECTIONS || width.is_some_and(|width| !width.is_finite() || width <= 0.0 || width > MAX_LOGICAL) {
|
||||
return Err(error(Rule::Bounds, "invalid remembered column dimensions/rank"));
|
||||
}
|
||||
if !zone.side() && (column.is_some() || width.is_some() || index != 0) {
|
||||
return Err(error(Rule::Placement, "non-side memory cannot contain column geometry"));
|
||||
}
|
||||
if let Some(column) = column {
|
||||
valid_id(&column.0)?;
|
||||
if !zone.side() {
|
||||
return Err(error(Rule::Placement, "only side sections have columns"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct Column {
|
||||
pub id: ColumnId,
|
||||
pub zone: Zone,
|
||||
pub width: f32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
|
||||
@@ -300,18 +449,183 @@ pub struct PanelInstance {
|
||||
pub memory: PlacementMemory,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
|
||||
pub const MAX_EXTENT_PRIORITY_RECORDS: usize = 4 * (MAX_INSTANCES + MAX_SECTIONS);
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(tag = "type", content = "id", rename_all = "snake_case")]
|
||||
pub enum ExtentPriorityTarget {
|
||||
Section(SectionId),
|
||||
Memory(InstanceId),
|
||||
SectionReturn(SectionId),
|
||||
MemoryReturn(InstanceId),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct ExtentPriorityRecord {
|
||||
pub target: ExtentPriorityTarget,
|
||||
pub zone: Zone,
|
||||
pub column: Option<ColumnId>,
|
||||
pub stored_priority: u16,
|
||||
pub priority: u16,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct ExtentPriorityContext {
|
||||
pub records: Vec<ExtentPriorityRecord>,
|
||||
pub complete: bool,
|
||||
}
|
||||
impl ExtentPriorityContext {
|
||||
pub fn validate(&self) -> PanelResult<()> {
|
||||
if self.records.len() > MAX_EXTENT_PRIORITY_RECORDS {
|
||||
return Err(error(Rule::CollectionLimit, "recovery priority record cap"));
|
||||
}
|
||||
let mut targets = BTreeSet::new();
|
||||
for record in &self.records {
|
||||
match &record.target {
|
||||
ExtentPriorityTarget::Section(id) | ExtentPriorityTarget::SectionReturn(id) => valid_id(&id.0)?,
|
||||
ExtentPriorityTarget::Memory(id) | ExtentPriorityTarget::MemoryReturn(id) => valid_id(&id.0)?,
|
||||
}
|
||||
if let Some(column) = &record.column {
|
||||
valid_id(&column.0)?;
|
||||
}
|
||||
if !targets.insert(&record.target) || (record.column.is_some() && !record.zone.side()) {
|
||||
return Err(error(Rule::Schema, "duplicate recovery priority target or invalid column"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn overrides(&self) -> impl Iterator<Item = &ExtentPriorityRecord> {
|
||||
self.records.iter().filter(|record| record.priority != record.stored_priority)
|
||||
}
|
||||
}
|
||||
|
||||
/// Ephemeral proof of the typed incoming layout's per-identity owner sets.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct ReplacementIdentityOwnership {
|
||||
pub sections: BTreeMap<SectionId, BTreeSet<InstanceId>>,
|
||||
pub columns: BTreeMap<ColumnId, BTreeSet<InstanceId>>,
|
||||
}
|
||||
|
||||
impl ReplacementIdentityOwnership {
|
||||
/// Capture only typed ownership, never quarantine or snapshot reservations.
|
||||
pub fn from_layout(layout: &Layout) -> PanelResult<Self> {
|
||||
if layout.instances.len() > MAX_INSTANCES
|
||||
|| layout.sections.len() > MAX_SECTIONS
|
||||
|| layout.columns.len() > MAX_SECTIONS
|
||||
|| layout.sections.iter().any(|section| section.tabs.len() > MAX_TABS)
|
||||
{
|
||||
return Err(error(Rule::CollectionLimit, "replacement ownership layout cap"));
|
||||
}
|
||||
let mut ownership = Self::default();
|
||||
for section in &layout.sections {
|
||||
ownership.sections.entry(section.id.clone()).or_default().extend(section.tabs.iter().cloned());
|
||||
if let Some(column) = §ion.column {
|
||||
ownership.columns.entry(column.clone()).or_default().extend(section.tabs.iter().cloned());
|
||||
}
|
||||
for instance in §ion.tabs {
|
||||
ownership.capture_return(instance, §ion.location);
|
||||
}
|
||||
}
|
||||
for panel in &layout.instances {
|
||||
ownership.sections.entry(panel.memory.section.clone()).or_default().insert(panel.id.clone());
|
||||
if let Some(column) = &panel.memory.column {
|
||||
ownership.columns.entry(column.clone()).or_default().insert(panel.id.clone());
|
||||
}
|
||||
ownership.capture_return(&panel.id, &panel.memory.location);
|
||||
}
|
||||
for column in &layout.columns {
|
||||
ownership.columns.entry(column.id.clone()).or_default();
|
||||
}
|
||||
ownership.validate()?;
|
||||
Ok(ownership)
|
||||
}
|
||||
|
||||
fn capture_return(&mut self, instance: &InstanceId, location: &SectionLocation) {
|
||||
if let SectionLocation::Window { return_to, .. } = location {
|
||||
if let Some(section) = &return_to.section {
|
||||
self.sections.entry(section.clone()).or_default().insert(instance.clone());
|
||||
}
|
||||
if let Some(join) = &return_to.join {
|
||||
self.sections.entry(join.section.clone()).or_default().insert(instance.clone());
|
||||
}
|
||||
if let Some(column) = &return_to.column {
|
||||
self.columns.entry(column.clone()).or_default().insert(instance.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn validate(&self) -> PanelResult<()> {
|
||||
if self.sections.len() > MAX_RESERVED_IDENTITIES || self.columns.len() > MAX_RESERVED_IDENTITIES {
|
||||
return Err(error(Rule::CollectionLimit, "replacement ownership identity cap"));
|
||||
}
|
||||
for id in self.sections.keys().map(|id| &id.0).chain(self.columns.keys().map(|id| &id.0)) {
|
||||
valid_id(id)?;
|
||||
}
|
||||
let mut count = 0usize;
|
||||
for owners in self.sections.values().chain(self.columns.values()) {
|
||||
count = count.saturating_add(owners.len());
|
||||
if owners.len() > MAX_INSTANCES || count > MAX_RESERVED_IDENTITIES {
|
||||
return Err(error(Rule::CollectionLimit, "replacement ownership owner cap"));
|
||||
}
|
||||
for instance in owners {
|
||||
valid_id(&instance.0)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct LayoutPreparationContext {
|
||||
pub sections: BTreeSet<SectionId>,
|
||||
pub columns: BTreeSet<ColumnId>,
|
||||
pub extent_priorities: ExtentPriorityContext,
|
||||
pub replacement_ownership: Option<ReplacementIdentityOwnership>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct Layout {
|
||||
pub version: u32,
|
||||
pub workspace: WorkspaceId,
|
||||
pub instances: Vec<PanelInstance>,
|
||||
/// Stable order, outermost first within each logical dock edge.
|
||||
pub sections: Vec<Section>,
|
||||
/// Outer-to-inner within each side, including retained dormant identities.
|
||||
#[serde(default)]
|
||||
pub columns: Vec<Column>,
|
||||
#[serde(skip)]
|
||||
pub extent_priority_context: ExtentPriorityContext,
|
||||
}
|
||||
|
||||
impl PartialEq for Layout {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.version == other.version
|
||||
&& self.workspace == other.workspace
|
||||
&& self.instances == other.instances
|
||||
&& self.sections == other.sections
|
||||
&& self.columns == other.columns
|
||||
&& self.latent_priority_overrides().eq(other.latent_priority_overrides())
|
||||
}
|
||||
}
|
||||
|
||||
impl Layout {
|
||||
fn latent_priority_overrides(&self) -> impl Iterator<Item = &ExtentPriorityRecord> {
|
||||
self.extent_priority_context.overrides().filter(move |record| match &record.target {
|
||||
ExtentPriorityTarget::Section(id) => self.section(id).is_err(),
|
||||
ExtentPriorityTarget::Memory(id) => self.instance(id).is_err(),
|
||||
ExtentPriorityTarget::SectionReturn(id) => !self.section(id).is_ok_and(|s| matches!(&s.location, SectionLocation::Window { .. })),
|
||||
ExtentPriorityTarget::MemoryReturn(id) => !self.instance(id).is_ok_and(|p| matches!(&p.memory.location, SectionLocation::Window { .. })),
|
||||
})
|
||||
}
|
||||
pub fn empty(workspace: WorkspaceId) -> Self {
|
||||
Self { version: LAYOUT_VERSION, workspace, instances: Vec::new(), sections: Vec::new() }
|
||||
Self {
|
||||
version: LAYOUT_VERSION,
|
||||
workspace,
|
||||
instances: Vec::new(),
|
||||
sections: Vec::new(),
|
||||
columns: Vec::new(),
|
||||
extent_priority_context: ExtentPriorityContext::default(),
|
||||
}
|
||||
}
|
||||
pub fn instance(&self, id: &InstanceId) -> PanelResult<&PanelInstance> {
|
||||
self.instances.iter().find(|p| p.id == *id).ok_or_else(|| error(Rule::MissingTarget, "instance not found"))
|
||||
@@ -322,6 +636,83 @@ impl Layout {
|
||||
pub fn containing(&self, id: &InstanceId) -> PanelResult<&Section> {
|
||||
self.sections.iter().find(|s| s.tabs.contains(id)).ok_or_else(|| error(Rule::MissingTarget, "instance has no open section"))
|
||||
}
|
||||
pub fn column(&self, id: &ColumnId) -> PanelResult<&Column> {
|
||||
self.columns.iter().find(|column| column.id == *id).ok_or_else(|| error(Rule::MissingTarget, "column not found"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Allocation scans remembered/native identities too; a proposal consumes no IDs.
|
||||
pub fn next_section_id(layout: &Layout) -> PanelResult<SectionId> {
|
||||
next_section_id_with_reservations(layout, &BTreeSet::new())
|
||||
}
|
||||
|
||||
/// External identities are data only, never fake placed sections.
|
||||
pub const MAX_RESERVED_IDENTITIES: usize = MAX_INSTANCES * 8 + MAX_SECTIONS * 8;
|
||||
|
||||
pub fn next_section_id_with_reservations(layout: &Layout, reserved: &BTreeSet<SectionId>) -> PanelResult<SectionId> {
|
||||
if reserved.len() > MAX_RESERVED_IDENTITIES {
|
||||
return Err(error(Rule::CollectionLimit, "external section reservation cap"));
|
||||
}
|
||||
for id in reserved {
|
||||
valid_id(&id.0)?;
|
||||
}
|
||||
let mut used: BTreeSet<&str> = layout.sections.iter().map(|s| s.id.0.as_str()).collect();
|
||||
used.extend(reserved.iter().map(|id| id.0.as_str()));
|
||||
for instance in &layout.instances {
|
||||
used.insert(&instance.memory.section.0);
|
||||
}
|
||||
for location in layout.sections.iter().map(|s| &s.location).chain(layout.instances.iter().map(|p| &p.memory.location)) {
|
||||
if let SectionLocation::Window { return_to, .. } = location {
|
||||
if let Some(section) = &return_to.section {
|
||||
used.insert(§ion.0);
|
||||
}
|
||||
if let Some(join) = &return_to.join {
|
||||
used.insert(&join.section.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
for ordinal in 1..=MAX_RESERVED_IDENTITIES * 2 + 1 {
|
||||
let id = format!("section-{ordinal}");
|
||||
if !used.contains(id.as_str()) {
|
||||
return SectionId::new(id);
|
||||
}
|
||||
}
|
||||
Err(error(Rule::CollectionLimit, "section identity allocation exhausted"))
|
||||
}
|
||||
|
||||
pub fn next_column_id(layout: &Layout) -> PanelResult<ColumnId> {
|
||||
next_column_id_with_reservations(layout, &BTreeSet::new())
|
||||
}
|
||||
|
||||
pub fn next_column_id_with_reservations(layout: &Layout, reserved: &BTreeSet<ColumnId>) -> PanelResult<ColumnId> {
|
||||
if reserved.len() > MAX_RESERVED_IDENTITIES {
|
||||
return Err(error(Rule::CollectionLimit, "external column reservation cap"));
|
||||
}
|
||||
for id in reserved {
|
||||
valid_id(&id.0)?;
|
||||
}
|
||||
let mut used: BTreeSet<&str> = layout.columns.iter().map(|c| c.id.0.as_str()).collect();
|
||||
used.extend(reserved.iter().map(|id| id.0.as_str()));
|
||||
used.extend(layout.sections.iter().filter_map(|s| s.column.as_ref().map(|c| c.0.as_str())));
|
||||
for instance in &layout.instances {
|
||||
if let Some(column) = &instance.memory.column {
|
||||
used.insert(&column.0);
|
||||
}
|
||||
}
|
||||
for location in layout.sections.iter().map(|s| &s.location).chain(layout.instances.iter().map(|p| &p.memory.location)) {
|
||||
if let SectionLocation::Window { return_to, .. } = location
|
||||
&& let Some(column) = &return_to.column
|
||||
{
|
||||
used.insert(&column.0);
|
||||
}
|
||||
}
|
||||
for ordinal in 1..=MAX_RESERVED_IDENTITIES * 2 + 1 {
|
||||
let id = format!("column-{ordinal}");
|
||||
if !used.contains(id.as_str()) {
|
||||
return ColumnId::new(id);
|
||||
}
|
||||
}
|
||||
Err(error(Rule::CollectionLimit, "column identity allocation exhausted"))
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
@@ -343,6 +734,19 @@ impl Availability {
|
||||
/// Missing entries mean available. Availability is live context, never layout persistence.
|
||||
pub type AvailabilityMap = BTreeMap<InstanceId, Availability>;
|
||||
|
||||
/// Read-only selection shared by command admission and controller presentation.
|
||||
pub fn presented_tab<'a>(section: &'a Section, availability: &AvailabilityMap) -> Option<&'a InstanceId> {
|
||||
if section.tabs.is_empty() || section.tabs.len() > MAX_TABS {
|
||||
return None;
|
||||
}
|
||||
let available = |id: &InstanceId| availability.get(id).is_none_or(|state| *state == Availability::Available);
|
||||
if section.tabs.contains(§ion.active) && available(§ion.active) {
|
||||
Some(§ion.active)
|
||||
} else {
|
||||
section.tabs.iter().find(|id| available(id))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct HostCapabilities {
|
||||
pub native_windows: bool,
|
||||
@@ -366,15 +770,64 @@ pub fn tab_bounds(layout: &Layout, registry: &PanelRegistry, section: &Section)
|
||||
Ok((min, max))
|
||||
}
|
||||
|
||||
pub fn column_bounds(layout: &Layout, registry: &PanelRegistry, column: &ColumnId) -> PanelResult<(f32, f32)> {
|
||||
layout.column(column)?;
|
||||
let mut min: f32 = 0.0;
|
||||
let mut max = MAX_LOGICAL;
|
||||
for section in layout.sections.iter().filter(|s| s.column.as_ref() == Some(column)) {
|
||||
let (lower, upper) = tab_bounds(layout, registry, section)?;
|
||||
min = min.max(lower.width);
|
||||
max = max.min(upper.width);
|
||||
}
|
||||
if min > max {
|
||||
return Err(error(Rule::IncompatibleTabs, "stacked section width constraints have no intersection"));
|
||||
}
|
||||
Ok((min, max))
|
||||
}
|
||||
|
||||
/// One row thickness must satisfy all Bottom cards, including inactive tabs.
|
||||
pub fn bottom_height_bounds(layout: &Layout, registry: &PanelRegistry) -> PanelResult<(f32, f32)> {
|
||||
if layout.sections.len() > MAX_SECTIONS || layout.instances.len() > MAX_INSTANCES || layout.sections.iter().any(|s| s.tabs.len() > MAX_TABS) {
|
||||
return Err(error(Rule::CollectionLimit, "Bottom bounds collection cap"));
|
||||
}
|
||||
let mut min: f32 = 0.0;
|
||||
let mut max = MAX_LOGICAL;
|
||||
let mut found = false;
|
||||
for section in layout.sections.iter().filter(|s| s.location.zone() == Zone::Bottom) {
|
||||
found = true;
|
||||
let (lower, upper) = tab_bounds(layout, registry, section)?;
|
||||
min = min.max(lower.height);
|
||||
max = max.min(upper.height);
|
||||
}
|
||||
if !found {
|
||||
return Err(error(Rule::MissingTarget, "Bottom row absent"));
|
||||
}
|
||||
if min > max {
|
||||
return Err(error(Rule::IncompatibleTabs, "Bottom row height constraints have no intersection"));
|
||||
}
|
||||
Ok((min, max))
|
||||
}
|
||||
|
||||
/// Bounded semantic validation, also required after serde and every transaction.
|
||||
pub fn validate(layout: &Layout, registry: &PanelRegistry) -> PanelResult<()> {
|
||||
layout.extent_priority_context.validate()?;
|
||||
if layout.version != LAYOUT_VERSION {
|
||||
return Err(error(Rule::Version, "unsupported layout version"));
|
||||
}
|
||||
valid_id(&layout.workspace.0)?;
|
||||
if layout.instances.len() > MAX_INSTANCES || layout.sections.len() > MAX_SECTIONS {
|
||||
if layout.instances.len() > MAX_INSTANCES || layout.sections.len() > MAX_SECTIONS || layout.columns.len() > MAX_SECTIONS {
|
||||
return Err(error(Rule::CollectionLimit, "layout collection limit"));
|
||||
}
|
||||
let mut columns = BTreeSet::new();
|
||||
for column in &layout.columns {
|
||||
valid_id(&column.id.0)?;
|
||||
if !columns.insert(&column.id) {
|
||||
return Err(error(Rule::DuplicateId, "duplicate column"));
|
||||
}
|
||||
if !column.zone.side() || !column.width.is_finite() || column.width <= 0.0 || column.width > MAX_LOGICAL {
|
||||
return Err(error(Rule::Bounds, "invalid side column"));
|
||||
}
|
||||
}
|
||||
let mut instances = BTreeSet::new();
|
||||
let mut kinds = BTreeSet::new();
|
||||
for p in &layout.instances {
|
||||
@@ -390,6 +843,8 @@ pub fn validate(layout: &Layout, registry: &PanelRegistry) -> PanelResult<()> {
|
||||
}
|
||||
p.memory.location.validate()?;
|
||||
p.memory.size.validate()?;
|
||||
validate_extent_priority(p.memory.preferred_extent, p.memory.extent_priority)?;
|
||||
validate_column_memory(p.memory.location.zone(), &p.memory.column, p.memory.column_index, p.memory.column_width, p.memory.weight)?;
|
||||
if p.memory.tab_index >= MAX_TABS || p.memory.section_index > MAX_SECTIONS {
|
||||
return Err(error(Rule::Bounds, "invalid placement memory"));
|
||||
}
|
||||
@@ -402,10 +857,13 @@ pub fn validate(layout: &Layout, registry: &PanelRegistry) -> PanelResult<()> {
|
||||
let mut hosts = BTreeSet::new();
|
||||
let mut pins = BTreeSet::new();
|
||||
let mut edges = BTreeSet::new();
|
||||
let mut last_columns = BTreeMap::<Zone, usize>::new();
|
||||
for s in &layout.sections {
|
||||
valid_id(&s.id.0)?;
|
||||
s.location.validate()?;
|
||||
s.size.validate()?;
|
||||
validate_extent_priority(s.preferred_extent, s.extent_priority)?;
|
||||
validate_weight(s.weight)?;
|
||||
if !sections.insert(&s.id) {
|
||||
return Err(error(Rule::DuplicateId, "duplicate section"));
|
||||
}
|
||||
@@ -421,6 +879,22 @@ pub fn validate(layout: &Layout, registry: &PanelRegistry) -> PanelResult<()> {
|
||||
return Err(error(Rule::DuplicateId, "native host reused"));
|
||||
}
|
||||
let zone = s.location.zone();
|
||||
if zone.side() {
|
||||
let id = s.column.as_ref().ok_or_else(|| error(Rule::Placement, "side section requires column"))?;
|
||||
let column = layout.column(id)?;
|
||||
let rank = layout
|
||||
.columns
|
||||
.iter()
|
||||
.filter(|c| c.zone == zone)
|
||||
.position(|c| c.id == *id)
|
||||
.ok_or_else(|| error(Rule::Placement, "section column has wrong side"))?;
|
||||
if column.zone != zone || last_columns.get(&zone).is_some_and(|last| *last > rank) {
|
||||
return Err(error(Rule::Placement, "sections must follow contiguous column order"));
|
||||
}
|
||||
last_columns.insert(zone, rank);
|
||||
} else if s.column.is_some() {
|
||||
return Err(error(Rule::Placement, "non-side section cannot have column"));
|
||||
}
|
||||
let first = edges.insert(zone);
|
||||
for id in &s.tabs {
|
||||
let instance = layout.instance(id)?;
|
||||
@@ -447,6 +921,14 @@ pub fn validate(layout: &Layout, registry: &PanelRegistry) -> PanelResult<()> {
|
||||
if !first {
|
||||
return Err(error(Rule::PinOrder, "pinned section must be outermost"));
|
||||
}
|
||||
if layout
|
||||
.columns
|
||||
.iter()
|
||||
.find(|column| column.zone == zone && layout.sections.iter().any(|s| s.column.as_ref() == Some(&column.id)))
|
||||
.is_some_and(|column| s.column.as_ref() != Some(&column.id))
|
||||
{
|
||||
return Err(error(Rule::PinOrder, "pinned group must occupy first live column"));
|
||||
}
|
||||
}
|
||||
}
|
||||
let (min, max) = tab_bounds(layout, registry, s)?;
|
||||
@@ -458,6 +940,7 @@ pub fn validate(layout: &Layout, registry: &PanelRegistry) -> PanelResult<()> {
|
||||
let spec = registry.get(&layout.instance(id)?.kind)?;
|
||||
if !spec.allowed_zones.contains(&return_to.zone)
|
||||
|| !return_to.size.within(spec.min_size, spec.max_size)
|
||||
|| return_to.column_width.is_some_and(|width| width < spec.min_size.width || width > spec.max_size.width)
|
||||
|| (return_to.collapsed && !spec.features.collapsible)
|
||||
{
|
||||
return Err(error(Rule::Placement, "native return violates member constraints"));
|
||||
@@ -465,11 +948,19 @@ pub fn validate(layout: &Layout, registry: &PanelRegistry) -> PanelResult<()> {
|
||||
}
|
||||
}
|
||||
}
|
||||
for column in &layout.columns {
|
||||
let (min, max) = column_bounds(layout, registry, &column.id)?;
|
||||
if column.width < min || column.width > max {
|
||||
return Err(error(Rule::Bounds, "column outside stacked tab bounds"));
|
||||
}
|
||||
}
|
||||
for p in &layout.instances {
|
||||
// Diagnose impossible tab groups before their shared size can make an
|
||||
// individual member's remembered size appear invalid.
|
||||
let spec = registry.get(&p.kind)?;
|
||||
if !p.memory.size.within(spec.min_size, spec.max_size) {
|
||||
if !p.memory.size.within(spec.min_size, spec.max_size)
|
||||
|| p.memory.column_width.is_some_and(|width| width < spec.min_size.width || width > spec.max_size.width)
|
||||
{
|
||||
return Err(error(Rule::Bounds, "invalid placement memory"));
|
||||
}
|
||||
if p.requested_open != seen.contains(&p.id) {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+1146
-30
File diff suppressed because it is too large.
Load diff
+4749
-16
File diff suppressed because it is too large.
Load diff
@@ -113,9 +113,9 @@ pub struct ExtrudeParams {
|
||||
/// Which way to extrude. Default: positive.
|
||||
#[serde(default)]
|
||||
pub direction: Option<DirectionParam>,
|
||||
/// Two Sides: a second distance the other way from the first side, which may be
|
||||
/// `through_all` or `to`; with `direction: negative` the first side goes against the normal
|
||||
/// and `distance2` along it.
|
||||
/// Two Sides: a second distance on the side `direction` leaves free; the first side may be
|
||||
/// `through_all` or `to`. With `direction: negative` the first side goes against the normal
|
||||
/// and `distance2` along it. A negative distance only turns its own side over.
|
||||
#[serde(default)]
|
||||
pub distance2: Option<LengthExpr>,
|
||||
/// Start this far from the sketch plane, along its normal.
|
||||
|
||||
@@ -88,6 +88,7 @@ pub mod render_ui;
|
||||
pub mod section;
|
||||
pub mod sheet;
|
||||
pub mod sketch;
|
||||
pub mod sketch_clipboard;
|
||||
pub mod sketch_constraints;
|
||||
pub mod sketch_create;
|
||||
pub mod sketch_ends;
|
||||
|
||||
@@ -46,6 +46,7 @@ pub enum Target {
|
||||
Workspace(WorkspaceId),
|
||||
Instance(InstanceId),
|
||||
Section(SectionId),
|
||||
Column(ColumnId),
|
||||
NativeHost(HostId),
|
||||
}
|
||||
impl From<Target> for LayoutTarget {
|
||||
@@ -54,6 +55,7 @@ impl From<Target> for LayoutTarget {
|
||||
Target::Workspace(id) => Self::Workspace(id),
|
||||
Target::Instance(id) => Self::Instance(id),
|
||||
Target::Section(id) => Self::Section(id),
|
||||
Target::Column(id) => Self::Column(id),
|
||||
Target::NativeHost(id) => Self::NativeHost(id),
|
||||
}
|
||||
}
|
||||
@@ -95,6 +97,20 @@ pub struct ReturnTo {
|
||||
pub size: OuterSize,
|
||||
pub collapsed: bool,
|
||||
#[serde(default)]
|
||||
pub section: Option<SectionId>,
|
||||
#[serde(default)]
|
||||
pub column: Option<ColumnId>,
|
||||
#[serde(default)]
|
||||
pub column_index: usize,
|
||||
#[serde(default)]
|
||||
pub column_width: Option<f32>,
|
||||
#[serde(default = "default_weight")]
|
||||
pub weight: f32,
|
||||
#[serde(default)]
|
||||
pub preferred_extent: Option<f32>,
|
||||
#[serde(default)]
|
||||
pub extent_priority: u16,
|
||||
#[serde(default)]
|
||||
pub join: Option<ReturnJoin>,
|
||||
}
|
||||
impl From<ReturnTo> for DockReturn {
|
||||
@@ -104,6 +120,13 @@ impl From<ReturnTo> for DockReturn {
|
||||
index: value.index,
|
||||
size: value.size.into(),
|
||||
collapsed: value.collapsed,
|
||||
section: value.section,
|
||||
column: value.column,
|
||||
column_index: value.column_index,
|
||||
column_width: value.column_width,
|
||||
weight: value.weight,
|
||||
preferred_extent: value.preferred_extent,
|
||||
extent_priority: value.extent_priority,
|
||||
join: value.join.map(|join| ReturnTab { section: join.section, index: join.index }),
|
||||
}
|
||||
}
|
||||
@@ -129,6 +152,7 @@ impl From<Location> for SectionLocation {
|
||||
pub enum Placement {
|
||||
NewSection { section: SectionId, index: usize, location: Location, size: OuterSize },
|
||||
JoinTab { section: SectionId, index: usize },
|
||||
Relative { section: SectionId, placement: RelativePlacement, new_section: SectionId, new_column: Option<ColumnId>, size: OuterSize },
|
||||
}
|
||||
impl From<Placement> for Destination {
|
||||
fn from(value: Placement) -> Self {
|
||||
@@ -137,6 +161,9 @@ impl From<Placement> for Destination {
|
||||
Self::NewSection { section, index, location: location.into(), size: size.into() }
|
||||
}
|
||||
Placement::JoinTab { section, index } => Self::JoinTab { section, index },
|
||||
Placement::Relative { section, placement, new_section, new_column, size } => {
|
||||
Self::Relative { section, placement, new_section, new_column, size: size.into() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -167,6 +194,16 @@ pub struct Move {
|
||||
pub id: Option<String>,
|
||||
pub destination: Placement,
|
||||
pub expected_revision: Option<u64>,
|
||||
#[serde(default)]
|
||||
pub activate: bool,
|
||||
}
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct HeaderAction {
|
||||
pub target: Option<Target>,
|
||||
pub id: Option<String>,
|
||||
pub action: ControlId,
|
||||
pub expected_revision: Option<u64>,
|
||||
}
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
@@ -174,6 +211,10 @@ pub struct Resize {
|
||||
pub target: Option<Target>,
|
||||
pub id: Option<String>,
|
||||
pub size: OuterSize,
|
||||
/// Dock thickness only: Bottom height or side column width. Both size
|
||||
/// components must be valid; the other component is ignored.
|
||||
#[serde(default)]
|
||||
pub thickness_only: bool,
|
||||
pub expected_revision: Option<u64>,
|
||||
}
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
//! Contracts and result types for the commands in `cmd/sketch_clipboard.rs`: copying, cutting
|
||||
//! and pasting sketch geometry (#10963).
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use schemars::{JsonSchema, Schema, SchemaGenerator};
|
||||
use serde::de::Error as _;
|
||||
use serde::{Deserialize, Deserializer, Serialize};
|
||||
use serde_json::Value;
|
||||
use solidcore_record::Vec2;
|
||||
|
||||
use super::types::{Point2, SketchRef, StringList, present};
|
||||
use crate::params;
|
||||
|
||||
/// Where a paste goes: a [`Point2`], with the paste's message.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct PastePoint(pub Vec2);
|
||||
|
||||
impl<'de> Deserialize<'de> for PastePoint {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
params::vec2(&Value::deserialize(d)?).map(PastePoint).ok_or_else(|| D::Error::custom("must be [x, y]"))
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for PastePoint {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"PastePoint".into()
|
||||
}
|
||||
fn inline_schema() -> bool {
|
||||
true
|
||||
}
|
||||
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
|
||||
generator.subschema_for::<Point2>()
|
||||
}
|
||||
}
|
||||
|
||||
/// Copy sketch curves and points, with the constraints and dimensions among them, to the sketch
|
||||
/// clipboard. The design is unchanged.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct CopyParams {
|
||||
/// Curve or point ids (default: the selected sketch geometry).
|
||||
#[serde(default)]
|
||||
pub entities: Option<StringList>,
|
||||
/// The sketch they are in (default: the one being edited).
|
||||
#[serde(default)]
|
||||
pub sketch: Option<SketchRef>,
|
||||
}
|
||||
|
||||
/// Copy sketch curves and points as `sketch.copy` does, then delete them, in one undo step.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct CutParams {
|
||||
/// Curve or point ids (default: the selected sketch geometry).
|
||||
#[serde(default)]
|
||||
pub entities: Option<StringList>,
|
||||
/// The sketch they are in (default: the one being edited).
|
||||
#[serde(default)]
|
||||
pub sketch: Option<SketchRef>,
|
||||
}
|
||||
|
||||
/// Paste what was copied into a sketch, with its constraints and dimensions, in one undo step.
|
||||
/// The pasted geometry is selected. Without `at` or `translate`, it goes a step away from the
|
||||
/// original in its own sketch (further each time), and at the same coordinates in another.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct PasteParams {
|
||||
/// The sketch point the copy's centre goes to. Takes the place of `translate`.
|
||||
#[serde(default, deserialize_with = "present")]
|
||||
#[schemars(with = "PastePoint")]
|
||||
pub at: Option<PastePoint>,
|
||||
/// How far to move the copy from where it was (mm).
|
||||
#[serde(default, deserialize_with = "present")]
|
||||
#[schemars(with = "PastePoint")]
|
||||
pub translate: Option<PastePoint>,
|
||||
/// The sketch to paste into (default: the one being edited).
|
||||
#[serde(default)]
|
||||
pub sketch: Option<SketchRef>,
|
||||
}
|
||||
|
||||
/// What `sketch.copy` and `sketch.cut` return: what is on the clipboard.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct Copied {
|
||||
/// How many curves, those of copied text included.
|
||||
pub curves: usize,
|
||||
/// How many points that belong to no copied curve.
|
||||
pub points: usize,
|
||||
/// How many texts.
|
||||
pub texts: usize,
|
||||
/// How many constraints and dimensions among them came along.
|
||||
pub constraints: usize,
|
||||
/// The centre of what was copied, in sketch coordinates: where `at` puts it.
|
||||
pub center: [f64; 2],
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// What `sketch.paste` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct Pasted {
|
||||
/// The new curves' ids.
|
||||
pub curves: Vec<String>,
|
||||
/// The new lone points' ids.
|
||||
pub points: Vec<String>,
|
||||
/// The new constraints' and dimensions' ids.
|
||||
pub constraints: Vec<String>,
|
||||
/// How far the copy was moved from where it was (mm).
|
||||
pub translate: [f64; 2],
|
||||
/// The sketch's solve: `{solved, dof}`.
|
||||
pub sketch: Value,
|
||||
/// In the warn parameter-check mode: what the call's parameters got wrong.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub param_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "sketch_clipboard_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,92 @@
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{Copied, CopyParams, CutParams, PasteParams, Pasted};
|
||||
use crate::Session;
|
||||
use crate::schema::tests::{assert_keys, conforms};
|
||||
use crate::schema::{ParamCheck, input_schema_for, output_schema_for};
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
|
||||
}
|
||||
|
||||
/// A sketch `A` being edited, as these commands need, with a line and a circle; the line is
|
||||
/// copied. Their ids.
|
||||
fn drawing(s: &mut Session) -> (String, String) {
|
||||
run(s, "sketch.create", json!({"plane": "XY", "name": "A"}));
|
||||
let line = run(s, "sketch.line", json!({"points": [[0, 0], [10, 0]]}))["curves"][0].as_str().map(str::to_string).unwrap_or_default();
|
||||
let circle =
|
||||
run(s, "sketch.circle.center", json!({"center": [30, 0], "radius": 4}))["curves"][0].as_str().map(str::to_string).unwrap_or_default();
|
||||
run(s, "sketch.copy", json!({"entities": [line]}));
|
||||
(line, circle)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schemas_and_the_key_check_agree() {
|
||||
assert_keys(input_schema_for::<CopyParams>(), &["entities", "sketch"]);
|
||||
assert_keys(input_schema_for::<CutParams>(), &["entities", "sketch"]);
|
||||
assert_keys(input_schema_for::<PasteParams>(), &["at", "sketch", "translate"]);
|
||||
}
|
||||
|
||||
/// A call that fails today gets the same message in strict. These commands run only while a
|
||||
/// sketch is being edited, so each call runs in one (`assert_strict_keeps_todays_errors` runs
|
||||
/// after a finished sketch).
|
||||
#[test]
|
||||
fn strict_keeps_todays_errors() {
|
||||
for (id, p) in [
|
||||
("sketch.copy", json!({})),
|
||||
("sketch.copy", json!({"entities": null})),
|
||||
("sketch.copy", json!({"entities": ["nope"]})),
|
||||
("sketch.copy", json!({"entities": "l1", "sketch": "Nope"})),
|
||||
("sketch.cut", json!({"entities": ["nope"]})),
|
||||
("sketch.paste", json!({"at": "x"})),
|
||||
("sketch.paste", json!({"at": null})),
|
||||
("sketch.paste", json!({"at": [1e9, 0]})),
|
||||
("sketch.paste", json!({"at": "x", "translate": [1, 2]})),
|
||||
("sketch.paste", json!({"translate": [1, 2, 3]})),
|
||||
("sketch.paste", json!({"translate": {"x": 1}})),
|
||||
("sketch.paste", json!({"sketch": "Nope"})),
|
||||
] {
|
||||
let error = |level: ParamCheck| {
|
||||
let mut s = Session::default();
|
||||
drawing(&mut s);
|
||||
s.param_check = level;
|
||||
s.execute(id, &p).err().map(|e| e.to_string())
|
||||
};
|
||||
let off = error(ParamCheck::Off);
|
||||
assert!(off.is_some(), "{id} {p} should fail today");
|
||||
assert_eq!(error(ParamCheck::Strict), off, "{id} {p}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #10963: copy, cut and paste reply as their output schemas say, in Warn without warnings for
|
||||
/// good calls and with them for a misspelt key: a copy of one curve and of the selection, pastes
|
||||
/// without a position, at a point and moved, and a cut pasted back.
|
||||
#[test]
|
||||
fn clipboard_commands_reply_with_their_schemas() {
|
||||
let (copied, pasted) = (output_schema_for::<Copied>(), output_schema_for::<Pasted>());
|
||||
let matches = |schema: &schemars::Schema, r: &Value, warned: bool| {
|
||||
let schema = schema.as_value();
|
||||
assert!(conforms(schema, schema, r), "{r} doesn't match {schema}");
|
||||
assert_eq!(r.get("param_warnings").is_some(), warned, "{r}");
|
||||
};
|
||||
let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
|
||||
let (line, circle) = drawing(&mut s);
|
||||
let r = run(&mut s, "sketch.copy", json!({"entities": [line, circle], "sketch": "A"}));
|
||||
matches(&copied, &r, false);
|
||||
assert_eq!((r["curves"].as_u64(), r["center"].as_array().map(Vec::len)), (Some(2), Some(2)), "{r}");
|
||||
let r = run(&mut s, "sketch.paste", json!({}));
|
||||
matches(&pasted, &r, false);
|
||||
assert_eq!(r["curves"].as_array().map(Vec::len), Some(2), "{r}");
|
||||
// The pasted curves are selected: a copy with no `entities` takes them.
|
||||
matches(&copied, &run(&mut s, "sketch.copy", json!({})), false);
|
||||
matches(&pasted, &run(&mut s, "sketch.paste", json!({"at": [50, 50]})), false);
|
||||
let r = run(&mut s, "sketch.paste", json!({"translate": {"x": 5, "y": -5}, "sketch": "A"}));
|
||||
matches(&pasted, &r, false);
|
||||
assert_eq!(r["translate"], json!([5.0, -5.0]), "{r}");
|
||||
matches(&copied, &run(&mut s, "sketch.cut", json!({"entities": circle})), false);
|
||||
matches(&pasted, &run(&mut s, "sketch.paste", json!({})), false);
|
||||
|
||||
matches(&copied, &run(&mut s, "sketch.copy", json!({"entities": [line], "entites": [line]})), true);
|
||||
matches(&copied, &run(&mut s, "sketch.cut", json!({"entities": [line], "sketc": "A"})), true);
|
||||
matches(&pasted, &run(&mut s, "sketch.paste", json!({"at": [0, 0], "tranlate": [1, 1]})), true);
|
||||
}
|
||||
@@ -198,9 +198,7 @@ sketch.constraint.polygon
|
||||
sketch.constraint.symmetry
|
||||
sketch.constraint.tangent
|
||||
sketch.construction
|
||||
sketch.copy
|
||||
sketch.create
|
||||
sketch.cut
|
||||
sketch.delete
|
||||
sketch.dimension
|
||||
sketch.dimension_text
|
||||
@@ -233,7 +231,6 @@ sketch.move_point
|
||||
sketch.offset
|
||||
sketch.offset.break
|
||||
sketch.options
|
||||
sketch.paste
|
||||
sketch.pattern.circular
|
||||
sketch.pattern.rectangular
|
||||
sketch.point
|
||||
|
||||
@@ -2087,6 +2087,15 @@ fn threemf_export_open_insert() {
|
||||
assert_eq!(s.model.state().bodies.len(), 3);
|
||||
assert!(rel(volume(&mut s), 2.0 * want) < 2e-3);
|
||||
assert!(s.execute("file.insert_mesh", &json!({"path": dir.join("x.step").to_string_lossy()})).is_err());
|
||||
// An STL's unit scales it to millimetres as it is read: inches are 25.4 mm each. 3MF states its own.
|
||||
let mut inch = Session::default();
|
||||
let r = run(&mut inch, "file.insert_mesh", json!({"path": stl.to_string_lossy(), "units": "in"}));
|
||||
assert_eq!(r["units"], "in", "{r}");
|
||||
assert!(rel(volume(&mut inch), want * 25.4f64.powi(3)) < 2e-3);
|
||||
for bad_units in [json!("furlong"), json!(7), json!("")] {
|
||||
assert!(inch.execute("file.insert_mesh", &json!({"path": stl.to_string_lossy(), "units": bad_units})).is_err());
|
||||
}
|
||||
assert!(inch.execute("file.insert_mesh", &json!({"path": p.to_string_lossy(), "units": "in"})).is_err());
|
||||
let junk = dir.join("junk.3mf");
|
||||
std::fs::write(&junk, b"PK\x03\x04 not really").unwrap();
|
||||
let before = s.doc.clone();
|
||||
@@ -2096,6 +2105,90 @@ fn threemf_export_open_insert() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A cube one unit across comes in as that unit in millimetres, for every unit: the sizes are
|
||||
/// written out here, not read from the table that scales the file.
|
||||
#[test]
|
||||
fn stl_cube_of_one_unit_comes_in_as_that_many_millimetres() {
|
||||
let dir = std::env::temp_dir().join(format!("solidcraft-stl-units-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let stl = dir.join("one.stl");
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "solid.box", json!({"length": 1, "width": 1, "height": 1}));
|
||||
run(&mut s, "file.save_mesh", json!({"path": stl.to_string_lossy()}));
|
||||
for (units, edge) in [("mm", 1.0_f64), ("cm", 10.0), ("m", 1000.0), ("in", 25.4), ("ft", 304.8)] {
|
||||
let mut t = Session::default();
|
||||
let r = run(&mut t, "file.insert_mesh", json!({"path": stl.to_string_lossy(), "units": units}));
|
||||
assert_eq!(r["units"], units, "{r}");
|
||||
let solidcraft_doc::FeatureKind::MeshImport { meshes, .. } = &t.doc.features[0].kind else { panic!("{units}: not a mesh import") };
|
||||
for axis in 0..3 {
|
||||
let along: Vec<f64> = meshes[0].positions.chunks(3).map(|p| p[axis]).collect();
|
||||
let (lo, hi) = (along.iter().cloned().fold(f64::MAX, f64::min), along.iter().cloned().fold(f64::MIN, f64::max));
|
||||
assert!(((hi - lo) - edge).abs() <= edge * 1e-12, "{units}: edge {} along axis {axis}, want {edge}", hi - lo);
|
||||
}
|
||||
assert!(rel(volume(&mut t), edge.powi(3)) < 1e-9, "{units}: volume {}", volume(&mut t));
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A unit given on import and a Scale feature after an import in millimetres make the same body,
|
||||
/// within floating-point precision, for each unitless mesh format: STL, OBJ and PLY (with faces).
|
||||
#[test]
|
||||
fn a_unit_on_import_matches_importing_in_millimetres_then_scaling() {
|
||||
let dir = std::env::temp_dir().join(format!("solidcraft-unit-vs-scale-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
// A cube one unit across, as the three formats write it.
|
||||
let corners = [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0], [0, 0, 1], [1, 0, 1], [1, 1, 1], [0, 1, 1]];
|
||||
let triangles =
|
||||
[[0, 2, 1], [0, 3, 2], [4, 5, 6], [4, 6, 7], [0, 1, 5], [0, 5, 4], [3, 7, 6], [3, 6, 2], [0, 4, 7], [0, 7, 3], [1, 2, 6], [1, 6, 5]];
|
||||
let vertex = |i: usize| format!("{} {} {}", corners[i][0], corners[i][1], corners[i][2]);
|
||||
let mut stl = String::from("solid cube\n");
|
||||
for t in triangles {
|
||||
stl += "facet normal 0 0 0\nouter loop\n";
|
||||
for i in t {
|
||||
stl += &format!("vertex {}\n", vertex(i));
|
||||
}
|
||||
stl += "endloop\nendfacet\n";
|
||||
}
|
||||
stl += "endsolid cube\n";
|
||||
let mut obj = String::from("o Cube\n");
|
||||
for i in 0..8 {
|
||||
obj += &format!("v {}\n", vertex(i));
|
||||
}
|
||||
for t in triangles {
|
||||
obj += &format!("f {} {} {}\n", t[0] + 1, t[1] + 1, t[2] + 1);
|
||||
}
|
||||
let mut ply = String::from("ply\nformat ascii 1.0\nelement vertex 8\nproperty float x\nproperty float y\nproperty float z\n");
|
||||
ply += "element face 12\nproperty list uchar int vertex_indices\nend_header\n";
|
||||
for i in 0..8 {
|
||||
ply += &format!("{}\n", vertex(i));
|
||||
}
|
||||
for t in triangles {
|
||||
ply += &format!("3 {} {} {}\n", t[0], t[1], t[2]);
|
||||
}
|
||||
let close = |a: f64, b: f64| (a - b).abs() <= 1e-9 * b.abs().max(1.0);
|
||||
for (extension, text) in [("stl", stl), ("obj", obj), ("ply", ply)] {
|
||||
let path = dir.join(format!("cube.{extension}"));
|
||||
std::fs::write(&path, text).unwrap();
|
||||
for (units, mm) in [("mm", 1.0_f64), ("cm", 10.0), ("m", 1000.0), ("in", 25.4), ("ft", 304.8)] {
|
||||
let mut with_unit = Session::default();
|
||||
run(&mut with_unit, "file.insert_mesh", json!({"path": path.to_string_lossy(), "units": units}));
|
||||
let mut scaled = Session::default();
|
||||
let inserted = run(&mut scaled, "file.insert_mesh", json!({"path": path.to_string_lossy()}));
|
||||
let body = inserted["bodies"][0].as_str().unwrap().to_string();
|
||||
run(&mut scaled, "solid.scale", json!({"bodies": [body], "factor": mm.to_string()}));
|
||||
let (a, b) = (with_unit.model.state().bodies[0].mesh().bounds(), scaled.model.state().bodies[0].mesh().bounds());
|
||||
let (a, b) = ([a.min.x, a.min.y, a.min.z, a.max.x, a.max.y, a.max.z], [b.min.x, b.min.y, b.min.z, b.max.x, b.max.y, b.max.z]);
|
||||
for (x, y) in a.into_iter().zip(b) {
|
||||
assert!(close(x, y), "{extension} {units}: bounds {a:?} against {b:?}");
|
||||
}
|
||||
let (va, vb) = (volume(&mut with_unit), volume(&mut scaled));
|
||||
assert!(rel(va, vb) < 1e-9, "{extension} {units}: volume {va} against {vb}");
|
||||
assert!(rel(va, mm.powi(3)) < 1e-9, "{extension} {units}: volume {va}, want {}", mm.powi(3));
|
||||
}
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn holes_at_sketch_points_threads_and_components() {
|
||||
let mut s = Session::default();
|
||||
|
||||
+109
-1
@@ -292,8 +292,27 @@ pub struct MeshFeature {
|
||||
/// feature. A glTF file's bodies are all built where they are (see [`read_gltf`] for its node
|
||||
/// tree), and it can't read buffers in other files.
|
||||
pub fn mesh_import_feature(bytes: &[u8], file: &str) -> Result<MeshFeature> {
|
||||
mesh_import_feature_in(bytes, file, 1.0)
|
||||
}
|
||||
|
||||
/// [`mesh_import_feature`] for a file whose coordinates are in a unit of `mm_per_unit`
|
||||
/// millimetres (25.4 for inches). The scaling is made once, as the file is read: the feature
|
||||
/// keeps the millimetre mesh and nothing of the unit. Only STL, OBJ and PLY files take a unit
|
||||
/// other than millimetres; a 3MF or glTF file says its own.
|
||||
pub fn mesh_import_feature_in(bytes: &[u8], file: &str, mm_per_unit: f64) -> Result<MeshFeature> {
|
||||
let _span = solidcraft_profile::span("import", "mesh_import_feature");
|
||||
if !mm_per_unit.is_finite() || mm_per_unit <= 0.0 {
|
||||
return Err(IoError::Invalid("the unit must be a positive number of millimetres".into()));
|
||||
}
|
||||
let own_units = |what: &str| {
|
||||
if mm_per_unit == 1.0 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(IoError::Invalid(format!("a {what} file states its own units; a unit applies to STL, OBJ and PLY files")))
|
||||
}
|
||||
};
|
||||
if is_gltf_path(file) {
|
||||
own_units("glTF")?;
|
||||
let mut no_files = |name: &str| Err(format!("`{name}` can't be read here"));
|
||||
let mut g = read_gltf(bytes, file, &mut no_files)?;
|
||||
g.flatten();
|
||||
@@ -305,7 +324,7 @@ pub fn mesh_import_feature(bytes: &[u8], file: &str) -> Result<MeshFeature> {
|
||||
let path = std::path::Path::new(file);
|
||||
let stem = path.file_stem().map(|s| s.to_string_lossy().to_string()).filter(|s| !s.trim().is_empty()).unwrap_or_else(|| "Mesh".into());
|
||||
let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase();
|
||||
let (objects, warnings) = if ext == "obj" {
|
||||
let (mut objects, warnings) = if ext == "obj" {
|
||||
obj::read_obj(bytes, &stem)?
|
||||
} else if ext == "ply" {
|
||||
ply::read_ply_mesh(bytes, &stem)?
|
||||
@@ -319,8 +338,20 @@ pub fn mesh_import_feature(bytes: &[u8], file: &str) -> Result<MeshFeature> {
|
||||
let triangles = (0..n).map(|i| [i * 3, i * 3 + 1, i * 3 + 2]).collect();
|
||||
(vec![MeshObject { name: stem.clone(), positions, triangles, ..Default::default() }], Vec::new())
|
||||
} else {
|
||||
own_units("3MF")?;
|
||||
read_3mf(bytes)?
|
||||
};
|
||||
if mm_per_unit != 1.0 {
|
||||
let limit = solidcraft_doc::point_cloud::MAX_COORD;
|
||||
for o in &mut objects {
|
||||
for p in &mut o.positions {
|
||||
*p = *p * mm_per_unit;
|
||||
if ![p.x, p.y, p.z].iter().all(|v| v.is_finite() && v.abs() <= limit) {
|
||||
return Err(IoError::Invalid(format!("mesh `{}` is out of range at this unit", o.name)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Check every mesh now, so the command fails rather than the timeline.
|
||||
let mut meshes = Vec::with_capacity(objects.len());
|
||||
for o in &objects {
|
||||
@@ -1011,6 +1042,83 @@ mod tests {
|
||||
solidcraft_kernel::measure(&solidcraft_kernel::mesh_body(&pos, &tris).unwrap()).unwrap().volume
|
||||
}
|
||||
|
||||
/// A unit scales an STL's coordinates to millimetres once, as it is read (an inch cube of 10 is
|
||||
/// 254 mm across); the feature keeps nothing of the unit. A bad unit, a unit on a file that
|
||||
/// states its own, and a size beyond the limits are refused.
|
||||
#[test]
|
||||
fn stl_unit_scales_the_mesh_as_it_is_read() {
|
||||
let stl = cube_stl(&[], b"solid exported by something", None, [0.0; 3]);
|
||||
let volume = |mm: f64| {
|
||||
let f = mesh_import_feature_in(&stl, "x.stl", mm).unwrap();
|
||||
let solidcraft_doc::FeatureKind::MeshImport { meshes, .. } = f.kind else { panic!() };
|
||||
let m = &meshes[0];
|
||||
let pos: Vec<Vec3> = m.positions.chunks(3).map(|c| Vec3::new(c[0], c[1], c[2])).collect();
|
||||
let tris: Vec<[u32; 3]> = m.triangles.chunks(3).map(|c| [c[0], c[1], c[2]]).collect();
|
||||
solidcraft_kernel::measure(&solidcraft_kernel::mesh_body(&pos, &tris).unwrap()).unwrap().volume
|
||||
};
|
||||
assert!((volume(1.0) - 1000.0).abs() < 1e-6);
|
||||
assert!((volume(25.4) - 1000.0 * 25.4f64.powi(3)).abs() < 1e-3 * 25.4f64.powi(3));
|
||||
assert!(mesh_import_feature_in(&stl, "x.stl", 0.0).is_err());
|
||||
assert!(mesh_import_feature_in(&stl, "x.stl", f64::NAN).is_err());
|
||||
assert!(mesh_import_feature_in(&stl, "x.stl", 1e12).is_err());
|
||||
assert!(mesh_import_feature_in(&stl, "x.3mf", 25.4).is_err());
|
||||
assert!(mesh_import_feature_in(&stl, "x.glb", 25.4).is_err());
|
||||
}
|
||||
|
||||
/// An STL holding `triangles` as a binary file.
|
||||
fn stl_of(triangles: &[[[f32; 3]; 3]]) -> Vec<u8> {
|
||||
let mut bytes = vec![0u8; 80];
|
||||
bytes.extend((triangles.len() as u32).to_le_bytes());
|
||||
for triangle in triangles {
|
||||
bytes.extend([0u8; 12]);
|
||||
for vertex in triangle {
|
||||
for coordinate in vertex {
|
||||
bytes.extend(coordinate.to_le_bytes());
|
||||
}
|
||||
}
|
||||
bytes.extend([0u8; 2]);
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
/// Every stored coordinate is the file's `f32` value widened to `f64` and multiplied by the
|
||||
/// unit's millimetres, exactly: no rounding through `f32`, and not scaled twice. The values
|
||||
/// are exact in `f32`, so the expected numbers carry no rounding of their own.
|
||||
#[test]
|
||||
fn stl_coordinates_are_the_widened_value_times_the_unit_exactly() {
|
||||
let (a, b, c, d) = ([0.5, -3.75, 1.25], [7.0, 0.25, -2.5], [-1.5, 4.0, 0.125], [2.0, 2.0, 9.5]);
|
||||
let triangles = [[a, b, c], [a, c, d], [a, d, b], [b, d, c]];
|
||||
let stl = stl_of(&triangles);
|
||||
for (unit, mm) in solidcraft_doc::point_cloud::UNITS {
|
||||
let feature = mesh_import_feature_in(&stl, "t.stl", mm).unwrap();
|
||||
let solidcraft_doc::FeatureKind::MeshImport { meshes, .. } = feature.kind else { panic!() };
|
||||
let want: Vec<f64> = triangles.iter().flatten().flatten().map(|v| f64::from(*v) * mm).collect();
|
||||
assert_eq!(&*meshes[0].positions, want.as_slice(), "{unit}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A PLY with faces, read as a mesh, takes a unit as an STL does: it states none either.
|
||||
#[test]
|
||||
fn ply_mesh_unit_scales_its_vertices_exactly() {
|
||||
let corners = [[0.5f32, -3.75, 1.25], [7.0, 0.25, -2.5], [-1.5, 4.0, 0.125], [2.0, 2.0, 9.5]];
|
||||
let mut ply = String::from("ply\nformat ascii 1.0\nelement vertex 4\nproperty float x\nproperty float y\nproperty float z\n");
|
||||
ply.push_str("element face 4\nproperty list uchar int vertex_indices\nend_header\n");
|
||||
for c in corners {
|
||||
ply.push_str(&format!("{} {} {}\n", c[0], c[1], c[2]));
|
||||
}
|
||||
ply.push_str("3 0 1 2\n3 0 2 3\n3 0 3 1\n3 1 3 2\n");
|
||||
let sorted = |mut v: Vec<f64>| {
|
||||
v.sort_by(f64::total_cmp);
|
||||
v
|
||||
};
|
||||
for (unit, mm) in solidcraft_doc::point_cloud::UNITS {
|
||||
let feature = mesh_import_feature_in(ply.as_bytes(), "t.ply", mm).unwrap();
|
||||
let solidcraft_doc::FeatureKind::MeshImport { meshes, .. } = feature.kind else { panic!() };
|
||||
let want: Vec<f64> = corners.iter().flatten().map(|v| f64::from(*v) * mm).collect();
|
||||
assert_eq!(sorted(meshes[0].positions.to_vec()), sorted(want), "{unit}");
|
||||
}
|
||||
}
|
||||
|
||||
/// STL quirks: a binary header starting with "solid", a zero triangle count, garbage
|
||||
/// normals, stray inverted facets and non-finite vertices.
|
||||
#[test]
|
||||
|
||||
@@ -340,6 +340,7 @@ pub(crate) fn owns_pointer(app: &SolveApp, proj: &Proj, p: Pos2) -> bool {
|
||||
|
||||
/// Draw the manipulator and the value box (called by the viewport after the model is drawn).
|
||||
pub fn show(app: &mut SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj) {
|
||||
crate::extrude_face_snap::set(None);
|
||||
// While OK computes, the inputs hold what it computes: no arrow to drag, no box to type in.
|
||||
if app.applying.is_some() {
|
||||
return;
|
||||
@@ -607,22 +608,25 @@ fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj,
|
||||
}
|
||||
// Two sides: the second distance gets its own arrow, the other way from the first side.
|
||||
if let (Kind::Extrude { direction: crate::dialogs::TWO_SIDES | crate::dialogs::TWO_SIDES_REVERSED, distance2, .. }, Some(n)) = (&mut d.kind, dir)
|
||||
&& let Some(l2) = crate::length_input::eval(&app.session.doc, distance2, ValueKind::Length).ok().filter(|v| v.is_finite())
|
||||
{
|
||||
drag_arrow(
|
||||
&app.session.doc,
|
||||
// Distance 2 stays on the side Direction gives it, whatever the sign of Distance 1. Only
|
||||
// a reach computed from the model (To Object, Through All) sends it the other way.
|
||||
let n2 = if sign < 0.0 { n } else { -n };
|
||||
let before = distance2.clone();
|
||||
// While its text does not evaluate (cleared, or a `-` typed first) there is no arrow,
|
||||
// but the box stays below the base so the typing can be finished there.
|
||||
let ts = crate::length_input::eval(&app.session.doc, distance2, ValueKind::Length).ok().filter(|v| v.is_finite()).and_then(|l2| {
|
||||
drag_arrow(&app.session.doc, ui, painter, proj, base, bs, n2, l2, true, egui::Id::unique("sc_manipulator2"), half_height, 0.0, distance2)
|
||||
});
|
||||
value_box_in(
|
||||
ui,
|
||||
painter,
|
||||
proj,
|
||||
base,
|
||||
bs,
|
||||
-(n * sign),
|
||||
l2,
|
||||
true,
|
||||
egui::Id::unique("sc_manipulator2"),
|
||||
half_height,
|
||||
0.0,
|
||||
(egui::Id::unique("sc_canvas_area2"), egui::Id::unique("sc_canvas_value2")),
|
||||
"Distance 2",
|
||||
distance2,
|
||||
(ts.unwrap_or(bs + vec2(16.0, 14.0)) + vec2(14.0, 8.0), egui::Align2::LEFT_TOP),
|
||||
*distance2 != before,
|
||||
false,
|
||||
box_place(app, proj),
|
||||
);
|
||||
}
|
||||
// A chamfer of two distances: Distance 2 gets its own arrow along the other face.
|
||||
@@ -755,6 +759,12 @@ fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj,
|
||||
}
|
||||
// A placement marker at the base: the arrow stands above it and the base dot is the marker's.
|
||||
let clear = crate::place_gizmo::arrow_clearance(app, d);
|
||||
// While an extrude's arrow is dragged, the flat faces it can stop at (#2398).
|
||||
let arrow_id = egui::Id::unique("sc_manipulator");
|
||||
let stops = match dir {
|
||||
Some(n) if ui.ctx().is_being_dragged(arrow_id) => crate::extrude_face_snap::stops(app, d, base, n * sign),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let Some((label, kind, value)) = d.primary() else { return };
|
||||
let len = all_span.or_else(|| {
|
||||
if to_span.is_some() && value.trim().is_empty() {
|
||||
@@ -775,21 +785,22 @@ fn draw(app: &SolveApp, ui: &mut egui::Ui, painter: &egui::Painter, proj: &Proj,
|
||||
let mut shown_value = format_len(&app.session.doc, half + baseline);
|
||||
let original_shown = shown_value.clone();
|
||||
let dragged = if to_span.is_some() || symmetric_scale != 1.0 { &mut shown_value } else { &mut *value };
|
||||
if let Some(ts) = drag_arrow(
|
||||
let drawn = drag_arrow_to(
|
||||
&app.session.doc,
|
||||
ui,
|
||||
painter,
|
||||
proj,
|
||||
base,
|
||||
bs,
|
||||
n,
|
||||
half + baseline,
|
||||
signed,
|
||||
egui::Id::unique("sc_manipulator"),
|
||||
ArrowLine { base, bs, n, l: half + baseline, signed, clear_px: clear },
|
||||
arrow_id,
|
||||
half_height,
|
||||
clear,
|
||||
&stops,
|
||||
dragged,
|
||||
) {
|
||||
);
|
||||
if let Some((_, Some(stop))) = &drawn {
|
||||
crate::extrude_face_snap::outline(app, painter, proj, stop);
|
||||
}
|
||||
crate::extrude_face_snap::set(drawn.as_ref().and_then(|(_, stop)| stop.clone()));
|
||||
if let Some((ts, _)) = drawn {
|
||||
if (to_span.is_some() || symmetric_scale != 1.0)
|
||||
&& shown_value != original_shown
|
||||
&& let Ok(v) = crate::length_input::eval(&app.session.doc, &shown_value, ValueKind::Length)
|
||||
@@ -1083,6 +1094,39 @@ fn drag_arrow(
|
||||
clear_px: f32,
|
||||
value: &mut String,
|
||||
) -> Option<Pos2> {
|
||||
let line = ArrowLine { base, bs, n, l, signed, clear_px };
|
||||
drag_arrow_to(doc, ui, painter, proj, line, id, half_height, &[], value).map(|(ts, _)| ts)
|
||||
}
|
||||
|
||||
/// Where a drag arrow stands: from `base` (on screen `bs`) along `n`, showing `l`; `signed` lets
|
||||
/// it go below zero, `clear_px` keeps that much of the base free (see [`drag_arrow`]).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct ArrowLine {
|
||||
base: Vec3,
|
||||
bs: Pos2,
|
||||
n: Vec3,
|
||||
l: f64,
|
||||
signed: bool,
|
||||
clear_px: f32,
|
||||
}
|
||||
|
||||
/// [`drag_arrow`] that also stops at `stops` (#2398): a drag whose tip comes near a stop's
|
||||
/// plane takes its distance exactly instead of a round step. Returns the tip's screen position
|
||||
/// and the stop it took this frame.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn drag_arrow_to(
|
||||
doc: &solidcraft_engine::doc::Document,
|
||||
ui: &mut egui::Ui,
|
||||
painter: &egui::Painter,
|
||||
proj: &Proj,
|
||||
line: ArrowLine,
|
||||
id: egui::Id,
|
||||
half_height: f64,
|
||||
stops: &[crate::extrude_face_snap::Stop],
|
||||
value: &mut String,
|
||||
) -> Option<(Pos2, Option<crate::extrude_face_snap::Stop>)> {
|
||||
let ArrowLine { base, bs, n, l, signed, clear_px } = line;
|
||||
let mut stopped = None;
|
||||
let t = Tokens::get();
|
||||
let min = f64::from(40.0 + clear_px) * 2.0 * half_height / f64::from(proj.rect.height().max(1.0));
|
||||
let tip = |length: f64| {
|
||||
@@ -1124,7 +1168,12 @@ fn drag_arrow(
|
||||
let v = v - ui.data(|d| d.get_temp::<f64>(grab)).unwrap_or(0.0);
|
||||
let free = crate::tool_modifiers::manipulator_free();
|
||||
let step = snap_step(half_height);
|
||||
let mut v = if free { v } else { (v / step).round() * step };
|
||||
stopped = if free { None } else { crate::extrude_face_snap::nearest(proj, base, n, v, stops).cloned() };
|
||||
let mut v = match &stopped {
|
||||
Some(stop) => stop.distance,
|
||||
None if free => v,
|
||||
None => (v / step).round() * step,
|
||||
};
|
||||
if !signed {
|
||||
v = v.max(if free { 1e-3 } else { step });
|
||||
}
|
||||
@@ -1141,7 +1190,7 @@ fn drag_arrow(
|
||||
painter.circle_stroke(ts, 8.0, Stroke::new(1.5, col));
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::Grab);
|
||||
}
|
||||
Some(ts)
|
||||
Some((ts, stopped))
|
||||
}
|
||||
|
||||
/// A fillet's radius spline on each of its edges (a spline fillet, or the splines a taper gave
|
||||
|
||||
@@ -27,6 +27,8 @@
|
||||
//! section the viewport shows (no window needed); the ground grid and the origin's axes as the
|
||||
//! window shows them, unless `grid` or `axes` says
|
||||
//! - `ui.icon_audit {reset?, stop?}`: collect/drain requested icon names, resolved masters and placeholder flags;
|
||||
//! - `ui.panel_fixture {enabled?, preset?}`: opt-in synthetic content in the real panel host;
|
||||
//! `{}` observes the current host, probe and Session without ticking or model commands
|
||||
//! - `ui.menu {x?, y?, target?, close?}`: open a context menu at a point (the viewport's marking
|
||||
//! menu, or a browser menu with `target: {type: body|sketch|component, …}`); without a point,
|
||||
//! the open menu and its items. `ui.menuPick {item}` runs an item by id or label;
|
||||
@@ -744,6 +746,13 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) ->
|
||||
"notice": app.blur_session.guard.notice, "opted_out": app.blur_session.guard.opted_out}}),
|
||||
)
|
||||
}
|
||||
"ui.panel_fixture" => {
|
||||
let result = crate::panel_runtime::control_specimen(app, p);
|
||||
if result.is_ok() && (p.get("enabled").is_some() || p.get("preset").is_some()) {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
wrap(result)
|
||||
}
|
||||
"ui.status_fixture" => wrap(crate::viewport_status_fixture::control(app, p)),
|
||||
"ui.workspace" => {
|
||||
if let Some(workspace) = s("workspace") {
|
||||
@@ -872,11 +881,15 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) ->
|
||||
})),
|
||||
"ui.file" => {
|
||||
let Some(path) = s("path") else { return err("path is required") };
|
||||
if p.get("insert").and_then(Value::as_bool).unwrap_or(false) {
|
||||
app.insert_path_async(path);
|
||||
} else {
|
||||
app.open_path_async(path);
|
||||
// A control call never meets the unit dialog an STL or OBJ file asks a person: it names
|
||||
// `units` itself, or the file is in millimetres.
|
||||
let kind =
|
||||
if p.get("insert").and_then(Value::as_bool).unwrap_or(false) { crate::file_load::Kind::Insert } else { crate::file_load::Kind::Open };
|
||||
let mut request = crate::file_load::Request::new(path, kind);
|
||||
if let Some(units) = p.get("units").filter(|u| !u.is_null()) {
|
||||
request.options.insert("units".into(), units.clone());
|
||||
}
|
||||
let _ = crate::file_load::begin_request(app, request);
|
||||
ok(json!({"busy": app.file_load.busy()}))
|
||||
}
|
||||
"ui.documents" => ok(crate::documents::control(app, p)),
|
||||
@@ -885,6 +898,7 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) ->
|
||||
Some(true) => {
|
||||
let rev = app.session.revision;
|
||||
app.home.show(rev);
|
||||
crate::panel_runtime::hide_app_host(app);
|
||||
}
|
||||
Some(false) => app.home.open = false,
|
||||
None => {}
|
||||
@@ -1611,8 +1625,15 @@ mod tests {
|
||||
let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), Default::default());
|
||||
app.enable_panel_runtime(h.runtime, Box::<FakeAppPanelServices>::default()).unwrap();
|
||||
app.panel_runtime_mut().unwrap().set_command_adapters(Box::new(catalogue), Box::new(FakeNativeAdapter::new(false))).unwrap();
|
||||
app.enable_universal_panel_host(HostOptions::default()).unwrap();
|
||||
prepare_panel_commands(&mut app);
|
||||
app
|
||||
}
|
||||
fn prepare_panel_commands(app: &mut crate::SolveApp) {
|
||||
use solidcraft_engine::panels::{LogicalRect, Point, Size};
|
||||
let capacity = LogicalRect { origin: Point { x: 0.0, y: 0.0 }, size: Size { width: 1400.0, height: 1000.0 } };
|
||||
app.panel_runtime.as_mut().unwrap().prepare_host(&app.session, capacity).unwrap();
|
||||
}
|
||||
fn panel_control(app: &mut crate::SolveApp, method: &str, params: serde_json::Value) -> serde_json::Value {
|
||||
let (request, _) = super::ControlRequest::new(method, params);
|
||||
match super::handle(app, &egui::Context::default(), &request) {
|
||||
@@ -1681,7 +1702,7 @@ mod tests {
|
||||
assert_eq!(reply["panel_error"]["rule"], "schema");
|
||||
assert_eq!(reply["param_check"], check);
|
||||
}
|
||||
panel_control(&mut app, "engine.execute", panel_steps()[0].clone());
|
||||
assert_eq!(panel_control(&mut app, "engine.execute", panel_steps()[0].clone())["ok"], true);
|
||||
let before = app.panel_runtime().unwrap().layout().inspect();
|
||||
let reply = panel_control(
|
||||
&mut app,
|
||||
@@ -1697,7 +1718,7 @@ mod tests {
|
||||
#[test]
|
||||
fn panel_control_catalogue_batches_and_scripts_retain_memory_and_refuse_unsupported_atomic_domains() {
|
||||
let mut app = panel_command_app();
|
||||
panel_control(&mut app, "engine.execute", panel_steps()[0].clone());
|
||||
assert_eq!(panel_control(&mut app, "engine.execute", panel_steps()[0].clone())["ok"], true);
|
||||
let reply = panel_control(
|
||||
&mut app,
|
||||
"engine.batch",
|
||||
@@ -1823,11 +1844,172 @@ mod tests {
|
||||
}
|
||||
|
||||
use serde_json::json;
|
||||
use solidcraft_engine::panels::ActionSink;
|
||||
use solidcraft_engine::{Sel, Session};
|
||||
|
||||
use super::*;
|
||||
use crate::Services;
|
||||
|
||||
#[test]
|
||||
fn panel_fixture_validates_whole_request_before_activation() {
|
||||
let mut app = SolveApp::new(Session::default(), Services::default());
|
||||
let doc = app.session.doc.clone();
|
||||
let model = app.session.model.state();
|
||||
let camera = app.cam;
|
||||
for params in [
|
||||
Value::Null,
|
||||
json!([]),
|
||||
json!({"enabled":null}),
|
||||
json!({"enabled":"true"}),
|
||||
json!({"preset":false}),
|
||||
json!({"preset":"unknown"}),
|
||||
json!({"preset":"x".repeat(4096)}),
|
||||
json!({"enabled":false,"preset":"docks"}),
|
||||
json!({"enabled":true,"unknown":0}),
|
||||
] {
|
||||
assert!(crate::panel_runtime::control_specimen(&mut app, ¶ms).is_err(), "{params}");
|
||||
assert!(app.panel_runtime().is_none());
|
||||
assert!(!app.universal_panel_host_enabled());
|
||||
assert!(std::sync::Arc::ptr_eq(&doc, &app.session.doc));
|
||||
assert!(std::sync::Arc::ptr_eq(&model, &app.session.model.state()));
|
||||
assert_eq!(app.cam, camera);
|
||||
}
|
||||
let reply = crate::panel_runtime::control_specimen(&mut app, &json!({})).unwrap();
|
||||
assert_eq!(reply["enabled"], false);
|
||||
assert!(reply["host"].is_null());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn panel_fixture_presets_mount_retained_content_and_inspection_does_not_tick() {
|
||||
let mut h = crate::scenario::Harness::new();
|
||||
for (name, count) in [
|
||||
("docks", 4),
|
||||
("tabs", 4),
|
||||
("collapsed", 4),
|
||||
("floating", 4),
|
||||
("overflow", 24),
|
||||
("pinned", 4),
|
||||
("columns", 3),
|
||||
("stack_tabs", 4),
|
||||
("content_fill", 2),
|
||||
("inline", 1),
|
||||
] {
|
||||
let before = crate::panel_runtime::inspect_host_specimen(&mut h.app).unwrap()["session"].clone();
|
||||
h.step(&json!({"panel_fixture":{"enabled":true,"preset":name}})).unwrap();
|
||||
h.frames(2);
|
||||
assert!(h.app.universal_panel_host_enabled());
|
||||
assert!(h.app.universal_panel_frame().is_some());
|
||||
let first = crate::panel_runtime::inspect_host_specimen(&mut h.app).unwrap();
|
||||
let second = crate::panel_runtime::inspect_host_specimen(&mut h.app).unwrap();
|
||||
assert_eq!(first, second, "inspection itself must not tick or dispatch");
|
||||
assert_eq!(first["runtime"]["probe"]["preset"], name);
|
||||
assert_eq!(first["runtime"]["controller_count"], count);
|
||||
assert_eq!(first["session"], before, "host-only work changed Session for {name}");
|
||||
assert_eq!(first["runtime"]["probe"]["content_command_calls"], 0);
|
||||
let takeover = crate::panel_runtime::control_specimen(&mut h.app, &json!({"enabled":true,"preset":"tabs"}));
|
||||
assert!(takeover.is_err());
|
||||
assert_eq!(crate::panel_runtime::inspect_host_specimen(&mut h.app).unwrap(), second);
|
||||
h.step(&json!({"panel_fixture":{"enabled":false}})).unwrap();
|
||||
assert!(h.app.panel_runtime().is_none());
|
||||
assert!(!h.app.universal_panel_host_enabled());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn panel_fixture_teardown_honors_live_editor_guard_atomically() {
|
||||
fn click_visible_guard(h: &mut crate::scenario::Harness, guard: &str) {
|
||||
for _ in 0..16 {
|
||||
let body =
|
||||
h.app.universal_panel_frame().unwrap().layout.sections.iter().find(|section| section.instance.0 == "specimen-0").unwrap().body;
|
||||
let body = crate::panel_runtime::egui_rect(body.expect("expanded specimen body"));
|
||||
let checkbox = h
|
||||
.output
|
||||
.accesskit_update
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.nodes
|
||||
.iter()
|
||||
.find(|(_, node)| node.role() == egui::accesskit::Role::CheckBox && node.label() == Some(guard))
|
||||
.and_then(|(_, node)| node.bounds())
|
||||
.map(|bounds| {
|
||||
egui::Rect::from_min_max(egui::pos2(bounds.x0 as f32, bounds.y0 as f32), egui::pos2(bounds.x1 as f32, bounds.y1 as f32))
|
||||
});
|
||||
if let Some(checkbox) = checkbox.filter(|bounds| body.contains(bounds.center())) {
|
||||
assert!(checkbox.intersect(body).is_positive(), "the real checkbox must be visible inside its actual Body clip");
|
||||
let at = checkbox.center();
|
||||
h.frame_with(vec![egui::Event::PointerMoved(at)]);
|
||||
for pressed in [true, false] {
|
||||
h.frame_with(vec![
|
||||
egui::Event::PointerMoved(at),
|
||||
egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE },
|
||||
]);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// The specimen owns this ScrollArea. Accessibility also lists
|
||||
// clipped content, so reveal the real checkbox before clicking.
|
||||
let at = egui::pos2(body.center().x, body.top() + 4.0);
|
||||
h.frame_with(vec![
|
||||
egui::Event::PointerMoved(at),
|
||||
egui::Event::MouseWheel {
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
unit: egui::MouseWheelUnit::Point,
|
||||
delta: egui::vec2(0.0, -120.0),
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
phase: egui::TouchPhase::Move,
|
||||
},
|
||||
]);
|
||||
for _ in 0..120 {
|
||||
if !h.ctx.input(|input| input.is_scrolling()) {
|
||||
break;
|
||||
}
|
||||
h.frame();
|
||||
}
|
||||
assert!(!h.ctx.input(|input| input.is_scrolling()), "the checkbox click requires a settled Body scroll");
|
||||
}
|
||||
panic!("the actual specimen guard checkbox was never revealed in its Body");
|
||||
}
|
||||
let mut h = crate::scenario::Harness::new();
|
||||
h.step(&json!({"panel_fixture":{"preset":"docks"}})).unwrap();
|
||||
let guard = h.app.tr("ui.panel_fixture.guard").to_string();
|
||||
click_visible_guard(&mut h, &guard);
|
||||
let before = crate::panel_runtime::inspect_host_specimen(&mut h.app).unwrap();
|
||||
let editor = &before["runtime"]["probe"]["controllers"][0];
|
||||
assert_eq!(editor["reject_cancel"], true);
|
||||
assert_eq!(editor["transaction_live"], true);
|
||||
assert!(crate::panel_runtime::control_specimen(&mut h.app, &json!({"enabled":false})).is_err());
|
||||
assert_eq!(crate::panel_runtime::inspect_host_specimen(&mut h.app).unwrap(), before);
|
||||
click_visible_guard(&mut h, &guard);
|
||||
h.step(&json!({"panel_fixture":{"enabled":false}})).unwrap();
|
||||
assert!(h.app.panel_runtime().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn panel_fixture_rejects_takeover_and_teardown_of_unrelated_runtime() {
|
||||
let harness = crate::panel_runtime::PanelMountHarness::new(false).unwrap();
|
||||
#[derive(Default)]
|
||||
struct Provider {
|
||||
models: crate::panel_runtime::FakeModels,
|
||||
commands: crate::panel_runtime::FakeContentCommands,
|
||||
local: crate::panel_runtime::FakeLocalServices,
|
||||
}
|
||||
impl crate::panel_runtime::AppPanelServices for Provider {
|
||||
fn refresh_read_only(&mut self, _: &Session) -> solidcraft_engine::panels::PanelResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
fn services(&mut self) -> crate::panel_runtime::ContentServices<'_> {
|
||||
crate::panel_runtime::ContentServices { models: &self.models, commands: &mut self.commands, local: &mut self.local }
|
||||
}
|
||||
}
|
||||
let mut app = SolveApp::new(Session::default(), Services::default());
|
||||
app.panel_runtime = Some(crate::panel_runtime::AppPanelRuntime::new(harness.runtime, Box::<Provider>::default()).unwrap());
|
||||
let before = app.panel_runtime().unwrap().layout().inspect();
|
||||
for params in [json!({"enabled":true}), json!({"enabled":false})] {
|
||||
assert!(crate::panel_runtime::control_specimen(&mut app, ¶ms).is_err());
|
||||
assert_eq!(app.panel_runtime().unwrap().layout().inspect(), before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn viewport_status_fixture_rejects_hostile_presets_without_mutating_the_session() {
|
||||
let mut h = crate::scenario::Harness::new();
|
||||
|
||||
@@ -1270,6 +1270,26 @@ impl Dialog {
|
||||
{
|
||||
inp.items = default_profiles(s);
|
||||
}
|
||||
if matches!(d.kind, Kind::SketchModify(crate::sketch_modify_ui::Mod::Mirror)) && app.preferences.sketch_mirror_auto_line {
|
||||
let state = s.model.state();
|
||||
if let Some(sketch) = s.active_sketch.and_then(|id| state.sketch(id)) {
|
||||
let mut lines = s.selection.iter().filter_map(|sel| {
|
||||
let Sel::SketchCurve { id, sketch: from } = sel else { return None };
|
||||
if from.is_some() && *from != s.active_sketch {
|
||||
return None;
|
||||
}
|
||||
let curve = sketch.sketch.curves.get(sketch.sketch.curve_index(id)?)?;
|
||||
(curve.construction && matches!(curve.kind, solidcraft_engine::sketch::CurveKind::Line { .. })).then_some(curve)
|
||||
});
|
||||
if let Some(line) = lines.next()
|
||||
&& lines.next().is_none()
|
||||
&& let Some(input) = d.inputs.get_mut(1)
|
||||
&& input.items.is_empty()
|
||||
{
|
||||
input.items.push(Sel::SketchCurve { id: line.id.clone(), sketch: None });
|
||||
}
|
||||
}
|
||||
}
|
||||
d.sync_thread(s);
|
||||
d.sync_material(s);
|
||||
d.advance();
|
||||
@@ -3857,6 +3877,8 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
let window = panel.window(ctx);
|
||||
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 host = app.universal_panel_host_enabled();
|
||||
let mut painted = false;
|
||||
if let Kind::ConfirmDelete { with, fail, .. } = &d.kind {
|
||||
let detail = with.join(" · ");
|
||||
let (closed, action) = crate::ui_kit::Confirm::new(egui::Id::unique(("sc_dialog", title(&d.kind))), "delete", &heading)
|
||||
@@ -3864,6 +3886,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
.actions("Delete", "Cancel", None)
|
||||
.detail(&detail)
|
||||
.show(ctx, true, |ui| {
|
||||
painted = ui.is_visible() && !ui.is_sizing_pass();
|
||||
if !with.is_empty() {
|
||||
crate::ui_kit::text(ui, tr("Also deletes"), crate::ui_kit::Text::Report("also_deletes", false));
|
||||
}
|
||||
@@ -3873,9 +3896,10 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
});
|
||||
ok = action == crate::ui_kit::Action::Ok;
|
||||
cancel = closed || action == crate::ui_kit::Action::Cancel;
|
||||
app.viewport.dialog_rect = crate::scenario::rect_of("dialog:window");
|
||||
app.viewport.dialog_rect = crate::scenario::rect_of("dialog:window").filter(|_| !host || painted);
|
||||
} else {
|
||||
let response = window.open(&mut keep).show(ctx, |ui| {
|
||||
painted = ui.is_visible() && !ui.is_sizing_pass();
|
||||
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));
|
||||
@@ -3932,7 +3956,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
}
|
||||
}
|
||||
});
|
||||
app.viewport.dialog_rect = response.map(|r| r.response.rect);
|
||||
app.viewport.dialog_rect = response.filter(|_| !host || painted).map(|r| r.response.rect);
|
||||
// OK and Cancel in the view's corner do what the dialog's own do (#6709).
|
||||
if app.issue_report.draft.is_none() {
|
||||
match corner {
|
||||
@@ -4724,7 +4748,25 @@ fn look_at_sketch_from(app: &mut SolveApp, again: bool) {
|
||||
if let Some(ss) = app.session.active_sketch.and_then(|id| st.sketch(id)) {
|
||||
let n = facing(app, ss.plane.normal(), again);
|
||||
let to = square_sketch_axes(app.cam.looking_from(n), ss.plane.x, ss.plane.y);
|
||||
app.animate_to(onto_sketch(to, ss));
|
||||
if app.universal_panel_host_enabled() && again {
|
||||
let bounds = ss.sketch.bounds().map(|(lo, hi)| {
|
||||
let mut bounds = Aabb3::default();
|
||||
for point in [lo, hi, solidcore_record::Vec2::new(lo.x, hi.y), solidcore_record::Vec2::new(hi.x, lo.y)] {
|
||||
bounds.add(ss.plane.to_world(point));
|
||||
}
|
||||
bounds
|
||||
});
|
||||
let mut to = to;
|
||||
to.target = bounds.as_ref().map_or(ss.plane.origin, Aabb3::center);
|
||||
if let (Some(layout), Ok(usable)) = (app.viewport.layout.as_ref(), crate::shell::host_usable(app))
|
||||
&& let Some(centred) = crate::viewport_layout::centre_host_camera(to, bounds.as_ref(), layout, &usable, app.view_fov())
|
||||
{
|
||||
to = centred;
|
||||
}
|
||||
app.animate_to(to);
|
||||
} else {
|
||||
app.animate_to(onto_sketch(to, ss));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5181,13 +5223,17 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result<Vec<(String, Value)>, S
|
||||
}
|
||||
Kind::Revolve { angle, operation, axis: stored_axis } => {
|
||||
need(0, "profiles")?;
|
||||
let (sketch, idx) = profiles();
|
||||
// A sketch line is kept by id only when that id on the profile sketch is the
|
||||
// highlighted line. Ids repeat across sketches (#3726); the highlight and the angle
|
||||
// handle follow the pick's sketch, and a bare id would revolve about whatever line
|
||||
// the profile sketch happens to number the same.
|
||||
let axis = match sels(d, 1).first() {
|
||||
Some(Sel::Axis { name }) => json!(name),
|
||||
Some(Sel::SketchCurve { id, .. }) => json!(id),
|
||||
Some(curve @ Sel::SketchCurve { .. }) => sketch_curve_axis(app, curve, sketch.as_u64())?,
|
||||
Some(x) => axis_param(app, x)?,
|
||||
None => stored_axis.clone().ok_or("select an axis")?,
|
||||
};
|
||||
let (sketch, idx) = profiles();
|
||||
let mut p = json!({"axis": axis, "angle": angle, "operation": OPS.get(*operation).copied().unwrap_or("new")});
|
||||
// A planar body face revolves like a profile (#2747); profiles win when both are picked.
|
||||
let face = sels(d, 0).iter().find_map(|x| match x {
|
||||
@@ -6172,6 +6218,48 @@ pub(crate) fn takes_as_axis(s: &Session, sel: &Sel) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// A sketch curve picked as a revolve axis.
|
||||
///
|
||||
/// The highlight and the angle handle follow [`axis_of`] (the sketch the pick names, or the
|
||||
/// active sketch when it does not). Eval resolves a bare curve id on the profile sketch, and
|
||||
/// curve ids repeat from sketch to sketch (#3726), so that line can be a different edge — often
|
||||
/// the opposite side of a rectangle. Keep the id when the profile sketch's line is the
|
||||
/// highlighted one, so a same-sketch axis stays a sketch line. Otherwise pass the highlighted
|
||||
/// line as `{origin, dir}` in world coordinates (the command stores it in the component frame).
|
||||
/// A face profile has no sketch yet — its generated sketch numbers edges from `l1` again — so
|
||||
/// that pick is always the geometric line.
|
||||
pub(crate) fn sketch_curve_axis(app: &SolveApp, sel: &Sel, profile_sketch: Option<u64>) -> Result<Value, String> {
|
||||
let Sel::SketchCurve { id, .. } = sel else { return axis_param(app, sel) };
|
||||
let (origin, dir) = axis_of(app, sel).ok_or(AXIS_PICK)?;
|
||||
if !origin.is_finite() || !dir.is_finite() {
|
||||
return Err(AXIS_PICK.into());
|
||||
}
|
||||
let same = profile_sketch.and_then(|sketch| profile_axis_line(app, sketch, id)).is_some_and(|line| same_axis(line, (origin, dir)));
|
||||
if same { Ok(json!(id)) } else { Ok(json!({"origin": pt(origin), "dir": pt(dir)})) }
|
||||
}
|
||||
|
||||
/// The world line of curve `id` on `sketch`, when that curve is a line.
|
||||
fn profile_axis_line(app: &SolveApp, sketch: u64, id: &str) -> Option<(Vec3, Vec3)> {
|
||||
let st = app.session.world_state().ok()?;
|
||||
let ss = st.sketch(sketch)?;
|
||||
let c = ss.sketch.curves.get(ss.sketch.curve_index(id)?)?;
|
||||
let solidcraft_engine::sketch::CurveKind::Line { a, b } = c.kind else { return None };
|
||||
let pa = ss.plane.to_world(ss.sketch.point(a)?);
|
||||
let pb = ss.plane.to_world(ss.sketch.point(b)?);
|
||||
let dir = (pb - pa).normalized()?;
|
||||
(pa.is_finite() && dir.is_finite()).then_some((pa, dir))
|
||||
}
|
||||
|
||||
/// Whether two world lines are the same axis: parallel, and no gap between them.
|
||||
fn same_axis((o1, d1): (Vec3, Vec3), (o2, d2): (Vec3, Vec3)) -> bool {
|
||||
let (Some(d1), Some(d2)) = (d1.normalized(), d2.normalized()) else { return false };
|
||||
if d1.dot(d2).abs() <= 1.0 - 1e-9 {
|
||||
return false;
|
||||
}
|
||||
let sep = (o2 - o1).cross(d1).len();
|
||||
sep <= 1e-6 * (1.0 + o1.len() + o2.len())
|
||||
}
|
||||
|
||||
/// An axis input's pick as a command's `axis`: a world axis or construction axis by name, a
|
||||
/// circular edge or round face by reference, anything else (a sketch line, a straight edge) as
|
||||
/// its line.
|
||||
|
||||
@@ -178,6 +178,7 @@ impl Searched {
|
||||
/// The Joint and As-built Joint dialogs.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct JointForm {
|
||||
pub name: String,
|
||||
pub as_built: bool,
|
||||
/// Editing this joint (its origins stay; type, alignment and limits change).
|
||||
pub editing: Option<u64>,
|
||||
@@ -213,6 +214,7 @@ pub struct JointForm {
|
||||
impl JointForm {
|
||||
fn new(as_built: bool, doc: &solidcraft_engine::doc::Document) -> JointForm {
|
||||
JointForm {
|
||||
name: String::new(),
|
||||
as_built,
|
||||
editing: None,
|
||||
kind: 0,
|
||||
@@ -497,11 +499,20 @@ fn nearest_pick(own: &[&solidcraft_engine::doc::ModelBody], p: Vec3, edges: bool
|
||||
best.map(|(_, sel)| sel)
|
||||
}
|
||||
|
||||
/// Default name for a new joint based on its type (e.g. "Planar Joint1", "Revolute Joint1").
|
||||
pub(crate) fn default_joint_name(doc: &solidcraft_engine::doc::Document, kind: JointKind) -> String {
|
||||
let prefix = format!("{} Joint", kind_label(kind));
|
||||
let names: std::collections::BTreeSet<_> = doc.assembly.joints.iter().map(|j| j.name.as_str()).collect();
|
||||
let number = (1..=doc.assembly.joints.len().saturating_add(1)).find(|n| !names.contains(format!("{prefix}{n}").as_str())).unwrap_or(1);
|
||||
format!("{prefix}{number}")
|
||||
}
|
||||
|
||||
/// The Edit Joint dialog for a joint (by id). Its two sides show as the Joint dialog's do, each
|
||||
/// pre-filled with the pick it sits on.
|
||||
pub fn edit_joint(app: &SolveApp, id: u64) -> Option<Dialog> {
|
||||
let j = app.session.doc.assembly.joints.iter().find(|j| j.id == id)?;
|
||||
let mut f = JointForm::new(false, &app.session.doc);
|
||||
f.name = j.name.clone();
|
||||
f.editing = Some(id);
|
||||
f.sides = [side_pick(app, &j.a), side_pick(app, &j.b)];
|
||||
let mut inputs = side_inputs();
|
||||
@@ -799,6 +810,8 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Asm, inputs: &mut [Se
|
||||
(f.search, f.found_note, f.searched) = (None, None, None);
|
||||
f.found.clear();
|
||||
}
|
||||
let hint = default_joint_name(&app.session.doc, f.joint_kind());
|
||||
enter |= text_row(ui, "Name", &mut f.name, &hint).0;
|
||||
f.fit_limits(&app.session.doc);
|
||||
if !f.as_built {
|
||||
enter |= expr_row(ui, "Angle", &mut f.angle);
|
||||
@@ -1474,10 +1487,14 @@ pub fn commands(app: &SolveApp, k: &Asm, inputs: &[SelInput]) -> Result<Vec<(Str
|
||||
Asm::Joint(f) => {
|
||||
let kind = TYPES.get(f.kind).copied().unwrap_or("rigid");
|
||||
let jk = f.joint_kind();
|
||||
let custom_name = f.name.trim();
|
||||
let limits: Vec<Value> =
|
||||
f.limits.iter().take(jk.dofs().len()).map(|(on, lo, hi)| if *on { json!([lo, hi]) } else { Value::Null }).collect();
|
||||
if let Some(id) = f.editing {
|
||||
let mut p = json!({"joint": id, "type": kind, "flip": f.flip, "offset": f.offset[2]});
|
||||
if !custom_name.is_empty() {
|
||||
p["name"] = json!(custom_name);
|
||||
}
|
||||
// The angle only when the user changed it: a side moved without it turns B as joint.create would.
|
||||
if f.angle != f.angle_shown {
|
||||
p["angle"] = json!(f.angle);
|
||||
@@ -1506,6 +1523,9 @@ pub fn commands(app: &SolveApp, k: &Asm, inputs: &[SelInput]) -> Result<Vec<(Str
|
||||
return Err("select two components".into());
|
||||
}
|
||||
let mut p = json!({"type": kind, "a": occs.first(), "b": occs.get(1), "limits": limits});
|
||||
if !custom_name.is_empty() {
|
||||
p["name"] = json!(custom_name);
|
||||
}
|
||||
if let Some(x) = sel_items(inputs, 1).first().and_then(|x| snap_of(s, x)) {
|
||||
p["at"] = x.param;
|
||||
}
|
||||
@@ -1520,7 +1540,10 @@ pub fn commands(app: &SolveApp, k: &Asm, inputs: &[SelInput]) -> Result<Vec<(Str
|
||||
// Picked origins mate by default (the engine's default: B's z opposite A's, faces
|
||||
// meet face to face, a pin goes into its hole); the dialog's Flip is the command's
|
||||
// `flip`, which turns B the other way.
|
||||
let p = json!({"type": kind, "a": a_param, "b": b.param, "flip": f.flip, "offset": f.offset[2], "angle": f.angle, "limits": limits});
|
||||
let mut p = json!({"type": kind, "a": a_param, "b": b.param, "flip": f.flip, "offset": f.offset[2], "angle": f.angle, "limits": limits});
|
||||
if !custom_name.is_empty() {
|
||||
p["name"] = json!(custom_name);
|
||||
}
|
||||
cmd("joint.create", p)
|
||||
}
|
||||
Asm::JointOrigin { name, .. } => {
|
||||
|
||||
@@ -1470,3 +1470,36 @@ fn interference_checks_off_the_window_thread_and_drops_a_check_of_a_changed_desi
|
||||
compute(&mut app, true);
|
||||
assert_eq!(state(&app), (None, 0, false), "a check of the design before the change is dropped");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn joint_dialog_applies_custom_name_or_falls_back_to_type_default() {
|
||||
// 1. Empty name field: commands() generates payload without "name", backend creates "Rigid Joint1"
|
||||
let mut app = two_boxes();
|
||||
app.start("joint.create");
|
||||
let mut d = app.dialog.clone().unwrap();
|
||||
d.pick(&app.session, face_sel(&app.session, Vec3::new(10.0, 10.0, 10.0)).unwrap());
|
||||
d.pick(&app.session, face_sel(&app.session, Vec3::new(40.0, 10.0, 0.0)).unwrap());
|
||||
let cmds = apply_commands(&app, &d).unwrap();
|
||||
assert_eq!(cmds[0].0, "joint.create");
|
||||
assert!(cmds[0].1.get("name").is_none());
|
||||
for (id, p) in cmds {
|
||||
let r = app.run(&id, p).unwrap();
|
||||
assert_eq!(r["name"], "Rigid Joint1");
|
||||
}
|
||||
|
||||
// 2. Custom name in f.name: reset to fresh boxes so B is at its initial coordinates
|
||||
let mut app = two_boxes();
|
||||
app.start("joint.create");
|
||||
let mut d = app.dialog.clone().unwrap();
|
||||
d.pick(&app.session, face_sel(&app.session, Vec3::new(10.0, 10.0, 10.0)).unwrap());
|
||||
d.pick(&app.session, face_sel(&app.session, Vec3::new(40.0, 10.0, 0.0)).unwrap());
|
||||
if let Kind::Assembly(Asm::Joint(f)) = &mut d.kind {
|
||||
f.name = "MyCustomJoint".into();
|
||||
}
|
||||
let cmds = apply_commands(&app, &d).unwrap();
|
||||
assert_eq!(cmds[0].1["name"], "MyCustomJoint");
|
||||
for (id, p) in cmds {
|
||||
let r = app.run(&id, p).unwrap();
|
||||
assert_eq!(r["name"], "MyCustomJoint");
|
||||
}
|
||||
}
|
||||
@@ -528,9 +528,12 @@ pub fn commands(app: &SolveApp, k: &Surf, inputs: &[SelInput], extra: &Map<Strin
|
||||
Surf::Revolve { angle, symmetric, axis } => {
|
||||
need(0, "profiles or curves to revolve")?;
|
||||
let mut p = sheet_picks(app, items(inputs, 0))?;
|
||||
// Same as a solid revolve: a bare curve id is resolved on this profile sketch, where
|
||||
// it can name a different line than the one the pick highlights (#7452, #3726).
|
||||
let profile_sketch = p.get("sketch").and_then(Value::as_u64);
|
||||
p["axis"] = match items(inputs, 1).first() {
|
||||
Some(Sel::Axis { name }) => json!(name),
|
||||
Some(Sel::SketchCurve { id, .. }) => json!(id),
|
||||
Some(curve @ Sel::SketchCurve { .. }) => crate::dialogs::sketch_curve_axis(app, curve, profile_sketch)?,
|
||||
Some(x) => crate::dialogs::axis_param(app, x)?,
|
||||
None => axis.clone().ok_or("select an axis")?,
|
||||
};
|
||||
|
||||
@@ -597,6 +597,49 @@ fn two_sides_with_all_shows_distance_2_and_reverse_swaps_the_sides() {
|
||||
assert_eq!(extent(&h), e);
|
||||
}
|
||||
|
||||
/// Two Sides with a negative Distance 1: its side turns over, but Distance 2 stays where Direction
|
||||
/// puts it, and has its own value box like Distance 1.
|
||||
#[test]
|
||||
fn two_sides_second_arrow_stays_put_when_the_first_distance_turns_negative() {
|
||||
let mut h = Harness::new();
|
||||
h.app.home.open = false;
|
||||
h.app.run("sketch.create", json!({"plane":"XY","name":"Disc"})).unwrap();
|
||||
h.app.run("sketch.circle.center", json!({"center":[10,10],"radius":2})).unwrap();
|
||||
h.app.run("sketch.finish", json!({})).unwrap();
|
||||
h.app.run("solid.extrude", json!({"sketch":"Disc","distance":"-5 mm","distance2":"3 mm","name":"Depth"})).unwrap();
|
||||
h.frames(4);
|
||||
open(&mut h);
|
||||
assert!(h.widget("Distance 2").is_some(), "Two Sides shows the second side's distance");
|
||||
let centre = h.at(&json!({"world":[10,10,0]})).unwrap()[1] as f32;
|
||||
let tips = || (crate::scenario::handle_at("arrow").unwrap().y - centre, crate::scenario::handle_at("arrow2").unwrap().y - centre);
|
||||
let (first, second) = tips();
|
||||
assert!(first > 0.0 && second > 0.0, "the first arrow turned below the sketch, the second stayed below it: {first} {second}");
|
||||
}
|
||||
|
||||
/// Distance 2's box in the view stays while its text does not evaluate, so a cleared box or a
|
||||
/// `-` typed first can be finished there.
|
||||
#[test]
|
||||
fn two_sides_second_value_box_stays_while_its_text_is_incomplete() {
|
||||
let mut h = Harness::new();
|
||||
h.app.home.open = false;
|
||||
h.app.run("sketch.create", json!({"plane":"XY","name":"Disc"})).unwrap();
|
||||
h.app.run("sketch.circle.center", json!({"center":[10,10],"radius":2})).unwrap();
|
||||
h.app.run("sketch.finish", json!({})).unwrap();
|
||||
h.app.run("solid.extrude", json!({"sketch":"Disc","distance":"5 mm","distance2":"3 mm","name":"Depth"})).unwrap();
|
||||
h.frames(4);
|
||||
open(&mut h);
|
||||
let area = || egui::Id::unique("sc_canvas_area2");
|
||||
assert!(h.ctx.memory(|m| m.area_rect(area())).is_some(), "Distance 2's box in the view");
|
||||
for text in ["-", ""] {
|
||||
let Some(crate::dialogs::Dialog { kind: crate::dialogs::Kind::Extrude { distance2, .. }, .. }) = &mut h.app.dialog else {
|
||||
panic!("extrude dialog")
|
||||
};
|
||||
*distance2 = text.into();
|
||||
h.frames(3);
|
||||
assert!(h.ctx.read_response(egui::Id::unique("sc_canvas_value2")).is_some(), "Distance 2's box went away at {text:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Without value boxes in the view (Preferences, #9479), nothing covers the model: the command
|
||||
/// window's Distance takes the keyboard instead, its text selected, and the arrow still drags it.
|
||||
#[test]
|
||||
@@ -666,3 +709,106 @@ fn failed_face_extrusion_edit_keeps_context_until_escape_and_preserves_visibilit
|
||||
assert!(!h.app.body_visible("Source"));
|
||||
assert_eq!(h.app.session.visibility, visibility);
|
||||
}
|
||||
|
||||
/// A block 12.345678 mm thick under XY (so no round step lands on its underside), a 10 mm
|
||||
/// square sketched on its top and cut 5 mm into it, a second block beside it whose underside is
|
||||
/// at -7.777 mm, and the cut open in its editor.
|
||||
fn cut_into_block() -> Harness {
|
||||
let mut h = Harness::new();
|
||||
h.app.home.open = false;
|
||||
h.app.run("solid.box", json!({"length":30,"width":30,"height":12.345678,"corner":[-10,-10,-12.345678],"body_name":"Block"})).unwrap();
|
||||
h.app
|
||||
.run("solid.box", json!({"length":10,"width":10,"height":7.777,"corner":[40,0,-7.777],"body_name":"Beside","operation":"new_body"}))
|
||||
.unwrap();
|
||||
h.app.run("sketch.create", json!({"plane":"XY","name":"Pocket"})).unwrap();
|
||||
h.app.run("sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[10,10]})).unwrap();
|
||||
h.app.run("sketch.finish", json!({})).unwrap();
|
||||
let cut = json!({"sketch":"Pocket","direction":"negative","distance":"5 mm","operation":"cut","targets":["Block"],"name":"Depth"});
|
||||
h.app.run("solid.extrude", cut).unwrap();
|
||||
h.call("ui.view", json!({"view":"fit"}));
|
||||
h.frames(4);
|
||||
open(&mut h);
|
||||
h
|
||||
}
|
||||
|
||||
/// Presses the arrow's tip and holds it at the world point `to`, frame by frame, without letting
|
||||
/// go; returns the face the arrow stopped at then.
|
||||
fn hold_arrow_at(h: &mut Harness, to: Value) -> Option<crate::extrude_face_snap::Stop> {
|
||||
let from = h.at(&json!({"handle":"arrow"})).unwrap();
|
||||
let from = egui::pos2(from[0] as f32, from[1] as f32);
|
||||
let to = h.at(&to).unwrap();
|
||||
let to = egui::pos2(to[0] as f32, to[1] as f32);
|
||||
h.app.synthetic.push(egui::Event::PointerMoved(from));
|
||||
h.frame();
|
||||
h.app.synthetic.push(egui::Event::PointerButton {
|
||||
pos: from,
|
||||
button: egui::PointerButton::Primary,
|
||||
pressed: true,
|
||||
modifiers: h.app.synthetic_mods,
|
||||
});
|
||||
h.frame();
|
||||
for k in 1..=4 {
|
||||
h.app.synthetic.push(egui::Event::PointerMoved(from + (to - from) * (k as f32 / 4.0)));
|
||||
h.frame();
|
||||
}
|
||||
crate::extrude_face_snap::current()
|
||||
}
|
||||
|
||||
fn let_go(h: &mut Harness) {
|
||||
let at = h.ctx.input(|i| i.pointer.hover_pos()).unwrap_or_default();
|
||||
h.app.synthetic.push(egui::Event::PointerButton {
|
||||
pos: at,
|
||||
button: egui::PointerButton::Primary,
|
||||
pressed: false,
|
||||
modifiers: h.app.synthetic_mods,
|
||||
});
|
||||
h.frames(2);
|
||||
}
|
||||
|
||||
/// Extrude Cut depth stops at the far face (#2398): dragged near the block's underside, the
|
||||
/// cut's arrow takes its exact depth (not a round step) and outlines that face; OK cuts through.
|
||||
#[test]
|
||||
fn the_extrude_arrow_stops_at_a_parallel_face_and_outlines_it() {
|
||||
let mut h = cut_into_block();
|
||||
let stop = hold_arrow_at(&mut h, json!({"world":[5,5,-12.2]}));
|
||||
let stop = stop.expect("the arrow stops at the block's underside");
|
||||
assert_eq!((stop.body.as_str(), (stop.distance - 12.345678).abs() < 1e-9), ("Block", true), "{stop:?}");
|
||||
assert!((dialog_distance(&h) - 12.345678).abs() < 1e-9, "{}", dialog_distance(&h));
|
||||
let_go(&mut h);
|
||||
assert!(crate::extrude_face_snap::current().is_none(), "no outline once the arrow is let go");
|
||||
assert!((dialog_distance(&h) - 12.345678).abs() < 1e-9, "{}", dialog_distance(&h));
|
||||
h.step(&json!({"widget":"OK"})).unwrap();
|
||||
assert!(h.app.dialog.is_none(), "{:?}", h.app.session.log);
|
||||
let expected = 30.0 * 30.0 * 12.345678 - 10.0 * 10.0 * 12.345678;
|
||||
assert!((volume(&h, "Block") - expected).abs() < 1e-6, "{} for {expected}", volume(&h, "Block"));
|
||||
}
|
||||
|
||||
/// The free drag (Ctrl held) passes the face by, and a face beside the profile never catches the
|
||||
/// arrow: the distance stays the pointer's or a round step.
|
||||
#[test]
|
||||
fn the_extrude_arrow_passes_faces_beside_the_profile_and_in_a_free_drag() {
|
||||
let mut h = cut_into_block();
|
||||
// The other block's underside at -7.777 is not under the square.
|
||||
assert_eq!(hold_arrow_at(&mut h, json!({"world":[5,5,-7.75]})), None);
|
||||
assert!((dialog_distance(&h) - 7.777).abs() > 1e-6, "{}", dialog_distance(&h));
|
||||
let_go(&mut h);
|
||||
h.app.synthetic_mods.ctrl = true;
|
||||
assert_eq!(hold_arrow_at(&mut h, json!({"world":[5,5,-12.2]})), None);
|
||||
assert!((dialog_distance(&h) - 12.345678).abs() > 1e-3, "{}", dialog_distance(&h));
|
||||
let_go(&mut h);
|
||||
}
|
||||
|
||||
/// With Preferences › Design › "Extrude arrow stops at faces" off, the arrow keeps the old
|
||||
/// behaviour (#2398): dragged near the block's underside it takes a round step, not the face's
|
||||
/// distance, and nothing is outlined.
|
||||
#[test]
|
||||
fn without_face_stops_the_extrude_arrow_moves_in_round_steps() {
|
||||
let mut h = cut_into_block();
|
||||
h.app.preferences.extrude_arrow_face_stops = false;
|
||||
assert_eq!(hold_arrow_at(&mut h, json!({"world":[5,5,-12.2]})), None);
|
||||
let d = dialog_distance(&h);
|
||||
assert!((d - 12.345678).abs() > 1e-3, "{d}");
|
||||
let step = crate::canvas::snap_step(h.app.cam.half_height());
|
||||
assert!(((d / step).round() * step - d).abs() < 1e-9, "{d} is not a multiple of the {step} mm step");
|
||||
let_go(&mut h);
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
//! Extrude's distance arrow stops at faces (#2398). While the arrow is dragged, a flat face
|
||||
//! parallel to the profile takes the distance once the arrow's tip comes within a few screen
|
||||
//! points of its plane: the distance becomes exactly the face's, and the face is outlined. A
|
||||
//! cut dragged through a block so stops at the block's far side, and the outline shows it got
|
||||
//! there. Only faces over the profile's footprint count (seen along the arrow), so faces off to
|
||||
//! the side of the profile don't catch the arrow. Holding Alt or Ctrl (the free drag) turns
|
||||
//! this off with the round steps. Preferences › Tools › `extrude_arrow_face_stops` (on by
|
||||
//! default) turns it off for good: the arrow then moves in round steps only, as before.
|
||||
//!
|
||||
//! The distance stays a distance: the face is not stored with the extrude (To Object does that).
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::sync::Arc;
|
||||
|
||||
use egui::{Pos2, Stroke};
|
||||
use solidcore_record::{Plane, Vec2, Vec3};
|
||||
use solidcraft_engine::Sel;
|
||||
use solidcraft_engine::doc::ModelState;
|
||||
use solidcraft_engine::geom::{Mesh, prelude::*};
|
||||
|
||||
use crate::SolveApp;
|
||||
use crate::dialogs::{Dialog, Kind};
|
||||
use crate::theme::Tokens;
|
||||
use crate::viewport::Proj;
|
||||
|
||||
/// How near (screen points) the arrow's tip must come to a face's plane to stop there.
|
||||
pub const SNAP_PX: f32 = 8.0;
|
||||
/// How closely (cosine) a face's normal must follow the arrow to count as parallel.
|
||||
const PARALLEL: f64 = 1.0 - 1e-6;
|
||||
/// The most faces looked at in one model, and the most points kept of each.
|
||||
const MAX_FACES: usize = 20_000;
|
||||
const MAX_POINTS: usize = 4_096;
|
||||
|
||||
/// A face the arrow can stop at: `distance` along the arrow from its base to the face's plane.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Stop {
|
||||
pub body: String,
|
||||
pub face: usize,
|
||||
pub distance: f64,
|
||||
}
|
||||
|
||||
/// A flat face of a body: a point on it, its unit normal and its corners' bounds.
|
||||
#[derive(Clone, Debug)]
|
||||
struct FlatFace {
|
||||
body: String,
|
||||
face: usize,
|
||||
point: Vec3,
|
||||
normal: Vec3,
|
||||
points: Vec<Vec3>,
|
||||
}
|
||||
|
||||
type Faces = (Option<Arc<ModelState>>, Arc<Vec<FlatFace>>);
|
||||
|
||||
thread_local! {
|
||||
/// The face the arrow stopped at this frame (for the outline, scenarios and tests).
|
||||
static CURRENT: RefCell<Option<Stop>> = const { RefCell::new(None) };
|
||||
/// The flat faces of the last model state looked at.
|
||||
static FACES: RefCell<Faces> = RefCell::new((None, Arc::new(Vec::new())));
|
||||
}
|
||||
|
||||
/// The face the arrow stopped at in the last frame drawn, if any.
|
||||
#[cfg(test)]
|
||||
pub fn current() -> Option<Stop> {
|
||||
CURRENT.with(|c| c.borrow().clone())
|
||||
}
|
||||
|
||||
pub(crate) fn set(stop: Option<Stop>) {
|
||||
CURRENT.with(|c| *c.borrow_mut() = stop);
|
||||
}
|
||||
|
||||
/// The flat faces of a mesh: per face, the plane its triangles lie in (within a tolerance
|
||||
/// scaled to the mesh) and its points.
|
||||
fn flat_faces_of(body: &str, m: &Mesh) -> Vec<FlatFace> {
|
||||
let mut by_face: Vec<(Vec3, Vec<Vec3>)> = Vec::new();
|
||||
for (t, f) in m.triangles.iter().zip(&m.tri_face) {
|
||||
let f = *f as usize;
|
||||
if f >= MAX_FACES {
|
||||
continue;
|
||||
}
|
||||
let Some([a, b, c]) = m.tri(t) else { continue };
|
||||
if by_face.len() <= f {
|
||||
by_face.resize_with(f + 1, || (Vec3::ZERO, Vec::new()));
|
||||
}
|
||||
let Some((n, pts)) = by_face.get_mut(f) else { continue };
|
||||
*n += (b - a).cross(c - a);
|
||||
if pts.len() + 3 <= MAX_POINTS {
|
||||
pts.extend([a, b, c]);
|
||||
}
|
||||
}
|
||||
let tol = (m.bounds().diagonal() * 1e-6).max(1e-7) * 10.0;
|
||||
by_face
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.filter_map(|(face, (n, points))| {
|
||||
let normal = n.normalized()?;
|
||||
let point = *points.first()?;
|
||||
let flat = points.iter().all(|p| (*p - point).dot(normal).abs() <= tol);
|
||||
(flat && normal.is_finite()).then(|| FlatFace { body: body.to_string(), face, point, normal, points })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The flat faces of every body in `st`, kept while the state stays the same.
|
||||
fn flat_faces(st: &Arc<ModelState>) -> Arc<Vec<FlatFace>> {
|
||||
if let Some(known) = FACES.with(|c| {
|
||||
let c = c.borrow();
|
||||
c.0.as_ref().filter(|k| Arc::ptr_eq(k, st)).map(|_| c.1.clone())
|
||||
}) {
|
||||
return known;
|
||||
}
|
||||
let faces: Arc<Vec<FlatFace>> = Arc::new(st.bodies.iter().flat_map(|b| flat_faces_of(&b.name, &b.mesh())).collect());
|
||||
FACES.with(|c| *c.borrow_mut() = (Some(st.clone()), faces.clone()));
|
||||
faces
|
||||
}
|
||||
|
||||
/// The bounds, in the plane's own coordinates, of `points` seen along the plane's normal.
|
||||
fn bounds_2d(plane: &Plane, points: impl IntoIterator<Item = Vec3>) -> Option<(Vec2, Vec2)> {
|
||||
let mut out: Option<(Vec2, Vec2)> = None;
|
||||
for p in points {
|
||||
let q = plane.to_local(p);
|
||||
if !(q.x.is_finite() && q.y.is_finite()) {
|
||||
continue;
|
||||
}
|
||||
out = Some(match out {
|
||||
None => (q, q),
|
||||
Some((lo, hi)) => (Vec2::new(lo.x.min(q.x), lo.y.min(q.y)), Vec2::new(hi.x.max(q.x), hi.y.max(q.y))),
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// What the extrude starts from, as world points: its profiles' outlines, or its faces' points.
|
||||
fn footprint(app: &SolveApp, d: &Dialog, faces: &[FlatFace]) -> Vec<Vec3> {
|
||||
let Ok(st) = app.session.world_state() else { return Vec::new() };
|
||||
let mut out = Vec::new();
|
||||
for item in d.inputs.first().map(|i| i.items.as_slice()).unwrap_or_default() {
|
||||
match item {
|
||||
Sel::Profile { sketch, index } => {
|
||||
let (Some(ss), Some(plane)) = (st.sketch(*sketch), crate::canvas::profile_plane(app, *sketch)) else { continue };
|
||||
if let Some(p) = ss.profiles.get(*index) {
|
||||
out.extend(p.region.outer.polyline(1e-2).into_iter().take(MAX_POINTS).map(|q| plane.to_world(q)));
|
||||
}
|
||||
}
|
||||
Sel::Face { body, index, .. } => {
|
||||
if let Some(f) = faces.iter().find(|f| f.body == *body && f.face == *index) {
|
||||
out.extend(f.points.iter().copied());
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The faces the open extrude's arrow (from `base` along `n`) can stop at: flat faces of shown
|
||||
/// bodies, parallel to the arrow, off the base's own plane, over the footprint.
|
||||
pub(crate) fn stops(app: &SolveApp, d: &Dialog, base: Vec3, n: Vec3) -> Vec<Stop> {
|
||||
if !app.preferences.extrude_arrow_face_stops || !matches!(d.kind, Kind::Extrude { .. }) {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(plane) = Plane::from_normal(base, n) else { return Vec::new() };
|
||||
let Ok(st) = app.session.world_state() else { return Vec::new() };
|
||||
let faces = flat_faces(&st);
|
||||
let Some((lo, hi)) = bounds_2d(&plane, footprint(app, d, &faces)) else { return Vec::new() };
|
||||
let size = lo.dist(hi).max(1.0);
|
||||
let tol = size * 1e-6;
|
||||
let mut out: Vec<Stop> = faces
|
||||
.iter()
|
||||
.filter(|f| f.normal.dot(n).abs() >= PARALLEL && app.body_visible(&f.body))
|
||||
.filter_map(|f| {
|
||||
let distance = (f.point - base).dot(n);
|
||||
if !distance.is_finite() || distance.abs() <= tol {
|
||||
return None;
|
||||
}
|
||||
let (flo, fhi) = bounds_2d(&plane, f.points.iter().copied())?;
|
||||
let over = flo.x <= hi.x + tol && fhi.x >= lo.x - tol && flo.y <= hi.y + tol && fhi.y >= lo.y - tol;
|
||||
over.then(|| Stop { body: f.body.clone(), face: f.face, distance })
|
||||
})
|
||||
.collect();
|
||||
out.sort_by(|a, b| a.distance.total_cmp(&b.distance));
|
||||
out
|
||||
}
|
||||
|
||||
/// The stop nearest the arrow's tip on screen when the tip is at `along` (from `base` along
|
||||
/// `n`), if one is within [`SNAP_PX`].
|
||||
pub(crate) fn nearest<'a>(proj: &Proj, base: Vec3, n: Vec3, along: f64, stops: &'a [Stop]) -> Option<&'a Stop> {
|
||||
let tip = proj.to_screen(base + n * along)?;
|
||||
stops
|
||||
.iter()
|
||||
.filter_map(|s| Some((s, proj.to_screen(base + n * s.distance)?.distance(tip))))
|
||||
.filter(|(_, px)| *px <= SNAP_PX)
|
||||
.min_by(|a, b| a.1.total_cmp(&b.1))
|
||||
.map(|(s, _)| s)
|
||||
}
|
||||
|
||||
/// Outlines the face the arrow stopped at, as a hovered face's edges are drawn.
|
||||
pub(crate) fn outline(app: &SolveApp, painter: &egui::Painter, proj: &Proj, stop: &Stop) {
|
||||
let Ok(st) = app.session.world_state() else { return };
|
||||
let Some(b) = st.body(&stop.body) else { return };
|
||||
let m = b.mesh();
|
||||
let t = Tokens::get();
|
||||
let Ok(face) = u32::try_from(stop.face) else { return };
|
||||
for e in m.face_edges(face) {
|
||||
let Some(pts) = m.edges.get(e) else { continue };
|
||||
let screen: Vec<Pos2> = pts.iter().filter_map(|p| proj.to_screen(*p)).collect();
|
||||
if screen.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
painter.add(egui::Shape::line(screen.clone(), Stroke::new(5.0, t.hover_edge_halo)));
|
||||
painter.add(egui::Shape::line(screen, Stroke::new(2.5, t.hover_edge)));
|
||||
}
|
||||
}
|
||||
@@ -61,6 +61,9 @@ pub struct Request {
|
||||
pub design: Option<String>,
|
||||
/// The chat turn that requested the load. It must still be current when the file lands.
|
||||
pub(crate) chat_turn: Option<Arc<std::sync::atomic::AtomicBool>>,
|
||||
/// Insert the file as a mesh whatever its extension says: a PLY goes to `pointcloud.insert`
|
||||
/// unless the person chose Insert Mesh for it (then it needs its faces).
|
||||
pub mesh: bool,
|
||||
}
|
||||
|
||||
impl Request {
|
||||
@@ -74,6 +77,7 @@ impl Request {
|
||||
allow_hosts: Vec::new(),
|
||||
design: None,
|
||||
chat_turn: None,
|
||||
mesh: false,
|
||||
}
|
||||
}
|
||||
fn insert(&self) -> bool {
|
||||
@@ -88,7 +92,7 @@ impl Request {
|
||||
fn command(&self) -> (&'static str, Value) {
|
||||
match &self.kind {
|
||||
Kind::Open => ("doc.open", self.params()),
|
||||
Kind::Insert if solidcraft_engine::io::is_mesh_path(&self.path) => ("file.insert_mesh", self.params()),
|
||||
Kind::Insert if self.mesh || solidcraft_engine::io::is_mesh_path(&self.path) => ("file.insert_mesh", self.params()),
|
||||
Kind::Insert if solidcraft_engine::io::is_point_cloud_path(&self.path) => ("pointcloud.insert", self.params()),
|
||||
Kind::Insert => (insert_command(&self.path), self.params()),
|
||||
Kind::Recover { id, dir } => ("doc.recover", json!({"id": id, "dir": dir})),
|
||||
@@ -265,6 +269,10 @@ impl FileLoad {
|
||||
}
|
||||
|
||||
pub fn begin(app: &mut SolveApp, path: &str, insert: bool) {
|
||||
// An STL or OBJ file states no unit: ask which, then import (see `crate::mesh_units`).
|
||||
if crate::mesh_units::ask(app, path, insert) {
|
||||
return;
|
||||
}
|
||||
let _ = begin_request(app, Request::new(path, if insert { Kind::Insert } else { Kind::Open }));
|
||||
}
|
||||
|
||||
@@ -286,11 +294,11 @@ pub fn begin_request(app: &mut SolveApp, request: Request) -> Result<(), String>
|
||||
}
|
||||
let r = match &request.kind {
|
||||
Kind::Insert => {
|
||||
app.insert_path(&request.path);
|
||||
app.insert_path_with(&request.path, &request.options, request.mesh);
|
||||
Ok(Value::Null)
|
||||
}
|
||||
Kind::Open => {
|
||||
app.open_path(&request.path);
|
||||
app.open_path_with(&request.path, &request.options);
|
||||
// Opened in place of the blank tab it made, with no switch to it.
|
||||
crate::edit_in_place::attach(app);
|
||||
Ok(Value::Null)
|
||||
@@ -413,6 +421,7 @@ pub fn control(app: &mut SolveApp, req: crate::control::ControlRequest) -> Optio
|
||||
allow_hosts: Vec::new(),
|
||||
design: None,
|
||||
chat_turn: req.chat_turn,
|
||||
mesh: false,
|
||||
};
|
||||
let _ = begin_request(app, request);
|
||||
None
|
||||
@@ -1268,8 +1277,8 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
let id = egui::Id::unique("file_loading");
|
||||
let card_id = id.with("card");
|
||||
// Above the dialogs over the design; menus, tooltips and the resize edges stay above it.
|
||||
ctx.move_to_top(egui::LayerId::new(egui::Order::Middle, id));
|
||||
ctx.move_to_top(egui::LayerId::new(egui::Order::Middle, card_id));
|
||||
Container::bring_to_front(ctx, egui::LayerId::new(egui::Order::Middle, id));
|
||||
Container::bring_to_front(ctx, egui::LayerId::new(egui::Order::Middle, card_id));
|
||||
Container::new(ctx, Surface::InputShield).area(id).order(egui::Order::Middle).fixed_pos(cover.min).interactable(true).show(ctx, |ui| {
|
||||
ui.set_min_size(cover.size());
|
||||
ui.interact(cover, egui::Id::unique("file_loading_block"), egui::Sense::click_and_drag());
|
||||
@@ -1458,6 +1467,15 @@ mod tests {
|
||||
assert!(reply.try_recv().is_ok_and(|r| r["ok"] == json!(false)), "the caller hears it failed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ply_is_a_point_cloud_unless_inserted_as_a_mesh() {
|
||||
let mut request = Request::new("scan.ply", Kind::Insert);
|
||||
assert_eq!(request.command().0, "pointcloud.insert");
|
||||
assert_eq!(Request::new("scan.ply", Kind::Open).command().0, "doc.open");
|
||||
request.mesh = true;
|
||||
assert_eq!(request.command().0, "file.insert_mesh");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_queued_opens_reply_once_and_keep_one_session() {
|
||||
let mut app = SolveApp::new(Session::default(), Default::default());
|
||||
|
||||
@@ -57,6 +57,7 @@ impl Catalog {
|
||||
|
||||
static ENGLISH: Catalog = Catalog::new("en", "English", include_str!(concat!(env!("OUT_DIR"), "/locales/en.json")));
|
||||
static ARABIC: Catalog = Catalog::new("ar", "العربية", include_str!(concat!(env!("OUT_DIR"), "/locales/ar.json")));
|
||||
static BULGARIAN: Catalog = Catalog::new("bg", "Български", include_str!(concat!(env!("OUT_DIR"), "/locales/bg.json")));
|
||||
static BOSNIAN: Catalog = Catalog::new("bs", "Bosanski", include_str!(concat!(env!("OUT_DIR"), "/locales/bs.json")));
|
||||
static CATALAN: Catalog = Catalog::new("ca", "Català", include_str!(concat!(env!("OUT_DIR"), "/locales/ca.json")));
|
||||
static CZECH: Catalog = Catalog::new("cs", "Čeština", include_str!(concat!(env!("OUT_DIR"), "/locales/cs.json")));
|
||||
@@ -96,6 +97,7 @@ static CHINESE_TRADITIONAL: Catalog = Catalog::new("zh-TW", "繁體中文", incl
|
||||
pub const LOCALES: &[&Catalog] = &[
|
||||
&ENGLISH,
|
||||
&ARABIC,
|
||||
&BULGARIAN,
|
||||
&BOSNIAN,
|
||||
&CATALAN,
|
||||
&CZECH,
|
||||
|
||||
+222
-110
@@ -117,6 +117,7 @@ mod measurement_ui_tests;
|
||||
#[cfg(test)]
|
||||
mod menu_tests;
|
||||
pub(crate) mod mesh_lod;
|
||||
pub mod mesh_units;
|
||||
pub mod messages;
|
||||
pub(crate) mod motion;
|
||||
pub mod occurrence_drag;
|
||||
@@ -168,6 +169,7 @@ mod expression_complete;
|
||||
mod extrude_auto_to_object_tests;
|
||||
#[cfg(test)]
|
||||
mod extrude_edit_tests;
|
||||
mod extrude_face_snap;
|
||||
mod extrude_preview;
|
||||
mod file_load;
|
||||
mod file_picker;
|
||||
@@ -696,6 +698,8 @@ pub struct SolveApp {
|
||||
pub recovery_discard_all: bool,
|
||||
/// The selection's measurement in the view's corner (#7000).
|
||||
pub(crate) quick_measure: quick_measure::QuickMeasure,
|
||||
/// An STL or OBJ file waiting for the unit its coordinates are in (`mesh_units`).
|
||||
pub mesh_units: Option<mesh_units::Ask>,
|
||||
/// The bodies of a just-opened Y-up file, offered to be stood up (`stand_up`).
|
||||
pub stand_up: Option<Vec<String>>,
|
||||
/// The placement of the component that file came in as: the offer turns it.
|
||||
@@ -910,6 +914,7 @@ impl SolveApp {
|
||||
reopen_guard_dir: None,
|
||||
recovery_discard_all: false,
|
||||
quick_measure: Default::default(),
|
||||
mesh_units: None,
|
||||
stand_up: None,
|
||||
stand_up_occurrence: None,
|
||||
stand_up_reason: false,
|
||||
@@ -1718,6 +1723,25 @@ impl SolveApp {
|
||||
}
|
||||
if id == "view.normal_to" {
|
||||
if self.run(id, json!({"camera": self.cam})).is_ok() {
|
||||
if self.universal_panel_host_enabled()
|
||||
&& let (Some(mut camera), Some(layout), Ok(usable)) =
|
||||
(self.session.camera, self.viewport.layout.as_ref(), shell::host_usable(self))
|
||||
{
|
||||
// Match the established follow-view up-axis semantics before
|
||||
// calculating the exact full-domain projection offset.
|
||||
if !render_workspace::active(self) {
|
||||
camera.up = self.cam.up;
|
||||
}
|
||||
let bounds = viewport::selection_bounds(self);
|
||||
let centred = if render_workspace::active(self) {
|
||||
render_workspace::centre_host_product_camera(self, camera, bounds.as_ref(), layout, &usable)
|
||||
} else {
|
||||
viewport_layout::centre_host_camera(camera, bounds.as_ref(), layout, &usable, self.view_fov())
|
||||
};
|
||||
if let Some(centred) = centred {
|
||||
self.session.camera = Some(centred);
|
||||
}
|
||||
}
|
||||
self.follow_view_request(true);
|
||||
self.home.open = false;
|
||||
}
|
||||
@@ -1927,7 +1951,22 @@ impl SolveApp {
|
||||
linked_source::start_selected(self);
|
||||
return;
|
||||
}
|
||||
if matches!(id, "file.insert_step" | "file.insert_mesh" | "pointcloud.insert") {
|
||||
if id == "file.insert_mesh" {
|
||||
// Insert Mesh is an explicit ask for a mesh: a PLY chosen here is read as one (its
|
||||
// faces), after asking its unit, where any other way of inserting it is a point cloud.
|
||||
// Like Insert SVG it asks the host for its own kind of file (on the web a file dialog,
|
||||
// not the window that also opens and downloads designs), so the file comes straight
|
||||
// back here and nothing has to remember which command asked.
|
||||
self.pick_open_for(&["3mf", "stl", "obj", "ply", "glb", "gltf"], |app, path| {
|
||||
if let Some(path) = path
|
||||
&& !mesh_units::ask_ply_as_mesh(app, &path)
|
||||
{
|
||||
app.insert_path_async(&path);
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
if matches!(id, "file.insert_step" | "pointcloud.insert") {
|
||||
self.pick_open(|app, path| {
|
||||
if let Some(path) = path {
|
||||
app.insert_path_async(&path);
|
||||
@@ -2550,6 +2589,11 @@ impl SolveApp {
|
||||
}
|
||||
|
||||
pub fn open_path(&mut self, path: &str) {
|
||||
self.open_path_with(path, &Default::default());
|
||||
}
|
||||
|
||||
/// [`Self::open_path`] with the import options of the request (`units` of an STL or OBJ file).
|
||||
pub fn open_path_with(&mut self, path: &str, options: &serde_json::Map<String, Value>) {
|
||||
match documents::reuse_path(self, path) {
|
||||
Ok(true) => return,
|
||||
Err(e) => {
|
||||
@@ -2560,7 +2604,9 @@ impl SolveApp {
|
||||
}
|
||||
self.home.open = false;
|
||||
documents::prepare_open(self);
|
||||
if let Ok(r) = self.run("doc.open", json!({ "path": path })) {
|
||||
let mut params = options.clone();
|
||||
params.insert("path".into(), json!(path));
|
||||
if let Ok(r) = self.run("doc.open", Value::Object(params)) {
|
||||
// An opened design comes up at the home view, not at the angle the design before it
|
||||
// was left at: `prepare_open` keeps the camera when it reuses a blank design.
|
||||
self.cam.set_view(StandardView::Iso);
|
||||
@@ -2591,9 +2637,23 @@ impl SolveApp {
|
||||
|
||||
/// Insert CAD bodies, meshes or sketch drawing geometry into the current design.
|
||||
pub fn insert_path(&mut self, path: &str) {
|
||||
let cmd = if solidcraft_engine::io::is_point_cloud_path(path) { "pointcloud.insert" } else { file_load::insert_command(path) };
|
||||
self.insert_path_with(path, &Default::default(), false);
|
||||
}
|
||||
|
||||
/// [`Self::insert_path`] with the import options of the request (`units` of an STL or OBJ file).
|
||||
/// `mesh`: insert it as a mesh whatever its extension says (a PLY with faces).
|
||||
pub fn insert_path_with(&mut self, path: &str, options: &serde_json::Map<String, Value>, mesh: bool) {
|
||||
let cmd = if mesh {
|
||||
"file.insert_mesh"
|
||||
} else if solidcraft_engine::io::is_point_cloud_path(path) {
|
||||
"pointcloud.insert"
|
||||
} else {
|
||||
file_load::insert_command(path)
|
||||
};
|
||||
let before: Vec<String> = crate::open_meshing::session_world(&self.session).bodies.iter().map(|b| b.name.clone()).collect();
|
||||
if let Ok(r) = self.run(cmd, json!({ "path": path })) {
|
||||
let mut params = options.clone();
|
||||
params.insert("path".into(), json!(path));
|
||||
if let Ok(r) = self.run(cmd, Value::Object(params)) {
|
||||
self.fit_view();
|
||||
stand_up::offer(self, path, &before, Some(&r));
|
||||
if let Some(summary) = timeline::import_status(self, &r) {
|
||||
@@ -2688,6 +2748,13 @@ impl SolveApp {
|
||||
/// rectangle to frame into is the one from before the Home screen or a dialog covered it.
|
||||
fn try_fitted_bounds(&self, cam: Camera, bounds: &solidcraft_engine::geom::Aabb3) -> Option<Camera> {
|
||||
let layout = self.viewport.layout.as_ref()?;
|
||||
if self.universal_panel_frame().is_some() {
|
||||
let usable = shell::host_usable(self).ok()?;
|
||||
if render_workspace::active(self) {
|
||||
return render_workspace::fit_host_product_bounds(self, cam, bounds, layout, &usable);
|
||||
}
|
||||
return viewport_layout::fit_host_bounds(cam, bounds, layout, &usable, self.view_fov(), f64::from(self.preferences.home_fit_size));
|
||||
}
|
||||
if render_workspace::active(self) {
|
||||
return viewport_layout::fit_product_bounds(cam, bounds, &render_workspace::picture_layout(self, layout));
|
||||
}
|
||||
@@ -2706,6 +2773,8 @@ impl SolveApp {
|
||||
|
||||
/// [`Self::navigator_fitted`] for `bounds`, or `None` when the layout can't frame it yet.
|
||||
fn navigator_fitted_bounds(&self, mut cam: Camera, bounds: &solidcraft_engine::geom::Aabb3) -> Option<Camera> {
|
||||
use solidcraft_engine::geom::Vec3Geom as _;
|
||||
|
||||
if bounds.is_empty() || !bounds.min.is_finite() || !bounds.max.is_finite() {
|
||||
return None;
|
||||
}
|
||||
@@ -2715,11 +2784,20 @@ impl SolveApp {
|
||||
// square, so the layout fit of that cube is the sphere's.
|
||||
let offset = solidcore_record::Vec3::new(radius, radius, radius);
|
||||
let sphere = solidcraft_engine::geom::Aabb3 { min: centre - offset, max: centre + offset };
|
||||
let mut probe = Camera::default();
|
||||
// Keep Classic's original probe; the opt-in host retains the authored lens and up axis.
|
||||
let mut probe = if self.universal_panel_host_enabled() { cam } else { Camera::default() };
|
||||
probe.set_view(StandardView::Front);
|
||||
let framed = self.try_fitted_bounds(probe, &sphere)?;
|
||||
cam.target = centre;
|
||||
cam.distance = framed.distance;
|
||||
if self.universal_panel_frame().is_some() {
|
||||
// Carry the sphere's one screen centre into the requested basis too.
|
||||
// Recentring its cube in each direction would choose different footprints.
|
||||
let offset = framed.target - centre;
|
||||
let (front_right, front_up, _) = framed.basis();
|
||||
let (right, up, _) = cam.basis();
|
||||
cam.target = centre + right * offset.dot(front_right) + up * offset.dot(front_up);
|
||||
}
|
||||
cam.is_valid().then_some(cam)
|
||||
}
|
||||
|
||||
@@ -2959,7 +3037,7 @@ impl SolveApp {
|
||||
// Shortcuts run here, before `ui` installs the language scope: a tool started by its
|
||||
// key must build its translated hint in the user's language, not in English.
|
||||
let _language = crate::i18n::scope(&self.preferences.language);
|
||||
panel_runtime::tick_app(self);
|
||||
panel_runtime::tick_app(self, ctx);
|
||||
// Sleep/wake often skips frames without a device-lost signal; refresh egui GPU textures
|
||||
// when the frame clock jumps so the chrome is not stuck blank (#8749).
|
||||
let frame_time = ctx.input(|i| i.time);
|
||||
@@ -3029,6 +3107,7 @@ impl SolveApp {
|
||||
self.issue_screenshots(ctx);
|
||||
if self.issue_report.draft.is_none() && self.file_picker.is_none() {
|
||||
// Completion owns its keys before either CAD shortcuts or text editors see them.
|
||||
panel_runtime::reserve_host_input(self, ctx);
|
||||
if !keymap::capturing(self) {
|
||||
expression_complete::begin_frame(ctx);
|
||||
}
|
||||
@@ -3215,6 +3294,7 @@ impl SolveApp {
|
||||
agent_chat::settings::dialog(self, ui.ctx());
|
||||
}
|
||||
if self.home.open {
|
||||
panel_runtime::hide_app_host(self);
|
||||
home::show(self, ui);
|
||||
if self.home.open {
|
||||
// Agent detection runs in the background and is only received by `agent_chat::poll`
|
||||
@@ -3227,127 +3307,145 @@ impl SolveApp {
|
||||
}
|
||||
}
|
||||
// The status bar first: it spans the window's width below History and the side panels.
|
||||
status_bar::show(self, ui);
|
||||
let floating = render_workspace::active(self) || ui_kit::Container::new(ui.ctx(), ui_kit::Surface::Panel).floating();
|
||||
timeline::follow_view_pick(self);
|
||||
render_ui::focus_shortcut(self, ui);
|
||||
let show_timeline = self.ui.show_timeline && !render_workspace::active(self) && !self.preferences.history_in_browser;
|
||||
let left_timeline = show_timeline && self.preferences.timeline_left;
|
||||
timeline_left::animate_folds(self, ui.ctx());
|
||||
if !floating && !self.embedded {
|
||||
toolbar::toolbar(self, ui);
|
||||
}
|
||||
theme::TabAccent::publish(self, ui.ctx());
|
||||
browser::publish_row_prefs(self, ui.ctx());
|
||||
if !floating {
|
||||
agent_chat::show(self, ui);
|
||||
}
|
||||
if !floating && show_timeline && !left_timeline {
|
||||
timeline::timeline(self, ui);
|
||||
}
|
||||
// Browser hugs its contents in either layout; it never becomes a full-height blank column.
|
||||
if !self.ui.show_browser || render_ui::focused(self) {
|
||||
self.shell.browser = None;
|
||||
shell::register_panel(self, "render:browser", None, None);
|
||||
shell::register_panel(self, "render:appearances", None, None);
|
||||
}
|
||||
if floating || left_timeline || !show_timeline {
|
||||
self.shell.history = None;
|
||||
}
|
||||
// The model draws next: a dialog the toolbar closed last frame no longer shows its sketch.
|
||||
dialogs::sync_feature_edit(self);
|
||||
let full = ui.available_rect_before_wrap();
|
||||
if floating {
|
||||
let cards = toolbar::shell_cards(self, full);
|
||||
self.shell.cards = vec![cards.workspace, cards.ribbon];
|
||||
self.shell.history = if left_timeline {
|
||||
let below_ribbon = egui::Rect::from_min_max(egui::pos2(full.left(), cards.bottom), full.max);
|
||||
// A dialog in the left column holds the History's place.
|
||||
(!dialog_column::holds(self)).then(|| timeline_left::floating_rect(self, below_ribbon))
|
||||
} else {
|
||||
show_timeline.then(|| timeline::floating_rect(full))
|
||||
};
|
||||
// Draw the scene first, then let the unchanged panel layouts cover it. The
|
||||
// viewport keeps its full projection even underneath the browser and cards.
|
||||
preview::update(self, ui.ctx());
|
||||
// A camera drag that began on the model keeps capture across cards. New
|
||||
// gestures over chrome are blocked, as are selection drags into the ribbon.
|
||||
let continuing_navigation = ui.input(|i| {
|
||||
(i.pointer.middle_down() || i.pointer.secondary_down())
|
||||
&& i.pointer.press_origin().is_some_and(|p| full.contains(p) && !shell::covered(self, p))
|
||||
});
|
||||
// A captured comparison divider also keeps its primary drag across floating cards.
|
||||
let continuing_comparison = render_workspace::comparison_drag_captured(self) && ui.input(|i| i.pointer.primary_down());
|
||||
let blocked =
|
||||
!continuing_navigation && !continuing_comparison && ui.input(|i| i.pointer.latest_pos()).is_some_and(|p| shell::covered(self, p));
|
||||
let mut viewport_ui = ui.new_child(egui::UiBuilder::new().max_rect(full).id_salt("floating_viewport"));
|
||||
if blocked {
|
||||
// Disabled only to shield the scene from input under a card or menu; it must
|
||||
// not fade, or the whole viewport dims whenever the pointer is over the shell.
|
||||
viewport_ui.visuals_mut().disabled_alpha = 1.0;
|
||||
viewport_ui.disable();
|
||||
if self.universal_panel_host_enabled() {
|
||||
self.universal_workspace_ui(ui);
|
||||
// Browser-owned editors retain their independent legacy windows,
|
||||
// drafts and capture questions while the Browser host is suppressed.
|
||||
browser::editors(self, ui);
|
||||
} else {
|
||||
status_bar::show(self, ui);
|
||||
let floating = render_workspace::active(self) || ui_kit::Container::new(ui.ctx(), ui_kit::Surface::Panel).floating();
|
||||
timeline::follow_view_pick(self);
|
||||
render_ui::focus_shortcut(self, ui);
|
||||
let show_timeline = self.ui.show_timeline && !render_workspace::active(self) && !self.preferences.history_in_browser;
|
||||
let left_timeline = show_timeline && self.preferences.timeline_left;
|
||||
timeline_left::animate_folds(self, ui.ctx());
|
||||
if !floating && !self.embedded {
|
||||
toolbar::toolbar(self, ui);
|
||||
}
|
||||
self.show_workspace(&mut viewport_ui);
|
||||
shell::paint_top_corners(ui.painter(), full, theme::Tokens::get().app_bar);
|
||||
toolbar::toolbar(self, ui);
|
||||
theme::TabAccent::publish(self, ui.ctx());
|
||||
}
|
||||
if floating && show_timeline && !left_timeline {
|
||||
timeline::timeline(self, ui);
|
||||
}
|
||||
dialog_column::layout(self, ui.available_rect_before_wrap());
|
||||
if left_timeline {
|
||||
timeline_left::left_panel(self, ui);
|
||||
}
|
||||
if render_workspace::active(self) {
|
||||
render_ui::shots_strip(self, ui);
|
||||
render_workspace::panel(self, ui);
|
||||
}
|
||||
if self.ui.show_browser && !render_ui::focused(self) {
|
||||
browser::browser(self, ui);
|
||||
}
|
||||
// All shared semantic content has now submitted its output. Apply it before the
|
||||
// viewport/dialog/menu consumers, regardless of which presentations were visible.
|
||||
semantic_content::finalize(self, ui.ctx());
|
||||
browser::editors(self, ui);
|
||||
if floating {
|
||||
agent_chat::show(self, ui);
|
||||
}
|
||||
Container::new(ui.ctx(), Surface::Viewport)
|
||||
.central()
|
||||
.frame(Container::new(ui.ctx(), Surface::Viewport).edge_frame(egui::Color32::TRANSPARENT))
|
||||
.show(ui, |ui| {
|
||||
let panel_content = ui.max_rect();
|
||||
self.shell.content = Some(shell::workspace_content(self, panel_content));
|
||||
if floating {
|
||||
self.shell.panels = [
|
||||
egui::Rect::from_min_max(egui::pos2(full.left(), panel_content.top()), egui::pos2(panel_content.left(), full.bottom())),
|
||||
egui::Rect::from_min_max(egui::pos2(panel_content.right(), panel_content.top()), full.max),
|
||||
]
|
||||
.into_iter()
|
||||
.filter(|r| r.is_positive())
|
||||
.collect();
|
||||
viewport::refresh_layout(self, ui.ctx());
|
||||
browser::publish_row_prefs(self, ui.ctx());
|
||||
if !floating {
|
||||
agent_chat::show(self, ui);
|
||||
}
|
||||
if !floating && show_timeline && !left_timeline {
|
||||
timeline::timeline(self, ui);
|
||||
}
|
||||
// Browser hugs its contents in either layout; it never becomes a full-height blank column.
|
||||
if !self.ui.show_browser || render_ui::focused(self) {
|
||||
self.shell.browser = None;
|
||||
shell::register_panel(self, "render:browser", None, None);
|
||||
shell::register_panel(self, "render:appearances", None, None);
|
||||
}
|
||||
if floating || left_timeline || !show_timeline {
|
||||
self.shell.history = None;
|
||||
}
|
||||
// The model draws next: a dialog the toolbar closed last frame no longer shows its sketch.
|
||||
dialogs::sync_feature_edit(self);
|
||||
let full = ui.available_rect_before_wrap();
|
||||
if floating {
|
||||
let cards = toolbar::shell_cards(self, full);
|
||||
self.shell.cards = vec![cards.workspace, cards.ribbon];
|
||||
self.shell.history = if left_timeline {
|
||||
let below_ribbon = egui::Rect::from_min_max(egui::pos2(full.left(), cards.bottom), full.max);
|
||||
// A dialog in the left column holds the History's place.
|
||||
(!dialog_column::holds(self)).then(|| timeline_left::floating_rect(self, below_ribbon))
|
||||
} else {
|
||||
preview::update(self, ui.ctx());
|
||||
self.show_workspace(ui);
|
||||
show_timeline.then(|| timeline::floating_rect(full))
|
||||
};
|
||||
// Draw the scene first, then let the unchanged panel layouts cover it. The
|
||||
// viewport keeps its full projection even underneath the browser and cards.
|
||||
preview::update(self, ui.ctx());
|
||||
// A camera drag that began on the model keeps capture across cards. New
|
||||
// gestures over chrome are blocked, as are selection drags into the ribbon.
|
||||
let continuing_navigation = ui.input(|i| {
|
||||
(i.pointer.middle_down() || i.pointer.secondary_down())
|
||||
&& i.pointer.press_origin().is_some_and(|p| full.contains(p) && !shell::covered(self, p))
|
||||
});
|
||||
// A captured comparison divider also keeps its primary drag across floating cards.
|
||||
let continuing_comparison = render_workspace::comparison_drag_captured(self) && ui.input(|i| i.pointer.primary_down());
|
||||
let blocked =
|
||||
!continuing_navigation && !continuing_comparison && ui.input(|i| i.pointer.latest_pos()).is_some_and(|p| shell::covered(self, p));
|
||||
let mut viewport_ui = ui.new_child(egui::UiBuilder::new().max_rect(full).id_salt("floating_viewport"));
|
||||
if blocked {
|
||||
// Disabled only to shield the scene from input under a card or menu; it must
|
||||
// not fade, or the whole viewport dims whenever the pointer is over the shell.
|
||||
viewport_ui.visuals_mut().disabled_alpha = 1.0;
|
||||
viewport_ui.disable();
|
||||
}
|
||||
});
|
||||
self.show_workspace(&mut viewport_ui);
|
||||
shell::paint_top_corners(ui.painter(), full, theme::Tokens::get().app_bar);
|
||||
toolbar::toolbar(self, ui);
|
||||
theme::TabAccent::publish(self, ui.ctx());
|
||||
}
|
||||
if floating && show_timeline && !left_timeline {
|
||||
timeline::timeline(self, ui);
|
||||
}
|
||||
dialog_column::layout(self, ui.available_rect_before_wrap());
|
||||
if left_timeline {
|
||||
timeline_left::left_panel(self, ui);
|
||||
}
|
||||
if render_workspace::active(self) {
|
||||
render_ui::shots_strip(self, ui);
|
||||
render_workspace::panel(self, ui);
|
||||
}
|
||||
if self.ui.show_browser && !render_ui::focused(self) {
|
||||
browser::browser(self, ui);
|
||||
}
|
||||
// Apply shared Browser/History output before viewport and menu consumers.
|
||||
semantic_content::finalize(self, ui.ctx());
|
||||
browser::editors(self, ui);
|
||||
if floating {
|
||||
agent_chat::show(self, ui);
|
||||
}
|
||||
Container::new(ui.ctx(), Surface::Viewport)
|
||||
.central()
|
||||
.frame(Container::new(ui.ctx(), Surface::Viewport).edge_frame(egui::Color32::TRANSPARENT))
|
||||
.show(ui, |ui| {
|
||||
let panel_content = ui.max_rect();
|
||||
self.shell.content = Some(shell::workspace_content(self, panel_content));
|
||||
if floating {
|
||||
self.shell.panels = [
|
||||
egui::Rect::from_min_max(egui::pos2(full.left(), panel_content.top()), egui::pos2(panel_content.left(), full.bottom())),
|
||||
egui::Rect::from_min_max(egui::pos2(panel_content.right(), panel_content.top()), full.max),
|
||||
]
|
||||
.into_iter()
|
||||
.filter(|r| r.is_positive())
|
||||
.collect();
|
||||
viewport::refresh_layout(self, ui.ctx());
|
||||
} else {
|
||||
preview::update(self, ui.ctx());
|
||||
self.show_workspace(ui);
|
||||
}
|
||||
});
|
||||
}
|
||||
if render_workspace::active(self) {
|
||||
render_ui::overlays(self, ui);
|
||||
}
|
||||
// Measure current persistent sketch chrome before the host's early
|
||||
// confirmation pair. Its answer still precedes this frame's dialog.
|
||||
if self.universal_panel_host_enabled() {
|
||||
sketch_palette::show(self, ui.ctx());
|
||||
self.viewport.host_windows = ui_kit::Container::host_window_regions(ui.ctx());
|
||||
viewport::refresh_layout(self, ui.ctx());
|
||||
}
|
||||
// Before the dialog: a click on the view's OK or Cancel is for this frame's dialog.
|
||||
view_confirm::show(self, ui.ctx());
|
||||
dialogs::show(self, ui.ctx());
|
||||
issue_report::CadInput::block(self, ui, report_input);
|
||||
sketch_palette::show(self, ui.ctx());
|
||||
self.resolve_fit(ui.ctx());
|
||||
if !self.universal_panel_host_enabled() {
|
||||
sketch_palette::show(self, ui.ctx());
|
||||
}
|
||||
if !self.universal_panel_host_enabled() {
|
||||
self.resolve_fit(ui.ctx());
|
||||
}
|
||||
params_dialog::show(self, ui.ctx());
|
||||
design_properties::show(self, ui.ctx());
|
||||
sketch_report::show(self, ui.ctx());
|
||||
bom_panel::show(self, ui.ctx());
|
||||
material_card_review::show(self, ui.ctx());
|
||||
recovery_ui::show(self, ui.ctx());
|
||||
mesh_units::show(self, ui.ctx());
|
||||
stand_up::show(self, ui.ctx());
|
||||
prefs_notice::show(self, ui.ctx());
|
||||
context_menu::show(self, ui.ctx());
|
||||
@@ -3359,6 +3457,20 @@ impl SolveApp {
|
||||
shortcut_box::show(self, ui.ctx());
|
||||
prefs::show(self, ui.ctx());
|
||||
toolbar_custom::window(self, ui.ctx());
|
||||
// All persistent producers have now registered this pass's actual
|
||||
// visible paint. Place independent controls and finish result navigation
|
||||
// against those footprints; the render domain stays unchanged.
|
||||
if self.universal_panel_host_enabled() {
|
||||
self.viewport.host_windows = ui_kit::Container::host_window_regions(ui.ctx());
|
||||
if let Some(rect) = self.viewport.rect.filter(|rect| rect.is_positive() && rect.is_finite()) {
|
||||
let mut controls = ui.new_child(egui::UiBuilder::new().id_salt("universal_panel_controls").max_rect(rect));
|
||||
controls.set_clip_rect(controls.clip_rect().intersect(rect));
|
||||
render_workspace::host_result_overlays(self, &mut controls);
|
||||
viewport::show_host_controls(self, &mut controls, rect);
|
||||
}
|
||||
self.resolve_fit(ui.ctx());
|
||||
}
|
||||
panel_runtime::finish_app_host(self, ui);
|
||||
}
|
||||
|
||||
fn show_workspace(&mut self, ui: &mut egui::Ui) {
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
//! Asking which unit an STL or OBJ file is in. These formats carry no unit, so a file made in
|
||||
//! inches would come in 25.4 times too small. When a person opens, inserts or drops one, a small
|
||||
//! dialog asks for the unit first: OK imports with it (`units` of `file.insert_mesh` and
|
||||
//! `doc.open`, which scale the coordinates to millimetres as the file is read), Cancel imports
|
||||
//! nothing. The design keeps the millimetre mesh and not the unit, so a different unit is tried by
|
||||
//! importing the file again.
|
||||
//!
|
||||
//! Only interactive entry points ask ([`file_load::begin`]): a script, the control channel or MCP
|
||||
//! calls the commands with their own `units`, or none for millimetres, and never meets a dialog.
|
||||
|
||||
use serde_json::json;
|
||||
use solidcraft_engine::doc::point_cloud::UNITS;
|
||||
|
||||
use crate::{SolveApp, file_load, ui_kit};
|
||||
|
||||
/// A file waiting for its unit.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Ask {
|
||||
/// The file.
|
||||
pub path: String,
|
||||
/// Insert it into the design (else open it as a new design).
|
||||
pub insert: bool,
|
||||
/// The chosen unit: an index into the unit list, millimetres first.
|
||||
pub choice: usize,
|
||||
/// Insert it as a mesh whatever its extension says (a PLY chosen with Insert Mesh).
|
||||
pub mesh: bool,
|
||||
}
|
||||
|
||||
/// Files that state no unit of their own and take one when imported.
|
||||
pub fn needs_unit(path: &str) -> bool {
|
||||
let lower = path.to_ascii_lowercase();
|
||||
lower.ends_with(".stl") || lower.ends_with(".obj")
|
||||
}
|
||||
|
||||
/// Ask for the unit of `path` before it is imported. Returns whether the file was held for the
|
||||
/// answer (the caller then stops: the dialog starts the import itself). The web app asks too, for
|
||||
/// the file a person uploaded, before its mesh is made.
|
||||
pub fn ask(app: &mut SolveApp, path: &str, insert: bool) -> bool {
|
||||
if !needs_unit(path) {
|
||||
return false;
|
||||
}
|
||||
app.mesh_units = Some(Ask { path: path.into(), insert, choice: default_choice(), mesh: false });
|
||||
true
|
||||
}
|
||||
|
||||
/// Insert Mesh was chosen and `path` is a PLY: ask its unit, then insert it as a mesh (its faces)
|
||||
/// and not as the point cloud every other way of inserting a PLY makes. Returns whether it was
|
||||
/// held for the answer; another file goes on as the extension says.
|
||||
pub fn ask_ply_as_mesh(app: &mut SolveApp, path: &str) -> bool {
|
||||
if !solidcraft_engine::io::is_ply_path(path) {
|
||||
return false;
|
||||
}
|
||||
app.mesh_units = Some(Ask { path: path.into(), insert: true, choice: default_choice(), mesh: true });
|
||||
true
|
||||
}
|
||||
|
||||
/// The unit chosen when the dialog opens: millimetres, the unit a file is read in without one.
|
||||
fn default_choice() -> usize {
|
||||
UNITS.iter().position(|(name, _)| *name == "mm").unwrap_or(0)
|
||||
}
|
||||
|
||||
/// The unit's id for `units` (`mm`, `in`, ...) at `choice`.
|
||||
fn unit_at(choice: usize) -> &'static str {
|
||||
UNITS.get(choice).map_or("mm", |(name, _)| name)
|
||||
}
|
||||
|
||||
/// The dialog, while a file waits for its unit.
|
||||
pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
let Some(mut ask) = app.mesh_units.clone() else { return };
|
||||
let file = std::path::Path::new(&ask.path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| ask.path.clone());
|
||||
// The symbols themselves (mm, cm, m, in, ft), as everywhere else units are chosen.
|
||||
let names: Vec<&str> = UNITS.iter().map(|(name, _)| *name).collect();
|
||||
let (closed, action) =
|
||||
ui_kit::Window::new(egui::Id::unique("sc_mesh_units"), "import", crate::i18n::tr("ui.point_cloud_units")).show(ctx, true, |ui| {
|
||||
ui_kit::text(ui, &file, ui_kit::Text::Report("file", false));
|
||||
ui_kit::choice_row(ui, crate::i18n::tr("ui.units"), "mesh_units", &mut ask.choice, &names);
|
||||
});
|
||||
for (handle, key) in [("mesh_units:ok", "dialog:ok"), ("mesh_units:cancel", "dialog:cancel")] {
|
||||
if let Some(at) = crate::scenario::handle_at(key) {
|
||||
crate::scenario::publish_handle(handle, at);
|
||||
}
|
||||
}
|
||||
match action {
|
||||
ui_kit::Action::Ok => {
|
||||
app.mesh_units = None;
|
||||
let kind = if ask.insert { file_load::Kind::Insert } else { file_load::Kind::Open };
|
||||
let mut request = file_load::Request::new(&ask.path, kind);
|
||||
request.mesh = ask.mesh;
|
||||
request.options.insert("units".into(), json!(unit_at(ask.choice)));
|
||||
let _ = file_load::begin_request(app, request);
|
||||
}
|
||||
ui_kit::Action::Cancel => app.mesh_units = None,
|
||||
ui_kit::Action::None if closed => app.mesh_units = None,
|
||||
_ => app.mesh_units = Some(ask),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn only_stl_and_obj_files_ask() {
|
||||
for path in ["part.stl", "PART.STL", "a/b/c.Obj", "x.obj"] {
|
||||
assert!(needs_unit(path), "{path}");
|
||||
}
|
||||
for path in ["part.3mf", "part.step", "part.glb", "part.ply", "stl", "part.stl.txt", ""] {
|
||||
assert!(!needs_unit(path), "{path}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ply_asks_only_when_it_is_inserted_as_a_mesh() {
|
||||
let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default());
|
||||
// Open and Insert keep sending a PLY to the point cloud: no dialog.
|
||||
assert!(!ask(&mut app, "scan.ply", true) && !ask(&mut app, "scan.PLY", false));
|
||||
assert!(app.mesh_units.is_none());
|
||||
// Insert Mesh is explicit: the dialog, then the mesh command.
|
||||
assert!(!ask_ply_as_mesh(&mut app, "part.stl"), "only a PLY needs this route");
|
||||
assert!(ask_ply_as_mesh(&mut app, "scan.ply"));
|
||||
let held = app.mesh_units.clone().expect("held");
|
||||
assert_eq!((held.path.as_str(), held.insert, held.mesh, unit_at(held.choice)), ("scan.ply", true, true, "mm"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn millimetres_come_first_and_a_bad_choice_is_millimetres() {
|
||||
assert_eq!(unit_at(0), "mm");
|
||||
assert_eq!(unit_at(3), "in");
|
||||
assert_eq!(unit_at(99), "mm");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_stl_waits_for_its_unit_and_the_control_channel_does_not() {
|
||||
let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default());
|
||||
file_load::begin(&mut app, "part.stl", true);
|
||||
let ask = app.mesh_units.clone().expect("asked");
|
||||
assert_eq!((ask.path.as_str(), ask.insert, unit_at(ask.choice)), ("part.stl", true, "mm"));
|
||||
assert!(app.file_load.idle(), "nothing is imported until OK");
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,22 @@ use crate::prefs::{OrbitAround, pivot_under};
|
||||
use crate::space_mouse::{BridgeMotion, Motion};
|
||||
use crate::viewport::{Hit, NavMode, axis_rect, nearest_quarter_turn, pick, pick_cached, projection};
|
||||
|
||||
/// Take a predominantly horizontal wheel gesture for a hovered scroll viewport.
|
||||
/// Leave vertical input for its enclosing page, and leave horizontal input
|
||||
/// unconsumed when this viewport is already at the requested end.
|
||||
pub(crate) fn take_horizontal_wheel(ui: &egui::Ui, offset: f32, max_offset: f32) -> f32 {
|
||||
ui.input_mut(|input| {
|
||||
let delta = input.smooth_scroll_delta;
|
||||
if delta.x == 0.0 || delta.x.abs() <= delta.y.abs() {
|
||||
return 0.0;
|
||||
}
|
||||
if (offset - delta.x).clamp(0.0, max_offset) != offset {
|
||||
input.smooth_scroll_delta.x = 0.0;
|
||||
}
|
||||
delta.x
|
||||
})
|
||||
}
|
||||
|
||||
/// What a page's camera may do.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct NavCaps {
|
||||
@@ -38,6 +54,27 @@ impl NavCaps {
|
||||
pub const RENDER: NavCaps = NavCaps { orbit: true, pick: true };
|
||||
}
|
||||
|
||||
/// Give a panel the wheel delta left by its children, one movable axis at a time.
|
||||
/// Boundary deltas remain available to the panel host's input fallback.
|
||||
pub(crate) fn panel_scroll_offset(ctx: &egui::Context, previous: egui::Vec2, maximum: egui::Vec2) -> egui::Vec2 {
|
||||
let mut offset = previous;
|
||||
ctx.input_mut(|input| {
|
||||
if maximum.x > 0.0 && input.smooth_scroll_delta.x != 0.0 {
|
||||
offset.x = (previous.x - input.smooth_scroll_delta.x).clamp(0.0, maximum.x);
|
||||
if offset.x != previous.x {
|
||||
input.smooth_scroll_delta.x = 0.0;
|
||||
}
|
||||
}
|
||||
if maximum.y > 0.0 && input.smooth_scroll_delta.y != 0.0 {
|
||||
offset.y = (previous.y - input.smooth_scroll_delta.y).clamp(0.0, maximum.y);
|
||||
if offset.y != previous.y {
|
||||
input.smooth_scroll_delta.y = 0.0;
|
||||
}
|
||||
}
|
||||
});
|
||||
offset
|
||||
}
|
||||
|
||||
/// Supplies the scroll phases browsers omit, before the shared navigation sees input.
|
||||
#[derive(Default)]
|
||||
pub struct WebWheelGestures {
|
||||
@@ -1253,6 +1290,40 @@ fn orbit_camera(app: &mut SolveApp, dx: f64, dy: f64) {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use solidcraft_engine::geom::prelude::*;
|
||||
|
||||
#[test]
|
||||
fn panel_wheel_consumes_only_axes_that_move_and_clamps_to_their_limits() {
|
||||
use egui::vec2;
|
||||
let ctx = crate::fonts::test_context();
|
||||
for (previous, delta, maximum, expected, remaining) in [
|
||||
(vec2(20.0, 30.0), vec2(-200.0, 200.0), vec2(100.0, 80.0), vec2(100.0, 0.0), egui::Vec2::ZERO),
|
||||
(vec2(100.0, 30.0), vec2(-10.0, 10.0), vec2(100.0, 80.0), vec2(100.0, 20.0), vec2(-10.0, 0.0)),
|
||||
(vec2(20.0, 0.0), vec2(10.0, 10.0), vec2(100.0, 80.0), vec2(10.0, 0.0), vec2(0.0, 10.0)),
|
||||
(egui::Vec2::ZERO, vec2(-10.0, -10.0), egui::Vec2::ZERO, egui::Vec2::ZERO, vec2(-10.0, -10.0)),
|
||||
] {
|
||||
crate::test_support::frame(&ctx, egui::RawInput::default(), |ui| {
|
||||
ui.input_mut(|input| input.smooth_scroll_delta = delta);
|
||||
assert_eq!(super::panel_scroll_offset(ui.ctx(), previous, maximum), expected);
|
||||
assert_eq!(ui.input(|input| input.smooth_scroll_delta), remaining);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn panel_wheel_leaves_child_consumed_axes_and_raw_fallback_untouched() {
|
||||
use egui::vec2;
|
||||
let ctx = crate::fonts::test_context();
|
||||
let event = web_wheel(egui::MouseWheelUnit::Point, vec2(-12.0, -18.0), egui::Modifiers::NONE);
|
||||
crate::test_support::frame(&ctx, egui::RawInput { events: vec![event], ..Default::default() }, |ui| {
|
||||
// A child has already consumed Y; only its unclaimed X reaches the host.
|
||||
ui.input_mut(|input| input.smooth_scroll_delta = vec2(-12.0, 0.0));
|
||||
let events = ui.input(|input| input.events.clone());
|
||||
assert_eq!(super::panel_scroll_offset(ui.ctx(), vec2(5.0, 7.0), vec2(40.0, 40.0)), vec2(17.0, 7.0));
|
||||
assert_eq!(ui.input(|input| input.smooth_scroll_delta), egui::Vec2::ZERO);
|
||||
assert_eq!(ui.input(|input| input.events.clone()), events, "raw fallback ownership stays with the host");
|
||||
});
|
||||
}
|
||||
|
||||
fn web_wheel(unit: egui::MouseWheelUnit, delta: egui::Vec2, modifiers: egui::Modifiers) -> egui::Event {
|
||||
egui::Event::MouseWheel { source: egui::MouseWheelSource::Unknown, unit, delta, modifiers, phase: egui::TouchPhase::Move }
|
||||
}
|
||||
|
||||
@@ -138,9 +138,82 @@ pub(crate) fn editor_layout(stage: Rect, prefs: &NavigationBar, label_width: imp
|
||||
|
||||
pub(crate) fn measured(app: &SolveApp, ctx: &egui::Context, content: Rect) -> BarLayout {
|
||||
let t = Tokens::get();
|
||||
measure(content, &app.preferences.navigation_bar, navigation_bar::canvas_caps(app), |slot| {
|
||||
let label_width = |slot: &Slot| {
|
||||
ctx.fonts_mut(|fonts| fonts.layout_no_wrap(slot_text(app, slot).to_owned(), crate::fonts::medium(ui_kit::NAV_TEXT), t.form_ink).size().x)
|
||||
})
|
||||
};
|
||||
let mut bar = measure(content, &app.preferences.navigation_bar, navigation_bar::canvas_caps(app), label_width);
|
||||
let Some(_) = app.universal_panel_frame() else {
|
||||
return bar;
|
||||
};
|
||||
if !bar.rect.is_positive() {
|
||||
return bar;
|
||||
}
|
||||
let Ok(region) = crate::shell::host_usable(app) else {
|
||||
bar.rect = Rect::NOTHING;
|
||||
bar.slots.clear();
|
||||
bar.more = Rect::NOTHING;
|
||||
return bar;
|
||||
};
|
||||
let preferred = bar.rect.center();
|
||||
let place = |bar: &BarLayout| {
|
||||
region.place_footprint(
|
||||
solidcraft_engine::panels::Size { width: bar.rect.width(), height: bar.rect.height() },
|
||||
solidcraft_engine::panels::Point { x: preferred.x, y: preferred.y },
|
||||
t.space_4,
|
||||
)
|
||||
};
|
||||
let mut location = place(&bar);
|
||||
if location.is_none() {
|
||||
// Keep the existing value/label/More policy when a full row cannot fit.
|
||||
// Measure a smaller row, then validate its complete footprint against
|
||||
// the contour rather than anchoring it to a fictitious central strip.
|
||||
let width = region
|
||||
.free
|
||||
.iter()
|
||||
.filter(|bounds| bounds.size.height >= bar.rect.height() + 2.0 * t.space_4)
|
||||
.map(|bounds| (bounds.size.width - 2.0 * t.space_4).max(0.0))
|
||||
.max_by(f32::total_cmp)
|
||||
.unwrap_or(0.0);
|
||||
bar = measure(
|
||||
Rect::from_min_size(content.min, vec2(width, content.height())),
|
||||
&app.preferences.navigation_bar,
|
||||
navigation_bar::canvas_caps(app),
|
||||
label_width,
|
||||
);
|
||||
if bar.rect.is_positive() {
|
||||
location = place(&bar);
|
||||
}
|
||||
}
|
||||
if location.is_none() {
|
||||
// A minimal More row may span adjacent sweep slabs even when no single
|
||||
// free piece is tall enough. Validate that measured footprint directly.
|
||||
let metrics = ui_kit::NavigationMetrics::for_size(app.preferences.navigation_bar.size);
|
||||
let width = metrics.button + 2.0 * (ui_kit::NAV_BORDER + ui_kit::NAV_PADDING + ui_kit::NAV_EDGE);
|
||||
bar = measure(
|
||||
Rect::from_min_size(content.min, vec2(width, content.height())),
|
||||
&app.preferences.navigation_bar,
|
||||
navigation_bar::canvas_caps(app),
|
||||
label_width,
|
||||
);
|
||||
if bar.rect.is_positive() {
|
||||
location = place(&bar);
|
||||
}
|
||||
}
|
||||
if let Some(location) = location {
|
||||
let delta = crate::panel_runtime::egui_rect(location).min - bar.rect.min;
|
||||
bar.rect = bar.rect.translate(delta);
|
||||
for (_, rect) in &mut bar.slots {
|
||||
*rect = rect.translate(delta);
|
||||
}
|
||||
if bar.more.is_positive() {
|
||||
bar.more = bar.more.translate(delta);
|
||||
}
|
||||
} else {
|
||||
bar.rect = Rect::NOTHING;
|
||||
bar.slots.clear();
|
||||
bar.more = Rect::NOTHING;
|
||||
}
|
||||
bar
|
||||
}
|
||||
|
||||
fn selected(app: &SolveApp, id: &str) -> bool {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use solidcraft_engine::Session;
|
||||
use solidcraft_engine::panels::*;
|
||||
|
||||
use super::runtime::standalone_header_action;
|
||||
use super::*;
|
||||
|
||||
/// Later content adapters supply their own services. The app integration exposes
|
||||
@@ -14,21 +15,29 @@ pub trait AppPanelServices {
|
||||
pub struct AppPanelRuntime {
|
||||
runtime: PanelRuntime,
|
||||
services: Box<dyn AppPanelServices>,
|
||||
native: Box<dyn NativeHostAdapter>,
|
||||
host: Option<WorkspacePanelHost>,
|
||||
last_tick_frame: Option<u64>,
|
||||
last_error: Option<PanelError>,
|
||||
catalogue: Box<dyn commands::LayoutCatalogue>,
|
||||
native: Box<dyn NativeHostAdapter>,
|
||||
adapters_set: bool,
|
||||
}
|
||||
impl AppPanelRuntime {
|
||||
pub fn new(runtime: PanelRuntime, services: Box<dyn AppPanelServices>) -> Self {
|
||||
Self {
|
||||
pub fn new(runtime: PanelRuntime, services: Box<dyn AppPanelServices>) -> PanelResult<Self> {
|
||||
runtime.require_live()?;
|
||||
if runtime.layout().layout().sections.iter().any(|section| section.location.zone() == Zone::Window) {
|
||||
return Err(error(Rule::Lifecycle, "install the app adapter before creating or restoring native placement"));
|
||||
}
|
||||
Ok(Self {
|
||||
runtime,
|
||||
services,
|
||||
native: Box::<InAppNativeAdapter>::default(),
|
||||
host: None,
|
||||
last_tick_frame: None,
|
||||
last_error: None,
|
||||
catalogue: Box::<commands::InMemoryCatalogue>::default(),
|
||||
native: Box::new(UnavailableNative),
|
||||
adapters_set: false,
|
||||
}
|
||||
})
|
||||
}
|
||||
pub fn last_error(&self) -> Option<&PanelError> {
|
||||
self.last_error.as_ref()
|
||||
@@ -39,94 +48,429 @@ impl AppPanelRuntime {
|
||||
/// Internal capability injection. Production preferences/native realization
|
||||
/// remain peer work. Installation is once-only and precedes native hosts.
|
||||
pub fn set_command_adapters(&mut self, catalogue: Box<dyn commands::LayoutCatalogue>, native: Box<dyn NativeHostAdapter>) -> PanelResult<()> {
|
||||
if self.adapters_set {
|
||||
return Err(error(Rule::Lifecycle, "application panel adapters are already installed"));
|
||||
}
|
||||
if self.runtime.layout().layout().sections.iter().any(|s| matches!(&s.location, SectionLocation::Window { .. })) {
|
||||
return Err(error(Rule::Lifecycle, "cannot replace adapters with live native hosts"));
|
||||
}
|
||||
self.set_native_adapter(native)?;
|
||||
self.catalogue = catalogue;
|
||||
self.native = native;
|
||||
self.adapters_set = true;
|
||||
Ok(())
|
||||
}
|
||||
/// Actual application boundaries refresh the current document/model context
|
||||
/// even when no frame tick ran between two sequential programmatic steps.
|
||||
fn refresh_context(&mut self, session: &Session) -> PanelResult<()> {
|
||||
self.services.refresh_read_only(session)?;
|
||||
let mut environment = self.runtime.environment().clone();
|
||||
environment.document = Some(DocumentId::new(session.document_id.clone())?);
|
||||
let services = self.services.services();
|
||||
self.runtime.set_environment(environment, services.local)?;
|
||||
self.runtime.refresh_context(services.models, services.local)
|
||||
}
|
||||
pub fn command(&mut self, session: &Session, id: &str, params: &serde_json::Value) -> PanelResult<serde_json::Value> {
|
||||
self.refresh_context(session)?;
|
||||
let registry = self.runtime.layout().registry().clone();
|
||||
let mut services = self.services.services();
|
||||
let mut sink = RuntimeActionSink { runtime: &mut self.runtime, native: self.native.as_mut(), services: &mut services };
|
||||
commands::execute(
|
||||
id,
|
||||
params,
|
||||
&mut commands::PanelCommandContext {
|
||||
sink: &mut sink,
|
||||
registry: ®istry,
|
||||
catalogue: self.catalogue.as_mut(),
|
||||
web: cfg!(target_arch = "wasm32"),
|
||||
},
|
||||
)
|
||||
if !matches!(id, "panel.list" | "layout.get")
|
||||
&& let Some(host) = &mut self.host
|
||||
{
|
||||
host.cancel_gesture();
|
||||
}
|
||||
let command = commands::parse_command(id, params)?;
|
||||
self.reconcile(session)?;
|
||||
if !matches!(&command, commands::PanelCommand::HeaderAction(_)) {
|
||||
self.refresh_metrics()?;
|
||||
self.refresh_reservations()?;
|
||||
}
|
||||
self.with_command_context(|context| commands::execute_command(command, context))
|
||||
}
|
||||
pub fn command_batch(&mut self, session: &Session, steps: &[serde_json::Value]) -> PanelResult<serde_json::Value> {
|
||||
if let Some(host) = &mut self.host {
|
||||
host.cancel_gesture();
|
||||
}
|
||||
// Unsupported intent mixtures refuse before even context lifecycle or
|
||||
// availability publication; supported calls then read current context.
|
||||
commands::preflight_batch(steps, &self.runtime.layout().layout().workspace)?;
|
||||
self.refresh_context(session)?;
|
||||
let registry = self.runtime.layout().registry().clone();
|
||||
let mut services = self.services.services();
|
||||
let mut sink = RuntimeActionSink { runtime: &mut self.runtime, native: self.native.as_mut(), services: &mut services };
|
||||
commands::execute_batch(
|
||||
steps,
|
||||
&mut commands::PanelCommandContext {
|
||||
self.reconcile(session)?;
|
||||
if !matches!(steps, [step] if step.get("command").or_else(|| step.get("id")).and_then(serde_json::Value::as_str) == Some("panel.action")) {
|
||||
self.refresh_metrics()?;
|
||||
self.refresh_reservations()?;
|
||||
}
|
||||
self.with_command_context(|context| commands::execute_batch(steps, context))
|
||||
}
|
||||
/// Commands borrow the same adapter, provider and local overlay ledger as
|
||||
/// host gestures. Forward committed focus effects without parsing JSON.
|
||||
fn with_command_context<R>(&mut self, execute: impl FnOnce(&mut commands::PanelCommandContext<'_>) -> PanelResult<R>) -> PanelResult<R> {
|
||||
let Self { runtime, services, native, catalogue, host, .. } = self;
|
||||
let registry = runtime.layout().registry().clone();
|
||||
let scope = runtime_scope(runtime);
|
||||
let mut services = services.services();
|
||||
let mut committed = None;
|
||||
let run = |host: Option<&mut WorkspacePanelHost>, services: &mut ContentServices<'_>| {
|
||||
let mut live = RuntimeActionSink { runtime: &mut *runtime, native: native.as_mut(), services };
|
||||
let mut admitted = AdmittedActionSink { live: &mut live, host, proposal: std::cell::RefCell::new(None) };
|
||||
let mut sink = CommandActionSink { live: &mut admitted, committed: &mut committed };
|
||||
execute(&mut commands::PanelCommandContext {
|
||||
sink: &mut sink,
|
||||
registry: ®istry,
|
||||
catalogue: self.catalogue.as_mut(),
|
||||
catalogue: catalogue.as_mut(),
|
||||
web: cfg!(target_arch = "wasm32"),
|
||||
},
|
||||
)
|
||||
})
|
||||
};
|
||||
let result = if let Some(host) = host.as_mut() {
|
||||
host.with_command_services(&scope, &mut services, |host, services| run(Some(host), services))
|
||||
} else {
|
||||
run(None, &mut services)
|
||||
};
|
||||
if let Some(host) = host {
|
||||
host.reconcile_scope(runtime);
|
||||
if let Some(reply) = committed {
|
||||
host.note_reply(&reply);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
/// All forwarding borrows the exact provider injected at enablement.
|
||||
fn with_services<R>(&mut self, use_services: impl FnOnce(&mut PanelRuntime, &mut ContentServices<'_>) -> PanelResult<R>) -> PanelResult<R> {
|
||||
let mut services = self.services.services();
|
||||
use_services(&mut self.runtime, &mut services)
|
||||
/// Inspection borrows the exact injected provider. A read-only runtime keeps
|
||||
/// callers from bypassing the app's single stored native resource owner.
|
||||
pub fn with_services<R>(&mut self, use_services: impl FnOnce(&PanelRuntime, &mut ContentServices<'_>) -> PanelResult<R>) -> PanelResult<R> {
|
||||
self.with_adapters(|runtime, _native, services| use_services(runtime, services))
|
||||
}
|
||||
fn with_adapters<R>(
|
||||
&mut self,
|
||||
use_services: impl FnOnce(&mut PanelRuntime, &mut dyn NativeHostAdapter, &mut ContentServices<'_>) -> PanelResult<R>,
|
||||
) -> PanelResult<R> {
|
||||
let Self { runtime, services, native, host, .. } = self;
|
||||
let scope = runtime_scope(runtime);
|
||||
let mut services = services.services();
|
||||
if let Some(host) = host {
|
||||
host.with_local_services(&scope, &mut services, |services| use_services(runtime, native.as_mut(), services))
|
||||
} else {
|
||||
use_services(runtime, native.as_mut(), &mut services)
|
||||
}
|
||||
}
|
||||
pub fn dispatch(&mut self, session: &Session, action: LayoutAction) -> PanelResult<LayoutReply> {
|
||||
self.refresh_context(session)?;
|
||||
let mut services = self.services.services();
|
||||
RuntimeActionSink { runtime: &mut self.runtime, native: self.native.as_mut(), services: &mut services }.dispatch(action)
|
||||
if let Some(host) = &mut self.host {
|
||||
host.cancel_gesture();
|
||||
}
|
||||
self.reconcile(session)?;
|
||||
if !standalone_header_action(&action) {
|
||||
self.refresh_metrics()?;
|
||||
self.refresh_reservations()?;
|
||||
}
|
||||
self.with_command_context(|context| commands::execute_layout_action(action, context))
|
||||
}
|
||||
pub fn mount(&mut self, resolved: &ResolvedLayout, host: &mut dyn PanelHost) -> PanelResult<()> {
|
||||
self.with_services(|runtime, services| runtime.mount(resolved, host, services))
|
||||
/// All host actions use one retained native adapter and the injected provider.
|
||||
pub fn dispatch_host(&mut self, session: &Session, action: LayoutAction) -> PanelResult<LayoutReply> {
|
||||
self.dispatch(session, action)
|
||||
}
|
||||
/// Install before native placement exists. Replacing an adapter while it owns
|
||||
/// resources would orphan those resources and is rejected atomically.
|
||||
pub fn set_native_adapter(&mut self, native: Box<dyn NativeHostAdapter>) -> PanelResult<()> {
|
||||
self.runtime.require_live()?;
|
||||
if self.adapters_set {
|
||||
return Err(error(Rule::Lifecycle, "application panel adapters are already installed"));
|
||||
}
|
||||
if self.runtime.layout().layout().sections.iter().any(|section| section.location.zone() == Zone::Window) {
|
||||
return Err(error(Rule::Lifecycle, "redock native hosts before replacing their adapter"));
|
||||
}
|
||||
let capabilities = native.capabilities();
|
||||
if capabilities.max_native_hosts > MAX_SECTIONS || !capabilities.native_windows && capabilities.max_native_hosts != 0 {
|
||||
return Err(error(Rule::Capability, "invalid native adapter capacity"));
|
||||
}
|
||||
self.native = native;
|
||||
Ok(())
|
||||
}
|
||||
pub fn native_capabilities(&self) -> HostCapabilities {
|
||||
self.native.capabilities()
|
||||
}
|
||||
pub fn host(&self) -> Option<&WorkspacePanelHost> {
|
||||
self.host.as_ref()
|
||||
}
|
||||
pub fn enable_host(&mut self, options: HostOptions) -> PanelResult<()> {
|
||||
self.runtime.require_live()?;
|
||||
if self.host.is_some() {
|
||||
return Err(error(Rule::Lifecycle, "universal panel host already enabled"));
|
||||
}
|
||||
if !self.native.capabilities().native_windows
|
||||
&& self.runtime.layout().layout().sections.iter().any(|section| section.location.zone() == Zone::Window)
|
||||
{
|
||||
return Err(error(Rule::Capability, "redock existing native placements through their adapter before enabling the in-app host"));
|
||||
}
|
||||
self.host = Some(WorkspacePanelHost::new(options)?);
|
||||
Ok(())
|
||||
}
|
||||
pub fn disable_host(&mut self) -> PanelResult<()> {
|
||||
if self.host.is_some() {
|
||||
self.with_adapters(|runtime, _native, services| runtime.mount_in_app(&ResolvedLayout::default(), &mut EmptyPanelHost, services))?;
|
||||
}
|
||||
self.host = None;
|
||||
Ok(())
|
||||
}
|
||||
/// Hiding the application workspace is an input/presentation transition,
|
||||
/// independent of layout revision. Retained owners keep their live services.
|
||||
fn hide_in_app(&mut self) -> PanelResult<()> {
|
||||
if let Some(host) = &mut self.host {
|
||||
host.invalidate_context();
|
||||
}
|
||||
self.with_adapters(|runtime, _native, services| runtime.mount_in_app(&ResolvedLayout::default(), &mut EmptyPanelHost, services))
|
||||
}
|
||||
pub fn prepare_host(&mut self, session: &Session, capacity: LogicalRect) -> PanelResult<()> {
|
||||
self.prepare_host_in_domain(session, capacity, capacity, &[])
|
||||
}
|
||||
|
||||
pub fn prepare_host_in_domain(
|
||||
&mut self,
|
||||
session: &Session,
|
||||
render_domain: LogicalRect,
|
||||
capacity: LogicalRect,
|
||||
chrome: &[LogicalRect],
|
||||
) -> PanelResult<()> {
|
||||
self.reconcile(session)?;
|
||||
self.refresh_metrics()?;
|
||||
if let Some(host) = &mut self.host {
|
||||
host.capture_reservations(&self.runtime, self.catalogue.as_ref())?;
|
||||
host.note_native_capabilities(self.native.capabilities());
|
||||
}
|
||||
let result = self.host.as_mut().ok_or_else(|| error(Rule::Lifecycle, "universal panel host disabled"))?.prepare_in_domain(
|
||||
&self.runtime,
|
||||
render_domain,
|
||||
capacity,
|
||||
chrome,
|
||||
);
|
||||
if result.is_err() {
|
||||
self.with_adapters(|runtime, _native, services| runtime.mount_in_app(&ResolvedLayout::default(), &mut EmptyPanelHost, services))?;
|
||||
}
|
||||
result
|
||||
}
|
||||
pub fn show_host(&mut self, session: &Session, ui: &mut egui::Ui) -> PanelResult<()> {
|
||||
self.show_host_impl(session, ui, false)
|
||||
}
|
||||
pub fn show_host_deferred(&mut self, session: &Session, ui: &mut egui::Ui) -> PanelResult<()> {
|
||||
self.show_host_impl(session, ui, true)
|
||||
}
|
||||
fn show_host_impl(&mut self, session: &Session, ui: &mut egui::Ui, deferred: bool) -> PanelResult<()> {
|
||||
let geometry = self.host.as_ref().and_then(WorkspacePanelHost::prepared_geometry);
|
||||
self.reconcile(session)?;
|
||||
self.refresh_metrics()?;
|
||||
if let Some(host) = &mut self.host
|
||||
&& host.frame().is_none()
|
||||
&& let Some((domain, capacity, chrome)) = geometry
|
||||
{
|
||||
host.prepare_in_domain(&self.runtime, domain, capacity, &chrome)?;
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
let mut services = self.services.services();
|
||||
let host = self.host.as_mut().ok_or_else(|| error(Rule::Lifecycle, "universal panel host disabled"))?;
|
||||
if deferred {
|
||||
host.show_deferred(ui, &mut self.runtime, self.native.as_mut(), &mut services)
|
||||
} else {
|
||||
host.show(ui, &mut self.runtime, self.native.as_mut(), &mut services, self.catalogue.as_mut())
|
||||
}
|
||||
}
|
||||
/// Finish after every window/modal has registered its current layer. Refresh
|
||||
/// current Session again before dispatch, without a background update.
|
||||
pub fn finish_host(&mut self, session: &Session, ui: &mut egui::Ui) -> PanelResult<()> {
|
||||
if !self.host.as_ref().is_some_and(WorkspacePanelHost::has_pending) {
|
||||
return Ok(());
|
||||
}
|
||||
self.reconcile(session)?;
|
||||
self.refresh_metrics()?;
|
||||
let mut services = self.services.services();
|
||||
if let Some(host) = &mut self.host {
|
||||
host.finish(ui, &mut self.runtime, self.native.as_mut(), &mut services, self.catalogue.as_mut())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
/// Complete root/in-app cohort only. Native peers always use mount_native,
|
||||
/// even while the shared root renderer is disabled.
|
||||
pub fn mount(&mut self, session: &Session, resolved: &ResolvedLayout, host: &mut dyn PanelHost) -> PanelResult<()> {
|
||||
self.reconcile(session)?;
|
||||
if self.host.is_some() {
|
||||
return Err(error(Rule::Lifecycle, "universal host owns the complete in-app presentation frame"));
|
||||
}
|
||||
self.with_adapters(|runtime, _native, services| runtime.mount_in_app(resolved, host, services))
|
||||
}
|
||||
pub fn mount_native(&mut self, session: &Session, native_host: &HostId, resolved: &ResolvedLayout, host: &mut dyn PanelHost) -> PanelResult<()> {
|
||||
self.reconcile(session)?;
|
||||
self.with_adapters(|runtime, _native, services| runtime.mount_native(native_host, resolved, host, services))
|
||||
}
|
||||
pub fn content_action(&mut self, session: &Session, instance: &InstanceId, action: &ControlId) -> PanelResult<()> {
|
||||
self.refresh_context(session)?;
|
||||
self.with_services(|runtime, services| runtime.content_action(instance, action, services))
|
||||
self.reconcile(session)?;
|
||||
self.with_adapters(|runtime, _native, services| runtime.content_action(instance, action, services))
|
||||
}
|
||||
fn refresh_reservations(&mut self) -> PanelResult<()> {
|
||||
if let Some(host) = &mut self.host {
|
||||
host.capture_reservations(&self.runtime, self.catalogue.as_ref())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn refresh_metrics(&mut self) -> PanelResult<()> {
|
||||
if let Some(host) = &mut self.host {
|
||||
let services = self.services.services();
|
||||
if let Err(reason) = host.capture_metrics(&self.runtime, services.models) {
|
||||
host.invalidate_context();
|
||||
self.runtime.suspend_presentations(services.local);
|
||||
return Err(reason);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Current Session is refreshed at every presentation/action boundary, even
|
||||
/// after this egui frame's one background tick. No controller update runs.
|
||||
pub fn reconcile(&mut self, session: &Session) -> PanelResult<()> {
|
||||
let before = self.runtime.environment().clone();
|
||||
let revision = self.runtime.layout().inspect().revision;
|
||||
let result = (|| {
|
||||
self.services.refresh_read_only(session)?;
|
||||
let mut environment = self.runtime.environment().clone();
|
||||
environment.document = Some(DocumentId::new(session.document_id.clone())?);
|
||||
self.with_adapters(|runtime, _native, services| runtime.reconcile_context(environment, services))
|
||||
})();
|
||||
match &result {
|
||||
Ok(()) => {
|
||||
if self.runtime.update_errors().is_empty() {
|
||||
self.last_error = None;
|
||||
}
|
||||
if (self.runtime.environment() != &before || self.runtime.layout().inspect().revision != revision)
|
||||
&& let Some(host) = &mut self.host
|
||||
{
|
||||
host.invalidate_context();
|
||||
host.reconcile_scope(&self.runtime);
|
||||
}
|
||||
}
|
||||
Err(reason) => {
|
||||
self.last_error = Some(reason.clone());
|
||||
if let Some(host) = &mut self.host {
|
||||
host.invalidate_context();
|
||||
}
|
||||
let services = self.services.services();
|
||||
self.runtime.suspend_presentations(services.local);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
pub fn tick(&mut self, session: &Session) -> PanelResult<()> {
|
||||
let refresh = self.services.refresh_read_only(session);
|
||||
let mut environment = self.runtime.environment().clone();
|
||||
environment.document = Some(DocumentId::new(session.document_id.clone())?);
|
||||
let mut services = self.services.services();
|
||||
self.runtime.set_environment(environment, services.local)?;
|
||||
let update = self.runtime.update(&mut services);
|
||||
refresh.and(update)
|
||||
let result = match self.services.refresh_read_only(session) {
|
||||
Ok(()) => (|| {
|
||||
let mut environment = self.runtime.environment().clone();
|
||||
environment.document = Some(DocumentId::new(session.document_id.clone())?);
|
||||
self.with_adapters(|runtime, _native, services| {
|
||||
runtime.set_environment(environment, services.local)?;
|
||||
runtime.update(services)
|
||||
})
|
||||
})(),
|
||||
Err(reason) => {
|
||||
// The provider still represents the previous context. Never
|
||||
// admit the incoming Session owner against those stale models.
|
||||
if let Some(host) = &mut self.host {
|
||||
host.invalidate_context();
|
||||
}
|
||||
// Retained background owners still receive this tick's one
|
||||
// service attempt. Bounded failures remain in update_errors;
|
||||
// the caller receives the original refresh failure.
|
||||
let _update = self.with_adapters(|runtime, _native, services| runtime.update(services));
|
||||
let services = self.services.services();
|
||||
self.runtime.suspend_presentations(services.local);
|
||||
Err(reason)
|
||||
}
|
||||
};
|
||||
self.last_error = result.as_ref().err().cloned();
|
||||
result
|
||||
}
|
||||
/// Explicit teardown preflights all owners before any controller is destroyed.
|
||||
pub fn shutdown(&mut self) -> PanelResult<()> {
|
||||
if self.runtime.layout().layout().sections.iter().any(|section| matches!(§ion.location, SectionLocation::Window { .. })) {
|
||||
return Err(error(Rule::Lifecycle, "redock native panels before disabling their application adapter"));
|
||||
self.with_adapters(|runtime, native, services| runtime.shutdown_with_native(native, services.local))
|
||||
}
|
||||
}
|
||||
|
||||
/// Observe typed replies from the authoritative command sink, including repeated
|
||||
/// Focus requests whose persistent focused instance has not changed.
|
||||
struct CommandActionSink<'a> {
|
||||
live: &'a mut dyn ActionSink,
|
||||
committed: &'a mut Option<LayoutReply>,
|
||||
}
|
||||
|
||||
/// The app has a real captured placement environment. Structural commands may
|
||||
/// not bypass its allocator merely because they arrived over a control channel.
|
||||
pub(super) struct AdmittedActionSink<'a, 'runtime, 'services> {
|
||||
pub(super) live: &'a mut RuntimeActionSink<'runtime, 'services>,
|
||||
pub(super) host: Option<&'a mut WorkspacePanelHost>,
|
||||
pub(super) proposal: std::cell::RefCell<Option<super::runtime::RuntimeHostProposal>>,
|
||||
}
|
||||
impl AdmittedActionSink<'_, '_, '_> {
|
||||
fn project_owned(&self, action: LayoutAction, context: Option<&LayoutPreparationContext>) -> PanelResult<Layout> {
|
||||
if standalone_header_action(&action) {
|
||||
return match context {
|
||||
Some(context) => self.live.project_in_context(action, context),
|
||||
None => self.live.project(action),
|
||||
};
|
||||
}
|
||||
let services = self.services.services();
|
||||
self.runtime.shutdown(services.local)
|
||||
let host = self.host.as_ref().ok_or_else(|| error(Rule::Availability, "panel host environment is unavailable"))?;
|
||||
let reference = host.command_reference(self.live.runtime)?;
|
||||
let mut cached = self.proposal.try_borrow_mut().map_err(|_| error(Rule::Lifecycle, "panel proposal already borrowed"))?;
|
||||
if let Some(proposal) = cached.as_ref().filter(|proposal| proposal.action() == &action) {
|
||||
let freshness = (|| {
|
||||
if let Some(context) = context {
|
||||
proposal.validate_preparation_context(context)?;
|
||||
}
|
||||
proposal.validate(self.live.runtime, &reference, self.live.services.models)
|
||||
})();
|
||||
if let Err(reason) = freshness {
|
||||
cached.take();
|
||||
return Err(reason);
|
||||
}
|
||||
return Ok(proposal.layout().clone());
|
||||
}
|
||||
let proposal = match cached.take() {
|
||||
Some(previous) => self.live.runtime.revise_host_proposal(previous, reference, action, context, self.live.services.models)?,
|
||||
None => match context {
|
||||
Some(context) => self.live.runtime.prepare_host_proposal_in_context(reference, action, context, self.live.services.models)?,
|
||||
None => self.live.runtime.prepare_host_proposal(reference, action, self.live.services.models)?,
|
||||
},
|
||||
};
|
||||
let layout = proposal.layout().clone();
|
||||
*cached = Some(proposal);
|
||||
Ok(layout)
|
||||
}
|
||||
fn dispatch_owned(&mut self, action: LayoutAction, context: Option<&LayoutPreparationContext>) -> PanelResult<LayoutReply> {
|
||||
if action == LayoutAction::Inspect {
|
||||
return Ok(self.inspect());
|
||||
}
|
||||
if standalone_header_action(&action) {
|
||||
return match context {
|
||||
Some(context) => self.live.dispatch_in_context(action, context),
|
||||
None => self.live.dispatch(action),
|
||||
};
|
||||
}
|
||||
self.project_owned(action.clone(), context)?;
|
||||
let proposal = self.proposal.get_mut().take().ok_or_else(|| error(Rule::Lifecycle, "panel proposal missing"))?;
|
||||
if proposal.action() != &action {
|
||||
return Err(error(Rule::Revision, "panel dispatch intent changed"));
|
||||
}
|
||||
let reply = self.live.runtime.commit_host_proposal(proposal, self.live.native, self.live.services)?;
|
||||
Ok(super::runtime::normalize_native_reply(reply, &self.live.native.capabilities()))
|
||||
}
|
||||
}
|
||||
impl ActionSink for AdmittedActionSink<'_, '_, '_> {
|
||||
fn project(&self, action: LayoutAction) -> PanelResult<Layout> {
|
||||
self.project_owned(action, None)
|
||||
}
|
||||
fn project_in_context(&self, action: LayoutAction, context: &LayoutPreparationContext) -> PanelResult<Layout> {
|
||||
self.project_owned(action, Some(context))
|
||||
}
|
||||
fn inspect(&self) -> LayoutReply {
|
||||
self.live.inspect()
|
||||
}
|
||||
fn dispatch(&mut self, action: LayoutAction) -> PanelResult<LayoutReply> {
|
||||
self.dispatch_owned(action, None)
|
||||
}
|
||||
fn dispatch_in_context(&mut self, action: LayoutAction, context: &LayoutPreparationContext) -> PanelResult<LayoutReply> {
|
||||
self.dispatch_owned(action, Some(context))
|
||||
}
|
||||
}
|
||||
impl ActionSink for CommandActionSink<'_> {
|
||||
fn project_in_context(&self, action: LayoutAction, context: &LayoutPreparationContext) -> PanelResult<Layout> {
|
||||
self.live.project_in_context(action, context)
|
||||
}
|
||||
fn dispatch_in_context(&mut self, action: LayoutAction, context: &LayoutPreparationContext) -> PanelResult<LayoutReply> {
|
||||
let reply = self.live.dispatch_in_context(action, context)?;
|
||||
*self.committed = Some(reply.clone());
|
||||
Ok(reply)
|
||||
}
|
||||
fn project(&self, action: LayoutAction) -> PanelResult<Layout> {
|
||||
self.live.project(action)
|
||||
}
|
||||
fn inspect(&self) -> LayoutReply {
|
||||
self.live.inspect()
|
||||
}
|
||||
fn dispatch(&mut self, action: LayoutAction) -> PanelResult<LayoutReply> {
|
||||
let reply = self.live.dispatch(action)?;
|
||||
*self.committed = Some(reply.clone());
|
||||
Ok(reply)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -148,12 +492,27 @@ impl crate::SolveApp {
|
||||
.ok_or_else(|| error(Rule::Capability, "application panel runtime is not enabled"))?
|
||||
.command_batch(&self.session, steps)
|
||||
}
|
||||
pub fn enable_universal_panel_host(&mut self, options: HostOptions) -> PanelResult<()> {
|
||||
self.panel_runtime.as_mut().ok_or_else(|| error(Rule::Lifecycle, "enable a panel runtime before its host"))?.enable_host(options)
|
||||
}
|
||||
pub fn disable_universal_panel_host(&mut self) -> PanelResult<()> {
|
||||
if let Some(integration) = &mut self.panel_runtime {
|
||||
integration.disable_host()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn universal_panel_host_enabled(&self) -> bool {
|
||||
self.panel_runtime.as_ref().is_some_and(|integration| integration.host.is_some())
|
||||
}
|
||||
pub fn universal_panel_frame(&self) -> Option<&HostFrame> {
|
||||
self.panel_runtime.as_ref()?.host.as_ref()?.frame()
|
||||
}
|
||||
/// Internal opt-in only: no preference, control method, command or default change.
|
||||
pub fn enable_panel_runtime(&mut self, runtime: PanelRuntime, services: Box<dyn AppPanelServices>) -> PanelResult<()> {
|
||||
if self.panel_runtime.is_some() {
|
||||
return Err(error(Rule::Lifecycle, "panel runtime already enabled"));
|
||||
}
|
||||
let mut integration = AppPanelRuntime::new(runtime, services);
|
||||
let mut integration = AppPanelRuntime::new(runtime, services)?;
|
||||
integration.tick(&self.session)?;
|
||||
self.panel_runtime = Some(integration);
|
||||
Ok(())
|
||||
@@ -164,11 +523,23 @@ impl crate::SolveApp {
|
||||
pub fn panel_runtime_mut(&mut self) -> Option<&mut AppPanelRuntime> {
|
||||
self.panel_runtime.as_mut()
|
||||
}
|
||||
pub fn set_panel_native_adapter(&mut self, native: Box<dyn NativeHostAdapter>) -> PanelResult<()> {
|
||||
self.panel_runtime.as_mut().ok_or_else(|| error(Rule::Lifecycle, "panel runtime disabled"))?.set_native_adapter(native)
|
||||
}
|
||||
pub fn dispatch_panel_layout(&mut self, action: LayoutAction) -> PanelResult<LayoutReply> {
|
||||
self.panel_runtime.as_mut().ok_or_else(|| error(Rule::Lifecycle, "panel runtime disabled"))?.dispatch(&self.session, action)
|
||||
}
|
||||
pub fn mount_panels(&mut self, resolved: &ResolvedLayout, host: &mut dyn PanelHost) -> PanelResult<()> {
|
||||
self.panel_runtime.as_mut().ok_or_else(|| error(Rule::Lifecycle, "panel runtime disabled"))?.mount(resolved, host)
|
||||
self.panel_runtime.as_mut().ok_or_else(|| error(Rule::Lifecycle, "panel runtime disabled"))?.mount(&self.session, resolved, host)
|
||||
}
|
||||
/// A complete set for one native host; empty unmounts just that viewport.
|
||||
pub fn mount_native_panels(&mut self, native_host: &HostId, resolved: &ResolvedLayout, host: &mut dyn PanelHost) -> PanelResult<()> {
|
||||
self.panel_runtime.as_mut().ok_or_else(|| error(Rule::Lifecycle, "panel runtime disabled"))?.mount_native(
|
||||
&self.session,
|
||||
native_host,
|
||||
resolved,
|
||||
host,
|
||||
)
|
||||
}
|
||||
pub fn panel_content_action(&mut self, instance: &InstanceId, action: &ControlId) -> PanelResult<()> {
|
||||
self.panel_runtime.as_mut().ok_or_else(|| error(Rule::Lifecycle, "panel runtime disabled"))?.content_action(&self.session, instance, action)
|
||||
@@ -185,27 +556,172 @@ impl crate::SolveApp {
|
||||
}
|
||||
}
|
||||
|
||||
/// No platform window is claimed without an injected native implementation.
|
||||
struct UnavailableNative;
|
||||
impl NativeHostAdapter for UnavailableNative {
|
||||
fn capabilities(&self) -> HostCapabilities {
|
||||
HostCapabilities::default()
|
||||
}
|
||||
fn prepare(&self, effects: &[HostEffect]) -> PanelResult<()> {
|
||||
if effects
|
||||
.iter()
|
||||
.any(|effect| matches!(effect, HostEffect::CreateNative { .. } | HostEffect::RebindNative { .. } | HostEffect::ReleaseNative { .. }))
|
||||
{
|
||||
return Err(error(Rule::Capability, "native adapter not injected"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn commit(&mut self, _effects: &[HostEffect]) {}
|
||||
}
|
||||
|
||||
pub(crate) fn tick_app(app: &mut crate::SolveApp) {
|
||||
pub(crate) fn tick_app(app: &mut crate::SolveApp, ctx: &egui::Context) {
|
||||
if let Some(integration) = &mut app.panel_runtime {
|
||||
let frame = ctx.cumulative_frame_nr();
|
||||
if integration.last_tick_frame == Some(frame) {
|
||||
return;
|
||||
}
|
||||
integration.last_tick_frame = Some(frame);
|
||||
// Errors remain inspectable without inventing untranslated production UI.
|
||||
integration.last_error = integration.tick(&app.session).err();
|
||||
}
|
||||
}
|
||||
|
||||
/// Called on the actual hidden transition, including a control-channel Home
|
||||
/// open/close interval between paints. No tick, destruction or owner rebind.
|
||||
pub(crate) fn hide_app_host(app: &mut crate::SolveApp) {
|
||||
if let Some(integration) = &mut app.panel_runtime
|
||||
&& let Err(reason) = integration.hide_in_app()
|
||||
{
|
||||
integration.last_error = Some(reason);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn reserve_host_input(app: &mut crate::SolveApp, ctx: &egui::Context) {
|
||||
let Some(integration) = &mut app.panel_runtime else {
|
||||
return;
|
||||
};
|
||||
let Some(host) = &mut integration.host else {
|
||||
return;
|
||||
};
|
||||
if host.wants_escape(&integration.runtime) && crate::ui_kit::Container::reserve_host_escape(ctx) {
|
||||
host.request_escape();
|
||||
app.esc_handled = true;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn finish_app_host(app: &mut crate::SolveApp, ui: &mut egui::Ui) {
|
||||
if let Some(integration) = &mut app.panel_runtime
|
||||
&& let Err(reason) = integration.finish_host(&app.session, ui)
|
||||
{
|
||||
integration.last_error = Some(reason);
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::SolveApp {
|
||||
/// Alternate placement only. The caller keeps the app bar, ribbon, existing
|
||||
/// viewport/navigation and late feature/system overlays in their normal flow.
|
||||
pub(crate) fn universal_workspace_ui(&mut self, ui: &mut egui::Ui) {
|
||||
// Capture before either ribbon or bottom chrome consumes root layout.
|
||||
// Rendering and picking always share this full domain below the app bar.
|
||||
let render_domain = ui.available_rect_before_wrap();
|
||||
self.viewport.host_confirm = None;
|
||||
crate::ui_kit::Container::begin_host_windows(ui.ctx());
|
||||
self.viewport.host_windows = Some(Vec::new());
|
||||
if self.session.active_sketch.is_none() {
|
||||
self.viewport.palette_rect = None;
|
||||
}
|
||||
// Clear stale Browser-owned metadata; the retained independent
|
||||
// redefine/feature editor publishes its actual paint later in this pass.
|
||||
if self.dialog.is_none() {
|
||||
self.viewport.dialog_rect = None;
|
||||
}
|
||||
// Unoccupied dock capacity and ribbon spacing are application backdrop,
|
||||
// not panel paint/input regions. Cover the native GPU clear through the
|
||||
// shared viewport surface without changing any declared panel geometry.
|
||||
let backdrop = crate::ui_kit::Container::new(ui.ctx(), crate::ui_kit::Surface::Viewport);
|
||||
crate::ui_kit::Container::paint_frame(ui.painter(), backdrop.edge_frame(crate::theme::Tokens::get().panel), ui.available_rect_before_wrap());
|
||||
crate::timeline::follow_view_pick(self);
|
||||
crate::render_ui::focus_shortcut(self, ui);
|
||||
crate::dialogs::sync_feature_edit(self);
|
||||
if cfg!(not(target_arch = "wasm32")) && self.preferences.agent_chat_popped {
|
||||
// Keep the previous embedded-window rect for hover shortcuts.
|
||||
// `show` owns geometry/lifecycle and also polls in this path.
|
||||
crate::agent_chat::show(self, ui);
|
||||
} else {
|
||||
// The root Assistant panel is suppressed. Forget only presentation
|
||||
// geometry and placement, so a later pop uses the saved window place.
|
||||
self.agent_chat.panel_rect = None;
|
||||
self.agent_chat.drop_rect = None;
|
||||
self.agent_chat.dock_space = None;
|
||||
self.agent_chat.window_placed = false;
|
||||
crate::agent_chat::poll(self, ui.ctx());
|
||||
}
|
||||
self.shell.browser = None;
|
||||
self.shell.browser_hidden = false;
|
||||
self.shell.history = None;
|
||||
self.shell.panels.clear();
|
||||
self.shell.workspace_panels.clear();
|
||||
self.shell.dialog_column = None;
|
||||
self.shell.left_space = None;
|
||||
self.shell.history_dock_space = None;
|
||||
self.shell.history_folding = None;
|
||||
self.shell.history_fold_motion = None;
|
||||
crate::theme::TabAccent::publish(self, ui.ctx());
|
||||
crate::browser::publish_row_prefs(self, ui.ctx());
|
||||
let mut placement = render_domain;
|
||||
self.shell.status_bar = if crate::status_bar::shown(self) {
|
||||
let height = crate::status_bar::HEIGHT.min(placement.height().max(0.0));
|
||||
let bar = egui::Rect::from_min_max(egui::pos2(placement.left(), placement.bottom() - height), placement.max);
|
||||
placement.max.y = bar.top();
|
||||
Some(bar)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if !self.embedded {
|
||||
let cards = crate::toolbar::shell_cards(self, placement);
|
||||
self.shell.cards = vec![cards.workspace, cards.ribbon];
|
||||
placement.min.y = cards.bottom.min(placement.bottom()).max(placement.top());
|
||||
} else {
|
||||
self.shell.cards.clear();
|
||||
}
|
||||
let gap = crate::ui_kit::Container::new(ui.ctx(), crate::ui_kit::Surface::Panel).gap();
|
||||
placement.min.x += gap.min(placement.width() / 2.0);
|
||||
placement.max.x -= gap.min(placement.width());
|
||||
placement.max.y -= gap.min(placement.height());
|
||||
if self.embedded {
|
||||
placement.min.y += gap.min(placement.height());
|
||||
}
|
||||
let chrome: Vec<_> = self
|
||||
.shell
|
||||
.cards
|
||||
.iter()
|
||||
.copied()
|
||||
.chain(self.shell.status_bar)
|
||||
.map(|bounds| bounds.intersect(render_domain))
|
||||
.filter(|bounds| bounds.is_positive() && bounds.is_finite())
|
||||
.map(logical_rect)
|
||||
.collect();
|
||||
let prepared = match &mut self.panel_runtime {
|
||||
Some(integration) => {
|
||||
let result = (|| {
|
||||
if let Some(host) = &mut integration.host {
|
||||
host.note_egui_context(ui.ctx());
|
||||
host.set_gap(gap)?;
|
||||
}
|
||||
integration.prepare_host_in_domain(&self.session, logical_rect(render_domain), logical_rect(placement), &chrome)
|
||||
})();
|
||||
if let Err(reason) = &result {
|
||||
integration.last_error = Some(reason.clone());
|
||||
}
|
||||
result.is_ok()
|
||||
}
|
||||
None => false,
|
||||
};
|
||||
self.shell.content = Some(render_domain);
|
||||
if render_domain.is_positive() && render_domain.is_finite() {
|
||||
crate::preview::update(self, ui.ctx());
|
||||
let mut scene = ui.new_child(egui::UiBuilder::new().id_salt("universal_panel_viewport").max_rect(render_domain));
|
||||
scene.set_clip_rect(scene.clip_rect().intersect(render_domain));
|
||||
self.show_workspace(&mut scene);
|
||||
}
|
||||
// Chrome paints and receives input above the full-domain scene. Its
|
||||
// measured rectangles affect usable space, never the camera projection.
|
||||
crate::status_bar::show(self, ui);
|
||||
if !self.embedded {
|
||||
crate::toolbar::toolbar(self, ui);
|
||||
}
|
||||
crate::ui_kit::Container::new(ui.ctx(), crate::ui_kit::Surface::Viewport)
|
||||
.central()
|
||||
.frame(crate::ui_kit::Container::new(ui.ctx(), crate::ui_kit::Surface::Viewport).edge_frame(egui::Color32::TRANSPARENT))
|
||||
.show(ui, |ui| {
|
||||
if prepared
|
||||
&& let Some(integration) = &mut self.panel_runtime
|
||||
&& let Err(reason) = integration.show_host_deferred(&self.session, ui)
|
||||
{
|
||||
integration.last_error = Some(reason);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ pub struct FixtureState {
|
||||
pub reopens: u64,
|
||||
pub applies: u64,
|
||||
pub finishes: u64,
|
||||
pub pulses: u64,
|
||||
pub reparents: u64,
|
||||
pub destroys: u64,
|
||||
pub transaction_live: bool,
|
||||
@@ -94,7 +95,7 @@ impl PanelController for FixtureController {
|
||||
let summary = self.state.try_borrow().ok().map(|s| (s.updates, s.transaction_live));
|
||||
PanelPresentation {
|
||||
title: format!("Specimen {}", self.instance.0),
|
||||
icon: "panel".into(),
|
||||
icon: "list".into(),
|
||||
status: summary.map(|(updates, live)| format!("updates={updates}; transaction={live}")),
|
||||
attention: self.editor,
|
||||
actions: if self.editor {
|
||||
@@ -435,10 +436,10 @@ impl PanelHost for FakePanelHost {
|
||||
context.validate()?;
|
||||
let mut failure = None;
|
||||
let ctx = self.context.clone();
|
||||
let _output = ctx.run_ui(egui::RawInput::default(), |root_ui| {
|
||||
let mut output = ctx.run_ui(egui::RawInput::default(), |root_ui| {
|
||||
crate::ui_kit::Container::new(root_ui.ctx(), crate::ui_kit::Surface::Viewport).central().show(root_ui, |ui| {
|
||||
for slot in [ContentSlot::Header, ContentSlot::Body, ContentSlot::Footer] {
|
||||
if failure.is_some() {
|
||||
if failure.is_some() || geometry.body.is_none() {
|
||||
break;
|
||||
}
|
||||
if let Err(reason) = content.render(slot, ui, context, services) {
|
||||
@@ -448,6 +449,7 @@ impl PanelHost for FakePanelHost {
|
||||
}
|
||||
});
|
||||
});
|
||||
output.textures_delta.clear();
|
||||
if let Some(reason) = failure {
|
||||
return Err(reason);
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ pub struct PanelContext {
|
||||
pub viewport: ViewportId,
|
||||
pub native_host: Option<HostId>,
|
||||
pub outer: LogicalRect,
|
||||
pub usable_body: LogicalRect,
|
||||
pub usable_body: Option<LogicalRect>,
|
||||
pub flow: Flow,
|
||||
pub size_class: SizeClass,
|
||||
pub focused: bool,
|
||||
@@ -25,9 +25,11 @@ impl PanelContext {
|
||||
self.owner.validate()?;
|
||||
LocalScope { workspace: self.workspace.clone(), document: self.document.clone(), viewport: self.viewport.clone() }.validate()?;
|
||||
self.outer.validate()?;
|
||||
self.usable_body.validate()?;
|
||||
if !self.outer.contains_rect(self.usable_body) {
|
||||
return Err(error(Rule::Bounds, "presentation body outside host"));
|
||||
if let Some(body) = self.usable_body {
|
||||
body.validate()?;
|
||||
if !self.outer.contains_rect(body) {
|
||||
return Err(error(Rule::Bounds, "presentation body outside host"));
|
||||
}
|
||||
}
|
||||
if let Some(host) = &self.native_host {
|
||||
valid_id(&host.0)?;
|
||||
@@ -138,6 +140,11 @@ impl LocalRequest {
|
||||
/// host-local focus/overlays but retains the content controller and its owner.
|
||||
pub trait PanelLocalServices {
|
||||
fn request(&mut self, scope: &LocalScope, request: LocalRequest) -> PanelResult<()>;
|
||||
/// Optional UI-only provenance for an actual overlay Area. Existing local
|
||||
/// providers receive the same typed request; no layer enters saved state.
|
||||
fn request_overlay_layer(&mut self, scope: &LocalScope, instance: &InstanceId, region: InputRegion, _layer: egui::LayerId) -> PanelResult<()> {
|
||||
self.request(scope, LocalRequest::Overlay { instance: instance.clone(), region })
|
||||
}
|
||||
fn release(&mut self, scope: &LocalScope, instance: &InstanceId);
|
||||
}
|
||||
|
||||
@@ -186,6 +193,8 @@ pub enum ContentSlot {
|
||||
Header,
|
||||
Body,
|
||||
Footer,
|
||||
/// One total short-wide row, sharing its height with the host controls.
|
||||
Inline,
|
||||
}
|
||||
|
||||
/// Shared host adapter seam. Geometry is resolved by the host; content chooses
|
||||
@@ -210,6 +219,26 @@ pub trait NativeHostAdapter {
|
||||
fn commit(&mut self, effects: &[HostEffect]);
|
||||
}
|
||||
|
||||
/// Persistent truthful default for the internal in-app host. It owns no native
|
||||
/// resources and must never acknowledge a create/rebind/release effect.
|
||||
#[derive(Default)]
|
||||
pub struct InAppNativeAdapter;
|
||||
impl NativeHostAdapter for InAppNativeAdapter {
|
||||
fn capabilities(&self) -> HostCapabilities {
|
||||
HostCapabilities { native_windows: false, persistence: false, max_native_hosts: 0 }
|
||||
}
|
||||
fn prepare(&self, effects: &[HostEffect]) -> PanelResult<()> {
|
||||
if effects
|
||||
.iter()
|
||||
.any(|effect| matches!(effect, HostEffect::CreateNative { .. } | HostEffect::RebindNative { .. } | HostEffect::ReleaseNative { .. }))
|
||||
{
|
||||
return Err(error(Rule::Capability, "in-app adapter has no native resources"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn commit(&mut self, _effects: &[HostEffect]) {}
|
||||
}
|
||||
|
||||
/// Existing ui_kit is the outer boundary. This adapter paints into host-provided
|
||||
/// space; it does not invent windows, docking gestures or a second camera path.
|
||||
pub struct EguiPanelHost<'a> {
|
||||
@@ -242,20 +271,23 @@ impl PanelHost for EguiPanelHost<'_> {
|
||||
}
|
||||
let rect = |r: LogicalRect| egui::Rect::from_min_size(egui::pos2(r.origin.x, r.origin.y), egui::vec2(r.size.width, r.size.height));
|
||||
let outer = rect(geometry.outer);
|
||||
let body = rect(geometry.body);
|
||||
let body = geometry.body.map(rect);
|
||||
let parent_clip = self.ui.clip_rect().intersect(outer);
|
||||
let container = crate::ui_kit::Container::new(self.ui.ctx(), crate::ui_kit::Surface::Panel);
|
||||
let frame = container.frame(self.ui.ctx(), crate::theme::Tokens::get().dialog_body, crate::frame::Side::Left).inner_margin(0);
|
||||
let mut failure = None;
|
||||
self.ui.scope_builder(
|
||||
egui::UiBuilder::new().id_salt(("panel_runtime", &geometry.instance.0, &context.owner, &context.viewport.0)).max_rect(outer),
|
||||
egui::UiBuilder::new().scope_id(egui::Id::unique(("panel_runtime", &geometry.instance.0, &context.owner))).max_rect(outer),
|
||||
|ui| {
|
||||
ui.set_clip_rect(ui.clip_rect().intersect(parent_clip));
|
||||
container.show_frame(ui, frame, outer, |ui| {
|
||||
// Slots have explicit bounds. No mandatory ScrollArea around content.
|
||||
let header = egui::Rect::from_min_max(outer.min, egui::pos2(outer.right(), body.top()));
|
||||
let footer = egui::Rect::from_min_max(egui::pos2(outer.left(), body.bottom()), outer.max);
|
||||
for (slot, bounds) in [(ContentSlot::Header, header), (ContentSlot::Body, body), (ContentSlot::Footer, footer)] {
|
||||
let header = egui::Rect::from_min_max(outer.min, egui::pos2(outer.right(), body.map_or(outer.bottom(), |body| body.top())));
|
||||
let footer = body.map(|body| egui::Rect::from_min_max(egui::pos2(outer.left(), body.bottom()), outer.max));
|
||||
for (slot, bounds) in [(ContentSlot::Header, Some(header)), (ContentSlot::Body, body), (ContentSlot::Footer, footer)] {
|
||||
let Some(bounds) = bounds else {
|
||||
continue;
|
||||
};
|
||||
if failure.is_some() {
|
||||
break;
|
||||
}
|
||||
@@ -298,7 +330,9 @@ impl PanelHost for EguiPanelHost<'_> {
|
||||
});
|
||||
});
|
||||
}
|
||||
if let Err(reason) = content.render(slot, ui, context, services) {
|
||||
if geometry.body.is_some()
|
||||
&& let Err(reason) = content.render(slot, ui, context, services)
|
||||
{
|
||||
failure = Some(reason);
|
||||
}
|
||||
});
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,14 +1,22 @@
|
||||
//! Opt-in common panel runtime. No production registrations, gestures or preferences.
|
||||
//! Opt-in common panel runtime. No production registrations or shipping default changes.
|
||||
//! Model/commands, controller state, presentation and layout have separate owners.
|
||||
mod app;
|
||||
mod fixtures;
|
||||
mod host;
|
||||
mod interaction;
|
||||
mod layout;
|
||||
mod runtime;
|
||||
mod specimen;
|
||||
mod workspace;
|
||||
|
||||
pub use app::*;
|
||||
pub use fixtures::*;
|
||||
pub use host::*;
|
||||
pub use interaction::*;
|
||||
pub use layout::*;
|
||||
pub use runtime::*;
|
||||
pub use specimen::*;
|
||||
pub use workspace::*;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -4,6 +4,16 @@ use solidcraft_engine::panels::*;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A floating rectangle changes geometry, not the controller's presentation
|
||||
/// host. Keep its keyboard/overlay ownership while retaining ordinary reparent
|
||||
/// guards for changed groups, dock edges, native hosts and workspaces.
|
||||
fn same_presentation_host(before: Option<(&SectionId, &SectionLocation)>, after: Option<(&SectionId, &SectionLocation)>) -> bool {
|
||||
match (before, after) {
|
||||
(Some((before_id, SectionLocation::Floating { .. })), Some((after_id, SectionLocation::Floating { .. }))) => before_id == after_id,
|
||||
_ => before == after,
|
||||
}
|
||||
}
|
||||
|
||||
/// Retention spans every open document, independently of the active layout.
|
||||
pub const MAX_RETAINED_DOCUMENT_OWNERS: usize = crate::documents::MAX_OPEN;
|
||||
/// Application, workspace and window owners share a separate bounded budget.
|
||||
@@ -122,6 +132,21 @@ pub trait PanelController {
|
||||
/// Runs for retained controllers, including hidden, closed and inactive documents.
|
||||
fn update(&mut self, owner: &ContentOwner, services: &mut ContentServices<'_>) -> PanelResult<()>;
|
||||
fn presentation(&self) -> PanelPresentation;
|
||||
/// Capture bounded read-only measurement data. The returned immutable
|
||||
/// provider can answer candidate widths without borrowing live controllers,
|
||||
/// rendering hidden bodies or calling mutable services. The default reports
|
||||
/// registration's preferred outer height honestly, not an intrinsic extent.
|
||||
fn measure(&self, _owner: &ContentOwner, _models: &dyn PanelModels, spec: &PanelSpec) -> PanelResult<std::sync::Arc<dyn HostContentMetrics>> {
|
||||
Ok(std::sync::Arc::new(PreferredPanelMetrics { height: spec.default_size.height, policy: spec.side_height_policy }))
|
||||
}
|
||||
/// Read the live measurement source through this same controller. Immutable
|
||||
/// providers cannot report later source changes through their old revision.
|
||||
/// A cheap override must include every model/style/policy input to measure;
|
||||
/// the safe default captures a new bounded provider for comparison only.
|
||||
/// Neither path may render, tick services or publish owner state.
|
||||
fn measurement_revision(&self, owner: &ContentOwner, models: &dyn PanelModels, spec: &PanelSpec) -> PanelResult<u64> {
|
||||
Ok(self.measure(owner, models, spec)?.revision())
|
||||
}
|
||||
/// MUST be side-effect-free. Failure rejects the whole layout transaction.
|
||||
/// Validate cancellation and reserve anything fallible before committing.
|
||||
/// State notifications are observational and cannot veto a layout change.
|
||||
@@ -129,17 +154,71 @@ pub trait PanelController {
|
||||
/// Infallible application of an already prepared lifecycle transition.
|
||||
fn lifecycle(&mut self, event: &LifecycleEvent);
|
||||
fn render(&mut self, slot: ContentSlot, ui: &mut egui::Ui, context: &PanelContext, services: &mut ContentServices<'_>) -> PanelResult<()>;
|
||||
/// Safe fallback for existing content; adapters can supply compact controls.
|
||||
fn render_inline(&mut self, ui: &mut egui::Ui, context: &PanelContext, services: &mut ContentServices<'_>) -> PanelResult<()> {
|
||||
self.render(ContentSlot::Body, ui, context, services)
|
||||
}
|
||||
/// Validate a binding without mutating its owner. Implementations may add
|
||||
/// transaction-specific refusals here, before any host state commits.
|
||||
fn prepare_action(&self, _owner: &ContentOwner, action: &ControlId, _models: &dyn PanelModels) -> PanelResult<()> {
|
||||
let presentation = self.presentation();
|
||||
presentation.validate()?;
|
||||
let binding = presentation
|
||||
.actions
|
||||
.iter()
|
||||
.find(|binding| binding.id == *action)
|
||||
.ok_or_else(|| error(Rule::Capability, "content action has no controller binding"))?;
|
||||
if !binding.enabled {
|
||||
return Err(error(Rule::Availability, binding.disabled_reason.as_deref().unwrap_or("content action unavailable")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Apply/Finish/Cancel/Stop stay explicit content actions, never layout mutations.
|
||||
fn action(&mut self, owner: &ContentOwner, action: &ControlId, services: &mut ContentServices<'_>) -> PanelResult<()>;
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct PreferredPanelMetrics {
|
||||
height: f32,
|
||||
policy: SideHeightPolicy,
|
||||
}
|
||||
impl HostContentMetrics for PreferredPanelMetrics {
|
||||
fn measure(&self, request: &ContentMeasureRequest) -> PanelResult<SideContentMeasure> {
|
||||
Ok(SideContentMeasure { request: request.clone(), needed_height: self.height.max(request.chrome_height), policy: self.policy })
|
||||
}
|
||||
fn revision(&self) -> u64 {
|
||||
u64::from(self.height.to_bits()) * 2 + u64::from(self.policy == SideHeightPolicy::Fill)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct CapturedPanelMetrics {
|
||||
panels: BTreeMap<InstanceId, std::sync::Arc<dyn HostContentMetrics>>,
|
||||
revision: u64,
|
||||
}
|
||||
impl HostContentMetrics for CapturedPanelMetrics {
|
||||
fn measure(&self, request: &ContentMeasureRequest) -> PanelResult<SideContentMeasure> {
|
||||
self.panels.get(&request.instance).ok_or_else(|| error(Rule::Availability, "content metrics unavailable"))?.measure(request)
|
||||
}
|
||||
fn revision(&self) -> u64 {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut signature = std::collections::hash_map::DefaultHasher::new();
|
||||
self.revision.hash(&mut signature);
|
||||
for (id, provider) in &self.panels {
|
||||
id.hash(&mut signature);
|
||||
provider.revision().hash(&mut signature);
|
||||
}
|
||||
signature.finish()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ControllerBinding {
|
||||
pub ownership: Ownership,
|
||||
/// Staging may be discarded on failure; do not publish external side effects.
|
||||
pub create: Box<dyn Fn(&PanelInstance, &ContentOwner) -> PanelResult<Box<dyn PanelController>>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct ControllerKey {
|
||||
pub instance: InstanceId,
|
||||
pub owner: ContentOwner,
|
||||
@@ -158,6 +237,58 @@ struct RetainedController {
|
||||
availability: Availability,
|
||||
}
|
||||
|
||||
/// Private, side-effect-free owner cohort. Providers and newly created
|
||||
/// controllers survive projection and are moved into the successful commit.
|
||||
struct RuntimeCohort {
|
||||
base_environment: RuntimeEnvironment,
|
||||
base_revision: u64,
|
||||
environment: RuntimeEnvironment,
|
||||
staged: BTreeMap<ControllerKey, RetainedController>,
|
||||
availability: AvailabilityMap,
|
||||
metrics: std::sync::Arc<dyn HostContentMetrics>,
|
||||
metric_revision: u64,
|
||||
providers: BTreeMap<ControllerKey, std::sync::Arc<dyn HostContentMetrics>>,
|
||||
}
|
||||
|
||||
pub(crate) struct RuntimeHostProposal {
|
||||
candidate: PreparedHostLayout,
|
||||
reference: HostLayout,
|
||||
source_reference: HostLayout,
|
||||
cohort: RuntimeCohort,
|
||||
}
|
||||
impl RuntimeHostProposal {
|
||||
pub(crate) fn action(&self) -> &LayoutAction {
|
||||
self.candidate.action()
|
||||
}
|
||||
pub(crate) fn layout(&self) -> &Layout {
|
||||
self.candidate.prepared().layout()
|
||||
}
|
||||
pub(crate) fn validate_preparation_context(&self, context: &LayoutPreparationContext) -> PanelResult<()> {
|
||||
if self.reference.geometry_policy.identity_reservations.preparation_context()? != *context {
|
||||
return Err(error(Rule::Revision, "host proposal preparation context changed"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(crate) fn validate_captured(&self, runtime: &PanelRuntime, models: &dyn PanelModels) -> PanelResult<()> {
|
||||
self.validate(runtime, &self.source_reference, models)
|
||||
}
|
||||
pub(crate) fn validate(&self, runtime: &PanelRuntime, reference: &HostLayout, models: &dyn PanelModels) -> PanelResult<()> {
|
||||
if &self.source_reference != reference {
|
||||
return Err(error(Rule::Revision, "host proposal source environment changed"));
|
||||
}
|
||||
self.candidate.validate_current(runtime.layout(), &runtime_scope(runtime), &self.reference)?;
|
||||
let snapshot = self.candidate.proposal_snapshot();
|
||||
if self.cohort.availability != snapshot.availability || !std::sync::Arc::ptr_eq(&self.cohort.metrics, &snapshot.metrics) {
|
||||
return Err(error(Rule::Revision, "runtime cohort differs from admitted host snapshot"));
|
||||
}
|
||||
runtime.validate_cohort(self.layout(), &self.cohort, models)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn standalone_header_action(action: &LayoutAction) -> bool {
|
||||
matches!(action, LayoutAction::Apply { mutations, .. } if matches!(mutations.as_slice(), [Mutation::HeaderAction { .. }]))
|
||||
}
|
||||
|
||||
/// Layout stays on the app, controllers on their content owners, host services on
|
||||
/// their local scopes. None of these values enter document serialization or undo.
|
||||
pub struct PanelRuntime {
|
||||
@@ -176,6 +307,24 @@ pub struct RuntimeUpdateError {
|
||||
pub error: PanelError,
|
||||
}
|
||||
|
||||
/// A mount supplies the complete presented set for exactly this cohort. Native
|
||||
/// viewport adapters must never reconcile another viewport's presentation.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
enum PresentationCohort {
|
||||
All,
|
||||
InApp,
|
||||
Native(HostId),
|
||||
}
|
||||
impl PresentationCohort {
|
||||
fn includes(&self, current: Option<&HostId>, previous: Option<&HostId>) -> bool {
|
||||
match self {
|
||||
Self::All => true,
|
||||
Self::InApp => current.is_none() && previous.is_none(),
|
||||
Self::Native(host) => current == Some(host) || previous == Some(host),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A scoped live action sink for host and future command routing. It includes the
|
||||
/// runtime lifecycle guard rather than exposing a mutable bare LayoutService.
|
||||
pub struct RuntimeActionSink<'a, 'services> {
|
||||
@@ -183,23 +332,30 @@ pub struct RuntimeActionSink<'a, 'services> {
|
||||
pub native: &'a mut dyn NativeHostAdapter,
|
||||
pub services: &'a mut ContentServices<'services>,
|
||||
}
|
||||
|
||||
pub(crate) fn normalize_native_reply(mut reply: LayoutReply, native: &HostCapabilities) -> LayoutReply {
|
||||
reply.capabilities.native_windows &= native.native_windows;
|
||||
reply.capabilities.max_native_hosts = reply.capabilities.max_native_hosts.min(native.max_native_hosts);
|
||||
reply
|
||||
}
|
||||
|
||||
impl ActionSink for RuntimeActionSink<'_, '_> {
|
||||
fn project_in_context(&self, action: LayoutAction, context: &LayoutPreparationContext) -> PanelResult<Layout> {
|
||||
self.runtime.layout.project_with_context(action, context)
|
||||
}
|
||||
fn dispatch_in_context(&mut self, action: LayoutAction, context: &LayoutPreparationContext) -> PanelResult<LayoutReply> {
|
||||
let reply = self.runtime.dispatch_in_context(action, context, self.native, self.services)?;
|
||||
Ok(normalize_native_reply(reply, &self.native.capabilities()))
|
||||
}
|
||||
fn project(&self, action: LayoutAction) -> PanelResult<Layout> {
|
||||
self.runtime.layout.project(action)
|
||||
}
|
||||
fn dispatch(&mut self, action: LayoutAction) -> PanelResult<LayoutReply> {
|
||||
let mut reply = self.runtime.dispatch(action, self.native, self.services)?;
|
||||
let native = self.native.capabilities();
|
||||
reply.capabilities.native_windows &= native.native_windows;
|
||||
reply.capabilities.max_native_hosts = reply.capabilities.max_native_hosts.min(native.max_native_hosts);
|
||||
Ok(reply)
|
||||
let reply = self.runtime.dispatch(action, self.native, self.services)?;
|
||||
Ok(normalize_native_reply(reply, &self.native.capabilities()))
|
||||
}
|
||||
fn inspect(&self) -> LayoutReply {
|
||||
let mut reply = self.runtime.layout.inspect();
|
||||
let native = self.native.capabilities();
|
||||
reply.capabilities.native_windows &= native.native_windows;
|
||||
reply.capabilities.max_native_hosts = reply.capabilities.max_native_hosts.min(native.max_native_hosts);
|
||||
reply
|
||||
normalize_native_reply(self.runtime.layout.inspect(), &self.native.capabilities())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -237,13 +393,242 @@ impl PanelRuntime {
|
||||
pub fn environment(&self) -> &RuntimeEnvironment {
|
||||
&self.environment
|
||||
}
|
||||
/// Snapshot only current available owners. No controller render/update, list
|
||||
/// enumeration, command or local input service runs during metric capture.
|
||||
pub fn capture_metrics(&self, models: &dyn PanelModels) -> PanelResult<std::sync::Arc<dyn HostContentMetrics>> {
|
||||
// Current-frame collection never creates/discards a controller. The
|
||||
// explicit context reconciliation must retain owners before painting.
|
||||
Ok(self.capture_cohort_with(self.layout.layout(), self.environment.clone(), BTreeMap::new(), BTreeMap::new(), models)?.metrics)
|
||||
}
|
||||
fn capture_cohort(&self, layout: &Layout, models: &dyn PanelModels) -> PanelResult<RuntimeCohort> {
|
||||
self.require_live()?;
|
||||
let mut environment = self.environment.clone();
|
||||
environment.workspace = layout.workspace.clone();
|
||||
environment.validate()?;
|
||||
let staged = self.stage_controllers(layout, &environment)?;
|
||||
self.capture_cohort_with(layout, environment, staged, BTreeMap::new(), models)
|
||||
}
|
||||
fn capture_cohort_with(
|
||||
&self,
|
||||
layout: &Layout,
|
||||
environment: RuntimeEnvironment,
|
||||
staged: BTreeMap<ControllerKey, RetainedController>,
|
||||
mut providers: BTreeMap<ControllerKey, std::sync::Arc<dyn HostContentMetrics>>,
|
||||
models: &dyn PanelModels,
|
||||
) -> PanelResult<RuntimeCohort> {
|
||||
use std::hash::{Hash, Hasher};
|
||||
self.require_live()?;
|
||||
let availability = self.cohort_availability(layout, &environment, &staged, models)?;
|
||||
let mut panels = BTreeMap::new();
|
||||
let mut signature = std::collections::hash_map::DefaultHasher::new();
|
||||
for instance in &layout.instances {
|
||||
instance.id.hash(&mut signature);
|
||||
if !instance.requested_open || availability.get(&instance.id) != Some(&Availability::Available) {
|
||||
continue;
|
||||
}
|
||||
let key = self.key_in(instance, &environment)?;
|
||||
let retained = self
|
||||
.controllers
|
||||
.get(&key)
|
||||
.or_else(|| staged.get(&key))
|
||||
.ok_or_else(|| error(Rule::Availability, "content metrics controller unavailable"))?;
|
||||
let metrics = match providers.get(&key) {
|
||||
Some(metrics) => metrics.clone(),
|
||||
None => {
|
||||
let metrics = retained.controller.measure(&key.owner, models, self.layout.registry().get(&instance.kind)?)?;
|
||||
providers.insert(key.clone(), metrics.clone());
|
||||
metrics
|
||||
}
|
||||
};
|
||||
key.hash(&mut signature);
|
||||
panels.insert(instance.id.clone(), metrics);
|
||||
}
|
||||
let metrics = std::sync::Arc::new(CapturedPanelMetrics { panels, revision: signature.finish() });
|
||||
let metric_revision = metrics.revision();
|
||||
Ok(RuntimeCohort {
|
||||
base_environment: self.environment.clone(),
|
||||
base_revision: self.layout.inspect().revision,
|
||||
environment,
|
||||
staged,
|
||||
availability,
|
||||
metrics,
|
||||
metric_revision,
|
||||
providers,
|
||||
})
|
||||
}
|
||||
fn cohort_availability(
|
||||
&self,
|
||||
layout: &Layout,
|
||||
environment: &RuntimeEnvironment,
|
||||
staged: &BTreeMap<ControllerKey, RetainedController>,
|
||||
models: &dyn PanelModels,
|
||||
) -> PanelResult<AvailabilityMap> {
|
||||
let mut availability = AvailabilityMap::new();
|
||||
for instance in &layout.instances {
|
||||
let state = match self.key_in(instance, environment) {
|
||||
Ok(key) => match self.controllers.get(&key).or_else(|| staged.get(&key)) {
|
||||
Some(retained) => {
|
||||
let state = retained.controller.availability(&key.owner, models);
|
||||
if matches!(&state, Availability::Unavailable { reason } if reason.is_empty() || reason.len() > 256) {
|
||||
return Err(error(Rule::Availability, "controller availability reason bound"));
|
||||
}
|
||||
if self.update_errors.iter().any(|e| e.controller.as_ref() == Some(&key)) { retained.availability.clone() } else { state }
|
||||
}
|
||||
None => Availability::Unavailable { reason: "content controller unavailable".into() },
|
||||
},
|
||||
Err(reason) => Availability::Unavailable { reason: reason.detail },
|
||||
};
|
||||
availability.insert(instance.id.clone(), state);
|
||||
}
|
||||
Ok(availability)
|
||||
}
|
||||
fn validate_cohort(&self, layout: &Layout, cohort: &RuntimeCohort, models: &dyn PanelModels) -> PanelResult<()> {
|
||||
self.require_live()?;
|
||||
if self.environment != cohort.base_environment
|
||||
|| self.layout.inspect().revision != cohort.base_revision
|
||||
|| self.cohort_availability(layout, &cohort.environment, &cohort.staged, models)? != cohort.availability
|
||||
|| cohort.metrics.revision() != cohort.metric_revision
|
||||
{
|
||||
return Err(error(Rule::Revision, "runtime proposal cohort changed"));
|
||||
}
|
||||
for instance in &layout.instances {
|
||||
if !instance.requested_open || cohort.availability.get(&instance.id) != Some(&Availability::Available) {
|
||||
continue;
|
||||
}
|
||||
let key = self.key_in(instance, &cohort.environment)?;
|
||||
let retained = self
|
||||
.controllers
|
||||
.get(&key)
|
||||
.or_else(|| cohort.staged.get(&key))
|
||||
.ok_or_else(|| error(Rule::Revision, "measured controller is no longer retained"))?;
|
||||
let original = cohort.providers.get(&key).ok_or_else(|| error(Rule::Revision, "controller metric source snapshot missing"))?;
|
||||
let live = retained.controller.measurement_revision(&key.owner, models, self.layout.registry().get(&instance.kind)?)?;
|
||||
if live != original.revision() {
|
||||
return Err(error(Rule::Revision, "controller measurement source changed after capture"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(crate) fn prepare_host_proposal(
|
||||
&self,
|
||||
reference: HostLayout,
|
||||
action: LayoutAction,
|
||||
models: &dyn PanelModels,
|
||||
) -> PanelResult<RuntimeHostProposal> {
|
||||
self.prepare_host_proposal_with(reference, action, models, None, None)
|
||||
}
|
||||
pub(crate) fn prepare_host_proposal_in_context(
|
||||
&self,
|
||||
reference: HostLayout,
|
||||
action: LayoutAction,
|
||||
context: &LayoutPreparationContext,
|
||||
models: &dyn PanelModels,
|
||||
) -> PanelResult<RuntimeHostProposal> {
|
||||
self.prepare_host_proposal_with(reference, action, models, None, Some(context))
|
||||
}
|
||||
pub(crate) fn revise_host_proposal(
|
||||
&self,
|
||||
previous: RuntimeHostProposal,
|
||||
reference: HostLayout,
|
||||
action: LayoutAction,
|
||||
context: Option<&LayoutPreparationContext>,
|
||||
models: &dyn PanelModels,
|
||||
) -> PanelResult<RuntimeHostProposal> {
|
||||
previous.validate(self, &reference, models)?;
|
||||
let context = match context {
|
||||
Some(context) => context.clone(),
|
||||
None => previous.reference.geometry_policy.identity_reservations.preparation_context()?,
|
||||
};
|
||||
self.prepare_host_proposal_with(reference, action, models, Some(previous.cohort), Some(&context))
|
||||
}
|
||||
fn prepare_host_proposal_with(
|
||||
&self,
|
||||
source_reference: HostLayout,
|
||||
action: LayoutAction,
|
||||
models: &dyn PanelModels,
|
||||
previous: Option<RuntimeCohort>,
|
||||
context: Option<&LayoutPreparationContext>,
|
||||
) -> PanelResult<RuntimeHostProposal> {
|
||||
// Workspace/preset staging can supply an incoming envelope context. Keep
|
||||
// the outgoing painted environment independently for freshness, while B
|
||||
// owns the exact supplied preparation environment throughout admission.
|
||||
let mut reference = source_reference.clone();
|
||||
if let Some(context) = context {
|
||||
let reservations = HostIdentityReservations {
|
||||
sections: context.sections.clone(),
|
||||
columns: context.columns.clone(),
|
||||
extent_priorities: context.extent_priorities.clone(),
|
||||
replacement_ownership: context.replacement_ownership.clone(),
|
||||
};
|
||||
reservations.validate()?;
|
||||
reference.geometry_policy.identity_reservations = reservations;
|
||||
}
|
||||
let mut cohort = None;
|
||||
let candidate = prepare_host_layout_with_snapshot(&self.layout, &runtime_scope(self), &reference, action, |layout| {
|
||||
let captured = if let Some(previous) = previous {
|
||||
let mut environment = self.environment.clone();
|
||||
environment.workspace = layout.workspace.clone();
|
||||
environment.validate()?;
|
||||
let staged = self.stage_controllers_with(layout, &environment, previous.staged)?;
|
||||
self.capture_cohort_with(layout, environment, staged, previous.providers, models)?
|
||||
} else {
|
||||
self.capture_cohort(layout, models)?
|
||||
};
|
||||
let snapshot = HostProposalSnapshot { availability: captured.availability.clone(), metrics: captured.metrics.clone() };
|
||||
cohort = Some(captured);
|
||||
Ok(snapshot)
|
||||
})?;
|
||||
Ok(RuntimeHostProposal {
|
||||
candidate,
|
||||
reference,
|
||||
source_reference,
|
||||
cohort: cohort.ok_or_else(|| error(Rule::Lifecycle, "host capture callback was not called"))?,
|
||||
})
|
||||
}
|
||||
/// Pointer candidates already own their geometry. Capture current retained
|
||||
/// owners without replaying their action, and reject a mismatching snapshot.
|
||||
pub(crate) fn retain_host_candidate(
|
||||
&self,
|
||||
candidate: PreparedHostLayout,
|
||||
reference: HostLayout,
|
||||
models: &dyn PanelModels,
|
||||
) -> PanelResult<RuntimeHostProposal> {
|
||||
candidate.validate_current(&self.layout, &runtime_scope(self), &reference)?;
|
||||
let layout = candidate.prepared().layout();
|
||||
let environment = self.environment.clone();
|
||||
if layout.workspace != environment.workspace {
|
||||
return Err(error(Rule::Revision, "pointer candidate changed workspace"));
|
||||
}
|
||||
// Fresh comparison providers come from the same retained/staged objects.
|
||||
// Keep B's original aggregate for geometry/commit when revisions agree.
|
||||
let mut cohort = self.capture_cohort(layout, models)?;
|
||||
let snapshot = candidate.proposal_snapshot();
|
||||
if cohort.availability != snapshot.availability || cohort.metrics.revision() != snapshot.metrics.revision() {
|
||||
return Err(error(Rule::Revision, "pointer proposed measurement sources changed"));
|
||||
}
|
||||
cohort.metrics = snapshot.metrics.clone();
|
||||
cohort.metric_revision = snapshot.metrics.revision();
|
||||
Ok(RuntimeHostProposal { candidate, source_reference: reference.clone(), reference, cohort })
|
||||
}
|
||||
pub(crate) fn commit_host_proposal(
|
||||
&mut self,
|
||||
proposal: RuntimeHostProposal,
|
||||
native: &mut dyn NativeHostAdapter,
|
||||
services: &mut ContentServices<'_>,
|
||||
) -> PanelResult<LayoutReply> {
|
||||
proposal.validate_captured(self, services.models)?;
|
||||
let RuntimeHostProposal { candidate, reference, cohort, .. } = proposal;
|
||||
let action = candidate.action().clone();
|
||||
let prepared = candidate.into_prepared(&self.layout, &runtime_scope(self), &reference)?;
|
||||
self.commit_layout(Some(action), prepared, native, services, Some(cohort))
|
||||
}
|
||||
pub fn controller_count(&self) -> usize {
|
||||
self.controllers.len()
|
||||
}
|
||||
pub fn update_errors(&self) -> &[RuntimeUpdateError] {
|
||||
&self.update_errors
|
||||
}
|
||||
fn require_live(&self) -> PanelResult<()> {
|
||||
pub(crate) fn require_live(&self) -> PanelResult<()> {
|
||||
if self.destroyed {
|
||||
return Err(error(Rule::Lifecycle, "runtime destroyed"));
|
||||
}
|
||||
@@ -257,6 +642,16 @@ impl PanelRuntime {
|
||||
value.validate()?;
|
||||
Ok(value)
|
||||
}
|
||||
/// Read inactive tabs/rails through the registered ownership policy. This
|
||||
/// never creates, updates or renders a controller.
|
||||
pub fn instance_presentation(&self, instance: &InstanceId) -> PanelResult<PanelPresentation> {
|
||||
self.require_live()?;
|
||||
let key = self.key(self.layout.layout().instance(instance)?)?;
|
||||
self.presentation(&key)
|
||||
}
|
||||
pub fn instance_owner(&self, instance: &InstanceId) -> PanelResult<ContentOwner> {
|
||||
self.key(self.layout.layout().instance(instance)?).map(|key| key.owner)
|
||||
}
|
||||
fn key(&self, instance: &PanelInstance) -> PanelResult<ControllerKey> {
|
||||
self.key_in(instance, &self.environment)
|
||||
}
|
||||
@@ -309,10 +704,71 @@ impl PanelRuntime {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Re-read owner/context availability without ticking background work or
|
||||
/// evaluating a model. App boundaries use this after Session changes later
|
||||
/// in the same egui frame; incoming controllers are staged and retained.
|
||||
pub fn reconcile_context(&mut self, environment: RuntimeEnvironment, services: &mut ContentServices<'_>) -> PanelResult<()> {
|
||||
self.require_live()?;
|
||||
self.set_environment(environment, services.local)?;
|
||||
let staged = self.stage_controllers(self.layout.layout(), &self.environment)?;
|
||||
self.controllers.extend(staged);
|
||||
let mut availability = AvailabilityMap::new();
|
||||
let mut retained_availability = Vec::new();
|
||||
for instance in &self.layout.layout().instances {
|
||||
let state = match self.key(instance) {
|
||||
Ok(key) => {
|
||||
let retained = self.controllers.get(&key).ok_or_else(|| error(Rule::Availability, "content controller unavailable"))?;
|
||||
let available = retained.controller.availability(&key.owner, services.models);
|
||||
if matches!(&available, Availability::Unavailable { reason } if reason.is_empty() || reason.len() > 256) {
|
||||
return Err(error(Rule::Availability, "controller availability reason bound"));
|
||||
}
|
||||
// A boundary refresh is not a successful background tick.
|
||||
let state = if self.update_errors.iter().any(|failure| failure.controller.as_ref() == Some(&key)) {
|
||||
retained.availability.clone()
|
||||
} else {
|
||||
available
|
||||
};
|
||||
retained_availability.push((key, state.clone()));
|
||||
state
|
||||
}
|
||||
Err(reason) => Availability::Unavailable { reason: reason.detail },
|
||||
};
|
||||
availability.insert(instance.id.clone(), state);
|
||||
}
|
||||
self.layout.set_availability(availability)?;
|
||||
for (key, state) in retained_availability {
|
||||
if let Some(retained) = self.controllers.get_mut(&key) {
|
||||
retained.availability = state;
|
||||
}
|
||||
}
|
||||
self.sync_states(None, services.local);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Fail closed when a current-Session provider/context cannot be reconciled.
|
||||
/// Hiding releases local input but never closes or destroys retained drafts.
|
||||
pub fn suspend_presentations(&mut self, local: &mut dyn PanelLocalServices) {
|
||||
for (key, retained) in &mut self.controllers {
|
||||
if retained.state.presented || retained.state.activated {
|
||||
local.release(&retained.scope, &key.instance);
|
||||
retained.state.presented = false;
|
||||
retained.state.activated = false;
|
||||
retained.controller.lifecycle(&LifecycleEvent::State(retained.state.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn stage_controllers(&self, layout: &Layout, environment: &RuntimeEnvironment) -> PanelResult<BTreeMap<ControllerKey, RetainedController>> {
|
||||
let mut staged = BTreeMap::new();
|
||||
self.stage_controllers_with(layout, environment, BTreeMap::new())
|
||||
}
|
||||
fn stage_controllers_with(
|
||||
&self,
|
||||
layout: &Layout,
|
||||
environment: &RuntimeEnvironment,
|
||||
mut staged: BTreeMap<ControllerKey, RetainedController>,
|
||||
) -> PanelResult<BTreeMap<ControllerKey, RetainedController>> {
|
||||
let mut owner_counts = BTreeMap::<ContentOwner, usize>::new();
|
||||
for key in self.controllers.keys() {
|
||||
for key in self.controllers.keys().chain(staged.keys()) {
|
||||
*owner_counts.entry(key.owner.clone()).or_default() += 1;
|
||||
}
|
||||
let mut document_owners = owner_counts.keys().filter(|owner| matches!(owner, ContentOwner::Document(_))).count();
|
||||
@@ -375,27 +831,7 @@ impl PanelRuntime {
|
||||
pub fn refresh_context(&mut self, models: &dyn PanelModels, local: &mut dyn PanelLocalServices) -> PanelResult<()> {
|
||||
self.require_live()?;
|
||||
let staged = self.stage_controllers(self.layout.layout(), &self.environment)?;
|
||||
let mut availability = AvailabilityMap::new();
|
||||
for instance in &self.layout.layout().instances {
|
||||
let state = match self.key(instance) {
|
||||
Ok(key) => match self.controllers.get(&key).or_else(|| staged.get(&key)) {
|
||||
Some(retained) => {
|
||||
let state = retained.controller.availability(&key.owner, models);
|
||||
if matches!(&state,Availability::Unavailable { reason } if reason.is_empty() || reason.len() > 256) {
|
||||
return Err(error(Rule::Availability, "controller availability reason bound"));
|
||||
}
|
||||
if self.update_errors.iter().any(|failure| failure.controller.as_ref() == Some(&key)) {
|
||||
retained.availability.clone()
|
||||
} else {
|
||||
state
|
||||
}
|
||||
}
|
||||
None => Availability::Unavailable { reason: "content controller unavailable".into() },
|
||||
},
|
||||
Err(reason) => Availability::Unavailable { reason: reason.detail },
|
||||
};
|
||||
availability.insert(instance.id.clone(), state);
|
||||
}
|
||||
let availability = self.cohort_availability(self.layout.layout(), &self.environment, &staged, models)?;
|
||||
self.layout.set_availability(availability.clone())?;
|
||||
self.controllers.extend(staged);
|
||||
for instance in &self.layout.layout().instances {
|
||||
@@ -481,8 +917,57 @@ impl PanelRuntime {
|
||||
if self.destroyed {
|
||||
return Err(error(Rule::Lifecycle, "runtime destroyed"));
|
||||
}
|
||||
if let LayoutAction::Apply { mutations, .. } = &action
|
||||
&& mutations.iter().any(|m| matches!(m, Mutation::HeaderAction { .. }))
|
||||
{
|
||||
if !standalone_header_action(&action) {
|
||||
return Err(error(Rule::Capability, "header actions cannot be mixed with layout mutations"));
|
||||
}
|
||||
let prepared = self.layout.prepare(action.clone())?;
|
||||
if let [Mutation::HeaderAction { instance, action }] = mutations.as_slice() {
|
||||
let key = self.key(self.layout.layout().instance(instance)?)?;
|
||||
let retained = self.controllers.get(&key).ok_or_else(|| error(Rule::Availability, "header action controller unavailable"))?;
|
||||
retained.controller.availability(&key.owner, services.models).require()?;
|
||||
retained.availability.require()?;
|
||||
retained.controller.prepare_action(&key.owner, action, services.models)?;
|
||||
self.content_action(instance, action, services)?;
|
||||
}
|
||||
return self.layout.commit(prepared);
|
||||
}
|
||||
let prepared = self.layout.prepare(action.clone())?;
|
||||
self.commit_layout(Some(action), prepared, native, services, None)
|
||||
}
|
||||
|
||||
/// Host-disabled/native adapters still prepare against the full envelope
|
||||
/// context and the same once-created proposed owners used for lifecycle.
|
||||
fn dispatch_in_context(
|
||||
&mut self,
|
||||
action: LayoutAction,
|
||||
context: &LayoutPreparationContext,
|
||||
native: &mut dyn NativeHostAdapter,
|
||||
services: &mut ContentServices<'_>,
|
||||
) -> PanelResult<LayoutReply> {
|
||||
if action == LayoutAction::Inspect || standalone_header_action(&action) {
|
||||
return self.dispatch(action, native, services);
|
||||
}
|
||||
self.require_live()?;
|
||||
let owners = self.layout.project_with_context(action.clone(), context)?;
|
||||
let cohort = self.capture_cohort(&owners, services.models)?;
|
||||
let prepared = self.layout.prepare_with_context(action.clone(), &cohort.availability, context)?;
|
||||
self.commit_layout(Some(action), prepared, native, services, Some(cohort))
|
||||
}
|
||||
|
||||
fn commit_layout(
|
||||
&mut self,
|
||||
action: Option<LayoutAction>,
|
||||
mut prepared: PreparedLayout,
|
||||
native: &mut dyn NativeHostAdapter,
|
||||
services: &mut ContentServices<'_>,
|
||||
cohort: Option<RuntimeCohort>,
|
||||
) -> PanelResult<LayoutReply> {
|
||||
self.require_live()?;
|
||||
let requests: Vec<_> = match &action {
|
||||
LayoutAction::Apply { mutations, .. } => mutations
|
||||
Some(LayoutAction::Apply { mutations, .. }) => mutations
|
||||
.iter()
|
||||
.filter_map(|m| match m {
|
||||
Mutation::Open { instance, .. }
|
||||
@@ -492,13 +977,13 @@ impl PanelRuntime {
|
||||
_ => None,
|
||||
})
|
||||
.collect(),
|
||||
LayoutAction::Inspect | LayoutAction::Replace { .. } => Vec::new(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let replacement = matches!(&action, LayoutAction::Replace { .. });
|
||||
let replacement = matches!(&action, Some(LayoutAction::Replace { .. }));
|
||||
let mut explicit_close = BTreeSet::new();
|
||||
let mut explicit_destroy = BTreeSet::new();
|
||||
let mut explicit_open = BTreeSet::new();
|
||||
if let LayoutAction::Apply { mutations, .. } = &action {
|
||||
if let Some(LayoutAction::Apply { mutations, .. }) = &action {
|
||||
for mutation in mutations {
|
||||
match mutation {
|
||||
Mutation::Close { instance } => {
|
||||
@@ -514,9 +999,16 @@ impl PanelRuntime {
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut prepared = self.layout.prepare(action)?;
|
||||
let mut environment = self.environment.clone();
|
||||
environment.workspace = prepared.layout().workspace.clone();
|
||||
let cohort = match cohort {
|
||||
Some(cohort) => cohort,
|
||||
None => self.capture_cohort(prepared.layout(), services.models)?,
|
||||
};
|
||||
self.validate_cohort(prepared.layout(), &cohort, services.models)?;
|
||||
let RuntimeCohort { environment, mut staged, availability, .. } = cohort;
|
||||
// A batch may replace an earlier private snapshot. Only controllers in
|
||||
// its final owner cohort are published; discarded stages never ticked.
|
||||
let proposed_keys: BTreeSet<_> = prepared.layout().instances.iter().filter_map(|p| self.key_in(p, &environment).ok()).collect();
|
||||
staged.retain(|key, _| proposed_keys.contains(key));
|
||||
let capabilities = native.capabilities();
|
||||
if capabilities.max_native_hosts > MAX_SECTIONS {
|
||||
return Err(error(Rule::Capability, "native adapter reports invalid capacity"));
|
||||
@@ -524,25 +1016,6 @@ impl PanelRuntime {
|
||||
if prepared.effects().iter().any(|e| matches!(e, HostEffect::CreateNative { .. })) && !capabilities.native_windows {
|
||||
return Err(error(Rule::Capability, "native adapter is unavailable"));
|
||||
}
|
||||
let staged = self.stage_controllers(prepared.layout(), &environment)?;
|
||||
let mut availability = AvailabilityMap::new();
|
||||
for instance in &prepared.layout().instances {
|
||||
let state = match self.key_in(instance, &environment) {
|
||||
Ok(key) => match self.controllers.get(&key).or_else(|| staged.get(&key)) {
|
||||
Some(retained) => {
|
||||
let state = retained.controller.availability(&key.owner, services.models);
|
||||
if matches!(&state, Availability::Unavailable { reason } if reason.is_empty() || reason.len() > 256) {
|
||||
return Err(error(Rule::Availability, "controller availability reason bound"));
|
||||
}
|
||||
// A failed retained service cannot become healthy solely by moving it.
|
||||
if self.update_errors.iter().any(|e| e.controller.as_ref() == Some(&key)) { retained.availability.clone() } else { state }
|
||||
}
|
||||
None => Availability::Unavailable { reason: "content controller unavailable".into() },
|
||||
},
|
||||
Err(reason) => Availability::Unavailable { reason: reason.detail },
|
||||
};
|
||||
availability.insert(instance.id.clone(), state);
|
||||
}
|
||||
prepared.set_availability(availability.clone())?;
|
||||
for id in requests {
|
||||
if let Ok(instance) = prepared.layout().instance(&id)
|
||||
@@ -575,7 +1048,7 @@ impl PanelRuntime {
|
||||
let same_controller = after.is_some_and(|p| self.key_in(p, &environment).is_ok_and(|k| k == *key))
|
||||
&& before.is_some_and(|p| self.key(p).is_ok_and(|k| k == *key));
|
||||
if same_controller
|
||||
&& (old != new || self.environment.workspace != environment.workspace)
|
||||
&& (!same_presentation_host(old, new) || self.environment.workspace != environment.workspace)
|
||||
&& before.is_some_and(|p| p.requested_open)
|
||||
&& after.is_some_and(|p| p.requested_open)
|
||||
{
|
||||
@@ -583,8 +1056,34 @@ impl PanelRuntime {
|
||||
events.push((key.clone(), LifecycleEvent::Reparent));
|
||||
}
|
||||
}
|
||||
let header_actions: Vec<_> = prepared
|
||||
.effects()
|
||||
.iter()
|
||||
.filter_map(|effect| match effect {
|
||||
HostEffect::HeaderAction { instance, action } => Some((instance.clone(), action.clone())),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
// A fallible owner action is its own command. Mixing it with structural
|
||||
// changes could otherwise commit half a content/layout transaction.
|
||||
if !header_actions.is_empty() && !matches!(&action, Some(LayoutAction::Apply { mutations, .. }) if mutations.len() == 1) {
|
||||
return Err(error(Rule::Capability, "header actions cannot be mixed with layout mutations"));
|
||||
}
|
||||
for (instance, action) in &header_actions {
|
||||
let key = self.key_in(prepared.layout().instance(instance)?, &environment)?;
|
||||
let retained = self
|
||||
.controllers
|
||||
.get(&key)
|
||||
.or_else(|| staged.get(&key))
|
||||
.ok_or_else(|| error(Rule::Availability, "header action controller unavailable"))?;
|
||||
retained.availability.require()?;
|
||||
retained.controller.prepare_action(&key.owner, action, services.models)?;
|
||||
}
|
||||
// Effects are available from the same candidate, before irreversible work.
|
||||
native.prepare(prepared.effects())?;
|
||||
for (instance, action) in &header_actions {
|
||||
self.content_action(instance, action, services)?;
|
||||
}
|
||||
let reply = self.layout.commit(prepared)?;
|
||||
self.controllers.extend(staged);
|
||||
if replacement {
|
||||
@@ -625,8 +1124,13 @@ impl PanelRuntime {
|
||||
}
|
||||
|
||||
fn sync_states(&mut self, resolved: Option<&ResolvedLayout>, local: &mut dyn PanelLocalServices) {
|
||||
self.sync_presented_states(resolved, &PresentationCohort::All, local);
|
||||
}
|
||||
|
||||
fn sync_presented_states(&mut self, resolved: Option<&ResolvedLayout>, cohort: &PresentationCohort, local: &mut dyn PanelLocalServices) {
|
||||
let active_keys: BTreeSet<_> = self.layout.layout().instances.iter().filter_map(|p| self.key(p).ok()).collect();
|
||||
let scope = self.scope();
|
||||
let availability: AvailabilityMap = self.layout.layout().instances.iter().map(|p| (p.id.clone(), self.layout.availability(&p.id))).collect();
|
||||
let mut pending = Vec::new();
|
||||
for (key, retained) in &self.controllers {
|
||||
let instance = self.layout.layout().instance(&key.instance).ok();
|
||||
@@ -639,10 +1143,12 @@ impl PanelRuntime {
|
||||
SectionLocation::Window { host, .. } => Some(host.clone()),
|
||||
_ => None,
|
||||
});
|
||||
let peek = &self.layout.interaction().peek;
|
||||
let selected = section.is_some_and(|s| (!s.collapsed && s.active == key.instance) || peek.as_ref() == Some(&key.instance));
|
||||
if !cohort.includes(host.as_ref(), retained.native_host.as_ref()) {
|
||||
continue;
|
||||
}
|
||||
let selected = section.is_some_and(|s| !s.collapsed && presented_tab(s, &availability) == Some(&key.instance));
|
||||
let geometry_presented = match resolved {
|
||||
Some(r) => r.panels.iter().any(|p| p.instance == key.instance),
|
||||
Some(r) => r.panels.iter().any(|p| p.instance == key.instance && !p.painted.is_empty()),
|
||||
None => retained.state.presented && retained.section == section_id && retained.native_host == host && selected,
|
||||
};
|
||||
let presented = current && requested_open && available == Availability::Available && geometry_presented;
|
||||
@@ -673,10 +1179,63 @@ impl PanelRuntime {
|
||||
}
|
||||
|
||||
pub fn mount(&mut self, resolved: &ResolvedLayout, host: &mut dyn PanelHost, services: &mut ContentServices<'_>) -> PanelResult<()> {
|
||||
self.mount_frame(resolved, host, services, &PresentationCohort::All, true)
|
||||
}
|
||||
|
||||
/// Mount exactly once with every currently presented in-app section,
|
||||
/// including an empty set when hidden. Native peers are not deactivated.
|
||||
pub fn mount_in_app(&mut self, resolved: &ResolvedLayout, host: &mut dyn PanelHost, services: &mut ContentServices<'_>) -> PanelResult<()> {
|
||||
self.mount_frame(resolved, host, services, &PresentationCohort::InApp, true)
|
||||
}
|
||||
|
||||
/// Includes every currently presented section in one native host, or an
|
||||
/// empty set to unmount only that host. Root and sibling windows survive.
|
||||
pub fn mount_native(
|
||||
&mut self,
|
||||
native_host: &HostId,
|
||||
resolved: &ResolvedLayout,
|
||||
host: &mut dyn PanelHost,
|
||||
services: &mut ContentServices<'_>,
|
||||
) -> PanelResult<()> {
|
||||
valid_id(&native_host.0)?;
|
||||
if !resolved.rails.is_empty() {
|
||||
return Err(error(Rule::Placement, "native cohort cannot mount root rails"));
|
||||
}
|
||||
self.mount_frame(resolved, host, services, &PresentationCohort::Native(native_host.clone()), true)
|
||||
}
|
||||
|
||||
pub(crate) fn repaint_in_app(
|
||||
&mut self,
|
||||
resolved: &ResolvedLayout,
|
||||
host: &mut dyn PanelHost,
|
||||
services: &mut ContentServices<'_>,
|
||||
) -> PanelResult<()> {
|
||||
self.mount_frame(resolved, host, services, &PresentationCohort::InApp, false)
|
||||
}
|
||||
|
||||
/// After a kit Area sizing pass, reconcile actual visibility without
|
||||
/// invoking any content renderer twice or deactivating native peers.
|
||||
pub(crate) fn reconcile_in_app_presentation(&mut self, resolved: &ResolvedLayout, local: &mut dyn PanelLocalServices) {
|
||||
self.sync_presented_states(Some(resolved), &PresentationCohort::InApp, local);
|
||||
}
|
||||
|
||||
fn mount_frame(
|
||||
&mut self,
|
||||
resolved: &ResolvedLayout,
|
||||
host: &mut dyn PanelHost,
|
||||
services: &mut ContentServices<'_>,
|
||||
cohort: &PresentationCohort,
|
||||
reconcile: bool,
|
||||
) -> PanelResult<()> {
|
||||
self.require_live()?;
|
||||
resolved.validate()?;
|
||||
for record in &resolved.unpresented {
|
||||
self.layout.layout().section(&record.section)?;
|
||||
let section = self.layout.layout().section(&record.section)?;
|
||||
if let PresentationCohort::Native(expected) = cohort
|
||||
&& !matches!(§ion.location, SectionLocation::Window { host, .. } if host == expected)
|
||||
{
|
||||
return Err(error(Rule::Placement, "unpresented section belongs to another host"));
|
||||
}
|
||||
}
|
||||
let mut ids = BTreeSet::new();
|
||||
for geometry in &resolved.panels {
|
||||
@@ -685,18 +1244,25 @@ impl PanelRuntime {
|
||||
return Err(error(Rule::ExactlyOnce, "panel mounted twice"));
|
||||
}
|
||||
let section = self.layout.layout().containing(&geometry.instance)?;
|
||||
let native_host = match §ion.location {
|
||||
SectionLocation::Window { host, .. } => Some(host),
|
||||
_ => None,
|
||||
};
|
||||
if !cohort.includes(native_host, native_host) {
|
||||
return Err(error(Rule::Placement, "content belongs to another presentation cohort"));
|
||||
}
|
||||
if section.id != geometry.section
|
||||
|| section.location.zone() != geometry.zone
|
||||
|| !self.layout.layout().instance(&geometry.instance)?.requested_open
|
||||
{
|
||||
return Err(error(Rule::Placement, "resolved host differs from live layout"));
|
||||
}
|
||||
let peek = self.layout.interaction().peek.as_ref() == Some(&geometry.instance);
|
||||
if section.active != geometry.instance && !peek || section.collapsed && !peek {
|
||||
let availability: AvailabilityMap = section.tabs.iter().map(|id| (id.clone(), self.layout.availability(id))).collect();
|
||||
if presented_tab(section, &availability) != Some(&geometry.instance) || section.collapsed && geometry.body.is_some() {
|
||||
return Err(error(Rule::Placement, "cannot mount inactive or collapsed tab content"));
|
||||
}
|
||||
let (min, max) = tab_bounds(self.layout.layout(), self.layout.registry(), section)?;
|
||||
if !geometry.outer.size.within(min, max) {
|
||||
if !section.collapsed && !geometry.outer.size.within(min, max) {
|
||||
return Err(error(Rule::Bounds, "host violates tab outer bounds"));
|
||||
}
|
||||
if self.layout.availability(&geometry.instance) != Availability::Available {
|
||||
@@ -705,13 +1271,18 @@ impl PanelRuntime {
|
||||
let key = self.key(self.layout.layout().instance(&geometry.instance)?)?;
|
||||
self.controllers.get(&key).ok_or_else(|| error(Rule::Availability, "content controller unavailable"))?.availability.require()?;
|
||||
}
|
||||
self.sync_states(Some(resolved), services.local);
|
||||
if reconcile {
|
||||
self.sync_presented_states(Some(resolved), cohort, services.local);
|
||||
}
|
||||
let interaction = self.layout.interaction().clone();
|
||||
for geometry in &resolved.panels {
|
||||
if geometry.painted.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let instance = self.layout.layout().instance(&geometry.instance)?;
|
||||
let key = self.key(instance)?;
|
||||
let retained = self.controllers.get_mut(&key).ok_or_else(|| error(Rule::MissingTarget, "call update before mount"))?;
|
||||
let (flow, size_class) = responsive(geometry.zone, geometry.body.size, retained.flow)?;
|
||||
let (flow, size_class) = responsive(geometry.zone, geometry.outer.size, retained.flow)?;
|
||||
let context = PanelContext {
|
||||
instance: geometry.instance.clone(),
|
||||
owner: key.owner.clone(),
|
||||
@@ -796,4 +1367,37 @@ impl PanelRuntime {
|
||||
self.destroyed = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Release the exact native resources belonging to this runtime only after
|
||||
/// every controller and native adapter has accepted teardown.
|
||||
pub fn shutdown_with_native(&mut self, native: &mut dyn NativeHostAdapter, local: &mut dyn PanelLocalServices) -> PanelResult<()> {
|
||||
if self.destroyed {
|
||||
return Ok(());
|
||||
}
|
||||
let effects: Vec<_> = if native.capabilities().native_windows {
|
||||
self.layout
|
||||
.layout()
|
||||
.sections
|
||||
.iter()
|
||||
.filter_map(|section| match §ion.location {
|
||||
SectionLocation::Window { host, .. } => Some(HostEffect::ReleaseNative { host: host.clone() }),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
for retained in self.controllers.values() {
|
||||
retained.controller.prepare_lifecycle(&LifecycleEvent::DestroyOwner)?;
|
||||
}
|
||||
native.prepare(&effects)?;
|
||||
for (key, retained) in &mut self.controllers {
|
||||
local.release(&retained.scope, &key.instance);
|
||||
retained.controller.lifecycle(&LifecycleEvent::DestroyOwner);
|
||||
}
|
||||
native.commit(&effects);
|
||||
self.controllers.clear();
|
||||
self.destroyed = true;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,657 @@
|
||||
//! Bounded, explicitly enabled synthetic content in the real SolveApp host.
|
||||
//! This is an evidence seam, never a production registration or saved preference.
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::collections::BTreeMap;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use solidcraft_engine::Session;
|
||||
use solidcraft_engine::panels::*;
|
||||
|
||||
use super::*;
|
||||
|
||||
const WORKSPACE: &str = "panel_fixture.workspace";
|
||||
const INSPECT: &str = "panel_fixture.inspect";
|
||||
const PRESETS: &[&str] = &["docks", "tabs", "collapsed", "floating", "overflow", "pinned", "columns", "stack_tabs", "content_fill", "inline"];
|
||||
type SpecimenIdentities = Rc<RefCell<BTreeMap<ControllerKey, Rc<()>>>>;
|
||||
|
||||
fn preset(value: &str) -> PanelResult<()> {
|
||||
if PRESETS.contains(&value) { Ok(()) } else { Err(error(Rule::Schema, "unknown synthetic panel preset")) }
|
||||
}
|
||||
|
||||
/// The caller explicitly opts into original synthetic content at the actual
|
||||
/// workspace composition point. An existing runtime is never replaced.
|
||||
pub fn enable_host_specimen(app: &mut crate::SolveApp, name: &str) -> PanelResult<()> {
|
||||
preset(name)?;
|
||||
if app.panel_runtime().is_some() {
|
||||
return Err(error(Rule::Lifecycle, "panel specimen cannot take over an existing runtime"));
|
||||
}
|
||||
let (layout, registry) = specimen_layout(name)?;
|
||||
let instances = layout.instances.clone();
|
||||
let service = LayoutService::new(registry, layout, HostCapabilities::default())?;
|
||||
let mut runtime = PanelRuntime::new(
|
||||
service,
|
||||
RuntimeEnvironment {
|
||||
workspace: WorkspaceId::new(WORKSPACE)?,
|
||||
document: Some(DocumentId::new(app.session.document_id.clone())?),
|
||||
window: HostId::new("panel_fixture.window")?,
|
||||
viewport: ViewportId::new("panel_fixture.viewport")?,
|
||||
direction: if crate::bidi::has_rtl(app.tr("ui.panel_fixture.caption")) { Direction::Rtl } else { Direction::Ltr },
|
||||
motion: Motion::Animated,
|
||||
},
|
||||
)?;
|
||||
let probe = FixtureProbe::default();
|
||||
let identities = SpecimenIdentities::default();
|
||||
for (kind, editor, ownership) in [
|
||||
("fixture.editor", true, Ownership::Document),
|
||||
("fixture.log", false, Ownership::Workspace),
|
||||
("fixture.fill", false, Ownership::Workspace),
|
||||
("fixture.pin", false, Ownership::Workspace),
|
||||
] {
|
||||
let binding = fixture_controller_binding(&probe, editor, ownership);
|
||||
let create = binding.create;
|
||||
let visible_probe = probe.clone();
|
||||
let visible_identities = identities.clone();
|
||||
runtime.register(
|
||||
PanelKind::new(kind)?,
|
||||
ControllerBinding {
|
||||
ownership,
|
||||
create: Box::new(move |instance, owner| {
|
||||
let inner = create(instance, owner)?;
|
||||
Ok(Box::new(VisibleSpecimen {
|
||||
inner,
|
||||
probe: visible_probe.clone(),
|
||||
identities: visible_identities.clone(),
|
||||
identity: Rc::new(()),
|
||||
key: ControllerKey { instance: instance.id.clone(), owner: owner.clone() },
|
||||
editor,
|
||||
title_key: if editor {
|
||||
"ui.panel_fixture.editor"
|
||||
} else if instance.kind.0 == "fixture.fill" {
|
||||
"ui.panel_fixture.fill"
|
||||
} else if instance.kind.0 == "fixture.pin" {
|
||||
"ui.panel_fixture.pin"
|
||||
} else {
|
||||
"ui.panel_fixture.log"
|
||||
},
|
||||
}))
|
||||
}),
|
||||
},
|
||||
)?;
|
||||
}
|
||||
let calls = Rc::new(Cell::new(0));
|
||||
let services = SpecimenServices {
|
||||
models: SpecimenModels { name: name.into(), probe, identities, instances, calls: calls.clone() },
|
||||
commands: SpecimenCommands { calls },
|
||||
local: FakeLocalServices::default(),
|
||||
};
|
||||
// Stage the complete integration before publishing it. Factories, the first
|
||||
// service tick and host option validation may all fail without taking over
|
||||
// the app or leaving a partially enabled specimen behind.
|
||||
let mut integration = AppPanelRuntime::new(runtime, Box::new(services))?;
|
||||
integration.tick(&app.session)?;
|
||||
integration.enable_host(HostOptions::default())?;
|
||||
app.panel_runtime = Some(integration);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn specimen_layout(name: &str) -> PanelResult<(Layout, PanelRegistry)> {
|
||||
let mut registry = PanelRegistry::default();
|
||||
for (kind, title, pinned, fill, editor) in [
|
||||
("fixture.editor", "ui.panel_fixture.editor", false, false, true),
|
||||
("fixture.log", "ui.panel_fixture.log", false, false, false),
|
||||
("fixture.fill", "ui.panel_fixture.fill", false, true, false),
|
||||
("fixture.pin", "ui.panel_fixture.pin", true, false, false),
|
||||
] {
|
||||
let mut allowed_zones = [Zone::Left, Zone::Right, Zone::Bottom, Zone::Floating].into_iter().collect::<std::collections::BTreeSet<_>>();
|
||||
if pinned {
|
||||
allowed_zones.remove(&Zone::Bottom);
|
||||
}
|
||||
registry.register(PanelSpec {
|
||||
kind: PanelKind::new(kind)?,
|
||||
title_key: title.into(),
|
||||
icon: "list".into(),
|
||||
allowed_zones,
|
||||
default_zone: Zone::Left,
|
||||
min_size: Size { width: 240.0, height: if editor { 120.0 } else { 40.0 } },
|
||||
default_size: Size { width: 280.0, height: 240.0 },
|
||||
max_size: Size { width: MAX_LOGICAL, height: 1200.0 },
|
||||
edge_rule: if pinned { EdgeRule::PinOuter } else { EdgeRule::None },
|
||||
surface: PanelSurface::FollowZone,
|
||||
features: PanelFeatures { multi_instance: !editor, popout: false, hot_closable: editor, ..PanelFeatures::default() },
|
||||
side_height_policy: if fill { SideHeightPolicy::Fill } else { SideHeightPolicy::Content },
|
||||
header_actions: if editor {
|
||||
vec![HeaderActionSpec { id: ControlId::new("apply")?, label_key: "ui.panel_fixture.apply".into(), icon: "list".into() }]
|
||||
} else {
|
||||
Vec::new()
|
||||
},
|
||||
text_heavy: editor,
|
||||
})?;
|
||||
}
|
||||
let mut layout = Layout::empty(WorkspaceId::new(WORKSPACE)?);
|
||||
let count = if name == "overflow" {
|
||||
24
|
||||
} else if name == "columns" {
|
||||
3
|
||||
} else if name == "content_fill" {
|
||||
2
|
||||
} else if name == "inline" {
|
||||
1
|
||||
} else {
|
||||
4
|
||||
};
|
||||
for index in 0..count {
|
||||
let id = InstanceId::new(format!("specimen-{index}"))?;
|
||||
let kind = if name == "inline" {
|
||||
"fixture.log"
|
||||
} else if name == "content_fill" && index == 1 {
|
||||
"fixture.fill"
|
||||
} else if name == "pinned" && index == 1 {
|
||||
"fixture.pin"
|
||||
} else if index == 0 {
|
||||
"fixture.editor"
|
||||
} else {
|
||||
"fixture.log"
|
||||
};
|
||||
let zone = if name == "inline" {
|
||||
Zone::Bottom
|
||||
} else if matches!(name, "columns" | "stack_tabs") {
|
||||
Zone::Left
|
||||
} else if name == "content_fill" {
|
||||
if index == 0 { Zone::Left } else { Zone::Right }
|
||||
} else {
|
||||
match index % 3 {
|
||||
0 => Zone::Left,
|
||||
1 => Zone::Right,
|
||||
_ => Zone::Bottom,
|
||||
}
|
||||
};
|
||||
let location = if name == "floating" {
|
||||
SectionLocation::Floating { origin: Point { x: 48.0 + index as f32 * 64.0, y: 48.0 + index as f32 * 48.0 } }
|
||||
} else {
|
||||
SectionLocation::Dock { zone }
|
||||
};
|
||||
let group = if name == "tabs" {
|
||||
index % 2
|
||||
} else if name == "stack_tabs" && index == 3 {
|
||||
1
|
||||
} else {
|
||||
index
|
||||
};
|
||||
let section_id = SectionId::new(format!("specimen-section-{group}"))?;
|
||||
let column = if location.zone().side() {
|
||||
Some(ColumnId::new(if name == "columns" {
|
||||
format!("specimen-column-{index}")
|
||||
} else {
|
||||
format!("specimen-column-{}", if zone == Zone::Left { "left" } else { "right" })
|
||||
})?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let size = if name == "inline" { Size { width: 760.0, height: 64.0 } } else { Size { width: 280.0, height: 240.0 } };
|
||||
let collapsed = name == "collapsed";
|
||||
let (location, column, collapsed, tab_index) = if let Some(section) = layout.sections.iter_mut().find(|section| section.id == section_id) {
|
||||
let tab_index = section.tabs.len();
|
||||
section.tabs.push(id.clone());
|
||||
(section.location.clone(), section.column.clone(), section.collapsed, tab_index)
|
||||
} else {
|
||||
if let Some(column) = &column
|
||||
&& !layout.columns.iter().any(|existing| existing.id == *column)
|
||||
{
|
||||
layout.columns.push(Column { id: column.clone(), zone, width: size.width });
|
||||
}
|
||||
layout.sections.push(Section {
|
||||
id: section_id.clone(),
|
||||
location: location.clone(),
|
||||
column: column.clone(),
|
||||
weight: 1.0,
|
||||
preferred_extent: None,
|
||||
extent_priority: 0,
|
||||
tabs: vec![id.clone()],
|
||||
active: id.clone(),
|
||||
size,
|
||||
collapsed,
|
||||
});
|
||||
(location, column, collapsed, 0)
|
||||
};
|
||||
let column_index = layout
|
||||
.columns
|
||||
.iter()
|
||||
.filter(|existing| existing.zone == location.zone())
|
||||
.position(|existing| Some(&existing.id) == column.as_ref())
|
||||
.unwrap_or(0);
|
||||
layout.instances.push(PanelInstance {
|
||||
id,
|
||||
kind: PanelKind::new(kind)?,
|
||||
requested_open: true,
|
||||
memory: PlacementMemory {
|
||||
section: section_id,
|
||||
location,
|
||||
section_index: group,
|
||||
tab_index,
|
||||
size,
|
||||
collapsed,
|
||||
column: column.clone(),
|
||||
column_index,
|
||||
column_width: column.map(|_| size.width),
|
||||
weight: 1.0,
|
||||
preferred_extent: None,
|
||||
extent_priority: 0,
|
||||
},
|
||||
});
|
||||
}
|
||||
// Columns own contiguous section runs even when fixture creation interleaves
|
||||
// logical zones. This ordering is independent of instance identity.
|
||||
layout.sections.sort_by_key(|section| {
|
||||
section.column.as_ref().and_then(|id| layout.columns.iter().position(|column| column.id == *id)).unwrap_or(MAX_SECTIONS)
|
||||
});
|
||||
for (section_index, section) in layout.sections.iter().enumerate() {
|
||||
for (tab_index, id) in section.tabs.iter().enumerate() {
|
||||
if let Some(instance) = layout.instances.iter_mut().find(|instance| instance.id == *id) {
|
||||
instance.memory.section_index = section_index;
|
||||
instance.memory.tab_index = tab_index;
|
||||
}
|
||||
}
|
||||
}
|
||||
validate(&layout, ®istry)?;
|
||||
Ok((layout, registry))
|
||||
}
|
||||
struct VisibleSpecimen {
|
||||
inner: Box<dyn PanelController>,
|
||||
probe: FixtureProbe,
|
||||
identities: SpecimenIdentities,
|
||||
identity: Rc<()>,
|
||||
key: ControllerKey,
|
||||
editor: bool,
|
||||
title_key: &'static str,
|
||||
}
|
||||
impl PanelController for VisibleSpecimen {
|
||||
fn availability(&self, owner: &ContentOwner, models: &dyn PanelModels) -> Availability {
|
||||
self.inner.availability(owner, models)
|
||||
}
|
||||
fn update(&mut self, owner: &ContentOwner, services: &mut ContentServices<'_>) -> PanelResult<()> {
|
||||
self.inner.update(owner, services)?;
|
||||
// Publish only from a live update, never from a staged factory. Keeping
|
||||
// the token until teardown also prevents address reuse in evidence.
|
||||
let mut identities = self.identities.try_borrow_mut().map_err(|_| error(Rule::Lifecycle, "specimen identity probe borrowed"))?;
|
||||
if identities.len() >= MAX_RETAINED_CONTROLLERS && !identities.contains_key(&self.key) {
|
||||
return Err(error(Rule::CollectionLimit, "specimen identity probe cap"));
|
||||
}
|
||||
identities.insert(self.key.clone(), self.identity.clone());
|
||||
Ok(())
|
||||
}
|
||||
fn presentation(&self) -> PanelPresentation {
|
||||
let snapshot = self.probe.state(&self.key).ok();
|
||||
PanelPresentation {
|
||||
title: crate::i18n::format("ui.panel_fixture.title", &[("title", crate::i18n::tr(self.title_key)), ("id", &self.key.instance.0)]),
|
||||
icon: "list".into(),
|
||||
status: snapshot.map(|state| crate::i18n::format("ui.panel_fixture.updates", &[("count", &state.updates.to_string())])),
|
||||
attention: self.editor,
|
||||
actions: if self.editor {
|
||||
[("apply", "ui.panel_fixture.apply"), ("cancel", "ui.panel_fixture.cancel"), ("finish", "ui.panel_fixture.finish")]
|
||||
.into_iter()
|
||||
.map(|(id, key)| RuntimeAction {
|
||||
id: ControlId(id.into()),
|
||||
label: crate::i18n::tr(key).into(),
|
||||
enabled: true,
|
||||
disabled_reason: None,
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
},
|
||||
}
|
||||
}
|
||||
fn measure(&self, _owner: &ContentOwner, _models: &dyn PanelModels, spec: &PanelSpec) -> PanelResult<Arc<dyn HostContentMetrics>> {
|
||||
let t = crate::theme::Tokens::get();
|
||||
let rows = if self.editor { 7.0 } else { 5.0 };
|
||||
Ok(Arc::new(SpecimenMetrics {
|
||||
// The actual body below uses fixed-height truncated labels and a
|
||||
// three-row editor. No hidden renderer or draft enumeration needed.
|
||||
body_height: rows * t.control_height + (rows - 1.0) * t.space_4 + 2.0 * t.space_2,
|
||||
policy: spec.side_height_policy,
|
||||
}))
|
||||
}
|
||||
fn prepare_lifecycle(&self, event: &LifecycleEvent) -> PanelResult<()> {
|
||||
self.inner.prepare_lifecycle(event)
|
||||
}
|
||||
fn lifecycle(&mut self, event: &LifecycleEvent) {
|
||||
self.inner.lifecycle(event);
|
||||
}
|
||||
fn render(&mut self, slot: ContentSlot, ui: &mut egui::Ui, context: &PanelContext, services: &mut ContentServices<'_>) -> PanelResult<()> {
|
||||
self.inner.render(slot, ui, context, services)?;
|
||||
match slot {
|
||||
ContentSlot::Header => {
|
||||
ui.label(crate::i18n::tr("ui.panel_fixture.caption"));
|
||||
}
|
||||
ContentSlot::Body => {
|
||||
// Content owns its scrolling; the host still clips all three slots.
|
||||
let mut result = Ok(());
|
||||
egui::ScrollArea::vertical().id_salt(("specimen-body", &self.key.instance.0)).show(ui, |ui| {
|
||||
result = self.probe.edit(&self.key, |state| {
|
||||
let t = crate::theme::Tokens::get();
|
||||
ui.spacing_mut().item_spacing.y = t.space_4;
|
||||
ui.spacing_mut().interact_size.y = t.control_height;
|
||||
ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate);
|
||||
ui.add_sized(
|
||||
[ui.available_width(), t.control_height],
|
||||
egui::Label::new(crate::i18n::tr("ui.panel_fixture.explanation")).truncate(),
|
||||
);
|
||||
let draft_label = crate::i18n::tr("ui.panel_fixture.draft");
|
||||
let label = ui.add_sized([ui.available_width(), t.control_height], egui::Label::new(draft_label).truncate());
|
||||
let draft_id = egui::Id::unique(("specimen-draft", &context.instance, &context.owner));
|
||||
let edit = crate::ui_kit::text_area(ui, draft_label, draft_id, &mut state.draft, 3, 1024);
|
||||
let _ = edit.labelled_by(label.id);
|
||||
if self.editor {
|
||||
crate::ui_kit::checkbox(ui, crate::i18n::tr("ui.panel_fixture.guard"), &mut state.reject_cancel);
|
||||
ui.add_sized(
|
||||
[ui.available_width(), t.control_height],
|
||||
egui::Label::new(crate::i18n::tr(if state.transaction_live {
|
||||
"ui.panel_fixture.live"
|
||||
} else {
|
||||
"ui.panel_fixture.finished"
|
||||
}))
|
||||
.truncate(),
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
result?;
|
||||
}
|
||||
ContentSlot::Footer => {
|
||||
ui.label(crate::i18n::tr("ui.panel_fixture.footer"));
|
||||
}
|
||||
ContentSlot::Inline => {
|
||||
self.render_inline(ui, context, services)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn action(&mut self, owner: &ContentOwner, action: &ControlId, services: &mut ContentServices<'_>) -> PanelResult<()> {
|
||||
self.inner.action(owner, action, services)
|
||||
}
|
||||
fn render_inline(&mut self, ui: &mut egui::Ui, context: &PanelContext, services: &mut ContentServices<'_>) -> PanelResult<()> {
|
||||
self.inner.render(ContentSlot::Body, ui, context, services)?;
|
||||
self.probe.edit(&self.key, |state| {
|
||||
// A real editable synthetic value occupies the same total row as
|
||||
// shared actions. This is not a production History timeline.
|
||||
ui.horizontal_centered(|ui| {
|
||||
ui.add(egui::Label::new(crate::i18n::tr("ui.panel_fixture.inline")).truncate());
|
||||
let id = egui::Id::unique(("specimen-draft", &context.instance, &context.owner));
|
||||
crate::ui_kit::cell_editor(ui, id, &mut state.draft, crate::i18n::tr("ui.panel_fixture.draft"), false);
|
||||
});
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct SpecimenMetrics {
|
||||
body_height: f32,
|
||||
policy: SideHeightPolicy,
|
||||
}
|
||||
impl HostContentMetrics for SpecimenMetrics {
|
||||
fn measure(&self, request: &ContentMeasureRequest) -> PanelResult<SideContentMeasure> {
|
||||
Ok(SideContentMeasure { request: request.clone(), needed_height: request.chrome_height + self.body_height, policy: self.policy })
|
||||
}
|
||||
fn revision(&self) -> u64 {
|
||||
u64::from(self.body_height.to_bits()) * 2 + u64::from(self.policy == SideHeightPolicy::Fill)
|
||||
}
|
||||
}
|
||||
|
||||
struct SpecimenModels {
|
||||
name: String,
|
||||
probe: FixtureProbe,
|
||||
identities: SpecimenIdentities,
|
||||
instances: Vec<PanelInstance>,
|
||||
calls: Rc<Cell<u64>>,
|
||||
}
|
||||
impl PanelModels for SpecimenModels {
|
||||
fn read(&self, _owner: &ContentOwner, key: &str) -> PanelResult<Value> {
|
||||
if key == "fixture.editable" {
|
||||
return Ok(json!(true));
|
||||
}
|
||||
if key != INSPECT {
|
||||
return Err(error(Rule::MissingTarget, "unknown specimen model read"));
|
||||
}
|
||||
let mut states = Vec::new();
|
||||
let identities = self.identities.try_borrow().map_err(|_| error(Rule::Lifecycle, "specimen identity probe borrowed"))?;
|
||||
for (key, identity) in identities.iter() {
|
||||
let state = self.probe.state(key)?;
|
||||
states.push(json!({
|
||||
"instance": key.instance, "owner": owner_observation(&key.owner),
|
||||
"controller_identity":format!("{:p}", Rc::as_ptr(identity)),
|
||||
"updates": state.updates, "renders": state.renders, "cancels": state.cancels,
|
||||
"reopens": state.reopens, "applies": state.applies, "finishes": state.finishes, "pulses":state.pulses,
|
||||
"reparents": state.reparents, "destroys": state.destroys, "draft": state.draft,
|
||||
"transaction_live": state.transaction_live, "reject_cancel": state.reject_cancel,
|
||||
"state": state.last_state.map(|s| json!({"open":s.requested_open,"presented":s.presented,"activated":s.activated,"destroyed":s.destroyed})),
|
||||
"last_clip": state.last_clip.map(|r| [r.min.x,r.min.y,r.max.x,r.max.y]),
|
||||
}));
|
||||
}
|
||||
Ok(json!({"preset":self.name,"controllers":states,"content_command_calls":self.calls.get()}))
|
||||
}
|
||||
}
|
||||
|
||||
struct SpecimenCommands {
|
||||
calls: Rc<Cell<u64>>,
|
||||
}
|
||||
impl ContentCommandSink for SpecimenCommands {
|
||||
fn execute(&mut self, _owner: &ContentOwner, command: &str, input: Value) -> PanelResult<Value> {
|
||||
if !matches!(command, "fixture.apply" | "fixture.finish") {
|
||||
return Err(error(Rule::MissingTarget, "unknown specimen content action"));
|
||||
}
|
||||
bounded_json(&input)?;
|
||||
self.calls.set(self.calls.get().saturating_add(1));
|
||||
// Explicit synthetic actions record calls; they never execute a Session command.
|
||||
Ok(Value::Null)
|
||||
}
|
||||
}
|
||||
|
||||
struct SpecimenServices {
|
||||
models: SpecimenModels,
|
||||
commands: SpecimenCommands,
|
||||
local: FakeLocalServices,
|
||||
}
|
||||
impl AppPanelServices for SpecimenServices {
|
||||
fn refresh_read_only(&mut self, session: &Session) -> PanelResult<()> {
|
||||
let document = DocumentId::new(session.document_id.clone())?;
|
||||
let scope =
|
||||
LocalScope { workspace: WorkspaceId::new(WORKSPACE)?, document: Some(document), viewport: ViewportId::new("panel_fixture.viewport")? };
|
||||
for instance in &self.models.instances {
|
||||
self.local.bind(instance.id.clone(), scope.clone())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn services(&mut self) -> ContentServices<'_> {
|
||||
ContentServices { models: &self.models, commands: &mut self.commands, local: &mut self.local }
|
||||
}
|
||||
}
|
||||
|
||||
/// Read-only observations from the current Session. Pointer strings are opaque
|
||||
/// process-local equality tokens, not stable IDs. No meshing/evaluation is called.
|
||||
/// The live-model counter excludes trial evaluations of cloned models.
|
||||
fn session_observation(app: &crate::SolveApp) -> Value {
|
||||
let session = &app.session;
|
||||
let state = session.model.state();
|
||||
let meshes: Vec<_> = state.bodies.iter().take(128).map(|body| body.cached_mesh().map(|mesh| format!("{:p}", Arc::as_ptr(&mesh)))).collect();
|
||||
json!({
|
||||
"document_id":session.document_id,"uid":session.uid,"revision":session.revision,
|
||||
"dirty":session.is_dirty(),"undo_depth":session.undo.len(),"redo_depth":session.redo.len(),
|
||||
"document_identity":format!("{:p}", Arc::as_ptr(&session.doc)),
|
||||
"model_identity":format!("{:p}", Arc::as_ptr(&state)),
|
||||
"cache_identity":format!("{:p}", Arc::as_ptr(&session.model.cache)),
|
||||
"recomputed":session.model.recomputed,"last_recomputed":session.model.last_recomputed,
|
||||
"cached_mesh_identities":meshes,"body_count":state.bodies.len(),"mesh_sample_limit":128,
|
||||
"camera":app.cam,"evaluation_count":session.evaluation_count(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Authenticated control transport and scenarios share this explicit opt-in.
|
||||
/// An empty object inspects without ticking services or dispatching layout/model actions.
|
||||
pub(crate) fn control_specimen(app: &mut crate::SolveApp, params: &Value) -> Result<Value, String> {
|
||||
let object = params.as_object().ok_or("panel_fixture params must be an object")?;
|
||||
if object.keys().any(|key| !matches!(key.as_str(), "enabled" | "preset")) {
|
||||
return Err("unknown panel_fixture parameter".into());
|
||||
}
|
||||
let enabled = object.get("enabled").map(|v| v.as_bool().ok_or("enabled must be a boolean")).transpose()?;
|
||||
let name = object.get("preset").map(|v| v.as_str().ok_or("preset must be a string")).transpose()?;
|
||||
if let Some(name) = name {
|
||||
preset(name).map_err(|e| e.to_string())?;
|
||||
}
|
||||
if enabled == Some(false) && name.is_some() {
|
||||
return Err("preset cannot be combined with enabled=false".into());
|
||||
}
|
||||
if enabled == Some(true) || name.is_some() {
|
||||
enable_host_specimen(app, name.unwrap_or("docks")).map_err(|e| e.to_string())?;
|
||||
}
|
||||
let owns_runtime = app.panel_runtime().is_some_and(|runtime| runtime.environment().workspace.0 == WORKSPACE);
|
||||
if enabled == Some(false) && app.panel_runtime().is_some() {
|
||||
if !owns_runtime {
|
||||
return Err("panel specimen cannot tear down another runtime".into());
|
||||
}
|
||||
// The workspace marker alone never authorizes teardown of injected
|
||||
// content: the retained specimen provider must also identify itself.
|
||||
app.panel_runtime_mut()
|
||||
.ok_or("panel specimen runtime disappeared")?
|
||||
.with_services(|_, services| services.models.read(&ContentOwner::Application, INSPECT))
|
||||
.map_err(|e| e.to_string())?;
|
||||
// Runtime shutdown preflights every controller before destroying any.
|
||||
// B's app integration also releases its host after successful shutdown.
|
||||
app.disable_panel_runtime().map_err(|e| e.to_string())?;
|
||||
}
|
||||
inspect_host_specimen(app).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Observe the current host, synthetic probe and actual Session without a tick,
|
||||
/// action dispatch, geometry evaluation or cold mesh creation.
|
||||
pub fn inspect_host_specimen(app: &mut crate::SolveApp) -> PanelResult<Value> {
|
||||
let owns_runtime = app.panel_runtime().is_some_and(|runtime| runtime.environment().workspace.0 == WORKSPACE);
|
||||
let mut reply = json!({"enabled":false,"session":session_observation(app),"host":host_observation(app),
|
||||
"effective_usable":app.viewport.layout.as_ref().and_then(|layout| layout.usable.as_ref()).map(|usable|
|
||||
json!({"domain":&usable.domain,"obstacles":&usable.obstacles,"free":&usable.free}))});
|
||||
if owns_runtime {
|
||||
let integration = app.panel_runtime_mut().ok_or_else(|| error(Rule::Lifecycle, "panel specimen runtime disappeared"))?;
|
||||
let probe = integration.with_services(|runtime, services| {
|
||||
let probe = services.models.read(&ContentOwner::Application, INSPECT)?;
|
||||
Ok(json!({"probe":probe,"layout":runtime.layout().inspect(),"controller_count":runtime.controller_count()}))
|
||||
})?;
|
||||
reply["enabled"] = json!(app.universal_panel_host_enabled());
|
||||
reply["runtime"] = probe;
|
||||
}
|
||||
Ok(reply)
|
||||
}
|
||||
|
||||
fn host_observation(app: &crate::SolveApp) -> Value {
|
||||
let Some(frame) = app.universal_panel_frame() else {
|
||||
return Value::Null;
|
||||
};
|
||||
let controls: Vec<_> = frame
|
||||
.controls
|
||||
.iter()
|
||||
.map(|control| {
|
||||
json!({
|
||||
"id":format!("{:016x}",control.id.value()), "target":target_observation(&control.target),
|
||||
"bounds":control.bounds,"role":control.role,
|
||||
"accessible_name":control.accessible_name,"enabled":control.enabled,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let layout = &frame.layout;
|
||||
let sections: Vec<_> = layout
|
||||
.sections
|
||||
.iter()
|
||||
.map(|section| {
|
||||
json!({
|
||||
"section":section.section,"instance":section.instance,"zone":section.zone,
|
||||
"outer":section.outer,"header":section.header,"body":section.body,"footer":section.footer,
|
||||
"collapsed":section.collapsed,"inline":section.inline,"surface":section.surface,"paint_alpha":section.paint_alpha,"hidden_tabs":section.hidden_tabs,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let overflow: Vec<_> =
|
||||
layout.overflow.iter().map(|entry| json!({"zone":entry.zone,"sections":entry.sections,"tabs":entry.tabs,"bounds":entry.bounds})).collect();
|
||||
let events: Vec<_> = frame
|
||||
.events
|
||||
.iter()
|
||||
.map(|event| match event {
|
||||
HostEvent::Regions { scope, revision, painted, input, occlusion, reservations } => json!({
|
||||
"type":"regions","scope":{"workspace":scope.workspace,"document":scope.document,"viewport":scope.viewport},
|
||||
"revision":revision,"painted":painted,"input":input,"occlusion":occlusion,"reservations":reservations,
|
||||
}),
|
||||
HostEvent::Committed { action, reply } => json!({"type":"committed","action":action,"reply":reply}),
|
||||
HostEvent::PreparedCommitted { reply } => json!({"type":"prepared_committed","reply":reply}),
|
||||
HostEvent::Rejected { action, error } => json!({"type":"rejected","action":action,"error":error}),
|
||||
HostEvent::ContentAction { instance, action, result } => {
|
||||
json!({"type":"content_action","instance":instance,"action":action,"result":result})
|
||||
}
|
||||
HostEvent::Focus { target } => json!({"type":"focus","target":target_observation(target)}),
|
||||
})
|
||||
.collect();
|
||||
json!({
|
||||
"controls":controls,"sections":sections,"overflow":overflow,"resolved":layout.resolved,"events":events,
|
||||
"capacity":layout.capacity,"viewport":layout.viewport,"extent":layout.extent,"scroll":layout.allocation_environment.scroll,"revision":layout.revision,"direction":layout.direction,
|
||||
"render_domain":layout.render_domain,"chrome_obstacles":layout.chrome_obstacles,
|
||||
"usable":{"domain":layout.usable.domain,"obstacles":layout.usable.obstacles,"free":layout.usable.free},
|
||||
"painted":layout.painted,"input":layout.input,"occlusion":layout.occlusion,"reservations":layout.reservations,
|
||||
"menu_bounds":frame.menu_bounds,
|
||||
"preview":frame.preview.as_ref().map(|preview| json!({"action":preview.action,"bounds":preview.bounds,"destination":preview.destination,"rejection":preview.rejection,
|
||||
"target":preview.target.as_ref().map(drop_target_observation),"targets":preview.targets.iter().map(|target| json!({"id":drop_target_observation(&target.id),"bounds":target.bounds,"destination":target.destination,"rejection":target.rejection})).collect::<Vec<_>>(),
|
||||
"tab_marker":preview.tab_marker,"projected":preview.projected.as_ref().map(|projected| json!({"sections":projected.sections.iter().map(|section| json!({"section":section.section,"instance":section.instance,"outer":section.outer,"body":section.body})).collect::<Vec<_>>(),"resolved":projected.resolved}))})),
|
||||
"reply":frame.reply,
|
||||
})
|
||||
}
|
||||
|
||||
fn drop_target_observation(target: &HostDropTargetId) -> Value {
|
||||
match target {
|
||||
HostDropTargetId::Dock { zone, before } => json!({"type":"dock","zone":zone,"before":before}),
|
||||
HostDropTargetId::Tab { section, before } => json!({"type":"tab","section":section,"before":before}),
|
||||
HostDropTargetId::Relative { section, placement } => json!({"type":"relative","section":section,"placement":placement}),
|
||||
}
|
||||
}
|
||||
|
||||
fn owner_observation(owner: &ContentOwner) -> Value {
|
||||
match owner {
|
||||
ContentOwner::Application => json!({"type":"application"}),
|
||||
ContentOwner::Workspace(id) => json!({"type":"workspace","id":id}),
|
||||
ContentOwner::Document(id) => json!({"type":"document","id":id}),
|
||||
ContentOwner::Window(id) => json!({"type":"window","id":id}),
|
||||
}
|
||||
}
|
||||
|
||||
fn target_observation(target: &HostControlTarget) -> Value {
|
||||
match target {
|
||||
HostControlTarget::Pointer(pointer) => match pointer {
|
||||
HostPointerTarget::Header { instance } => json!({"type":"header","instance":instance}),
|
||||
HostPointerTarget::Tab { instance } => json!({"type":"tab","instance":instance}),
|
||||
HostPointerTarget::Collapse { instance } => json!({"type":"collapse","instance":instance}),
|
||||
HostPointerTarget::Close { instance } => json!({"type":"close","instance":instance}),
|
||||
HostPointerTarget::HeaderAction { instance, action } => json!({"type":"header_action","instance":instance,"action":action}),
|
||||
HostPointerTarget::Rail { instance } => json!({"type":"rail","instance":instance}),
|
||||
HostPointerTarget::Surface { instance } => json!({"type":"surface","instance":instance}),
|
||||
HostPointerTarget::Menu { instance } => json!({"type":"menu","instance":instance}),
|
||||
HostPointerTarget::TabOverflow { section } => json!({"type":"tab_overflow","section":section}),
|
||||
HostPointerTarget::Sash { first, second } => json!({"type":"sash","first":first,"second":second}),
|
||||
HostPointerTarget::Resize { section, edge } => json!({"type":"resize","section":section,"edge":match edge {
|
||||
HostResizeEdge::Left => "left", HostResizeEdge::Right => "right", HostResizeEdge::Top => "top",
|
||||
HostResizeEdge::Bottom => "bottom", HostResizeEdge::BottomRight => "bottom_right",
|
||||
}}),
|
||||
HostPointerTarget::Overflow { zone } => json!({"type":"overflow","zone":zone}),
|
||||
HostPointerTarget::OverflowAll => json!({"type":"overflow_all"}),
|
||||
},
|
||||
HostControlTarget::Content { instance, action } => json!({"type":"content_action","instance":instance,"action":action}),
|
||||
HostControlTarget::PanelMenu { instance } => json!({"type":"panel_menu","instance":instance}),
|
||||
HostControlTarget::Scroll { horizontal } => json!({"type":"scroll","horizontal":horizontal}),
|
||||
HostControlTarget::Shared { instance, action } => {
|
||||
let action = match action {
|
||||
HostSharedAction::Focus => json!({"type":"focus"}),
|
||||
HostSharedAction::Close => json!({"type":"close"}),
|
||||
HostSharedAction::Collapse => json!({"type":"collapse"}),
|
||||
HostSharedAction::Move(zone) => json!({"type":"move","zone":zone}),
|
||||
HostSharedAction::Join(section) => json!({"type":"join","section":section}),
|
||||
HostSharedAction::Popout => json!({"type":"popout"}),
|
||||
};
|
||||
json!({"type":"shared_action","instance":instance,"action":action})
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+279
-178
@@ -31,6 +31,7 @@ mod mouse3d;
|
||||
mod navbar;
|
||||
mod navigation;
|
||||
mod sketch;
|
||||
mod theme_picker;
|
||||
mod tools;
|
||||
|
||||
use crate::SolveApp;
|
||||
@@ -1262,6 +1263,10 @@ preference_settings! {
|
||||
theme: String = "dark".into(), PAGE_APPEARANCE;
|
||||
/// A picture behind the model in place of the view's background; empty for none.
|
||||
background_image: String = String::new(), PAGE_APPEARANCE;
|
||||
/// Theme used when the operating system is light; unknown ids resolve to Light.
|
||||
theme_day: String = "light".into(), PAGE_APPEARANCE;
|
||||
/// Theme used when the operating system is dark; unknown ids resolve to Dark.
|
||||
theme_night: String = "dark".into(), PAGE_APPEARANCE;
|
||||
/// The 3D view's colours: the theme's own, or the Light or Dark theme's whatever the window
|
||||
/// uses (#4146).
|
||||
viewport_theme: crate::theme::ViewportTheme = crate::theme::ViewportTheme::Theme, PAGE_APPEARANCE;
|
||||
@@ -1435,6 +1440,9 @@ preference_settings! {
|
||||
/// How the offer is made for a file whose header names no program known to save Y up: a note
|
||||
/// over the view (the default), the dialog, or nothing (#7717).
|
||||
stand_up_unknown: StandUpUnknown = StandUpUnknown::default(), PAGE_DESIGN;
|
||||
/// Dragging Extrude's distance arrow stops at flat faces parallel to the profile over it and
|
||||
/// outlines them (`extrude_face_snap`, #2398). Off: the drag moves in round steps only.
|
||||
extrude_arrow_face_stops: bool = true, PAGE_TOOLS => check_id("prefs.extrude_arrow_face_stops");
|
||||
/// Extrude: with a profile picked, a face, vertex or parallel plane picked off its plane
|
||||
/// switches the extent to To Object (off: picks only add profiles, as before). A click into the
|
||||
/// Profiles box makes the next picks profiles again.
|
||||
@@ -1603,6 +1611,8 @@ preference_settings! {
|
||||
sketch_state_icons: bool = true, PAGE_SKETCH;
|
||||
/// Show the construction-line family in Sketch CREATE; off restores the earlier menu.
|
||||
sketch_construction_lines: bool = true, PAGE_SKETCH;
|
||||
/// Use the only straight construction line in the preselection as Mirror's reference.
|
||||
sketch_mirror_auto_line: bool = true, PAGE_SKETCH;
|
||||
/// A sketch tool's shortcut pressed again before the first point steps to the tool's next
|
||||
/// creation mode (#2459). Off (the default): the key starts the tool again, as it always has.
|
||||
shortcut_cycles_modes: bool = false, PAGE_SKETCH;
|
||||
@@ -1727,6 +1737,10 @@ pub struct PrefsWindow {
|
||||
applied_profile: Option<bool>,
|
||||
/// The appearance last asked of the native window ([`sync_window_theme`]).
|
||||
window_theme: Option<egui::SystemTheme>,
|
||||
/// Last observed OS tone, independent of the selected theme's tone.
|
||||
system_theme_dark: Option<bool>,
|
||||
/// Import callbacks fill the same slot as a card click; never persisted in preferences.
|
||||
theme_picker_night: bool,
|
||||
/// The perspective angle the view was last drawn with ([`follow_view_fov`]); 0 before the first.
|
||||
drawn_fov: f64,
|
||||
/// The search text of the interface font list.
|
||||
@@ -2016,151 +2030,10 @@ pub(crate) fn held_overlay(app: &SolveApp) -> Option<serde_json::Map<String, ser
|
||||
/// ones, with Import…, Export… (the theme on now as a complete file, to start a new one from)
|
||||
/// and Remove (an imported theme). Like the other preferences, a choice applies at once.
|
||||
fn theme_row(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
let mut choices = theme_choices(app);
|
||||
// While a file is followed (#7573) it is the theme, so no tile shows as chosen.
|
||||
let following = !app.prefs_window.follow.path(&app.preferences.theme_follow).is_empty();
|
||||
choices.sort_by_key(|(id, _)| match id.as_str() {
|
||||
"light" => 0,
|
||||
"dark" => 1,
|
||||
"system" => 2,
|
||||
_ => 3,
|
||||
});
|
||||
let mut tile_action: Option<(&str, String)> = None;
|
||||
let mut action_theme: Option<String> = None;
|
||||
let mut chosen: Option<String> = None;
|
||||
let mut action: Option<&str> = None;
|
||||
let mut import_tile = None;
|
||||
let t = Tokens::get();
|
||||
let width = t.space_24 * 3.0 + t.space_16;
|
||||
let height = t.space_24 * 4.0;
|
||||
let dark_sample = ui_kit::ThemeSample::from_tokens(&Tokens::dark());
|
||||
let carousel_id = "appearance_themes";
|
||||
// Reveal the active theme after a programmatic selection or import too.
|
||||
let selection_key = ui.make_persistent_id((carousel_id, "selection"));
|
||||
let carousel_key = ui.make_persistent_id(carousel_id);
|
||||
ui.data_mut(|data| {
|
||||
if data.get_temp::<String>(selection_key).as_deref() != Some(app.preferences.theme.as_str()) {
|
||||
let index = choices.iter().position(|(id, _)| id == &app.preferences.theme).unwrap_or(0);
|
||||
data.insert_temp(carousel_key, index.saturating_sub(1));
|
||||
data.insert_temp(selection_key, app.preferences.theme.clone());
|
||||
}
|
||||
});
|
||||
let mut item = |ui: &mut egui::Ui, index: usize| {
|
||||
if let Some((id, label)) = choices.get(index) {
|
||||
let palette = match id.as_str() {
|
||||
"light" | "system" => Tokens::light(),
|
||||
"dark" => Tokens::dark(),
|
||||
_ => crate::theme_files::find(id, &app.preferences.custom_themes)
|
||||
.map(|f| resolved_theme(&app.preferences, f))
|
||||
.unwrap_or_else(Tokens::dark),
|
||||
};
|
||||
let custom = app.preferences.custom_themes.iter().any(|t| t.id == *id);
|
||||
let note = app.tr(if id == "system" {
|
||||
"prefs.follows_os"
|
||||
} else if custom {
|
||||
"prefs.imported_file"
|
||||
} else {
|
||||
"prefs.built_in"
|
||||
});
|
||||
let options = crate::theme_files::find(id, &app.preferences.custom_themes)
|
||||
.is_some_and(|file| !crate::theme_options::offered(file, crate::theme_options::PROVIDERS).is_empty());
|
||||
if crate::prefs_search::querying(ui) && !crate::prefs_search::visible(ui, &[label, note]) {
|
||||
return;
|
||||
}
|
||||
let sample = ui_kit::ThemeSample::from_tokens(&palette);
|
||||
let response = ui_kit::picture_card(
|
||||
ui,
|
||||
&ui_kit::Card {
|
||||
label,
|
||||
sub: Some(note),
|
||||
selected: !following && app.preferences.theme == *id,
|
||||
enabled: true,
|
||||
options: options.then(|| app.tr("prefs.theme_options_badge")),
|
||||
check: false,
|
||||
aspect: 124.0 / 76.0,
|
||||
figure: &|p, rect| {
|
||||
if id == "system" {
|
||||
ui_kit::paint_theme_system(p, rect, &sample, &dark_sample);
|
||||
} else {
|
||||
ui_kit::paint_theme_thumbnail(p, rect, &sample);
|
||||
}
|
||||
},
|
||||
},
|
||||
width.min(ui.available_width()),
|
||||
);
|
||||
if options {
|
||||
crate::scenario::publish_rect(&format!("prefs:theme_options_badge:{id}"), response.rect);
|
||||
}
|
||||
crate::scenario::publish_target(&format!("prefs:theme_tile:{id}"), response.rect);
|
||||
crate::scenario::publish_target(&format!("prefs:theme:{id}"), response.rect);
|
||||
if !following && app.preferences.theme == *id {
|
||||
crate::scenario::publish_target("prefs:theme", response.rect);
|
||||
}
|
||||
if response.clicked() {
|
||||
chosen = Some(id.clone());
|
||||
}
|
||||
ui_kit::Menu::context(&response, |ui| {
|
||||
ui_kit::Menu::show(ui, Tokens::get().form_card_width, |ui| {
|
||||
if ui_kit::MenuItem::new("theme_export", app.tr_label("Export…"), "export").show(ui).clicked() {
|
||||
tile_action = Some(("export", id.clone()));
|
||||
ui.close();
|
||||
}
|
||||
if custom {
|
||||
let mut remove = ui_kit::MenuItem::new("theme_remove", app.tr_label("Remove"), "delete");
|
||||
remove.danger = true;
|
||||
if remove.show(ui).clicked() {
|
||||
tile_action = Some(("remove", id.clone()));
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
} else {
|
||||
let tile = ui_kit::theme_import_tile(ui, app.tr_label("Import…"), app.tr("prefs.theme_file"))
|
||||
.backing_on_hover_text(app.tr("prefs.theme_import_hint"));
|
||||
import_tile = Some(tile.rect);
|
||||
if tile.clicked() {
|
||||
action = Some("import");
|
||||
}
|
||||
// The keyboard's paste needs no menu; this is for touch screens and the browser's mouse users.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
ui_kit::Menu::context(&tile, |ui| {
|
||||
ui_kit::Menu::show(ui, Tokens::get().form_card_width, |ui| {
|
||||
if ui_kit::MenuItem::new("theme_paste", app.tr("prefs.theme_paste"), "paste").show(ui).clicked() {
|
||||
action = Some("paste");
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
};
|
||||
if crate::prefs_search::suppress_chrome(ui) {
|
||||
for index in 0..=choices.len() {
|
||||
item(ui, index);
|
||||
}
|
||||
} else {
|
||||
ui_kit::carousel(ui, carousel_id, choices.len() + 1, width, height, &mut item);
|
||||
for (label, handle, help) in [
|
||||
("prefs.carousel_previous", "prefs:theme_previous", "prefs.appearance.previous_themes"),
|
||||
("prefs.carousel_next", "prefs:theme_next", "prefs.appearance.next_themes"),
|
||||
] {
|
||||
if let Some(rect) = crate::scenario::rect_of(&format!("prefs:carousel:{}", crate::i18n::tr(label))) {
|
||||
crate::scenario::publish_target(handle, rect);
|
||||
ui.interact(rect, ui.make_persistent_id((handle, "help")), egui::Sense::hover()).backing_on_hover_text(app.tr(help));
|
||||
}
|
||||
}
|
||||
}
|
||||
app.prefs_window.import_tile = import_tile;
|
||||
if let Some((kind, id)) = tile_action {
|
||||
action = Some(kind);
|
||||
action_theme = Some(id);
|
||||
}
|
||||
if let Some(id) = chosen {
|
||||
// Choosing a theme stops following a file (#7573).
|
||||
stop_following(app);
|
||||
select_theme(app, &id);
|
||||
ui.data_mut(|data| data.insert_temp(selection_key, id));
|
||||
}
|
||||
theme_picker::row(app, ui);
|
||||
}
|
||||
|
||||
fn theme_action(app: &mut SolveApp, ui: &mut egui::Ui, action: Option<&str>, action_theme: Option<String>) {
|
||||
match action {
|
||||
Some("import") => app.pick_open_for(&["json"], |app, path| {
|
||||
let Some(path) = path else { return };
|
||||
@@ -2178,7 +2051,7 @@ fn theme_row(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
}
|
||||
}
|
||||
Some("export") => {
|
||||
let system_dark = system_dark(app, ui.ctx()).unwrap_or(app.ui.dark);
|
||||
let system_dark = system_dark(app, ui.ctx()).unwrap_or_else(|| app.prefs_window.system_theme_dark.unwrap_or(app.ui.dark));
|
||||
let file = theme_file(app, action_theme.as_deref().unwrap_or(&app.preferences.theme), system_dark);
|
||||
let name = file.get("name").and_then(serde_json::Value::as_str).unwrap_or("Theme").to_string();
|
||||
let text = serde_json::to_string_pretty(&file).unwrap_or_default();
|
||||
@@ -2410,10 +2283,11 @@ pub fn apply(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
up_axis_changed(app);
|
||||
}
|
||||
follow_view_fov(app);
|
||||
if app.preferences.theme == "system"
|
||||
&& let Some(dark) = system_dark(app, ctx)
|
||||
{
|
||||
app.ui.dark = dark;
|
||||
let os_dark = system_dark(app, ctx).unwrap_or_else(|| app.prefs_window.system_theme_dark.unwrap_or(app.ui.dark));
|
||||
app.prefs_window.system_theme_dark = Some(os_dark);
|
||||
if app.preferences.theme == "system" {
|
||||
let id = theme_picker::active_id(&app.preferences, os_dark);
|
||||
app.ui.dark = crate::theme_files::find(id, &app.preferences.custom_themes).map_or(id == "dark", |f| f.base.is_dark());
|
||||
}
|
||||
// A theme file's palette, in place of its base's (dark or light); the visuals follow. A
|
||||
// followed file (#7573) wins while it is followed and has read completely once.
|
||||
@@ -2425,7 +2299,9 @@ pub fn apply(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
if let Some(custom) = &custom {
|
||||
app.ui.dark = custom.dark;
|
||||
}
|
||||
let follows_system = app.preferences.theme == "system" && custom.is_none();
|
||||
// Custom Day/Night palettes still need native OS appearance notifications. Fixing
|
||||
// the native window to the slot's tone can stop those notifications on macOS.
|
||||
let follows_system = app.preferences.theme == "system" && followed_theme(&app.preferences, &app.prefs_window.follow).is_none();
|
||||
if crate::theme::set_custom(custom) {
|
||||
app.styled = false;
|
||||
}
|
||||
@@ -3429,9 +3305,15 @@ fn button_jobs_that_read<'de, D: serde::Deserializer<'de>>(
|
||||
/// Every theme the Theme list offers, as (id, name): the modes, the built-in theme files, then
|
||||
/// the imported ones.
|
||||
fn theme_choices(app: &SolveApp) -> Vec<(String, String)> {
|
||||
let modes = THEMES.iter().map(|(id, label)| ((*id).to_string(), crate::i18n::tr_label(label).to_string()));
|
||||
let modes = THEMES.iter().filter(|(id, _)| *id != "system").map(|(id, label)| ((*id).to_string(), crate::i18n::tr_label(label).to_string()));
|
||||
let files = crate::theme_files::builtin().iter().chain(&app.preferences.custom_themes).map(|t| (t.id.clone(), t.name.clone()));
|
||||
modes.chain(files).collect()
|
||||
let mut choices: Vec<_> = modes.chain(files).collect();
|
||||
choices.sort_by_key(|(id, _)| match id.as_str() {
|
||||
"light" => 0,
|
||||
"dark" => 1,
|
||||
_ => 2,
|
||||
});
|
||||
choices
|
||||
}
|
||||
|
||||
/// Turn a theme on (a mode or a theme file's id); dark follows it.
|
||||
@@ -3529,7 +3411,11 @@ pub fn import_theme(app: &mut SolveApp, v: &serde_json::Value) -> Result<String,
|
||||
other => crate::theme_files::from_value(other)?,
|
||||
};
|
||||
let id = crate::theme_files::add(&mut app.preferences.custom_themes, theme)?;
|
||||
select_theme(app, &id);
|
||||
if app.prefs_window.open && app.prefs_window.section == PAGE_APPEARANCE {
|
||||
theme_picker::choose(app, app.prefs_window.theme_picker_night, &id);
|
||||
} else {
|
||||
select_theme(app, &id);
|
||||
}
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
@@ -3550,13 +3436,17 @@ fn remove_theme(app: &mut SolveApp, id: &str) -> Result<(), String> {
|
||||
fn current_theme_file(app: &SolveApp) -> serde_json::Value {
|
||||
match active_theme_file(app) {
|
||||
Some(f) => export_theme_file(f),
|
||||
None => theme_file(app, &app.preferences.theme, app.ui.dark),
|
||||
None => theme_file(app, &app.preferences.theme, app.prefs_window.system_theme_dark.unwrap_or(app.ui.dark)),
|
||||
}
|
||||
}
|
||||
|
||||
fn active_theme_file(app: &SolveApp) -> Option<&crate::theme_files::ThemeFile> {
|
||||
followed_theme(&app.preferences, &app.prefs_window.follow)
|
||||
.or_else(|| crate::theme_files::find(&app.preferences.theme, &app.preferences.custom_themes))
|
||||
followed_theme(&app.preferences, &app.prefs_window.follow).or_else(|| {
|
||||
crate::theme_files::find(
|
||||
theme_picker::active_id(&app.preferences, app.prefs_window.system_theme_dark.unwrap_or(app.ui.dark)),
|
||||
&app.preferences.custom_themes,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// The single runtime decision used by controls, ui.prefs and renderer activation. It never
|
||||
@@ -3895,9 +3785,10 @@ fn theme_options_reply(app: &SolveApp) -> solidcraft_engine::schema::ui_prefs::T
|
||||
/// Export the tile the user chose, without applying it or changing the dialog snapshot.
|
||||
fn theme_file(app: &SolveApp, id: &str, system_dark: bool) -> serde_json::Value {
|
||||
use crate::theme_files::{Base, export, find};
|
||||
let id = if id == "system" { theme_picker::slot_id(&app.preferences, system_dark) } else { id };
|
||||
match find(id, &app.preferences.custom_themes) {
|
||||
Some(f) => export_theme_file(f),
|
||||
None if id == "dark" || (id == "system" && system_dark) => export("Dark", Base::Dark, &crate::theme::Tokens::dark()),
|
||||
None if id == "dark" => export("Dark", Base::Dark, &crate::theme::Tokens::dark()),
|
||||
None => export("Light", Base::Light, &crate::theme::Tokens::light()),
|
||||
}
|
||||
}
|
||||
@@ -4236,8 +4127,11 @@ pub(crate) fn reveal_preference(h: &mut crate::scenario::Harness, handle: &str)
|
||||
// Keep small scroll steps so a target cannot be skipped on a long Preferences page.
|
||||
for _ in 0..32 {
|
||||
let page = crate::scenario::rect_of("dialog:page_body").expect("preference body");
|
||||
// Scroll offsets are pixel-rounded: the final item can extend a fraction
|
||||
// of a point beyond the viewport even at the maximum scroll offset.
|
||||
// Match the tolerance used by the colour-vision sample geometry checks.
|
||||
let visible = crate::scenario::rect_of(handle)
|
||||
.map(|r| page.contains_rect(r))
|
||||
.map(|r| page.expand(1.0).contains_rect(r))
|
||||
.unwrap_or_else(|| crate::scenario::handle_at(handle).is_some_and(|p| page.shrink(crate::theme::Tokens::get().space_16).contains(p)));
|
||||
if visible {
|
||||
return;
|
||||
@@ -4261,6 +4155,217 @@ pub(crate) fn reveal_preference(h: &mut crate::scenario::Harness, handle: &str)
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn theme_traits_use_resolved_background_and_maximal_contrast() {
|
||||
use theme_picker::{Classification, theme_traits};
|
||||
let light = Tokens::light();
|
||||
let dark = Tokens::dark();
|
||||
assert_eq!(theme_traits(&light), Classification { dark: false, high: false });
|
||||
assert_eq!(theme_traits(&dark), Classification { dark: true, high: false });
|
||||
for (ground, ink, night) in [(egui::Color32::WHITE, egui::Color32::BLACK, false), (egui::Color32::BLACK, egui::Color32::WHITE, true)] {
|
||||
let mut palette = light;
|
||||
palette.dialog_footer = ground;
|
||||
palette.form_ink = ink;
|
||||
assert_eq!(theme_traits(&palette), Classification { dark: night, high: true });
|
||||
}
|
||||
let mut palette = light;
|
||||
for (gray, night) in [(187, true), (188, false)] {
|
||||
palette.dialog_footer = egui::Color32::from_gray(gray);
|
||||
assert_eq!(theme_traits(&palette).dark, night, "linear luminance straddles 0.5");
|
||||
}
|
||||
let maximal: Vec<_> = crate::theme_files::builtin()
|
||||
.iter()
|
||||
.filter(|f| theme_traits(&resolved_theme(&Prefs::default(), f)).high)
|
||||
.map(|f| f.id.as_str())
|
||||
.collect();
|
||||
assert_eq!(maximal.len(), 4, "ordinary palettes must stay Standard: {maximal:?}");
|
||||
assert!(maximal.contains(&"1-bit") && maximal.contains(&"1-bit-dark"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn theme_slots_default_persist_allow_command_access_and_restore_with_appearance() {
|
||||
let mut h = crate::scenario::Harness::new();
|
||||
assert_eq!((&h.app.preferences.theme_day[..], &h.app.preferences.theme_night[..]), ("light", "dark"));
|
||||
let out = super::set(&mut h.app, &json!({"theme_day":"akari", "theme_night":"onyx"})).unwrap();
|
||||
assert_eq!((out["theme_day"].as_str(), out["theme_night"].as_str()), (Some("akari"), Some("onyx")));
|
||||
let out = h.call("ui.prefs", json!({}));
|
||||
assert_eq!(out["result"]["theme_day"], "akari");
|
||||
assert_eq!(out["result"]["theme_night"], "onyx");
|
||||
let mut restored = SolveApp::new(solidcraft_engine::Session::default(), Default::default());
|
||||
restored.load_prefs(&h.app.prefs());
|
||||
assert_eq!((restored.preferences.theme_day.as_str(), restored.preferences.theme_night.as_str()), ("akari", "onyx"));
|
||||
h.call("ui.prefs", json!({"theme_day":"clay", "theme_night":"clay-dark", "open":"Appearance"}));
|
||||
assert_eq!(h.app.preferences.theme_day, "clay");
|
||||
defaults(&mut h.app, PAGE_GENERAL);
|
||||
assert_eq!(h.app.preferences.theme_day, "clay", "another page's reset does not clear slots");
|
||||
defaults(&mut h.app, PAGE_APPEARANCE);
|
||||
assert_eq!((h.app.preferences.theme_day.as_str(), h.app.preferences.theme_night.as_str()), ("light", "dark"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn theme_slots_resolve_unknown_and_recursive_ids_without_changing_saved_intent() {
|
||||
let mut prefs = Prefs { theme: "system".into(), theme_day: "missing".into(), theme_night: "system".into(), ..Default::default() };
|
||||
assert_eq!(theme_picker::active_id(&prefs, false), "light");
|
||||
assert_eq!(theme_picker::active_id(&prefs, true), "dark");
|
||||
assert_eq!((&prefs.theme_day[..], &prefs.theme_night[..]), ("missing", "system"));
|
||||
prefs.theme = "onyx".into();
|
||||
assert_eq!(theme_picker::active_id(&prefs, false), "onyx");
|
||||
assert_eq!(theme_picker::active_id(&prefs, true), "onyx");
|
||||
let mut h = crate::scenario::Harness::new();
|
||||
h.app.services.desktop_dark = Some(Box::new(|| Some(false)));
|
||||
let out = h.call("ui.prefs", json!({"theme":"system", "theme_day":"missing", "theme_night":"system"}));
|
||||
assert!(out["error"].is_null(), "{out}");
|
||||
h.frames(2);
|
||||
assert!(!h.app.ui.dark);
|
||||
assert_eq!(h.app.preferences.theme_day, "missing");
|
||||
h.app.services.desktop_dark = Some(Box::new(|| Some(true)));
|
||||
h.frames(2);
|
||||
assert!(h.app.ui.dark);
|
||||
assert_eq!(h.app.preferences.theme_night, "system");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn theme_onyx_is_reachable_selectable_and_shows_its_options_in_both_views() {
|
||||
for grid in [false, true] {
|
||||
let mut h = crate::scenario::Harness::new();
|
||||
h.app.home.open = false;
|
||||
h.call("ui.resize", json!({"width":1467,"height":1146}));
|
||||
h.call("ui.prefs", json!({"language":"en","theme":"light","open":"Appearance"}));
|
||||
h.frames(5);
|
||||
if grid {
|
||||
h.step(&json!({"click":{"handle":"prefs:theme_view:1"}})).unwrap();
|
||||
h.frames(3);
|
||||
super::reveal_preference(&mut h, "prefs:theme_tile:onyx");
|
||||
} else {
|
||||
for _ in 0..theme_choices(&h.app).len() {
|
||||
if crate::scenario::rect_of("prefs:theme_tile:onyx").is_some() {
|
||||
break;
|
||||
}
|
||||
h.step(&json!({"click":{"handle":"prefs:theme_next"}})).unwrap();
|
||||
h.frames(3);
|
||||
}
|
||||
}
|
||||
h.step(&json!({"click":{"handle":"prefs:theme_tile:onyx"}})).unwrap();
|
||||
h.frames(4);
|
||||
assert_eq!(h.app.preferences.theme, "onyx");
|
||||
assert!(crate::scenario::rect_of("prefs:theme_options_badge:onyx").is_some());
|
||||
assert!(crate::scenario::rect_of("prefs:theme_options_header").is_some());
|
||||
let out = h.call("ui.prefs", json!({}));
|
||||
assert_eq!(out["result"]["theme_option_values"]["opacity"], 80.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn theme_system_resolves_custom_day_and_night_by_os_including_cross_tone_slots() {
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
};
|
||||
let desktop = Arc::new(AtomicBool::new(false));
|
||||
let reading = desktop.clone();
|
||||
let mut h = crate::scenario::Harness::new();
|
||||
h.app.services.desktop_dark = Some(Box::new(move || Some(reading.load(Ordering::Relaxed))));
|
||||
h.call("ui.prefs", json!({"theme":"system", "theme_day":"onyx", "theme_night":"akari"}));
|
||||
h.frames(3);
|
||||
assert!(h.app.ui.dark, "the OS is light, but the Day slot may hold a dark theme");
|
||||
assert_eq!(h.app.prefs_window.window_theme, Some(egui::SystemTheme::SystemDefault));
|
||||
assert_eq!(active_theme_file(&h.app).unwrap().id, "onyx");
|
||||
assert_eq!(current_theme_file(&h.app)["name"], "Onyx");
|
||||
desktop.store(true, Ordering::Relaxed);
|
||||
h.frames(3);
|
||||
assert!(!h.app.ui.dark);
|
||||
assert_eq!(active_theme_file(&h.app).unwrap().id, "akari");
|
||||
h.call("ui.prefs", json!({"theme_day":"dark", "theme_night":"light"}));
|
||||
h.frames(2);
|
||||
assert_eq!(current_theme_file(&h.app)["base"], "light");
|
||||
desktop.store(false, Ordering::Relaxed);
|
||||
h.frames(2);
|
||||
assert_eq!(current_theme_file(&h.app)["base"], "dark");
|
||||
// If OS observation temporarily disappears, the mode button must use the same
|
||||
// remembered OS tone as rendering, rather than the cross-tone slot's palette.
|
||||
h.app.services.desktop_dark = Some(Box::new(|| None));
|
||||
h.app.home.open = false;
|
||||
h.call("ui.prefs", json!({"open":"Appearance"}));
|
||||
h.frames(3);
|
||||
h.step(&json!({"click":{"handle":"prefs:theme_mode:0"}})).unwrap();
|
||||
assert_eq!(h.app.preferences.theme, "dark", "leaving System preserves the theme actually in effect");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn theme_mode_switches_preserve_the_effective_theme_and_fill_only_the_aimed_slot() {
|
||||
let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default());
|
||||
select_theme(&mut app, "onyx");
|
||||
theme_picker::switch_mode(&mut app, true, true);
|
||||
assert_eq!((&app.preferences.theme[..], &app.preferences.theme_day[..], &app.preferences.theme_night[..]), ("system", "light", "onyx"));
|
||||
theme_picker::choose(&mut app, false, "akari");
|
||||
assert_eq!((&app.preferences.theme[..], &app.preferences.theme_day[..], &app.preferences.theme_night[..]), ("system", "akari", "onyx"));
|
||||
theme_picker::switch_mode(&mut app, false, false);
|
||||
assert_eq!(app.preferences.theme, "akari", "leaving system picks the effective Day theme, not its tone's default");
|
||||
theme_picker::switch_mode(&mut app, true, false);
|
||||
theme_picker::choose(&mut app, true, "clay-dark");
|
||||
theme_picker::switch_mode(&mut app, false, true);
|
||||
assert_eq!(app.preferences.theme, "clay-dark");
|
||||
let mut state = theme_picker::State::default();
|
||||
assert!(!state.night && !state.grid && state.tone.is_none());
|
||||
state.aim(true);
|
||||
assert!(state.night && state.tone == Some(true));
|
||||
state.aim(false);
|
||||
assert!(!state.night && state.tone == Some(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn theme_filter_counts_ignore_only_their_own_group() {
|
||||
let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default());
|
||||
let file = crate::theme_files::from_value(&json!({"format":"solidcraft-theme/1", "name":"Imported maximal", "base":"dark", "colors":{"dialog_footer":"#000000", "form_ink":"#ffffff"}})).unwrap();
|
||||
crate::theme_files::add(&mut app.preferences.custom_themes, file).unwrap();
|
||||
let entries = theme_picker::entries(&app);
|
||||
let state = theme_picker::State { tone: Some(true), high: Some(false), imported: false, ..Default::default() };
|
||||
assert_eq!((state.count(&entries, "tone", false), state.count(&entries, "tone", true)), (8, 14));
|
||||
assert_eq!((state.count(&entries, "contrast", false), state.count(&entries, "contrast", true)), (14, 4));
|
||||
assert_eq!(state.count(&entries, "imported", true), 0);
|
||||
let state = theme_picker::State { high: Some(true), imported: true, ..state };
|
||||
assert_eq!(state.count(&entries, "tone", true), 1);
|
||||
assert_eq!(state.count(&entries, "contrast", true), 1);
|
||||
assert_eq!(state.count(&entries, "contrast", false), 0);
|
||||
assert_eq!(state.count(&entries, "imported", true), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn theme_carousel_wheel_passes_vertical_to_page_and_handles_horizontal_and_shift() {
|
||||
let mut h = crate::scenario::Harness::new();
|
||||
h.app.home.open = false;
|
||||
h.call("ui.resize", json!({"width":1467,"height":1146}));
|
||||
h.call("ui.prefs", json!({"language":"en","theme":"light","open":"Appearance"}));
|
||||
h.frames(6);
|
||||
for (delta, modifiers, horizontal) in [
|
||||
(egui::vec2(1.0, -96.0), egui::Modifiers::NONE, false),
|
||||
(egui::vec2(-180.0, 0.0), egui::Modifiers::NONE, true),
|
||||
(egui::vec2(0.0, -180.0), egui::Modifiers::SHIFT, true),
|
||||
] {
|
||||
let before = crate::scenario::rect_of("prefs:card:Light").unwrap();
|
||||
let at = crate::scenario::rect_of("prefs:theme_viewport").unwrap().center();
|
||||
h.frame_with(vec![
|
||||
egui::Event::PointerMoved(at),
|
||||
egui::Event::MouseWheel {
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
unit: egui::MouseWheelUnit::Point,
|
||||
delta,
|
||||
modifiers,
|
||||
phase: egui::TouchPhase::Move,
|
||||
},
|
||||
]);
|
||||
h.frames(60);
|
||||
let after = crate::scenario::rect_of("prefs:card:Light").unwrap();
|
||||
if horizontal {
|
||||
assert!(after.left() < before.left() - 100.0, "horizontal wheel must move a card: {before:?} -> {after:?}");
|
||||
assert!((after.top() - before.top()).abs() < 1.0, "horizontal wheel must leave the page in place");
|
||||
} else {
|
||||
assert!((after.left() - before.left()).abs() < 1.0, "vertical wheel must not move carousel");
|
||||
assert!(after.top() < before.top() - 50.0, "vertical wheel must scroll the page");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Profile operations switches the profiler when it changes, and only then: an agent's
|
||||
/// diagnostics.profile in between is not undone next frame.
|
||||
#[test]
|
||||
@@ -6170,6 +6275,7 @@ mod tests {
|
||||
("direct_interaction", json!(true), PAGE_TOOLS),
|
||||
("hole_snaps", json!(true), PAGE_TOOLS),
|
||||
("hole_moves", json!(true), PAGE_TOOLS),
|
||||
("extrude_arrow_face_stops", json!(false), PAGE_TOOLS),
|
||||
("extrude_auto_to_object", json!(false), PAGE_TOOLS),
|
||||
("extrude_view_isometric", json!(true), PAGE_TOOLS),
|
||||
("extrude_view_return", json!(true), PAGE_TOOLS),
|
||||
@@ -6194,6 +6300,7 @@ mod tests {
|
||||
("hide_constraint_glyphs_zoomed_out", json!(false), PAGE_SKETCH),
|
||||
("suppress_sketch_snap", json!(ModifierCombo::NONE), PAGE_SKETCH),
|
||||
("sketch_state_icons", json!(false), PAGE_SKETCH),
|
||||
("sketch_mirror_auto_line", json!(false), PAGE_SKETCH),
|
||||
("sketch_tracking_guides", json!(false), PAGE_SKETCH),
|
||||
("sketch_tracking_points", json!(false), PAGE_SKETCH),
|
||||
("sketch_align_points", json!(true), PAGE_SKETCH),
|
||||
@@ -6662,12 +6769,16 @@ mod tests {
|
||||
/// back complete, imported themes are saved with the preferences, Remove falls back to the
|
||||
/// base and Cancel takes an import back.
|
||||
#[test]
|
||||
fn system_theme_tile_export_uses_os_brightness_without_selecting_it() {
|
||||
fn system_theme_export_uses_os_slot_without_selecting_it() {
|
||||
let mut app = SolveApp::new(solidcraft_engine::Session::default(), Default::default());
|
||||
app.preferences.theme = "light".into();
|
||||
app.ui.dark = false;
|
||||
assert_eq!(theme_file(&app, "system", true)["base"], "dark");
|
||||
assert_eq!(theme_file(&app, "system", false)["base"], "light");
|
||||
app.preferences.theme_day = "akari".into();
|
||||
app.preferences.theme_night = "onyx".into();
|
||||
assert_eq!(theme_file(&app, "system", false)["name"], "Akari");
|
||||
assert_eq!(theme_file(&app, "system", true)["name"], "Onyx");
|
||||
assert_eq!(app.preferences.theme, "light");
|
||||
assert!(!app.ui.dark);
|
||||
}
|
||||
@@ -6856,15 +6967,7 @@ mod tests {
|
||||
h.app.home.open = false;
|
||||
h.call("ui.prefs", json!({"theme": "dark", "open": "Interface"}));
|
||||
h.frames(2);
|
||||
// The Import card is the last one in the theme carousel: page it into view.
|
||||
for _ in 0..40 {
|
||||
if h.app.prefs_window.import_tile.is_some() {
|
||||
break;
|
||||
}
|
||||
h.step(&json!({"click":{"handle":"prefs:theme_next"}})).unwrap();
|
||||
h.frames(2);
|
||||
}
|
||||
assert!(h.app.prefs_window.import_tile.is_some(), "the Import card is reachable in the theme carousel");
|
||||
assert!(h.app.prefs_window.import_tile.is_some(), "Import is always visible");
|
||||
let (root, out) = (h.dir.join("root"), h.dir.join("out"));
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
std::fs::create_dir_all(&out).unwrap();
|
||||
@@ -6875,7 +6978,7 @@ mod tests {
|
||||
h.app.services.pick_open = Some(Box::new(move |_| Box::pin(std::future::ready(Some(answer.clone())))));
|
||||
h.app.status = None;
|
||||
vfs::scoped(Some(vfs::PathScope::new([root.clone()])), || {
|
||||
h.step(&json!({"click":{"handle":"dialog:Import…"}})).unwrap();
|
||||
h.step(&json!({"click":{"handle":"prefs:theme_import"}})).unwrap();
|
||||
h.frames(4);
|
||||
});
|
||||
let status = h.app.status.clone().map(|(text, ..)| text);
|
||||
@@ -6992,28 +7095,26 @@ mod tests {
|
||||
});
|
||||
}
|
||||
assert!(painted_count, "count comes from actual themes");
|
||||
for _ in 0..choices.len() + 1 {
|
||||
while crate::scenario::rect_of("prefs:theme_previous").is_some() {
|
||||
h.step(&json!({"click":{"handle":"prefs:theme_previous"}})).unwrap();
|
||||
h.frames(2);
|
||||
h.frames(3);
|
||||
}
|
||||
let mut found = std::collections::BTreeSet::new();
|
||||
for _ in 0..choices.len() + 1 {
|
||||
for (id, _) in &choices {
|
||||
if let Some(rect) = crate::scenario::rect_of(&format!("prefs:theme:{id}")) {
|
||||
assert!(page.expand(1.0).contains_rect(rect), "{base} width={screen}: {id} {rect:?}");
|
||||
assert!((rect.width() - 88.0).abs() <= 1.0);
|
||||
found.insert(id.clone());
|
||||
}
|
||||
}
|
||||
if let Some(import) = h.app.prefs_window.import_tile {
|
||||
assert!(page.expand(1.0).contains_rect(import));
|
||||
if crate::scenario::rect_of("prefs:theme_next").is_none() {
|
||||
break;
|
||||
}
|
||||
h.step(&json!({"click":{"handle":"prefs:theme_next"}})).unwrap();
|
||||
h.frames(2);
|
||||
h.frames(3);
|
||||
}
|
||||
assert_eq!(found, choices.into_iter().map(|(id, _)| id).collect());
|
||||
assert!(h.app.prefs_window.import_tile.is_some(), "Import is the last carousel card");
|
||||
assert!(h.app.prefs_window.import_tile.is_some(), "Import stays visible while scrolling");
|
||||
assert_eq!(h.app.preferences.theme, base, "scrolling does not select a theme");
|
||||
assert_eq!(h.app.preferences.ui_scale, 1.0);
|
||||
assert_eq!(h.app.preferences.viewport_background, None);
|
||||
@@ -8185,7 +8286,7 @@ mod tests {
|
||||
let out = h.call("ui.prefs", json!({"theme": "gruvbox-dark-hard"}));
|
||||
assert_eq!(out["result"]["theme"], "gruvbox-dark", "{out}");
|
||||
assert_eq!(out["result"]["theme_option_values"]["contrast"], "hard");
|
||||
assert!(out["result"]["theme_ids"].as_array().is_some_and(|ids| ids.len() == 3 + crate::theme_files::builtin().len()), "{out}");
|
||||
assert!(out["result"]["theme_ids"].as_array().is_some_and(|ids| ids.len() == 2 + crate::theme_files::builtin().len()), "{out}");
|
||||
h.frames(2);
|
||||
let hard = resolved_theme(&h.app.preferences, active_theme_file(&h.app).unwrap());
|
||||
assert!(h.app.ui.dark);
|
||||
|
||||
@@ -90,6 +90,7 @@ fn drawing(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
"prefs.line_hover_tangent_arc",
|
||||
"prefs.sketch.center_arc",
|
||||
"prefs.sketch_construction_lines",
|
||||
"prefs.sketch_mirror_auto_line",
|
||||
"prefs.sketch.ellipse_axes",
|
||||
"prefs.sketch.auto_dimensions",
|
||||
"prefs.sketch.auto_locate",
|
||||
@@ -128,6 +129,7 @@ fn drawing(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
&mut app.preferences.center_arc_follows_cursor,
|
||||
);
|
||||
check(ui, "sketch_construction_lines", "prefs.sketch_construction_lines", None, &mut app.preferences.sketch_construction_lines);
|
||||
check(ui, "sketch_mirror_auto_line", "prefs.sketch_mirror_auto_line", None, &mut app.preferences.sketch_mirror_auto_line);
|
||||
check(ui, "ellipse_axes", "prefs.sketch.ellipse_axes", Some("prefs.sketch.ellipse_axes_note"), &mut app.preferences.ellipse_axes);
|
||||
check(
|
||||
ui,
|
||||
|
||||
@@ -0,0 +1,388 @@
|
||||
//! Appearance's theme browser. Only the Day/Night assignments are saved preferences.
|
||||
use super::*;
|
||||
use ui_kit::{ThemeGlyph as Glyph, ThemeSegment};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) struct Classification {
|
||||
pub dark: bool,
|
||||
pub high: bool,
|
||||
}
|
||||
|
||||
/// Interim traits until themes declare tone and contrast in a later file-contract change.
|
||||
/// Use the resolved thumbnail ground and primary ink. 20:1 reserves High contrast for
|
||||
/// near-maximal text/background contrast: four shipped palettes measure 21:1, while
|
||||
/// every other shipped palette is at most 16.006:1. No theme ids are special-cased.
|
||||
pub(super) fn theme_traits(t: &Tokens) -> Classification {
|
||||
let linear = solidcraft_engine::geom::srgb::decode8;
|
||||
let luminance = 0.2126 * linear(t.dialog_footer.r()) + 0.7152 * linear(t.dialog_footer.g()) + 0.0722 * linear(t.dialog_footer.b());
|
||||
Classification { dark: luminance < 0.5, high: crate::theme::contrast_ratio(t.form_ink, t.dialog_footer) >= 20.0 }
|
||||
}
|
||||
|
||||
pub(super) fn palette(p: &Prefs, id: &str) -> Tokens {
|
||||
match id {
|
||||
"light" => Tokens::light(),
|
||||
"dark" => Tokens::dark(),
|
||||
_ => crate::theme_files::find(id, &p.custom_themes).map(|f| resolved_theme(p, f)).unwrap_or_else(Tokens::dark),
|
||||
}
|
||||
}
|
||||
|
||||
/// No recursion through `system`, even for hand-edited or removed theme ids.
|
||||
pub(super) fn slot_id(p: &Prefs, night: bool) -> &str {
|
||||
let (id, fallback) = if night { (&p.theme_night, "dark") } else { (&p.theme_day, "light") };
|
||||
if matches!(id.as_str(), "light" | "dark") || crate::theme_files::find(id, &p.custom_themes).is_some() { id } else { fallback }
|
||||
}
|
||||
|
||||
pub(super) fn active_id(p: &Prefs, system_dark: bool) -> &str {
|
||||
if p.theme == "system" { slot_id(p, system_dark) } else { &p.theme }
|
||||
}
|
||||
|
||||
#[derive(Clone, Default, PartialEq)]
|
||||
pub(super) struct State {
|
||||
pub tone: Option<bool>,
|
||||
pub high: Option<bool>,
|
||||
pub imported: bool,
|
||||
pub grid: bool,
|
||||
pub night: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) struct Entry {
|
||||
id: String,
|
||||
name: String,
|
||||
palette: Tokens,
|
||||
class: Classification,
|
||||
imported: bool,
|
||||
options: bool,
|
||||
}
|
||||
|
||||
impl State {
|
||||
fn matches(&self, entry: &Entry, skip: &str) -> bool {
|
||||
(skip == "tone" || self.tone.is_none_or(|dark| dark == entry.class.dark))
|
||||
&& (skip == "contrast" || self.high.is_none_or(|high| high == entry.class.high))
|
||||
&& (skip == "imported" || !self.imported || entry.imported)
|
||||
}
|
||||
|
||||
pub(super) fn count(&self, entries: &[Entry], group: &str, value: bool) -> usize {
|
||||
entries
|
||||
.iter()
|
||||
.filter(|e| {
|
||||
self.matches(e, group)
|
||||
&& match group {
|
||||
"tone" => e.class.dark == value,
|
||||
"contrast" => e.class.high == value,
|
||||
_ => e.imported,
|
||||
}
|
||||
})
|
||||
.count()
|
||||
}
|
||||
|
||||
pub(super) fn aim(&mut self, night: bool) {
|
||||
self.night = night;
|
||||
self.tone = Some(night);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn entries(app: &SolveApp) -> Vec<Entry> {
|
||||
theme_choices(app)
|
||||
.into_iter()
|
||||
.map(|(id, name)| {
|
||||
let palette = palette(&app.preferences, &id);
|
||||
let class = theme_traits(&palette);
|
||||
let imported = app.preferences.custom_themes.iter().any(|f| f.id == id);
|
||||
let options = crate::theme_files::find(&id, &app.preferences.custom_themes)
|
||||
.is_some_and(|f| !crate::theme_options::offered(f, crate::theme_options::PROVIDERS).is_empty());
|
||||
Entry { id, name, palette, class, imported, options }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) fn switch_mode(app: &mut SolveApp, follow: bool, dark: bool) {
|
||||
if follow == (app.preferences.theme == "system") {
|
||||
return;
|
||||
}
|
||||
stop_following(app);
|
||||
if follow {
|
||||
let id = app.preferences.theme.clone();
|
||||
let night = theme_traits(&palette(&app.preferences, &id)).dark;
|
||||
fill_slot(&mut app.preferences, night, &id);
|
||||
app.preferences.theme = "system".into();
|
||||
} else {
|
||||
let id = active_id(&app.preferences, dark).to_owned();
|
||||
select_theme(app, &id);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn fill_slot(p: &mut Prefs, night: bool, id: &str) {
|
||||
if night {
|
||||
p.theme_night = id.to_owned();
|
||||
} else {
|
||||
p.theme_day = id.to_owned();
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn choose(app: &mut SolveApp, night: bool, id: &str) {
|
||||
if app.preferences.theme == "system" {
|
||||
fill_slot(&mut app.preferences, night, id);
|
||||
} else {
|
||||
stop_following(app);
|
||||
select_theme(app, id);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn row(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
if crate::prefs_search::suppress_chrome(ui) {
|
||||
row_contents(app, ui);
|
||||
return;
|
||||
}
|
||||
// The page scroller's host can be wider than its clipped content well. Give the
|
||||
// picker its real visible width, and never propagate a child's horizontal growth.
|
||||
let start = ui.next_widget_position();
|
||||
let width = ui.available_width().min((ui.clip_rect().right() - start.x).max(0.0));
|
||||
let mut child = ui.new_child(
|
||||
egui::UiBuilder::new()
|
||||
.id_salt("theme_picker_content")
|
||||
.max_rect(egui::Rect::from_min_size(start, egui::vec2(width, ui.available_height())))
|
||||
.layout(egui::Layout::top_down(egui::Align::Min)),
|
||||
);
|
||||
child.set_width(width);
|
||||
row_contents(app, &mut child);
|
||||
ui.allocate_exact_size(egui::vec2(width, child.min_size().y), egui::Sense::hover());
|
||||
}
|
||||
|
||||
fn row_contents(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
let key = ui.make_persistent_id("theme_picker_state");
|
||||
let mut state = ui.data(|d| d.get_temp::<State>(key)).unwrap_or_default();
|
||||
let search = crate::prefs_search::suppress_chrome(ui);
|
||||
let mut action = None;
|
||||
let mut action_theme = None;
|
||||
let t = Tokens::get();
|
||||
let dark = system_dark(app, ui.ctx()).unwrap_or_else(|| app.prefs_window.system_theme_dark.unwrap_or(app.ui.dark));
|
||||
let label = app.tr("prefs.picker.import");
|
||||
let import_width = ui_kit::ContentWidth::name(ui, label) + t.space_14 + t.space_6 + t.space_10 * 2.0;
|
||||
let (mode, import_rect) = ui_kit::theme_toolbar(
|
||||
ui,
|
||||
"mode",
|
||||
import_width,
|
||||
t.space_24 * 19.0 + t.space_4,
|
||||
|ui| {
|
||||
let mode = ui_kit::theme_segments(
|
||||
ui,
|
||||
"mode",
|
||||
&[
|
||||
ThemeSegment::new(app.tr("prefs.picker.one"), Glyph::Monitor, None),
|
||||
ThemeSegment::new(app.tr("prefs.picker.follow"), Glyph::Contrast, None),
|
||||
],
|
||||
Some(usize::from(app.preferences.theme == "system")),
|
||||
false,
|
||||
);
|
||||
if app.preferences.theme == "system" {
|
||||
ui_kit::settings_inline_note(ui, app.tr("prefs.picker.hint"));
|
||||
}
|
||||
mode
|
||||
},
|
||||
|ui| {
|
||||
let button = ui_kit::theme_import_button(ui, label).backing_on_hover_text(app.tr("prefs.theme_import_hint"));
|
||||
crate::scenario::publish_target("prefs:theme_import", button.rect);
|
||||
if button.clicked() {
|
||||
action = Some("import");
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
ui_kit::Menu::context(&button, |ui| {
|
||||
ui_kit::Menu::show(ui, t.form_card_width, |ui| {
|
||||
if ui_kit::MenuItem::new("theme_paste", app.tr("prefs.theme_paste"), "paste").show(ui).clicked() {
|
||||
action = Some("paste");
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
button.rect
|
||||
},
|
||||
);
|
||||
app.prefs_window.import_tile = Some(import_rect);
|
||||
if let Some(index) = mode {
|
||||
switch_mode(app, index == 1, dark);
|
||||
state.tone = if index == 1 { Some(state.night) } else { None };
|
||||
}
|
||||
let system = app.preferences.theme == "system";
|
||||
if system {
|
||||
let width = (ui.available_width() - t.space_10) / 2.0;
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = t.space_10;
|
||||
for night in [false, true] {
|
||||
let id = slot_id(&app.preferences, night);
|
||||
let name = theme_choices(app).into_iter().find(|(i, _)| i == id).map(|(_, n)| n).unwrap_or_default();
|
||||
let title = app.tr(if night { "prefs.picker.night" } else { "prefs.picker.day" });
|
||||
let aimed = state.night == night;
|
||||
let response = ui_kit::theme_slot(
|
||||
ui,
|
||||
&ui_kit::ThemeSlot {
|
||||
title,
|
||||
name: &name,
|
||||
aimed,
|
||||
night,
|
||||
width,
|
||||
hint: app.tr(if aimed { "prefs.picker.pick" } else { "prefs.picker.change" }),
|
||||
sample: ui_kit::ThemeSample::from_tokens(&palette(&app.preferences, id)),
|
||||
},
|
||||
);
|
||||
crate::scenario::publish_target(if night { "prefs:theme_slot:night" } else { "prefs:theme_slot:day" }, response.rect);
|
||||
if response.clicked() {
|
||||
state.aim(night);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
let entries = entries(app);
|
||||
let (filters, view) = ui_kit::theme_toolbar(
|
||||
ui,
|
||||
"filters",
|
||||
(t.space_24 + t.space_10) * 2.0,
|
||||
0.0,
|
||||
|ui| {
|
||||
let mut tone = state.tone;
|
||||
let mut high = state.high;
|
||||
let mut imported = state.imported;
|
||||
if let Some(index) = ui_kit::theme_segments(
|
||||
ui,
|
||||
"tone",
|
||||
&[
|
||||
ThemeSegment::new(app.tr("ui.light"), Glyph::Sun, Some(state.count(&entries, "tone", false))),
|
||||
ThemeSegment::new(app.tr("ui.dark"), Glyph::Moon, Some(state.count(&entries, "tone", true))),
|
||||
],
|
||||
state.tone.map(usize::from),
|
||||
false,
|
||||
) {
|
||||
let value = Some(index == 1);
|
||||
tone = if state.tone == value { None } else { value };
|
||||
}
|
||||
if let Some(index) = ui_kit::theme_segments(
|
||||
ui,
|
||||
"contrast",
|
||||
&[
|
||||
ThemeSegment::new(app.tr("prefs.picker.standard"), Glyph::None, Some(state.count(&entries, "contrast", false))),
|
||||
ThemeSegment::new(app.tr("prefs.picker.high"), Glyph::Contrast, Some(state.count(&entries, "contrast", true))),
|
||||
],
|
||||
state.high.map(usize::from),
|
||||
false,
|
||||
) {
|
||||
let value = Some(index == 1);
|
||||
high = if state.high == value { None } else { value };
|
||||
}
|
||||
if ui_kit::theme_segments(
|
||||
ui,
|
||||
"imported",
|
||||
&[ThemeSegment::new(app.tr("prefs.picker.imported"), Glyph::None, Some(state.count(&entries, "imported", true)))],
|
||||
state.imported.then_some(0),
|
||||
false,
|
||||
)
|
||||
.is_some()
|
||||
{
|
||||
imported = !state.imported;
|
||||
}
|
||||
(tone, high, imported)
|
||||
},
|
||||
|ui| {
|
||||
ui_kit::theme_segments(
|
||||
ui,
|
||||
"view",
|
||||
&[
|
||||
ThemeSegment::new(app.tr("prefs.picker.carousel"), Glyph::Carousel, None),
|
||||
ThemeSegment::new(app.tr("prefs.picker.grid"), Glyph::Grid, None),
|
||||
],
|
||||
Some(usize::from(state.grid)),
|
||||
true,
|
||||
)
|
||||
},
|
||||
);
|
||||
(state.tone, state.high, state.imported) = filters;
|
||||
if let Some(index) = view {
|
||||
state.grid = index == 1;
|
||||
}
|
||||
let visible: Vec<_> = entries.iter().filter(|e| search || state.matches(e, "")).collect();
|
||||
let following = !app.prefs_window.follow.path(&app.preferences.theme_follow).is_empty();
|
||||
let reveal = if system { slot_id(&app.preferences, state.night) } else { &app.preferences.theme };
|
||||
let selected_index = visible.iter().position(|e| e.id == reveal);
|
||||
let identity = format!("{reveal}:{:?}:{:?}:{}:{}", state.tone, state.high, state.imported, state.grid);
|
||||
let reveal_key = ui.make_persistent_id("theme_picker_reveal");
|
||||
let changed = ui.data(|d| d.get_temp::<String>(reveal_key)).as_ref() != Some(&identity);
|
||||
let mut chosen = None;
|
||||
let mut card = |ui: &mut egui::Ui, index: usize, width: f32| {
|
||||
let Some(e) = visible.get(index) else { return };
|
||||
let source = app.tr(if e.imported { "prefs.imported_file" } else { "prefs.built_in" });
|
||||
let note = if e.class.high { crate::i18n::format("prefs.picker.high_note", &[("source", source)]) } else { source.to_owned() };
|
||||
let day = system && slot_id(&app.preferences, false) == e.id;
|
||||
let night = system && slot_id(&app.preferences, true) == e.id;
|
||||
let selected = !following && if system { day || night } else { app.preferences.theme == e.id };
|
||||
let response = ui_kit::theme_card(
|
||||
ui,
|
||||
&ui_kit::ThemeCard {
|
||||
name: &e.name,
|
||||
note: ¬e,
|
||||
selected,
|
||||
day,
|
||||
night,
|
||||
dark: e.class.dark,
|
||||
high: e.class.high,
|
||||
options: e.options.then(|| app.tr("prefs.theme_options_badge")),
|
||||
sample: ui_kit::ThemeSample::from_tokens(&e.palette),
|
||||
},
|
||||
width,
|
||||
);
|
||||
let clipped = response.rect.intersect(ui.clip_rect());
|
||||
if clipped.is_positive() {
|
||||
crate::scenario::publish_target(&format!("prefs:theme_tile:{}", e.id), clipped);
|
||||
crate::scenario::publish_target(&format!("prefs:theme:{}", e.id), clipped);
|
||||
if e.options {
|
||||
crate::scenario::publish_rect(&format!("prefs:theme_options_badge:{}", e.id), clipped);
|
||||
}
|
||||
if selected && !system {
|
||||
crate::scenario::publish_target("prefs:theme", clipped);
|
||||
}
|
||||
}
|
||||
if response.clicked() {
|
||||
chosen = Some(e.id.clone());
|
||||
}
|
||||
ui_kit::Menu::context(&response, |ui| {
|
||||
ui_kit::Menu::show(ui, t.form_card_width, |ui| {
|
||||
if ui_kit::MenuItem::new("theme_export", app.tr_label("Export…"), "export").show(ui).clicked() {
|
||||
action = Some("export");
|
||||
action_theme = Some(e.id.clone());
|
||||
ui.close();
|
||||
}
|
||||
if e.imported {
|
||||
let mut remove = ui_kit::MenuItem::new("theme_remove", app.tr_label("Remove"), "delete");
|
||||
remove.danger = true;
|
||||
if remove.show(ui).clicked() {
|
||||
action = Some("remove");
|
||||
action_theme = Some(e.id.clone());
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
if search {
|
||||
for index in 0..visible.len() {
|
||||
card(ui, index, t.space_24 * 5.0);
|
||||
}
|
||||
} else if visible.is_empty() {
|
||||
ui_kit::theme_empty(ui, app.tr("prefs.picker.empty"), app.tr("prefs.picker.clear"), || {
|
||||
state.tone = None;
|
||||
state.high = None;
|
||||
state.imported = false;
|
||||
});
|
||||
} else {
|
||||
ui_kit::theme_browser(ui, "appearance_theme_picker", visible.len(), state.grid, changed.then_some(selected_index).flatten(), &mut card);
|
||||
}
|
||||
ui.data_mut(|d| {
|
||||
d.insert_temp(key, state.clone());
|
||||
d.insert_temp(reveal_key, identity);
|
||||
});
|
||||
if !search {
|
||||
app.prefs_window.theme_picker_night = state.night;
|
||||
}
|
||||
if let Some(id) = chosen {
|
||||
choose(app, state.night, &id);
|
||||
}
|
||||
super::theme_action(app, ui, action, action_theme);
|
||||
}
|
||||
@@ -35,6 +35,7 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
"extrude_auto_to_object",
|
||||
),
|
||||
(setting::auto_operation, "prefs.auto_operation_note", "auto_operation"),
|
||||
(setting::extrude_arrow_face_stops, "prefs.extrude_arrow_face_stops_note", "extrude_arrow_face_stops"),
|
||||
] {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
let response = setting(app, ui).backing_on_hover_text(app.tr(help));
|
||||
|
||||
@@ -838,6 +838,39 @@ pub(crate) fn follow(ui: &Ui, label: &str, rect: Rect) {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn theme_picker_names_and_controls_are_searchable_and_theme_results_reveal_real_cards() {
|
||||
let mut h = crate::scenario::Harness::new();
|
||||
h.app.home.open = false;
|
||||
h.call("ui.resize", serde_json::json!({"width":1467,"height":1146}));
|
||||
h.call("ui.prefs", serde_json::json!({"language":"en","theme":"system","open":"Appearance"}));
|
||||
for label in
|
||||
["Onyx", "Follow system", "One theme", "Carousel", "Grid", "Day theme", "Night theme", "High contrast", "Import theme file…", "Imported"]
|
||||
{
|
||||
h.app.prefs_window.filter = label.to_owned();
|
||||
h.frames(5);
|
||||
let (_, _, hits) = nav(&h.ctx);
|
||||
let matches: Vec<_> =
|
||||
hits.iter().enumerate().filter(|(_, hit)| hit.page == crate::prefs::PAGE_APPEARANCE && hit.label == label).collect();
|
||||
assert_eq!(
|
||||
matches.len(),
|
||||
1,
|
||||
"{label} has one searchable Appearance control: {:?}",
|
||||
hits.iter().map(|hit| (&hit.label, hit.page)).collect::<Vec<_>>()
|
||||
);
|
||||
if label == "Onyx" {
|
||||
set_cursor(&h.ctx, matches[0].0);
|
||||
h.frames(2);
|
||||
h.step(&serde_json::json!({"key":"Enter"})).unwrap();
|
||||
h.frames(25);
|
||||
let page = crate::scenario::rect_of("prefs:page_body").unwrap();
|
||||
let target = crate::scenario::rect_of("prefs:theme:onyx").unwrap();
|
||||
assert!(page.contains_rect(target));
|
||||
assert_eq!(h.app.preferences.theme, "system", "revealing a theme never selects it");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graphics_cards_tiles_and_short_status_labels_keep_search_paths_and_reveal() {
|
||||
for theme in ["light", "dark"] {
|
||||
|
||||
@@ -202,7 +202,9 @@ pub(crate) fn overlays(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
crate::render_workspace::environment_overlay(app, ui, viewport);
|
||||
crate::render_workspace::assign::selection_bar(app, ui, free);
|
||||
crate::render_workspace::assign::replacement_dialog(app, ui.ctx());
|
||||
crate::navigation_bar_view::show(app, ui, viewport);
|
||||
if !app.universal_panel_host_enabled() {
|
||||
crate::navigation_bar_view::show(app, ui, viewport);
|
||||
}
|
||||
crate::shell::register_panel(app, "render:compare-controls", None, None);
|
||||
if !crate::render_workspace::result_active(app) && app.session.render_selected_result().is_some() {
|
||||
let free = if crate::render_workspace::job_busy(app) { Container::below_navigation_row(free) } else { free };
|
||||
|
||||
@@ -146,6 +146,9 @@ pub struct State {
|
||||
pub upload_error: crate::gpu::UploadError,
|
||||
pub image_host: Option<solidcraft_engine::render::job::CpuHost>,
|
||||
pub view: ViewState,
|
||||
/// This frame's existing canvas response, consumed once after result chrome
|
||||
/// publishes its real input shields. Never stored in document/tab state.
|
||||
result_navigation: Option<(egui::Rect, egui::Response, bool)>,
|
||||
revision: u64,
|
||||
design_camera: Option<(Camera, bool)>,
|
||||
slot: SceneSlot,
|
||||
@@ -395,6 +398,9 @@ pub struct ViewState {
|
||||
result: bool,
|
||||
result_camera: Camera,
|
||||
result_scale: ResultScale,
|
||||
/// Full image domain and explicit scale policy last applied by the host.
|
||||
/// Panel geometry is deliberately absent: moving chrome never reframes.
|
||||
result_domain: Option<(egui::Rect, [u32; 2], f32, ResultScale)>,
|
||||
result_job: Option<solidcraft_engine::render::job::JobId>,
|
||||
}
|
||||
|
||||
@@ -464,6 +470,7 @@ impl Default for ViewState {
|
||||
result: false,
|
||||
result_camera: Camera { yaw: 0.0, pitch: std::f64::consts::FRAC_PI_2, ..Default::default() },
|
||||
result_scale: ResultScale::Fit,
|
||||
result_domain: None,
|
||||
result_job: None,
|
||||
}
|
||||
}
|
||||
@@ -486,6 +493,7 @@ impl Default for State {
|
||||
upload_error: Arc::new(Mutex::new(None)),
|
||||
image_host: None,
|
||||
view: Default::default(),
|
||||
result_navigation: None,
|
||||
revision: u64::MAX,
|
||||
design_camera: None,
|
||||
slot: Arc::new(Mutex::new(None)),
|
||||
@@ -660,6 +668,7 @@ pub(crate) fn comparison_drag_captured(app: &SolveApp) -> bool {
|
||||
|
||||
pub(crate) fn fit_result(app: &mut SolveApp) {
|
||||
app.render_workspace.view.result_scale = ResultScale::Fit;
|
||||
app.render_workspace.view.result_domain = None;
|
||||
}
|
||||
|
||||
/// Read-only identities for automation and diagnostics. Does not prepare a
|
||||
@@ -750,6 +759,10 @@ pub fn sync_backend(app: &mut SolveApp) {
|
||||
/// scheduling frames even after leaving Render so a browser job can finish in Design.
|
||||
pub fn tick(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
library::poll_import(app, ctx);
|
||||
if !app.universal_panel_host_enabled() {
|
||||
// Classic shell input and Fit run before the host overlay finalizer.
|
||||
crate::shell::register_panel(app, "render:result-controls", None, None);
|
||||
}
|
||||
if let Some(text) = app.render_workspace.clipboard_text.take() {
|
||||
ctx.copy_text(text);
|
||||
}
|
||||
@@ -1539,6 +1552,7 @@ fn remember_displayed_job(app: &mut SolveApp, preserve_view: bool) {
|
||||
app.render_workspace.view.result_job = Some(job);
|
||||
if !preserve_view {
|
||||
app.render_workspace.view.result_scale = ResultScale::Fit;
|
||||
app.render_workspace.view.result_domain = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1662,6 +1676,7 @@ pub(crate) fn with_result_camera(app: &mut SolveApp, navigate: impl FnOnce(&mut
|
||||
app.render_workspace.view.result_camera = std::mem::replace(&mut app.cam, preview);
|
||||
if app.render_workspace.view.result_camera != before {
|
||||
app.render_workspace.view.result_scale = ResultScale::Free;
|
||||
app.render_workspace.view.result_domain = None;
|
||||
}
|
||||
app.render_workspace.view.draft = draft;
|
||||
app.render_workspace.view.dirty = dirty;
|
||||
@@ -1697,7 +1712,40 @@ fn result_rect(camera: Camera, size: [u32; 2], canvas: egui::Rect) -> egui::Rect
|
||||
}
|
||||
|
||||
fn result_actions(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
if app.universal_panel_host_enabled() {
|
||||
// The comparison picker contains scoped controls (including Swap). Give
|
||||
// that compound widget its own row, then wrap actions at the original
|
||||
// viewport width even if the picker needs horizontal scrolling.
|
||||
let width = ui.available_width();
|
||||
let layout = if ui.layout().prefer_right_to_left() {
|
||||
egui::Layout::right_to_left(egui::Align::Center)
|
||||
} else {
|
||||
egui::Layout::left_to_right(egui::Align::Center)
|
||||
};
|
||||
ui.horizontal(|ui| compare::controls(app, ui));
|
||||
ui.allocate_ui_with_layout(egui::vec2(width, Tokens::get().control_height), layout.with_main_wrap(true), |ui| {
|
||||
result_action_controls(app, ui)
|
||||
});
|
||||
return;
|
||||
}
|
||||
compare::controls(app, ui);
|
||||
result_action_controls(app, ui);
|
||||
}
|
||||
|
||||
/// Keep enabled state on the wrapping UI itself. Button::Enabled opens a child
|
||||
/// scope in the remaining row space, so its button cannot wrap in the parent.
|
||||
/// Classic retains the original kit path and widget identities.
|
||||
fn result_action_button(ui: &mut egui::Ui, label: &str, enabled: bool, host: bool) -> egui::Response {
|
||||
if host {
|
||||
ui.add_enabled(enabled, |ui: &mut egui::Ui| crate::ui_kit::button(ui, label, crate::ui_kit::Button::Normal))
|
||||
} else {
|
||||
crate::ui_kit::button(ui, label, crate::ui_kit::Button::Enabled(enabled))
|
||||
}
|
||||
}
|
||||
|
||||
fn result_action_controls(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
crate::scenario::publish_rect("render:result-actions-clip", ui.clip_rect());
|
||||
let host = app.universal_panel_host_enabled();
|
||||
let results = app.render_workspace.view.retained.clone();
|
||||
if !results.is_empty() {
|
||||
let selected = results.iter().position(|result| Some(result.frame.job) == app.render_workspace.view.completed);
|
||||
@@ -1717,8 +1765,13 @@ fn result_actions(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
if let Some(index) = chosen {
|
||||
let _ = app.run("render.result.select", json!({"index":index}));
|
||||
}
|
||||
let discard =
|
||||
ui.add_enabled_ui(selected.is_some(), |ui| crate::ui_kit::StageBar::icon_action(ui, "delete", app.tr("cmd.render.result.discard"))).inner;
|
||||
let discard = if host {
|
||||
ui.add_enabled(selected.is_some(), |ui: &mut egui::Ui| {
|
||||
crate::ui_kit::StageBar::icon_action(ui, "delete", app.tr("cmd.render.result.discard"))
|
||||
})
|
||||
} else {
|
||||
ui.add_enabled_ui(selected.is_some(), |ui| crate::ui_kit::StageBar::icon_action(ui, "delete", app.tr("cmd.render.result.discard"))).inner
|
||||
};
|
||||
crate::scenario::publish_target("render:result-discard", discard.rect);
|
||||
if discard.clicked()
|
||||
&& let Some(index) = selected
|
||||
@@ -1728,21 +1781,18 @@ fn result_actions(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
}
|
||||
for (view, key) in [("model", "render.state_model"), ("fit", "render.output_fit"), ("actual", "render.result_actual")] {
|
||||
let enabled = view != "actual" || !reduced_display(app);
|
||||
if crate::ui_kit::button(ui, app.tr(key), crate::ui_kit::Button::Enabled(enabled)).clicked() {
|
||||
let response = result_action_button(ui, app.tr(key), enabled, host);
|
||||
crate::scenario::publish_target(&format!("render:result-{view}"), response.rect);
|
||||
if response.clicked() {
|
||||
let _ = app.run("render.result.view", json!({"view":view}));
|
||||
}
|
||||
}
|
||||
let copy = crate::ui_kit::button(
|
||||
ui,
|
||||
app.tr("render.output_copy"),
|
||||
crate::ui_kit::Button::Enabled(ribbon::action_ready(app, "render.result.copy").is_ok()),
|
||||
);
|
||||
let copy = result_action_button(ui, app.tr("render.output_copy"), ribbon::action_ready(app, "render.result.copy").is_ok(), host);
|
||||
crate::scenario::publish_target("render:result-copy", copy.rect);
|
||||
if copy.clicked() {
|
||||
app.start("render.result.copy");
|
||||
}
|
||||
let export =
|
||||
crate::ui_kit::button(ui, studio::export_label(app), crate::ui_kit::Button::Enabled(ribbon::action_ready(app, "render.export").is_ok()));
|
||||
let export = result_action_button(ui, studio::export_label(app), ribbon::action_ready(app, "render.export").is_ok(), host);
|
||||
crate::scenario::publish_target("render:result-export", export.rect);
|
||||
if export.clicked() {
|
||||
app.start("render.export");
|
||||
@@ -1763,34 +1813,225 @@ fn result_label(result: &solidcraft_engine::render_jobs::RetainedResult) -> Stri
|
||||
if result.stale { crate::i18n::format("render.results_stale_label", &[("result", &label)]) } else { label }
|
||||
}
|
||||
|
||||
fn result_header(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
let t = Tokens::get();
|
||||
let display = displayed_image(app).map(|display| (display.info.clone(), display.preview.cloned()));
|
||||
let state = match &display {
|
||||
Some((_, Some(_))) => "render.state_in_progress",
|
||||
Some(_) => "render.state_completed",
|
||||
None if ribbon::busy(app) => "render.state_in_progress",
|
||||
None => "render.result_title",
|
||||
};
|
||||
if app.universal_panel_host_enabled() {
|
||||
crate::ui_kit::text(ui, app.tr(state), crate::ui_kit::Text::Inline);
|
||||
result_actions(app, ui);
|
||||
} else {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
crate::ui_kit::text(ui, app.tr(state), crate::ui_kit::Text::Inline);
|
||||
result_actions(app, ui);
|
||||
});
|
||||
}
|
||||
let Some((info, preview)) = display else { return };
|
||||
if let Some(preview) = &preview {
|
||||
ui.colored_label(
|
||||
t.warning,
|
||||
format!(
|
||||
"{} · {} {} · {} {}",
|
||||
app.tr("render.result_provisional"),
|
||||
preview.samples_per_pixel,
|
||||
app.tr("render.cpu_progressive_spp"),
|
||||
app.tr("render.result_sequence"),
|
||||
preview.frame_sequence
|
||||
),
|
||||
);
|
||||
ui.small(app.tr("render.result_provisional_help"));
|
||||
}
|
||||
if let Some(display) = displayed_image(app)
|
||||
&& let Err(error) = display.image
|
||||
{
|
||||
ui.colored_label(t.warning, error);
|
||||
}
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.strong(format!("{} × {} px · PNG · {}", info.width, info.height, info.executor.as_str()));
|
||||
ui.label(format!(
|
||||
"{} {}:{}:{} · {} {}",
|
||||
app.tr("render.result_job"),
|
||||
info.job.session,
|
||||
info.job.serial,
|
||||
info.job.generation,
|
||||
app.tr("render.result_capture"),
|
||||
info.scene_generation
|
||||
));
|
||||
});
|
||||
if reduced_display(app) {
|
||||
ui.colored_label(t.warning, app.tr("render.result_reduced_display"));
|
||||
}
|
||||
let stale = info.scene_generation != app.session.revision;
|
||||
ui.colored_label(if stale { t.warning } else { t.text_dim }, app.tr(if stale { "render.image_stale" } else { "render.result_current" }));
|
||||
if app.render_workspace.view.job.is_some_and(|job| job != info.job) {
|
||||
ui.small(app.tr("render.result_retained"));
|
||||
}
|
||||
}
|
||||
|
||||
/// Result controls remain legacy chrome. Paint them after the shell, inside a
|
||||
/// real free contour piece, and record only the clipped card actually shown.
|
||||
/// No panel adapter, outer host or second navigation path is introduced.
|
||||
pub(crate) fn host_result_overlays(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
use crate::panel_runtime::{egui_rect, logical_rect};
|
||||
crate::shell::register_panel(app, "render:result-controls", None, None);
|
||||
if !app.universal_panel_host_enabled() || !active(app) || (!result_active(app) && app.render_workspace.view.compare.is_none()) {
|
||||
return;
|
||||
}
|
||||
let Some(canvas) = app.viewport.rect.filter(|rect| rect.is_finite() && rect.is_positive()) else { return };
|
||||
crate::viewport::refresh_layout(app, ui.ctx());
|
||||
if !crate::render_ui::focused(app)
|
||||
&& let Some(usable) = app.viewport.layout.as_ref().and_then(|layout| layout.usable.clone())
|
||||
{
|
||||
let t = Tokens::get();
|
||||
// Use an existing sweep piece, as other host controls do. A maximum
|
||||
// spanning rectangle search belongs to an explicit Fit, not each frame.
|
||||
let room = usable.free.iter().max_by(|a, b| (a.size.width * a.size.height).total_cmp(&(b.size.width * b.size.height))).copied();
|
||||
if let Some(room) = room {
|
||||
let mut bounds = egui_rect(room).intersect(canvas).shrink(t.space_4);
|
||||
bounds.max.x = bounds.right().min(bounds.left() + t.form_card_width * 2.0);
|
||||
if bounds.is_finite() && bounds.width() >= t.control_height + t.space_8 && bounds.height() >= t.control_height + t.space_8 {
|
||||
let painted = host_result_card(app, ui, bounds, canvas);
|
||||
if ui.is_visible() && !ui.is_sizing_pass() && painted.is_positive() && usable.contains_rect(logical_rect(painted)) {
|
||||
crate::shell::register_panel(app, "render:result-controls", Some(painted), None);
|
||||
crate::scenario::publish_rect("render:result-controls", painted);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
crate::viewport::refresh_layout(app, ui.ctx());
|
||||
if !result_active(app) && app.render_workspace.view.compare.is_none() {
|
||||
app.render_workspace.result_navigation = None;
|
||||
return;
|
||||
}
|
||||
update_host_result_camera(app, ui.ctx(), canvas);
|
||||
if let Some((rect, response, captured)) = app.render_workspace.result_navigation.take()
|
||||
&& !captured
|
||||
&& !host_navigation_captured(app)
|
||||
{
|
||||
let before = app.render_workspace.view.result_camera;
|
||||
with_result_camera(app, |app| {
|
||||
crate::navigation::handle(app, ui, rect, &response, crate::navigation::NavCaps { orbit: false, pick: false });
|
||||
});
|
||||
if app.render_workspace.view.result_camera != before {
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The existing legacy card, shared with bounded-widget regression fixtures.
|
||||
/// The caller alone records its footprint and finalizes the canvas response.
|
||||
fn host_result_card(app: &mut SolveApp, ui: &mut egui::Ui, bounds: egui::Rect, canvas: egui::Rect) -> egui::Rect {
|
||||
let t = Tokens::get();
|
||||
let mut controls = ui.new_child(egui::UiBuilder::new().max_rect(bounds).id_salt("render_host_result_controls"));
|
||||
controls.set_clip_rect(ui.clip_rect().intersect(bounds));
|
||||
let card = crate::ui_kit::Container::navigation_contents(&mut controls, |ui| {
|
||||
// A vertical-only ScrollArea grows to its child's minimum width,
|
||||
// outside this card's clip. Oversized compound controls must scroll.
|
||||
egui::ScrollArea::both()
|
||||
.id_salt("render_host_result_scroll")
|
||||
.min_scrolled_width(0.0)
|
||||
.min_scrolled_height(0.0)
|
||||
.max_width(ui.available_width())
|
||||
.max_height((bounds.height().min(t.form_card_width) - t.space_8).max(0.0))
|
||||
.show(ui, |ui| {
|
||||
if app.render_workspace.view.compare.is_some() {
|
||||
result_actions(app, ui);
|
||||
compare::summary(app, ui);
|
||||
} else {
|
||||
result_header(app, ui);
|
||||
}
|
||||
let camera = app.render_workspace.view.result_camera;
|
||||
let percent = f64::from(canvas.height() * ui.ctx().pixels_per_point()) / (2.0 * camera.half_height()) * 100.0;
|
||||
ui.small(format!("{percent:.1}%"));
|
||||
});
|
||||
});
|
||||
card.response.rect.intersect(controls.clip_rect())
|
||||
}
|
||||
|
||||
fn host_navigation_captured(app: &SolveApp) -> bool {
|
||||
// The root finishes host input after result navigation, so an existing
|
||||
// header/resize capture still owns this pass even when Primary releases.
|
||||
app.panel_runtime.as_ref().and_then(|runtime| runtime.host()).is_some_and(|host| host.interaction().is_captured())
|
||||
}
|
||||
|
||||
/// Apply Fit/Actual only for an explicit request, a new image domain or DPI.
|
||||
/// Ordinary panel moves cannot mutate either the image or product camera.
|
||||
fn update_host_result_camera(app: &mut SolveApp, ctx: &egui::Context, canvas: egui::Rect) {
|
||||
use crate::panel_runtime::egui_rect;
|
||||
use solidcraft_engine::panels::Point;
|
||||
let view = &app.render_workspace.view;
|
||||
let size = if let Some(comparison) = &view.compare {
|
||||
view.retained.iter().find(|result| result.frame.job == comparison.reference).map(|result| [result.frame.width, result.frame.height])
|
||||
} else {
|
||||
displayed_image(app).map(|display| [display.info.width, display.info.height])
|
||||
};
|
||||
let Some(size) = size else { return };
|
||||
let scale = view.result_scale;
|
||||
let domain = (canvas, size, ctx.pixels_per_point(), scale);
|
||||
if scale == ResultScale::Free || view.result_domain == Some(domain) {
|
||||
return;
|
||||
}
|
||||
let camera = if scale == ResultScale::Actual {
|
||||
result_camera(size, canvas, ctx.pixels_per_point(), scale)
|
||||
} else {
|
||||
let Some(usable) = app.viewport.layout.as_ref().and_then(|layout| layout.usable.as_ref()) else { return };
|
||||
let aspect = size[0].max(1) as f32 / size[1].max(1) as f32;
|
||||
let Some(room) = usable.fit_rect_with_clearance(aspect, Point { x: canvas.center().x, y: canvas.center().y }, Tokens::get().space_8) else {
|
||||
return;
|
||||
};
|
||||
let room = egui_rect(room);
|
||||
let mut camera = result_camera(size, room, ctx.pixels_per_point(), scale);
|
||||
// Keep the existing image-scale formula, expressed in the full canvas.
|
||||
camera.distance *= f64::from(canvas.height() / room.height());
|
||||
let units = 2.0 * camera.half_height() / f64::from(canvas.height());
|
||||
let offset = room.center() - canvas.center();
|
||||
camera.target.x = -f64::from(offset.x) * units;
|
||||
camera.target.y = f64::from(offset.y) * units;
|
||||
camera
|
||||
};
|
||||
if camera.is_valid() {
|
||||
app.render_workspace.view.result_camera = camera;
|
||||
app.render_workspace.view.result_domain = Some(domain);
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
|
||||
fn show_result(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
cache_render_images(app, ui.ctx());
|
||||
let t = Tokens::get();
|
||||
ui.painter().rect_filled(ui.max_rect(), 0.0, t.viewport_bottom);
|
||||
// The floating shell paints after this canvas. Keep image actions in its free
|
||||
// content area so neither ribbon nor Browser can cover their hit targets.
|
||||
let mut free = crate::render_ui::canvas(app, ui.max_rect());
|
||||
if ribbon::busy(app) {
|
||||
let host = app.universal_panel_host_enabled();
|
||||
if !host {
|
||||
// Classic framing and navigation cannot leave the host fit cache valid.
|
||||
app.render_workspace.view.result_domain = None;
|
||||
}
|
||||
let viewport = ui.max_rect();
|
||||
// The host image keeps its whole below-app-bar projection. Persistent
|
||||
// controls paint later, after the legacy shell has registered real bounds.
|
||||
let mut free = if host { viewport } else { crate::render_ui::canvas(app, viewport) };
|
||||
if !host && ribbon::busy(app) {
|
||||
free = crate::ui_kit::Container::below_navigation_row(free);
|
||||
}
|
||||
if host {
|
||||
app.viewport.rect = Some(viewport);
|
||||
crate::viewport::refresh_layout(app, ui.ctx());
|
||||
}
|
||||
let mut content = ui.new_child(egui::UiBuilder::new().max_rect(free).id_salt("render_result_content"));
|
||||
let ui = &mut content;
|
||||
let Some((info, preview)) = displayed_image(app).map(|display| (display.info.clone(), display.preview.cloned())) else {
|
||||
let Some(info) = displayed_image(app).map(|display| display.info.clone()) else {
|
||||
let message = match &app.render_workspace.image {
|
||||
Some((_, Err(error))) => error.clone(),
|
||||
_ if ribbon::busy(app) => app.tr("render.state_in_progress").to_string(),
|
||||
_ => app.tr("render.result_empty").to_string(),
|
||||
};
|
||||
crate::ui_kit::Container::navigation_contents(ui, |ui| {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
crate::ui_kit::text(
|
||||
ui,
|
||||
app.tr(if ribbon::busy(app) { "render.state_in_progress" } else { "render.result_title" }),
|
||||
crate::ui_kit::Text::Inline,
|
||||
);
|
||||
result_actions(app, ui);
|
||||
});
|
||||
});
|
||||
if !host {
|
||||
crate::ui_kit::Container::navigation_contents(ui, |ui| result_header(app, ui));
|
||||
}
|
||||
let canvas = ui.available_rect_before_wrap();
|
||||
ui.centered_and_justified(|ui| {
|
||||
ui.add(egui::Label::new(egui::RichText::new(message).size(t.font_heading).color(t.text)).wrap());
|
||||
@@ -1798,55 +2039,9 @@ fn show_result(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
app.viewport.rect = Some(canvas);
|
||||
return;
|
||||
};
|
||||
crate::ui_kit::Container::navigation_contents(ui, |ui| {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
crate::ui_kit::text(
|
||||
ui,
|
||||
app.tr(if preview.is_some() { "render.state_in_progress" } else { "render.state_completed" }),
|
||||
crate::ui_kit::Text::Inline,
|
||||
);
|
||||
result_actions(app, ui);
|
||||
});
|
||||
if let Some(preview) = &preview {
|
||||
ui.colored_label(
|
||||
t.warning,
|
||||
format!(
|
||||
"{} · {} {} · {} {}",
|
||||
app.tr("render.result_provisional"),
|
||||
preview.samples_per_pixel,
|
||||
app.tr("render.cpu_progressive_spp"),
|
||||
app.tr("render.result_sequence"),
|
||||
preview.frame_sequence
|
||||
),
|
||||
);
|
||||
ui.small(app.tr("render.result_provisional_help"));
|
||||
}
|
||||
if let Some(display) = displayed_image(app)
|
||||
&& let Err(error) = display.image
|
||||
{
|
||||
ui.colored_label(t.warning, error);
|
||||
}
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.strong(format!("{} × {} px · PNG · {}", info.width, info.height, info.executor.as_str()));
|
||||
ui.label(format!(
|
||||
"{} {}:{}:{} · {} {}",
|
||||
app.tr("render.result_job"),
|
||||
info.job.session,
|
||||
info.job.serial,
|
||||
info.job.generation,
|
||||
app.tr("render.result_capture"),
|
||||
info.scene_generation
|
||||
));
|
||||
});
|
||||
if reduced_display(app) {
|
||||
ui.colored_label(t.warning, app.tr("render.result_reduced_display"));
|
||||
}
|
||||
let stale = info.scene_generation != app.session.revision;
|
||||
ui.colored_label(if stale { t.warning } else { t.text_dim }, app.tr(if stale { "render.image_stale" } else { "render.result_current" }));
|
||||
if app.render_workspace.view.job.is_some_and(|job| job != info.job) {
|
||||
ui.small(app.tr("render.result_retained"));
|
||||
}
|
||||
});
|
||||
if !host {
|
||||
crate::ui_kit::Container::navigation_contents(ui, |ui| result_header(app, ui));
|
||||
}
|
||||
let rect = ui.available_rect_before_wrap();
|
||||
if rect.width() < 1.0 || rect.height() < 1.0 {
|
||||
return;
|
||||
@@ -1856,14 +2051,18 @@ fn show_result(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
crate::viewport::refresh_layout(app, ui.ctx());
|
||||
let size = [info.width, info.height];
|
||||
let scale = app.render_workspace.view.result_scale;
|
||||
if scale != ResultScale::Free {
|
||||
if !host && scale != ResultScale::Free {
|
||||
app.render_workspace.view.result_camera = result_camera(size, rect, ui.ctx().pixels_per_point(), scale);
|
||||
}
|
||||
with_result_camera(app, |app| {
|
||||
crate::navigation::handle(app, ui, rect, &response, crate::navigation::NavCaps { orbit: false, pick: false });
|
||||
});
|
||||
if host {
|
||||
app.render_workspace.result_navigation = Some((rect, response, false));
|
||||
} else {
|
||||
with_result_camera(app, |app| {
|
||||
crate::navigation::handle(app, ui, rect, &response, crate::navigation::NavCaps { orbit: false, pick: false });
|
||||
});
|
||||
}
|
||||
let after = app.render_workspace.view.result_scale;
|
||||
if after != scale && after != ResultScale::Free {
|
||||
if !host && after != scale && after != ResultScale::Free {
|
||||
app.render_workspace.view.result_camera = result_camera(size, rect, ui.ctx().pixels_per_point(), after);
|
||||
}
|
||||
let camera = app.render_workspace.view.result_camera;
|
||||
@@ -1894,15 +2093,19 @@ fn show_result(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
}
|
||||
painter.rect_stroke(image_rect, 0.0, egui::Stroke::new(1.0, t.border), egui::StrokeKind::Outside);
|
||||
}
|
||||
let percent = f64::from(rect.height() * ui.ctx().pixels_per_point()) / (2.0 * camera.half_height()) * 100.0;
|
||||
let label = painter.layout_no_wrap(format!("{percent:.1}%"), egui::FontId::proportional(t.font_label), t.text);
|
||||
let badge = egui::Rect::from_min_size(
|
||||
rect.left_bottom() + egui::vec2(t.space_8, -label.size().y - t.space_8 * 2.0),
|
||||
label.size() + egui::vec2(t.space_8 * 2.0, t.space_8),
|
||||
);
|
||||
painter.rect_filled(badge, t.control_radius, t.panel);
|
||||
painter.galley(badge.min + egui::vec2(t.space_8, t.space_8 * 0.5), label, t.text);
|
||||
crate::navigation_bar_view::show(app, ui, rect);
|
||||
if !host {
|
||||
let percent = f64::from(rect.height() * ui.ctx().pixels_per_point()) / (2.0 * camera.half_height()) * 100.0;
|
||||
let label = painter.layout_no_wrap(format!("{percent:.1}%"), egui::FontId::proportional(t.font_label), t.text);
|
||||
let badge = egui::Rect::from_min_size(
|
||||
rect.left_bottom() + egui::vec2(t.space_8, -label.size().y - t.space_8 * 2.0),
|
||||
label.size() + egui::vec2(t.space_8 * 2.0, t.space_8),
|
||||
);
|
||||
painter.rect_filled(badge, t.control_radius, t.panel);
|
||||
painter.galley(badge.min + egui::vec2(t.space_8, t.space_8 * 0.5), label, t.text);
|
||||
}
|
||||
if !app.universal_panel_host_enabled() {
|
||||
crate::navigation_bar_view::show(app, ui, rect);
|
||||
}
|
||||
}
|
||||
|
||||
/// What the product scene is extracted from: the document (appearances, the history marker),
|
||||
@@ -2197,6 +2400,43 @@ pub(crate) fn picture_layout(app: &SolveApp, layout: &crate::viewport_layout::La
|
||||
crate::viewport_layout::Layout { viewport: frame, drawable: layout.drawable.intersect(frame.shrink(16.0)), ..layout.clone() }
|
||||
}
|
||||
|
||||
/// The exact projection used by Frame/selected-Shot paint and picking, with
|
||||
/// current real host obstacles clipped to that picture rather than the window.
|
||||
pub(crate) fn host_picture_layout(
|
||||
app: &SolveApp,
|
||||
layout: &crate::viewport_layout::Layout,
|
||||
usable: &crate::panel_runtime::HostUsableRegion,
|
||||
) -> Option<crate::viewport_layout::Layout> {
|
||||
let picture = shot::preview_rect(app, layout.viewport).unwrap_or(layout.viewport);
|
||||
crate::viewport_layout::host_projection_layout(layout, usable, picture)
|
||||
}
|
||||
|
||||
/// Explicit product Fit shares the host fitter but keeps Render's authored lens
|
||||
/// and existing full-size Fit policy. Layout changes never call this helper.
|
||||
pub(crate) fn fit_host_product_bounds(
|
||||
app: &SolveApp,
|
||||
cam: Camera,
|
||||
bounds: &solidcraft_engine::geom::Aabb3,
|
||||
layout: &crate::viewport_layout::Layout,
|
||||
usable: &crate::panel_runtime::HostUsableRegion,
|
||||
) -> Option<Camera> {
|
||||
let picture = host_picture_layout(app, layout, usable)?;
|
||||
crate::viewport_layout::fit_host_bounds(cam, bounds, &picture, picture.usable.as_ref()?, cam.fov, 1.0)
|
||||
}
|
||||
|
||||
/// Look At/Centre uses the same picture and authored FOV while preserving the
|
||||
/// requested focus and distance contract of the shared centring implementation.
|
||||
pub(crate) fn centre_host_product_camera(
|
||||
app: &SolveApp,
|
||||
cam: Camera,
|
||||
bounds: Option<&solidcraft_engine::geom::Aabb3>,
|
||||
layout: &crate::viewport_layout::Layout,
|
||||
usable: &crate::panel_runtime::HostUsableRegion,
|
||||
) -> Option<Camera> {
|
||||
let picture = host_picture_layout(app, layout, usable)?;
|
||||
crate::viewport_layout::centre_host_camera(cam, bounds, &picture, picture.usable.as_ref()?, cam.fov)
|
||||
}
|
||||
|
||||
/// The size the product preview draws at for a viewport of `full` physical pixels: the full
|
||||
/// size when the viewport executor admits it, else the largest size at the same aspect it does.
|
||||
/// Without an executor the request is left for resolution to report.
|
||||
@@ -2226,6 +2466,7 @@ fn preview_background(app: &SolveApp) -> Tokens {
|
||||
}
|
||||
|
||||
pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
app.render_workspace.result_navigation = None;
|
||||
if app.render_workspace.view.compare.is_some() {
|
||||
app.render_workspace.view.environment_ring = environment::RingView::default();
|
||||
assign::stop(app);
|
||||
@@ -2288,8 +2529,10 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
crate::gpu::paint_background(ui.painter(), viewport, &preview_background(app));
|
||||
paint_product(app, ui, rect, app.cam, None);
|
||||
shot::overlay(app, ui, viewport);
|
||||
crate::viewport::axis_view(app, ui, viewport);
|
||||
crate::navigation_bar_view::show(app, ui, viewport);
|
||||
if !app.universal_panel_host_enabled() {
|
||||
crate::viewport::axis_view(app, ui, viewport);
|
||||
crate::navigation_bar_view::show(app, ui, viewport);
|
||||
}
|
||||
}
|
||||
|
||||
fn product_projection(camera: Camera, radius: f64, canvas: egui::Rect, image: Option<egui::Rect>) -> solidcraft_engine::render::Mat4 {
|
||||
@@ -2484,7 +2727,10 @@ pub(crate) fn apply_command(app: &mut SolveApp, id: &str, reply: &serde_json::Va
|
||||
}
|
||||
match view {
|
||||
"fit" => fit_result(app),
|
||||
"actual" => app.render_workspace.view.result_scale = ResultScale::Actual,
|
||||
"actual" => {
|
||||
app.render_workspace.view.result_scale = ResultScale::Actual;
|
||||
app.render_workspace.view.result_domain = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
app.cancel_view_animation();
|
||||
|
||||
@@ -40,7 +40,7 @@ pub(super) fn apply(app: &mut SolveApp, reply: &serde_json::Value) -> Result<(),
|
||||
.or(left)
|
||||
.ok_or("comparison needs a retained result")?;
|
||||
if app.render_workspace.view.compare.as_ref().is_none_or(|view| view.reference != reference) {
|
||||
app.render_workspace.view.result_scale = ResultScale::Fit;
|
||||
fit_result(app);
|
||||
}
|
||||
app.render_workspace.view.compare = Some(View { left, right, position, reference, dragging: false });
|
||||
app.render_workspace.view.result = true;
|
||||
@@ -181,6 +181,25 @@ fn label(app: &SolveApp, side: Option<JobId>) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn summary(app: &SolveApp, ui: &mut egui::Ui) {
|
||||
let Some(view) = &app.render_workspace.view.compare else { return };
|
||||
let Some(reference) = app.render_workspace.view.retained.iter().find(|result| result.frame.job == view.reference) else { return };
|
||||
let stale = app.render_workspace.view.retained.iter().any(|result| [view.left, view.right].contains(&Some(result.frame.job)) && result.stale);
|
||||
ui_kit::completion_text(ui, app.tr(if stale { "render.image_stale" } else { "render.result_current" }), !stale);
|
||||
let summary = crate::i18n::format(
|
||||
"render.compare_summary",
|
||||
&[
|
||||
("shot", reference.shot.as_deref().unwrap_or_else(|| crate::i18n::tr("render.results_unnamed"))),
|
||||
("width", &reference.frame.width.to_string()),
|
||||
("height", &reference.frame.height.to_string()),
|
||||
("seconds", &format!("{:.0}", reference.seconds)),
|
||||
("renderer", reference.frame.executor.as_str()),
|
||||
("revision", &reference.frame.scene_generation.to_string()),
|
||||
],
|
||||
);
|
||||
ui_kit::text(ui, &summary, ui_kit::Text::Inline);
|
||||
}
|
||||
|
||||
pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
cache_render_images(app, ui.ctx());
|
||||
if app.render_workspace.view.compare.is_none() {
|
||||
@@ -188,35 +207,34 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
return;
|
||||
}
|
||||
ui.painter().rect_filled(ui.max_rect(), 0.0, Tokens::get().viewport_bottom);
|
||||
let mut free = crate::render_ui::canvas(app, ui.max_rect());
|
||||
if ribbon::busy(app) {
|
||||
let host = app.universal_panel_host_enabled();
|
||||
if !host {
|
||||
// Classic framing and navigation cannot leave the host fit cache valid.
|
||||
app.render_workspace.view.result_domain = None;
|
||||
}
|
||||
let viewport = ui.max_rect();
|
||||
let mut free = if host { viewport } else { crate::render_ui::canvas(app, viewport) };
|
||||
if !host && ribbon::busy(app) {
|
||||
free = ui_kit::Container::below_navigation_row(free);
|
||||
}
|
||||
if host {
|
||||
app.viewport.rect = Some(viewport);
|
||||
crate::viewport::refresh_layout(app, ui.ctx());
|
||||
}
|
||||
let mut content = ui.new_child(egui::UiBuilder::new().max_rect(free).id_salt("render_compare_content"));
|
||||
let ui = &mut content;
|
||||
ui_kit::Container::navigation_contents(ui, |ui| {
|
||||
ui.horizontal_wrapped(|ui| result_actions(app, ui));
|
||||
});
|
||||
if !host {
|
||||
ui_kit::Container::navigation_contents(ui, |ui| {
|
||||
ui.horizontal_wrapped(|ui| result_actions(app, ui));
|
||||
});
|
||||
}
|
||||
let Some(view) = app.render_workspace.view.compare.clone() else { return };
|
||||
app.render_workspace.comparison_images.retain(|(job, _)| [view.left, view.right].contains(&Some(*job)));
|
||||
let Some(reference) = app.render_workspace.view.retained.iter().find(|result| result.frame.job == view.reference).cloned() else { return };
|
||||
let stale = app.render_workspace.view.retained.iter().any(|result| [view.left, view.right].contains(&Some(result.frame.job)) && result.stale);
|
||||
// Keep freshness and the capture summary below the image, as in the result board.
|
||||
ui_kit::Panel::pinned_footer(ui, "render_compare_summary", 2, |ui| {
|
||||
ui_kit::completion_text(ui, app.tr(if stale { "render.image_stale" } else { "render.result_current" }), !stale);
|
||||
let summary = crate::i18n::format(
|
||||
"render.compare_summary",
|
||||
&[
|
||||
("shot", reference.shot.as_deref().unwrap_or_else(|| crate::i18n::tr("render.results_unnamed"))),
|
||||
("width", &reference.frame.width.to_string()),
|
||||
("height", &reference.frame.height.to_string()),
|
||||
("seconds", &format!("{:.0}", reference.seconds)),
|
||||
("renderer", reference.frame.executor.as_str()),
|
||||
("revision", &reference.frame.scene_generation.to_string()),
|
||||
],
|
||||
);
|
||||
ui_kit::text(ui, &summary, ui_kit::Text::Inline);
|
||||
});
|
||||
if !host {
|
||||
// Classic keeps freshness and capture details below its image.
|
||||
ui_kit::Panel::pinned_footer(ui, "render_compare_summary", 2, |ui| summary(app, ui));
|
||||
}
|
||||
let canvas = ui.available_rect_before_wrap();
|
||||
if !canvas.is_positive() {
|
||||
return;
|
||||
@@ -225,7 +243,7 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
app.viewport.rect = Some(canvas);
|
||||
crate::viewport::refresh_layout(app, ui.ctx());
|
||||
let size = [reference.frame.width, reference.frame.height];
|
||||
if app.render_workspace.view.result_scale != ResultScale::Free {
|
||||
if !host && app.render_workspace.view.result_scale != ResultScale::Free {
|
||||
app.render_workspace.view.result_camera = result_camera(size, canvas, ui.ctx().pixels_per_point(), app.render_workspace.view.result_scale);
|
||||
}
|
||||
// Reserve the divider before navigation; captured drags cannot reach any camera path.
|
||||
@@ -240,7 +258,9 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
{
|
||||
app.set_status(error, true);
|
||||
}
|
||||
if !captured {
|
||||
if host {
|
||||
app.render_workspace.result_navigation = Some((canvas, response, captured));
|
||||
} else if !captured {
|
||||
with_result_camera(app, |app| {
|
||||
crate::navigation::handle(app, ui, canvas, &response, crate::navigation::NavCaps { orbit: false, pick: false });
|
||||
});
|
||||
|
||||
@@ -7433,3 +7433,738 @@ fn render_results_batch_continues_in_background_tabs_and_keeps_each_shot_result_
|
||||
assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len()));
|
||||
assert!(results.iter().all(|result| result.frame.scene_generation == captured_revision));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_product_fit_uses_frame_and_selected_shot_projection_with_its_own_fov() {
|
||||
use crate::panel_runtime::{logical_rect, resolve_usable_region};
|
||||
use crate::viewport_layout::Layout;
|
||||
use egui::{Rect, pos2, vec2};
|
||||
use solidcore_record::Vec3;
|
||||
use solidcraft_engine::geom::Aabb3;
|
||||
let mut h = Harness::new();
|
||||
enter(&mut h.app, true).unwrap();
|
||||
let name = h.app.render_workspace.view.name.clone();
|
||||
h.app.run("render.settings.set", json!({"name":name,"set":{"width":1024,"height":4096}})).unwrap();
|
||||
setups::load(&mut h.app);
|
||||
let viewport = Rect::from_min_max(pos2(0.0, 34.0), pos2(1400.0, 950.0));
|
||||
h.app.shell.content = Some(viewport);
|
||||
h.app.shell.workspace_panels.clear();
|
||||
h.app.preferences.perspective_fov = 1.2;
|
||||
h.app.ui.perspective = true;
|
||||
let bounds = Aabb3 { min: Vec3::new(-60.0, -10.0, -5.0), max: Vec3::new(60.0, 10.0, 5.0) };
|
||||
for selected_shot in [false, true] {
|
||||
h.app.render_workspace.view.stage = if selected_shot { Stage::Look } else { Stage::Frame };
|
||||
h.app.render_workspace.view.selection = if selected_shot { RenderSelection::Shot(name.clone()) } else { RenderSelection::Nothing };
|
||||
let picture = shot::preview_rect(&h.app, viewport).unwrap();
|
||||
assert!((picture.width() / picture.height() - 0.25).abs() < 1e-5);
|
||||
let obstacle = Rect::from_min_size(picture.min, vec2(picture.width() * 0.3, 160.0));
|
||||
let usable = resolve_usable_region(logical_rect(viewport), &[logical_rect(obstacle)]).unwrap();
|
||||
let layout = Layout::host_with_axis(viewport, &usable, crate::prefs::NavigatorStyle::Axes, egui::Vec2::ZERO, Rect::NOTHING, false);
|
||||
for fov in [0.0, 0.95] {
|
||||
let camera = Camera { fov, ..Default::default() };
|
||||
let fitted = fit_host_product_bounds(&h.app, camera, &bounds, &layout, &usable).unwrap();
|
||||
assert_eq!(fitted.fov, fov, "the Design FOV preference must never replace the product lens");
|
||||
let radius = (bounds.diagonal() + bounds.center().dist(fitted.target)).max(fitted.half_height() * 2.0).max(10.0);
|
||||
let mut footprint = Rect::NOTHING;
|
||||
for point in corners(&bounds) {
|
||||
let (x, y, _) = fitted.to_screen(point, f64::from(picture.width()), f64::from(picture.height()), radius).unwrap();
|
||||
footprint.extend_with(pos2(picture.left() + x as f32, picture.top() + y as f32));
|
||||
}
|
||||
assert!(picture.contains_rect(footprint.expand(Tokens::get().space_4)));
|
||||
assert!(!footprint.expand(Tokens::get().space_4).intersect(obstacle).is_positive());
|
||||
let centred = centre_host_product_camera(&h.app, camera, Some(&bounds), &layout, &usable).unwrap();
|
||||
assert_eq!(centred.distance.to_bits(), camera.distance.to_bits());
|
||||
assert_eq!(centred.fov, camera.fov);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_bounded_results_and_comparison_actions_are_visible_and_clickable() {
|
||||
use egui::{Event, Modifiers, PointerButton};
|
||||
for comparison in [false, true] {
|
||||
let (mut h, _, selected) = render_results_compare_fixture();
|
||||
h.app.preferences.language = "en".into();
|
||||
h.call("ui.resize", json!({"width":1440,"height":960}));
|
||||
h.app.run("view.render_stage", json!({"stage":"frame"})).unwrap();
|
||||
crate::panel_runtime::enable_host_specimen(&mut h.app, "tabs").unwrap();
|
||||
let select = |h: &mut Harness| {
|
||||
if comparison {
|
||||
h.app.run("render.compare", json!({"left":0,"right":1})).unwrap();
|
||||
} else {
|
||||
h.app.run("render.result.select", json!({"index":1})).unwrap();
|
||||
}
|
||||
h.frames(4);
|
||||
};
|
||||
select(&mut h);
|
||||
h.app.pending_fit = None;
|
||||
h.app.cancel_view_animation();
|
||||
let canvas = h.app.viewport.rect.unwrap();
|
||||
let document = h.app.session.doc.clone();
|
||||
let history = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision);
|
||||
let product = h.app.cam;
|
||||
let card = h.app.shell.workspace_panels["render:result-controls"].0;
|
||||
assert!(card.width() <= 528.0, "exercise the native report's bounded card: {card:?}");
|
||||
for target in [
|
||||
"render:results",
|
||||
"render:result-discard",
|
||||
"render:result-model",
|
||||
"render:result-fit",
|
||||
"render:result-actual",
|
||||
"render:result-copy",
|
||||
"render:result-export",
|
||||
"render:result-close",
|
||||
] {
|
||||
let rect = crate::scenario::rect_of(target).unwrap();
|
||||
assert!(card.contains_rect(rect), "{target}: {rect:?} outside {card:?}, comparison={comparison}");
|
||||
assert!(crate::scenario::rect_of("render:result-actions-clip").unwrap().contains_rect(rect), "{target} is clipped");
|
||||
}
|
||||
let click = |h: &mut Harness, target: &str| {
|
||||
let rect = crate::scenario::rect_of(target).unwrap();
|
||||
assert!(h.app.shell.workspace_panels["render:result-controls"].0.contains_rect(rect), "{target}");
|
||||
assert!(crate::scenario::rect_of("render:result-actions-clip").unwrap().contains_rect(rect), "{target}");
|
||||
let pos = rect.center();
|
||||
h.frame_with(vec![Event::PointerMoved(pos)]);
|
||||
h.frame_with(vec![Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }]);
|
||||
h.frame_with(vec![Event::PointerButton { pos, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }]);
|
||||
};
|
||||
click(&mut h, "render:result-actual");
|
||||
assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Actual);
|
||||
click(&mut h, "render:result-fit");
|
||||
assert_eq!(h.app.render_workspace.view.result_scale, ResultScale::Fit);
|
||||
if comparison {
|
||||
click(&mut h, "render:compare:swap");
|
||||
assert_eq!(h.app.render_workspace.view.compare.as_ref().unwrap().left, Some(selected));
|
||||
}
|
||||
click(&mut h, "render:result-copy");
|
||||
let mut copied = false;
|
||||
for _ in 0..4 {
|
||||
copied |= h.output.commands.iter().any(|command| matches!(command, egui::OutputCommand::CopyImage(image) if image.size == [16, 16]));
|
||||
h.frame();
|
||||
}
|
||||
assert!(copied, "Copy must receive a real pointer click inside the card");
|
||||
click(&mut h, "render:result-export");
|
||||
h.settle();
|
||||
assert!(h.dir.join("render.png").is_file(), "Export must receive the click and use the harness picker");
|
||||
click(&mut h, "render:result-model");
|
||||
assert!(!result_active(&h.app));
|
||||
assert!(h.app.render_workspace.view.compare.is_none());
|
||||
select(&mut h);
|
||||
click(&mut h, "render:result-close");
|
||||
assert!(!result_active(&h.app));
|
||||
assert!(h.app.render_workspace.view.compare.is_none());
|
||||
assert_eq!(h.app.render_workspace.view.completed, Some(selected));
|
||||
assert_eq!(h.app.viewport.rect, Some(canvas));
|
||||
assert_eq!(h.app.cam, product);
|
||||
assert!(Arc::ptr_eq(&document, &h.app.session.doc));
|
||||
assert_eq!((h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision), history);
|
||||
}
|
||||
}
|
||||
|
||||
/// Render the production legacy card at an assigned bound; no duplicate toolbar
|
||||
/// or controller logic. Full-app layout/navigation remain covered above.
|
||||
fn bounded_result_card_frame(h: &mut Harness, bounds: egui::Rect, events: Vec<egui::Event>) -> egui::Rect {
|
||||
let canvas = h.app.viewport.rect.unwrap();
|
||||
let time = h.ctx.input(|input| input.time) + 1.0 / 60.0;
|
||||
crate::scenario::clear_handles();
|
||||
let mut painted = egui::Rect::NOTHING;
|
||||
let mut output =
|
||||
h.ctx.run_ui(egui::RawInput { screen_rect: Some(canvas), time: Some(time), focused: true, events, ..Default::default() }, |ui| {
|
||||
painted = host_result_card(&mut h.app, ui, bounds, canvas)
|
||||
});
|
||||
output.textures_delta.clear();
|
||||
h.shapes = output.shapes;
|
||||
h.output = output.platform_output;
|
||||
painted
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_narrow_result_cards_scroll_real_actions_into_their_clip() {
|
||||
use egui::{Event, Modifiers, MouseWheelUnit, PointerButton, TouchPhase};
|
||||
for comparison in [false, true] {
|
||||
for width in [240.0, 120.0] {
|
||||
let (mut h, _, _) = render_results_compare_fixture();
|
||||
crate::panel_runtime::enable_host_specimen(&mut h.app, "tabs").unwrap();
|
||||
if comparison {
|
||||
h.app.run("render.compare", json!({"left":0,"right":1})).unwrap();
|
||||
} else {
|
||||
h.app.run("render.result.select", json!({"index":1})).unwrap();
|
||||
}
|
||||
h.frames(4);
|
||||
let canvas = h.app.viewport.rect.unwrap();
|
||||
let product = h.app.cam;
|
||||
let image = h.app.render_workspace.view.result_camera;
|
||||
let document = h.app.session.doc.clone();
|
||||
let history = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision);
|
||||
let bounds = egui::Rect::from_min_size(canvas.min, egui::vec2(width, 96.0));
|
||||
for _ in 0..4 {
|
||||
assert!(bounds.contains_rect(bounded_result_card_frame(&mut h, bounds, Vec::new())));
|
||||
}
|
||||
let initial_close = crate::scenario::rect_of("render:result-close").unwrap();
|
||||
let mut moved = false;
|
||||
for target in [
|
||||
"render:result-copy",
|
||||
"render:result-export",
|
||||
"render:result-fit",
|
||||
"render:result-actual",
|
||||
"render:result-close",
|
||||
"render:result-model",
|
||||
] {
|
||||
let clip = crate::scenario::rect_of("render:result-actions-clip").unwrap();
|
||||
assert!(bounds.contains_rect(bounded_result_card_frame(
|
||||
&mut h,
|
||||
bounds,
|
||||
vec![
|
||||
Event::PointerMoved(clip.center()),
|
||||
Event::MouseWheel {
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
unit: MouseWheelUnit::Point,
|
||||
delta: egui::Vec2::ZERO,
|
||||
modifiers: Modifiers::NONE,
|
||||
phase: TouchPhase::Start
|
||||
},
|
||||
],
|
||||
)));
|
||||
let mut interaction = None;
|
||||
for _ in 0..60 {
|
||||
let rect = crate::scenario::rect_of(target).unwrap();
|
||||
let clip = crate::scenario::rect_of("render:result-actions-clip").unwrap();
|
||||
let visible = rect.intersect(clip).intersect(bounds);
|
||||
// An intrinsic button can be wider than the card. Its clipped
|
||||
// centre must remain a usable target, even in the 120-point case.
|
||||
if visible.width() >= rect.width().min(24.0) && visible.height() >= rect.height().min(16.0) {
|
||||
assert!(bounds.contains_rect(bounded_result_card_frame(
|
||||
&mut h,
|
||||
bounds,
|
||||
vec![Event::MouseWheel {
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
unit: MouseWheelUnit::Point,
|
||||
delta: egui::Vec2::ZERO,
|
||||
modifiers: Modifiers::NONE,
|
||||
phase: TouchPhase::End,
|
||||
}],
|
||||
)));
|
||||
assert!(!h.ctx.input(|input| input.is_scrolling()));
|
||||
let rect = crate::scenario::rect_of(target).unwrap();
|
||||
let clip = crate::scenario::rect_of("render:result-actions-clip").unwrap();
|
||||
let visible = rect.intersect(clip).intersect(bounds);
|
||||
assert!(visible.width() >= rect.width().min(24.0) && visible.height() >= rect.height().min(16.0));
|
||||
interaction = Some(visible.center());
|
||||
break;
|
||||
}
|
||||
// A bracketed trackpad gesture follows the measured target, never a
|
||||
// reconstructed toolbar or a private scroll-state offset.
|
||||
let delta = clip.center() - rect.center();
|
||||
let painted = bounded_result_card_frame(
|
||||
&mut h,
|
||||
bounds,
|
||||
vec![
|
||||
Event::PointerMoved(clip.center()),
|
||||
Event::MouseWheel {
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
unit: MouseWheelUnit::Point,
|
||||
delta,
|
||||
modifiers: Modifiers::NONE,
|
||||
phase: TouchPhase::Move,
|
||||
},
|
||||
],
|
||||
);
|
||||
assert!(bounds.contains_rect(painted));
|
||||
// ScrollArea stores its new offset after laying out the content.
|
||||
// Publish the resulting geometry before measuring another delta.
|
||||
assert!(bounds.contains_rect(bounded_result_card_frame(&mut h, bounds, Vec::new())));
|
||||
moved |= crate::scenario::rect_of("render:result-close").unwrap() != initial_close;
|
||||
}
|
||||
let pos = interaction.unwrap_or_else(|| panic!("{target} must be reachable by scrolling: width={width}, comparison={comparison}"));
|
||||
assert!(bounds.contains(pos));
|
||||
assert!(crate::scenario::rect_of("render:result-actions-clip").unwrap().contains(pos));
|
||||
// Exercise the widest action through the real clipped widget;
|
||||
// other action outcomes are covered by the full-card fixture.
|
||||
if target == "render:result-model" {
|
||||
assert!(result_active(&h.app));
|
||||
for events in [
|
||||
vec![Event::PointerMoved(pos)],
|
||||
vec![Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }],
|
||||
vec![Event::PointerButton { pos, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }],
|
||||
] {
|
||||
assert!(bounds.contains_rect(bounded_result_card_frame(&mut h, bounds, events)));
|
||||
}
|
||||
assert!(!result_active(&h.app), "the clipped Model button must receive the pointer click");
|
||||
assert!(h.app.render_workspace.view.compare.is_none());
|
||||
}
|
||||
}
|
||||
assert!(moved, "the narrow fixture must exercise actual scrolling");
|
||||
assert_eq!(h.app.viewport.rect, Some(canvas));
|
||||
assert_eq!(h.app.cam, product);
|
||||
assert_eq!(h.app.render_workspace.view.result_camera, image);
|
||||
assert!(Arc::ptr_eq(&document, &h.app.session.doc));
|
||||
assert_eq!((h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision), history);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_tiny_result_cards_clip_paint_and_reject_off_card_action_clicks() {
|
||||
use egui::{Event, Modifiers, PointerButton};
|
||||
for comparison in [false, true] {
|
||||
let (mut h, _, _) = render_results_compare_fixture();
|
||||
crate::panel_runtime::enable_host_specimen(&mut h.app, "tabs").unwrap();
|
||||
if comparison {
|
||||
h.app.run("render.compare", json!({"left":0,"right":1})).unwrap();
|
||||
} else {
|
||||
h.app.run("render.result.select", json!({"index":1})).unwrap();
|
||||
}
|
||||
h.frames(4);
|
||||
let canvas = h.app.viewport.rect.unwrap();
|
||||
let bounds = egui::Rect::from_min_size(canvas.min, egui::vec2(48.0, 44.0));
|
||||
for _ in 0..4 {
|
||||
assert!(bounds.contains_rect(bounded_result_card_frame(&mut h, bounds, Vec::new())));
|
||||
}
|
||||
let mut visible_shapes = 0;
|
||||
for shape in &h.shapes {
|
||||
if shape.clip_rect.is_positive() && shape.shape.visual_bounding_rect().is_positive() {
|
||||
assert!(bounds.contains_rect(shape.clip_rect), "legacy card paint escaped: {:?}", shape.clip_rect);
|
||||
visible_shapes += 1;
|
||||
}
|
||||
}
|
||||
assert!(visible_shapes > 0, "the tiny card must still exercise visible paint clips");
|
||||
let pos = crate::scenario::rect_of("render:result-close").unwrap().center();
|
||||
assert!(!bounds.contains(pos), "the tiny fixture must put Close outside its real clip");
|
||||
assert!(canvas.contains(pos), "exercise clipping inside the screen, rather than an off-screen pointer");
|
||||
for events in [
|
||||
vec![Event::PointerMoved(pos)],
|
||||
vec![Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }],
|
||||
vec![Event::PointerButton { pos, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }],
|
||||
] {
|
||||
assert!(bounds.contains_rect(bounded_result_card_frame(&mut h, bounds, events)));
|
||||
}
|
||||
assert!(result_active(&h.app), "an off-card target rectangle cannot receive a click");
|
||||
assert_eq!(h.app.render_workspace.view.compare.is_some(), comparison);
|
||||
assert_eq!(h.app.viewport.rect, Some(canvas));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_results_and_comparison_keep_full_canvas_real_control_footprints_and_cameras_on_panel_changes() {
|
||||
use crate::panel_runtime::{egui_rect, logical_rect};
|
||||
for comparison in [false, true] {
|
||||
let (mut h, _, _) = render_results_compare_fixture();
|
||||
crate::panel_runtime::enable_host_specimen(&mut h.app, "docks").unwrap();
|
||||
if comparison {
|
||||
h.app.run("render.compare", json!({"left":0,"right":1})).unwrap();
|
||||
} else {
|
||||
h.app.run("render.result.select", json!({"index":1})).unwrap();
|
||||
}
|
||||
h.frames(4);
|
||||
h.app.pending_fit = None;
|
||||
h.app.cancel_view_animation();
|
||||
let domain = egui_rect(h.app.universal_panel_frame().unwrap().layout.render_domain);
|
||||
assert_eq!(h.app.viewport.rect, Some(domain));
|
||||
if comparison {
|
||||
assert_eq!(crate::scenario::rect_of("render:compare:canvas"), Some(domain));
|
||||
}
|
||||
let controls = h.app.shell.workspace_panels["render:result-controls"].0;
|
||||
assert!(domain.contains_rect(controls));
|
||||
assert!(h.app.shell.cards.iter().all(|card| !controls.intersect(*card).is_positive()), "the later ribbon must never cover actions");
|
||||
assert!(h.app.universal_panel_frame().unwrap().layout.usable.contains_rect(logical_rect(controls)));
|
||||
assert!(crate::shell::host_usable(&h.app).unwrap().obstacles.contains(&logical_rect(controls)));
|
||||
let product = h.app.cam;
|
||||
let image = h.app.render_workspace.view.result_camera;
|
||||
let draft = h.app.render_workspace.view.draft.clone();
|
||||
let dirty = h.app.render_workspace.view.dirty;
|
||||
let document = h.app.session.doc.clone();
|
||||
let history = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision);
|
||||
h.app.run_panel_command("panel.collapse", &json!({"target":{"type":"instance","id":"specimen-0"},"collapsed":true})).unwrap();
|
||||
h.frames(4);
|
||||
assert_eq!(h.app.viewport.rect, Some(domain));
|
||||
assert_eq!(h.app.cam, product);
|
||||
assert_eq!(h.app.render_workspace.view.result_camera, image, "an already fitted image is not reframed by panels");
|
||||
assert_eq!(h.app.render_workspace.view.draft, draft);
|
||||
assert_eq!(h.app.render_workspace.view.dirty, dirty);
|
||||
assert!(Arc::ptr_eq(&document, &h.app.session.doc));
|
||||
assert_eq!((h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision), history);
|
||||
h.app.run("render.result.view", json!({"view":"actual"})).unwrap();
|
||||
h.frames(3);
|
||||
let actual = result_rect(h.app.render_workspace.view.result_camera, [16, 16], domain);
|
||||
assert!((actual.width() * h.ctx.pixels_per_point() - 16.0).abs() < 1e-4);
|
||||
assert_eq!(h.app.cam, product);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_result_framing_recovers_after_classic_without_refitting_free_cameras_or_panel_moves() {
|
||||
use crate::panel_runtime::logical_rect;
|
||||
use solidcraft_engine::panels::ActionSink as _;
|
||||
for comparison in [false, true] {
|
||||
for scale in [ResultScale::Fit, ResultScale::Actual, ResultScale::Free] {
|
||||
let (mut h, _, _) = render_results_compare_fixture();
|
||||
crate::panel_runtime::enable_host_specimen(&mut h.app, "docks").unwrap();
|
||||
if comparison {
|
||||
h.app.run("render.compare", json!({"left":0,"right":1})).unwrap();
|
||||
} else {
|
||||
h.app.run("render.result.select", json!({"index":1})).unwrap();
|
||||
}
|
||||
h.frames(4);
|
||||
h.app.pending_fit = None;
|
||||
h.app.cancel_view_animation();
|
||||
match scale {
|
||||
ResultScale::Fit => {
|
||||
h.app.run("render.result.view", json!({"view":"fit"})).unwrap();
|
||||
}
|
||||
ResultScale::Actual => {
|
||||
h.app.run("render.result.view", json!({"view":"actual"})).unwrap();
|
||||
}
|
||||
ResultScale::Free => {
|
||||
with_result_camera(&mut h.app, |app| {
|
||||
app.cam.distance *= 0.7;
|
||||
app.cam.target.x += 7.0;
|
||||
app.cam.target.y -= 3.0;
|
||||
});
|
||||
}
|
||||
}
|
||||
h.frames(4);
|
||||
let canvas = h.app.viewport.rect.unwrap();
|
||||
let domain = h.app.render_workspace.view.result_domain;
|
||||
let image = h.app.render_workspace.view.result_camera;
|
||||
let product = h.app.cam;
|
||||
let draft = h.app.render_workspace.view.draft.clone();
|
||||
let dirty = h.app.render_workspace.view.dirty;
|
||||
let document = h.app.session.doc.clone();
|
||||
let history = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision);
|
||||
let layout = h.app.panel_runtime().unwrap().layout().inspect();
|
||||
let controllers = h.app.panel_runtime().unwrap().controller_count();
|
||||
assert_eq!(h.app.render_workspace.view.result_scale, scale);
|
||||
assert_eq!(domain.is_some(), scale != ResultScale::Free);
|
||||
match scale {
|
||||
ResultScale::Fit => {
|
||||
assert!(crate::shell::host_usable(&h.app).unwrap().contains_rect(logical_rect(result_rect(image, [16, 16], canvas))));
|
||||
}
|
||||
ResultScale::Actual => {
|
||||
assert!((result_rect(image, [16, 16], canvas).width() * h.ctx.pixels_per_point() - 16.0).abs() < 1e-4);
|
||||
}
|
||||
ResultScale::Free => {}
|
||||
}
|
||||
|
||||
// Disable only the host: the same runtime and retained content survive.
|
||||
h.app.disable_universal_panel_host().unwrap();
|
||||
h.frames(3);
|
||||
assert!(!h.app.universal_panel_host_enabled());
|
||||
assert_eq!(h.app.render_workspace.view.result_domain, None);
|
||||
let classic = h.app.render_workspace.view.result_camera;
|
||||
if scale == ResultScale::Free {
|
||||
assert_eq!(classic, image);
|
||||
} else {
|
||||
let classic_canvas = h.app.viewport.rect.unwrap();
|
||||
assert_ne!(classic_canvas, canvas);
|
||||
assert_eq!(classic, result_camera([16, 16], classic_canvas, h.ctx.pixels_per_point(), scale));
|
||||
assert_ne!(classic, image, "Classic must actually reframe the image: comparison={comparison}, scale={scale:?}");
|
||||
}
|
||||
assert_eq!(h.app.panel_runtime().unwrap().layout().inspect(), layout);
|
||||
assert_eq!(h.app.panel_runtime().unwrap().controller_count(), controllers);
|
||||
h.app.enable_universal_panel_host(Default::default()).unwrap();
|
||||
h.frames(4);
|
||||
assert_eq!(h.app.viewport.rect, Some(canvas), "the original host domain must return");
|
||||
assert_eq!(h.app.render_workspace.view.result_domain, domain);
|
||||
assert_eq!(h.app.render_workspace.view.result_camera, image, "comparison={comparison}, scale={scale:?}");
|
||||
assert_eq!(h.app.render_workspace.view.result_scale, scale);
|
||||
assert_eq!(h.app.panel_runtime().unwrap().layout().inspect(), layout);
|
||||
assert_eq!(h.app.panel_runtime().unwrap().controller_count(), controllers);
|
||||
|
||||
h.app
|
||||
.run_panel_command(
|
||||
"panel.move",
|
||||
&json!({"target":{"type":"instance","id":"specimen-0"},"destination":{
|
||||
"type":"new_section","section":"camera-moved","index":0,
|
||||
"location":{"type":"dock","zone":"right"},"size":{"width":280,"height":240}
|
||||
}}),
|
||||
)
|
||||
.unwrap();
|
||||
h.frames(4);
|
||||
assert_ne!(h.app.panel_runtime().unwrap().layout().inspect(), layout, "the panel move must commit");
|
||||
assert_eq!(h.app.viewport.rect, Some(canvas));
|
||||
assert_eq!(h.app.render_workspace.view.result_camera, image, "panel changes cannot refit {scale:?}");
|
||||
assert_eq!(h.app.render_workspace.view.result_domain, domain);
|
||||
assert_eq!(h.app.cam, product);
|
||||
assert_eq!(h.app.render_workspace.view.draft, draft);
|
||||
assert_eq!(h.app.render_workspace.view.dirty, dirty);
|
||||
assert!(Arc::ptr_eq(&document, &h.app.session.doc));
|
||||
assert_eq!((h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision), history);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_result_controls_shield_wheel_and_comparison_divider_keeps_capture() {
|
||||
use egui::{Event, Modifiers, MouseWheelUnit, PointerButton, vec2};
|
||||
let (mut h, _, _) = render_results_compare_fixture();
|
||||
crate::panel_runtime::enable_host_specimen(&mut h.app, "docks").unwrap();
|
||||
h.app.run("render.compare", json!({"left":0,"right":1})).unwrap();
|
||||
h.frames(4);
|
||||
h.app.preferences.nav = "maya".into();
|
||||
h.app.render_workspace.view.result_scale = ResultScale::Free;
|
||||
let product = h.app.cam;
|
||||
let image = h.app.render_workspace.view.result_camera;
|
||||
let controls = h.app.shell.workspace_panels["render:result-controls"].0;
|
||||
h.frame_with(vec![
|
||||
Event::PointerMoved(controls.center()),
|
||||
Event::MouseWheel {
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
unit: MouseWheelUnit::Point,
|
||||
delta: vec2(0.0, -300.0),
|
||||
modifiers: Modifiers::NONE,
|
||||
phase: egui::TouchPhase::Move,
|
||||
},
|
||||
]);
|
||||
assert_eq!(h.app.cam, product);
|
||||
assert_eq!(h.app.render_workspace.view.result_camera, image);
|
||||
let canvas = h.app.viewport.rect.unwrap();
|
||||
let start = crate::scenario::rect_of("render:compare:handle").unwrap().center();
|
||||
assert!(!controls.contains(start));
|
||||
h.frame_with(vec![
|
||||
Event::ModifiersChanged(Modifiers::ALT),
|
||||
Event::PointerMoved(start),
|
||||
Event::PointerButton { pos: start, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::ALT },
|
||||
]);
|
||||
let end = egui::pos2(canvas.right() + 100.0, start.y);
|
||||
h.frame_with(vec![
|
||||
Event::PointerMoved(end),
|
||||
Event::MouseWheel {
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
unit: MouseWheelUnit::Point,
|
||||
delta: vec2(0.0, -300.0),
|
||||
modifiers: Modifiers::ALT,
|
||||
phase: egui::TouchPhase::Move,
|
||||
},
|
||||
]);
|
||||
assert!((h.app.render_workspace.view.compare.as_ref().unwrap().position - 0.95).abs() < 1e-6);
|
||||
assert_eq!(h.app.render_workspace.view.result_camera, image);
|
||||
assert_eq!(h.app.cam, product);
|
||||
h.frame_with(vec![Event::PointerButton { pos: end, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::ALT }]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_panel_capture_blocks_result_navigation_through_release() {
|
||||
use crate::panel_runtime::{HostControlTarget, HostPointerTarget, HostResizeEdge, egui_rect};
|
||||
use egui::{Event, Modifiers, MouseWheelUnit, PointerButton, vec2};
|
||||
for comparison in [false, true] {
|
||||
for resize in [false, true] {
|
||||
let (mut h, _, _) = render_results_compare_fixture();
|
||||
crate::panel_runtime::enable_host_specimen(&mut h.app, "docks").unwrap();
|
||||
if comparison {
|
||||
h.app.run("render.compare", json!({"left":0,"right":1})).unwrap();
|
||||
} else {
|
||||
h.app.run("render.result.select", json!({"index":1})).unwrap();
|
||||
}
|
||||
h.frames(4);
|
||||
h.app.pending_fit = None;
|
||||
h.app.cancel_view_animation();
|
||||
h.app.preferences.nav = "maya".into();
|
||||
h.app.preferences.smooth_wheel_zoom = false;
|
||||
h.app.render_workspace.view.result_scale = ResultScale::Free;
|
||||
let product = h.app.cam;
|
||||
let image = h.app.render_workspace.view.result_camera;
|
||||
let frame = h.app.universal_panel_frame().unwrap();
|
||||
let section = frame.layout.sections.iter().find(|section| section.instance.0 == "specimen-0").unwrap();
|
||||
let target = if resize {
|
||||
HostPointerTarget::Resize { section: section.section.clone(), edge: HostResizeEdge::Right }
|
||||
} else {
|
||||
HostPointerTarget::Header { instance: section.instance.clone() }
|
||||
};
|
||||
let start = egui_rect(frame.controls.iter().find(|control| control.target == HostControlTarget::Pointer(target.clone())).unwrap().bounds)
|
||||
.center();
|
||||
let canvas = h.app.viewport.rect.unwrap();
|
||||
// Below this content-sized side card and away from the comparison divider.
|
||||
let end = egui::pos2(canvas.center().x + 80.0, canvas.center().y + 80.0);
|
||||
assert!(!crate::shell::covered(&h.app, end));
|
||||
assert!(!h.app.viewport.layout.as_ref().unwrap().navigation.contains(end));
|
||||
h.frame_with(vec![Event::PointerMoved(start)]);
|
||||
h.frame_with(vec![Event::PointerButton { pos: start, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }]);
|
||||
assert!(host_navigation_captured(&h.app), "the real host control must capture: comparison={comparison}, resize={resize}");
|
||||
h.frame_with(vec![Event::PointerMoved(end)]);
|
||||
assert!(host_navigation_captured(&h.app));
|
||||
assert!(!crate::shell::covered(&h.app, end), "wheel input must be over exposed canvas during capture");
|
||||
let wheel = || Event::MouseWheel {
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
unit: MouseWheelUnit::Point,
|
||||
delta: vec2(0.0, -300.0),
|
||||
modifiers: Modifiers::NONE,
|
||||
phase: egui::TouchPhase::Move,
|
||||
};
|
||||
h.frame_with(vec![wheel()]);
|
||||
assert_eq!(h.app.render_workspace.view.result_camera, image, "a stationary host drag still owns wheel input");
|
||||
h.frame_with(vec![
|
||||
Event::PointerButton { pos: end, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE },
|
||||
wheel(),
|
||||
]);
|
||||
assert!(!host_navigation_captured(&h.app));
|
||||
assert_eq!(h.app.render_workspace.view.result_camera, image, "host release cannot zoom the result");
|
||||
assert_eq!(h.app.cam, product);
|
||||
assert!(h.app.render_workspace.result_navigation.is_none(), "the deferred response is consumed once");
|
||||
// Navigation must recover after release. Find a point outside all current chrome.
|
||||
h.frames(2);
|
||||
let point = (1..10)
|
||||
.flat_map(|y| (1..10).map(move |x| canvas.min + canvas.size() * vec2(x as f32 / 10.0, y as f32 / 10.0)))
|
||||
.find(|point| !crate::shell::covered(&h.app, *point) && !h.app.viewport.layout.as_ref().unwrap().navigation.contains(*point))
|
||||
.unwrap();
|
||||
h.frame_with(vec![Event::PointerMoved(point)]);
|
||||
h.frame_with(vec![wheel()]);
|
||||
assert_ne!(h.app.render_workspace.view.result_camera, image, "fresh canvas wheel input resumes after host release");
|
||||
assert_eq!(h.app.cam, product);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabling_host_in_render_clears_result_controls_before_classic_layout_and_input() {
|
||||
use egui::{Event, Modifiers, MouseWheelUnit, vec2};
|
||||
for comparison in [false, true] {
|
||||
let (mut h, _, _) = render_results_compare_fixture();
|
||||
crate::panel_runtime::enable_host_specimen(&mut h.app, "docks").unwrap();
|
||||
if comparison {
|
||||
h.app.run("render.compare", json!({"left":0,"right":1})).unwrap();
|
||||
} else {
|
||||
h.app.run("render.result.select", json!({"index":1})).unwrap();
|
||||
}
|
||||
h.frames(4);
|
||||
h.app.pending_fit = None;
|
||||
h.app.cancel_view_animation();
|
||||
let controls = h.app.shell.workspace_panels["render:result-controls"].0;
|
||||
let product = h.app.cam;
|
||||
let document = h.app.session.doc.clone();
|
||||
let history = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision);
|
||||
h.app.disable_universal_panel_host().unwrap();
|
||||
// The stale entry exists at the transition; the first real Classic frame must remove it.
|
||||
assert!(h.app.shell.workspace_panels.contains_key("render:result-controls"));
|
||||
h.frame();
|
||||
assert!(active(&h.app));
|
||||
assert!(!h.app.universal_panel_host_enabled());
|
||||
assert_eq!(h.app.render_workspace.view.compare.is_some(), comparison);
|
||||
assert!(!h.app.shell.workspace_panels.contains_key("render:result-controls"));
|
||||
assert!(!crate::shell::fit_rects(&h.app).contains(&controls));
|
||||
assert!(!crate::shell::covered_rects(&h.app).contains(&controls));
|
||||
let layout = h.app.viewport.layout.as_ref().unwrap().clone();
|
||||
assert!(layout.usable.is_none());
|
||||
// Recomputing from the now-clean shell must match what Classic already consumed.
|
||||
crate::viewport::refresh_layout(&mut h.app, &h.ctx);
|
||||
let refreshed = h.app.viewport.layout.as_ref().unwrap();
|
||||
assert_eq!((layout.content, layout.middle, layout.drawable), (refreshed.content, refreshed.middle, refreshed.drawable));
|
||||
// Classic paints the image before its legacy panels update shell.content.
|
||||
// Keep the first-frame cleanup assertions above, then target the settled
|
||||
// Classic image rather than the previous host's full content rectangle.
|
||||
h.frames(3);
|
||||
let layout = h.app.viewport.layout.as_ref().unwrap().clone();
|
||||
let canvas = h.app.viewport.rect.unwrap();
|
||||
let responses = h.ctx.viewport(|viewport| {
|
||||
viewport
|
||||
.prev_pass
|
||||
.widgets
|
||||
.layers()
|
||||
.flat_map(|(_, widgets)| widgets.iter())
|
||||
.filter(|widget| widget.enabled && widget.rect == canvas && widget.sense == egui::Sense::click_and_drag())
|
||||
.copied()
|
||||
.collect::<Vec<_>>()
|
||||
});
|
||||
assert_eq!(responses.len(), 1, "identify the actual Classic image allocation, comparison={comparison}: {responses:?}");
|
||||
let response = responses[0];
|
||||
let divider =
|
||||
comparison.then(|| crate::scenario::rect_of("render:compare:divider").unwrap().expand(h.ctx.global_style().interaction.interact_radius));
|
||||
let point = (1..10)
|
||||
.flat_map(|y| (1..10).map(move |x| controls.min + controls.size() * vec2(x as f32 / 10.0, y as f32 / 10.0)))
|
||||
.chain((1..10).flat_map(|y| (1..10).map(move |x| canvas.min + canvas.size() * vec2(x as f32 / 10.0, y as f32 / 10.0))))
|
||||
.find(|point| {
|
||||
response.interact_rect.contains(*point)
|
||||
&& !crate::shell::covered(&h.app, *point)
|
||||
&& !layout.navigation.contains(*point)
|
||||
&& !divider.is_some_and(|divider| divider.contains(*point))
|
||||
&& h.ctx.layer_id_at(*point) == Some(response.layer_id)
|
||||
})
|
||||
.expect("an unoccluded point owned by the actual Classic image response");
|
||||
h.app.preferences.nav = "maya".into();
|
||||
h.app.preferences.smooth_wheel_zoom = false;
|
||||
h.app.render_workspace.view.result_scale = ResultScale::Free;
|
||||
assert!(!crate::frame::dock_dragging(&h.ctx), "a dock drag must not own Classic image input, comparison={comparison}");
|
||||
h.frame_with(vec![Event::PointerMoved(point)]);
|
||||
assert_eq!(h.app.viewport.mouse, Some(point), "shared navigation must accept the Classic image pointer, comparison={comparison}");
|
||||
let owned = h.ctx.read_response(response.id).expect("the Classic image response remains mounted");
|
||||
assert!(
|
||||
owned.enabled() && owned.contains_pointer() && owned.interact_rect.contains(point),
|
||||
"wheel input must belong to the image: {owned:?}"
|
||||
);
|
||||
assert_eq!(h.ctx.layer_id_at(point), Some(owned.layer_id));
|
||||
assert!(!comparison_drag_captured(&h.app), "the comparison divider must not own image input");
|
||||
let image = h.app.render_workspace.view.result_camera;
|
||||
h.frame_with(vec![Event::MouseWheel {
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
unit: MouseWheelUnit::Point,
|
||||
delta: vec2(0.0, -300.0),
|
||||
modifiers: Modifiers::NONE,
|
||||
phase: egui::TouchPhase::Move,
|
||||
}]);
|
||||
assert!(!crate::frame::dock_dragging(&h.ctx), "a dock drag must not own Classic image wheel input, comparison={comparison}");
|
||||
assert!(!comparison_drag_captured(&h.app), "the comparison divider must not own image wheel input");
|
||||
assert_eq!(h.app.viewport.mouse, Some(point), "shared navigation must accept the Classic image wheel pointer, comparison={comparison}");
|
||||
assert_ne!(
|
||||
h.app.render_workspace.view.result_camera,
|
||||
image,
|
||||
"the invisible host card must not block Classic wheel input: comparison={comparison}, mouse={:?}, raw/available events/smooth delta={:?}, wheel speed={}, scale/job={:?}",
|
||||
h.app.viewport.mouse,
|
||||
h.ctx.input(|input| (input.raw.events.clone(), input.events.clone(), input.smooth_scroll_delta)),
|
||||
h.app.preferences.wheel_zoom_speed,
|
||||
(h.app.render_workspace.view.result_scale, h.app.render_workspace.view.result_job)
|
||||
);
|
||||
h.app.run("render.result.view", json!({"view":"fit"})).unwrap();
|
||||
h.frame();
|
||||
assert_eq!(
|
||||
h.app.render_workspace.view.result_camera,
|
||||
result_camera([16, 16], h.app.viewport.rect.unwrap(), h.ctx.pixels_per_point(), ResultScale::Fit)
|
||||
);
|
||||
assert_eq!(h.app.cam, product);
|
||||
assert!(Arc::ptr_eq(&document, &h.app.session.doc));
|
||||
assert_eq!((h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision), history);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_empty_result_keeps_full_domain_and_tiny_blocked_controls_publish_nothing() {
|
||||
let mut h = output_viewer_fixture();
|
||||
crate::panel_runtime::enable_host_specimen(&mut h.app, "docks").unwrap();
|
||||
h.frames(3);
|
||||
h.app.render_workspace.view.result = true;
|
||||
let domain = h.app.viewport.rect.unwrap();
|
||||
let camera = h.app.render_workspace.view.result_camera;
|
||||
let ctx = h.ctx.clone();
|
||||
for size in [egui::vec2(4.0, 4.0), egui::vec2(40.0, 24.0), domain.size()] {
|
||||
let canvas = egui::Rect::from_min_size(domain.min, size);
|
||||
h.app.viewport.host_windows = Some(vec![domain]);
|
||||
let mut output = ctx.run_ui(egui::RawInput { screen_rect: Some(domain), ..Default::default() }, |ui| {
|
||||
let mut scene = ui.new_child(egui::UiBuilder::new().max_rect(canvas));
|
||||
show(&mut h.app, &mut scene);
|
||||
host_result_overlays(&mut h.app, ui);
|
||||
});
|
||||
output.textures_delta.clear();
|
||||
assert_eq!(h.app.viewport.rect, Some(canvas));
|
||||
assert!(!h.app.shell.workspace_panels.contains_key("render:result-controls"));
|
||||
assert_eq!(h.app.render_workspace.view.result_camera, camera);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classic_results_and_comparison_keep_their_reserved_chrome_and_scale_policy() {
|
||||
for comparison in [false, true] {
|
||||
let (mut h, _, _) = render_results_compare_fixture();
|
||||
assert!(!h.app.universal_panel_host_enabled(), "the production default remains Classic");
|
||||
if comparison {
|
||||
h.app.run("render.compare", json!({"left":0,"right":1})).unwrap();
|
||||
} else {
|
||||
h.app.run("render.result.select", json!({"index":1})).unwrap();
|
||||
}
|
||||
h.frames(3);
|
||||
let canvas = h.app.viewport.rect.unwrap();
|
||||
assert!(canvas.top() > crate::toolbar::APP_BAR_HEIGHT);
|
||||
assert_eq!(h.app.render_workspace.view.result_camera, result_camera([16, 16], canvas, h.ctx.pixels_per_point(), ResultScale::Fit));
|
||||
assert!(!h.app.shell.workspace_panels.contains_key("render:result-controls"));
|
||||
if comparison {
|
||||
assert_eq!(crate::scenario::rect_of("render:compare:canvas"), Some(canvas));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
use crate::dialogs::{Dialog, Kind, apply_commands};
|
||||
use crate::scenario::Harness;
|
||||
use serde_json::{Value, json};
|
||||
use solidcore_record::Vec3;
|
||||
use solidcraft_engine::Sel;
|
||||
use solidcraft_engine::doc::{AxisRef, FeatureKind};
|
||||
use solidcraft_engine::geom::prelude::*;
|
||||
|
||||
@@ -347,3 +350,245 @@ fn an_axis_origin_that_cannot_be_evaluated_is_kept_by_an_untouched_edit() {
|
||||
assert_eq!(saved_axis(&h), original, "surface: {surface}, moved: {moved}");
|
||||
}
|
||||
}
|
||||
|
||||
fn xy_rectangle(h: &mut Harness, name: &str, p0: [f64; 2], p1: [f64; 2]) -> u64 {
|
||||
h.app.run("sketch.create", json!({"plane": "XY", "name": name})).unwrap();
|
||||
h.app.run("sketch.rectangle.two_point", json!({"p0": p0, "p1": p1})).unwrap();
|
||||
h.app.run("sketch.finish", json!({})).unwrap();
|
||||
h.app.session.doc.find_feature(name).unwrap().id
|
||||
}
|
||||
|
||||
fn revolve_dialog(app: &crate::SolveApp, profiles: Vec<Sel>, axis: Sel) -> Dialog {
|
||||
let mut d = Dialog::for_command(app, "solid.revolve").unwrap();
|
||||
d.inputs[0].items = profiles;
|
||||
d.inputs[1].items = vec![axis];
|
||||
if let Kind::Revolve { angle, operation, .. } = &mut d.kind {
|
||||
*angle = "120 deg".into();
|
||||
*operation = 0;
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
fn vertical_id(app: &crate::SolveApp, sketch: u64, x: f64) -> String {
|
||||
let st = app.session.world_state().unwrap();
|
||||
let ss = st.sketch(sketch).unwrap();
|
||||
ss.sketch
|
||||
.curves
|
||||
.iter()
|
||||
.find_map(|c| {
|
||||
let solidcraft_engine::sketch::CurveKind::Line { a, b } = c.kind else { return None };
|
||||
let (pa, pb) = (ss.sketch.point(a)?, ss.sketch.point(b)?);
|
||||
((pa.x - x).abs() < 1e-6 && (pb.x - x).abs() < 1e-6).then(|| c.id.clone())
|
||||
})
|
||||
.unwrap_or_else(|| panic!("no vertical line at x={x}"))
|
||||
}
|
||||
|
||||
fn segment(app: &crate::SolveApp, sketch: u64, id: &str) -> (Vec3, Vec3) {
|
||||
let st = app.session.world_state().unwrap();
|
||||
let ss = st.sketch(sketch).unwrap();
|
||||
let i = ss.sketch.curve_index(id).unwrap_or_else(|| panic!("no curve {id}"));
|
||||
let c = &ss.sketch.curves[i];
|
||||
let solidcraft_engine::sketch::CurveKind::Line { a, b } = c.kind else { panic!("{id} is not a line") };
|
||||
(ss.plane.to_world(ss.sketch.point(a).unwrap()), ss.plane.to_world(ss.sketch.point(b).unwrap()))
|
||||
}
|
||||
|
||||
/// `(point_x, 5, 0)` rotated 80° about `x = axis_x` toward +Z.
|
||||
fn lift_xy(axis_x: f64, point_x: f64) -> Vec3 {
|
||||
let dx = point_x - axis_x;
|
||||
let t = 80.0_f64.to_radians();
|
||||
Vec3::new(axis_x + dx * t.cos(), 5.0, dx.abs() * t.sin())
|
||||
}
|
||||
|
||||
fn assert_pivots_on(preview: &solidcraft_engine::Preview, on_axis: Vec3, on_other: Vec3, what: &str) {
|
||||
let before: std::collections::BTreeSet<_> = preview.before.bodies.iter().map(|b| b.name.as_str()).collect();
|
||||
let body = preview
|
||||
.after
|
||||
.bodies
|
||||
.iter()
|
||||
.filter(|b| !before.contains(b.name.as_str()))
|
||||
.find(|b| b.body.classify_point(on_axis).is_ok_and(|c| c == solidcraft_engine::kernel::PointClass::Inside))
|
||||
.unwrap_or_else(|| panic!("{what}: no new body contains {on_axis:?}"));
|
||||
assert!(
|
||||
body.body.classify_point(on_other).is_ok_and(|c| c != solidcraft_engine::kernel::PointClass::Inside),
|
||||
"{what}: also contains the other edge's probe {on_other:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A dialog pick of the profile's own edge keeps that curve id, and the preview pivots on it
|
||||
/// rather than on the opposite side. Naming the sketch and leaving it unnamed while that sketch
|
||||
/// is active are the two ways a click stores the pick.
|
||||
#[test]
|
||||
fn dialog_axis_keeps_the_profile_line_when_it_is_the_highlighted_edge() {
|
||||
let mut h = Harness::new();
|
||||
let sketch = xy_rectangle(&mut h, "Profile", [10.0, 0.0], [30.0, 10.0]);
|
||||
let right = vertical_id(&h.app, sketch, 30.0);
|
||||
let left = vertical_id(&h.app, sketch, 10.0);
|
||||
assert_ne!(right, left);
|
||||
for named in [Some(sketch), None] {
|
||||
if named.is_none() {
|
||||
h.app.run("sketch.edit", json!({"sketch": "Profile"})).unwrap();
|
||||
}
|
||||
let d = revolve_dialog(&h.app, vec![Sel::Profile { sketch, index: 0 }], Sel::SketchCurve { id: right.clone(), sketch: named });
|
||||
let cmds = apply_commands(&h.app, &d).unwrap();
|
||||
assert_eq!(cmds[0].0, "solid.revolve");
|
||||
assert_eq!(cmds[0].1["axis"], json!(right), "named={named:?}");
|
||||
let preview = h.app.session.preview(&cmds).unwrap();
|
||||
assert_pivots_on(&preview, lift_xy(30.0, 10.5), lift_xy(10.0, 29.5), &format!("named={named:?}"));
|
||||
if named.is_none() {
|
||||
h.app.run("sketch.finish", json!({})).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Curve ids repeat across sketches (#3726). The highlighted line is this sketch's `l2` (x = 10);
|
||||
/// the profile sketch's line of the same id is the opposite edge (x = 30). The preview must pivot
|
||||
/// on the highlighted line, and the command must not pass the bare id.
|
||||
#[test]
|
||||
fn dialog_revolve_follows_the_highlighted_edge_when_the_curve_id_collides() {
|
||||
let mut h = Harness::new();
|
||||
let profile = xy_rectangle(&mut h, "Profile", [10.0, 0.0], [30.0, 10.0]);
|
||||
let right = vertical_id(&h.app, profile, 30.0);
|
||||
h.app.run("sketch.create", json!({"plane": "XY", "name": "Axis"})).unwrap();
|
||||
h.app.run("sketch.line", json!({"points": [[10, 0], [10, 10]], "ids": [right]})).unwrap();
|
||||
let axis_sketch = h.app.session.active_sketch.unwrap();
|
||||
let (highlighted, _) = segment(&h.app, axis_sketch, &right);
|
||||
let (profile_line, _) = segment(&h.app, profile, &right);
|
||||
assert!((highlighted.x - 10.0).abs() < 1e-6, "{highlighted:?}");
|
||||
assert!((profile_line.x - 30.0).abs() < 1e-6, "{profile_line:?}");
|
||||
for named in [Some(axis_sketch), None] {
|
||||
let d = revolve_dialog(&h.app, vec![Sel::Profile { sketch: profile, index: 0 }], Sel::SketchCurve { id: right.clone(), sketch: named });
|
||||
let cmds = apply_commands(&h.app, &d).unwrap();
|
||||
let axis = &cmds[0].1["axis"];
|
||||
let origin_x = axis["origin"][0].as_f64().unwrap_or_else(|| panic!("named={named:?} stored {axis}, the colliding id"));
|
||||
assert!((origin_x - 10.0).abs() < 1e-6, "named={named:?}: {axis}");
|
||||
let preview = h.app.session.preview(&cmds).unwrap();
|
||||
// About the highlighted edge x = 10, from a point near the far edge. The other probe is
|
||||
// the same construction about the profile sketch's line of this id.
|
||||
assert_pivots_on(&preview, lift_xy(10.0, 29.5), lift_xy(30.0, 10.5), &format!("named={named:?}"));
|
||||
}
|
||||
let (kind, mut inputs) = crate::dialogs_surface::start(&h.app, "surface.revolve").unwrap();
|
||||
let Kind::Surface(mut surf) = kind else { panic!("surface revolve") };
|
||||
if let crate::dialogs_surface::Surf::Revolve { angle, .. } = &mut surf {
|
||||
*angle = "120 deg".into();
|
||||
}
|
||||
inputs[0].items = vec![Sel::Profile { sketch: profile, index: 0 }];
|
||||
inputs[1].items = vec![Sel::SketchCurve { id: right, sketch: Some(axis_sketch) }];
|
||||
let cmds = crate::dialogs_surface::commands(&h.app, &surf, &inputs, &serde_json::Map::new()).unwrap();
|
||||
assert_eq!(cmds[0].0, "surface.revolve");
|
||||
assert!((cmds[0].1["axis"]["origin"][0].as_f64().unwrap() - 10.0).abs() < 1e-6, "{}", cmds[0].1["axis"]);
|
||||
}
|
||||
|
||||
fn linked_span(app: &crate::SolveApp, sketch: u64) -> (f64, f64, f64, f64) {
|
||||
let st = app.session.world_state().unwrap();
|
||||
let ss = st.sketch(sketch).unwrap();
|
||||
let mut xs = Vec::new();
|
||||
let mut ys = Vec::new();
|
||||
for c in &ss.sketch.curves {
|
||||
if c.link.is_none() {
|
||||
continue;
|
||||
}
|
||||
let solidcraft_engine::sketch::CurveKind::Line { a, b } = c.kind else { continue };
|
||||
for p in [ss.sketch.point(a), ss.sketch.point(b)].into_iter().flatten() {
|
||||
xs.push(p.x);
|
||||
ys.push(p.y);
|
||||
}
|
||||
}
|
||||
assert!(!xs.is_empty(), "the face sketch should project the face outline");
|
||||
(
|
||||
xs.iter().copied().fold(f64::MAX, f64::min),
|
||||
xs.iter().copied().fold(f64::MIN, f64::max),
|
||||
ys.iter().copied().fold(f64::MAX, f64::min),
|
||||
ys.iter().copied().fold(f64::MIN, f64::max),
|
||||
)
|
||||
}
|
||||
|
||||
/// A rectangle drawn across a face edge splits the sketch into two profiles. The picked drawn
|
||||
/// edge — and a second sketch's line that reuses that edge's id but lies on the other side —
|
||||
/// must be the axis the preview revolves about (#7452).
|
||||
#[test]
|
||||
fn face_sketch_two_profiles_revolve_about_the_highlighted_edge() {
|
||||
let mut h = Harness::new();
|
||||
h.app.run("solid.box", json!({"length": 40, "width": 30, "height": 20, "corner": [0, 0, 0]})).unwrap();
|
||||
h.app.run("sketch.create", json!({"plane": {"face": [20, 0, 10]}, "name": "OnFace"})).unwrap();
|
||||
let sketch = h.app.session.active_sketch.unwrap();
|
||||
let (x0, _, y0, y1) = linked_span(&h.app, sketch);
|
||||
let mid_y = (y0 + y1) * 0.5;
|
||||
// Twelve millimetres outside the face, eight inside, so a point near either vertical side
|
||||
// stays inside a revolve about that side and outside a revolve about the other.
|
||||
let left_x = x0 - 12.0;
|
||||
let right_x = x0 + 8.0;
|
||||
h.app.run("sketch.rectangle.two_point", json!({"p0": [left_x, mid_y - 4.0], "p1": [right_x, mid_y + 4.0]})).unwrap();
|
||||
h.app.run("sketch.finish", json!({})).unwrap();
|
||||
let st = h.app.session.world_state().unwrap();
|
||||
let ss = st.sketch(sketch).unwrap();
|
||||
assert!(ss.profiles.len() >= 2, "straddling the face edge should make two profiles, got {}", ss.profiles.len());
|
||||
let outside = ss
|
||||
.profiles
|
||||
.iter()
|
||||
.position(|p| p.centroid.x < x0 - 0.5)
|
||||
.unwrap_or_else(|| panic!("no profile outside the face: {:?}", ss.profiles.iter().map(|p| p.centroid).collect::<Vec<_>>()));
|
||||
let normal = ss.plane.normal();
|
||||
let drawn_at = |x: f64| {
|
||||
ss.sketch.curves.iter().find_map(|c| {
|
||||
if c.link.is_some() {
|
||||
return None;
|
||||
}
|
||||
let solidcraft_engine::sketch::CurveKind::Line { a, b } = c.kind else { return None };
|
||||
let (pa, pb) = (ss.sketch.point(a)?, ss.sketch.point(b)?);
|
||||
((pa.x - x).abs() < 1e-6 && (pb.x - x).abs() < 1e-6).then(|| c.id.clone())
|
||||
})
|
||||
};
|
||||
let right_id = drawn_at(right_x).unwrap_or_else(|| panic!("no drawn edge at {right_x}"));
|
||||
let left_id = drawn_at(left_x).unwrap_or_else(|| panic!("no drawn edge at {left_x}"));
|
||||
let (right_a, right_b) = segment(&h.app, sketch, &right_id);
|
||||
let (left_a, left_b) = segment(&h.app, sketch, &left_id);
|
||||
let right_mid = (right_a + right_b) * 0.5;
|
||||
let left_mid = (left_a + left_b) * 0.5;
|
||||
let span = right_mid.dist(left_mid);
|
||||
assert!((span - (right_x - left_x)).abs() < 1e-4, "sketch millimetres should match the face plane, span {span}");
|
||||
let across = (right_mid - left_mid).normalized().unwrap();
|
||||
// 0.5 mm in from the left edge, and 0.5 mm short of the face edge (the far side of the
|
||||
// outside region when the axis is the left edge).
|
||||
let near_left = left_mid + across * 0.5;
|
||||
let near_face = left_mid + across * 11.5;
|
||||
let right_dir = (right_b - right_a).normalized().unwrap();
|
||||
let left_dir = (left_b - left_a).normalized().unwrap();
|
||||
let about_right = spin(normal, right_mid, right_dir, near_left, 80.0);
|
||||
let about_left = spin(normal, left_mid, left_dir, near_face, 80.0);
|
||||
|
||||
let d = revolve_dialog(&h.app, vec![Sel::Profile { sketch, index: outside }], Sel::SketchCurve { id: right_id.clone(), sketch: Some(sketch) });
|
||||
let cmds = apply_commands(&h.app, &d).unwrap();
|
||||
assert_eq!(cmds[0].1["axis"], json!(right_id), "the drawn edge is this profile sketch's own line");
|
||||
let preview = h.app.session.preview(&cmds).unwrap();
|
||||
assert_pivots_on(&preview, about_right, about_left, "same-sketch face edge");
|
||||
|
||||
// Another sketch on the same face reuses the drawn edge's id for the opposite side.
|
||||
h.app.run("sketch.create", json!({"plane": {"face": [20, 0, 10]}, "name": "Other", "project_edges": false})).unwrap();
|
||||
h.app.run("sketch.line", json!({"points": [[left_x, mid_y - 4.0], [left_x, mid_y + 4.0]], "ids": [right_id]})).unwrap();
|
||||
let other = h.app.session.active_sketch.unwrap();
|
||||
let (other_a, other_b) = segment(&h.app, other, cmds[0].1["axis"].as_str().unwrap());
|
||||
let other_mid = (other_a + other_b) * 0.5;
|
||||
assert!(other_mid.dist(left_mid) < 1e-4, "the colliding line should lie on the left edge, got {other_mid:?} vs {left_mid:?}");
|
||||
assert!(other_mid.dist(right_mid) > 1.0, "it must not be the profile line");
|
||||
let colliding = cmds[0].1["axis"].as_str().unwrap().to_string();
|
||||
let d = revolve_dialog(&h.app, vec![Sel::Profile { sketch, index: outside }], Sel::SketchCurve { id: colliding, sketch: Some(other) });
|
||||
let cmds = apply_commands(&h.app, &d).unwrap();
|
||||
let origin = cmds[0].1["axis"]["origin"].as_array().unwrap_or_else(|| panic!("colliding pick stored {}", cmds[0].1["axis"]));
|
||||
let got = Vec3::new(origin[0].as_f64().unwrap(), origin[1].as_f64().unwrap(), origin[2].as_f64().unwrap());
|
||||
assert!(
|
||||
got.dist(other_mid) < 1.0 || (got - other_a).cross((other_b - other_a).normalized().unwrap()).len() < 1e-4,
|
||||
"axis {got:?} is not the highlighted line {other_a:?}–{other_b:?}"
|
||||
);
|
||||
let preview = h.app.session.preview(&cmds).unwrap();
|
||||
assert_pivots_on(&preview, about_left, about_right, "face sketch, colliding id");
|
||||
}
|
||||
|
||||
fn spin(normal: Vec3, origin: Vec3, dir: Vec3, point: Vec3, deg: f64) -> Vec3 {
|
||||
let mut axis = dir.normalized().unwrap();
|
||||
if axis.cross(point - origin).dot(normal) < 0.0 {
|
||||
axis = -axis;
|
||||
}
|
||||
let t = deg.to_radians();
|
||||
let v = point - origin;
|
||||
origin + v * t.cos() + axis.cross(v) * t.sin() + axis * (axis.dot(v) * (1.0 - t.cos()))
|
||||
}
|
||||
@@ -16,6 +16,8 @@
|
||||
//! cursor can act it out first); fails if the answer came in fewer than `min_frames` frames
|
||||
//! - `{"call": "ui.view", "params": {…}}`: any other control request (`fail: true` expects an
|
||||
//! error)
|
||||
//! - `{"panel_fixture": {"enabled": true, "preset": "docks"}}`: explicit synthetic content
|
||||
//! in the real workspace panel host; `{}` inspects and `{"enabled": false}` tears it down
|
||||
//! - `{"make_image": "pic.png"}`: a picture in the scenario's folder
|
||||
//! - `{"choose_file": "part.step"}`: the next Open picker returns that file of the scenario's
|
||||
//! folder (Save pickers save there)
|
||||
@@ -475,7 +477,9 @@ impl Harness {
|
||||
pub fn step(&mut self, s: &Value) -> Result<(), String> {
|
||||
let flag = |k: &str| s.get(k).and_then(Value::as_bool).unwrap_or(false);
|
||||
let res =
|
||||
if let Some(id) = s.get("start").and_then(Value::as_str) {
|
||||
if let Some(params) = s.get("panel_fixture") {
|
||||
self.call("ui.panel_fixture", params.clone())
|
||||
} else if let Some(id) = s.get("start").and_then(Value::as_str) {
|
||||
self.call("ui.start", json!({ "command": id }))
|
||||
} else if let Some(k) = s.get("key").and_then(Value::as_str) {
|
||||
{
|
||||
|
||||
@@ -118,7 +118,9 @@ const PROFILE_KEYS: &[&str] = &[
|
||||
"status_bar",
|
||||
"suppress_sketch_snap",
|
||||
"theme",
|
||||
"theme_day",
|
||||
"theme_follow",
|
||||
"theme_night",
|
||||
"theme_options",
|
||||
"timeline_collapsed",
|
||||
"timeline_left",
|
||||
|
||||
@@ -17,13 +17,15 @@ fn error(h: &mut Harness, id: &str, params: Value) -> String {
|
||||
#[test]
|
||||
fn a_profile_holds_input_and_interface_settings_but_not_the_machine() {
|
||||
let keys: Vec<&str> = keys().collect();
|
||||
assert_eq!(keys.len(), 100, "page presentation must not alter profile membership");
|
||||
assert_eq!(keys.len(), 102, "Appearance includes its two system-theme slots");
|
||||
for key in [
|
||||
"nav",
|
||||
"mouse_gestures",
|
||||
"radial_context_menu",
|
||||
"zoom_reverse",
|
||||
"theme",
|
||||
"theme_day",
|
||||
"theme_night",
|
||||
"ui_scale",
|
||||
"ui_font",
|
||||
"navigator_style",
|
||||
@@ -817,7 +819,9 @@ fn profile_keys_preserve_the_baseline_and_explicit_additions() {
|
||||
"status_bar",
|
||||
"suppress_sketch_snap",
|
||||
"theme",
|
||||
"theme_day",
|
||||
"theme_follow",
|
||||
"theme_night",
|
||||
"theme_options",
|
||||
"timeline_collapsed",
|
||||
"timeline_left",
|
||||
@@ -844,7 +848,7 @@ fn profile_keys_preserve_the_baseline_and_explicit_additions() {
|
||||
];
|
||||
let mut actual: Vec<_> = keys().collect();
|
||||
actual.sort_unstable();
|
||||
assert_eq!(expected.len(), 100);
|
||||
assert_eq!(expected.len(), 102);
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
|
||||
@@ -926,6 +930,24 @@ fn moved_profile_settings_survive_saved_roundtrip_and_apply() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn theme_day_and_night_are_captured_restored_and_saved_in_appearance_profiles() {
|
||||
let mut h = Harness::new();
|
||||
h.call("ui.prefs", json!({"theme":"system", "theme_day":"akari", "theme_night":"onyx"}));
|
||||
run(&mut h, "settings.profile.save", json!({"name":"System pair"}));
|
||||
let saved = h.app.settings_profiles.list[0].clone();
|
||||
assert_eq!(saved["preferences"]["theme_day"], "akari");
|
||||
assert_eq!(saved["preferences"]["theme_night"], "onyx");
|
||||
assert_eq!(sanitize(&saved).unwrap(), saved);
|
||||
h.call("ui.prefs", json!({"theme_day":"light", "theme_night":"dark"}));
|
||||
run(&mut h, "settings.profile.apply", json!({"name":"System pair"}));
|
||||
assert_eq!((&h.app.preferences.theme_day[..], &h.app.preferences.theme_night[..]), ("akari", "onyx"));
|
||||
for key in ["theme_day", "theme_night"] {
|
||||
let pages: Vec<_> = crate::prefs::FIELD_PAGES.iter().filter(|(field, _)| *field == key).map(|(_, page)| *page).collect();
|
||||
assert_eq!(pages, [Some(crate::prefs::PAGE_APPEARANCE)]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_sidebar_switches_saves_and_marks_edits_with_existing_commands() {
|
||||
let mut h = Harness::new();
|
||||
|
||||
+59
-13
@@ -148,45 +148,88 @@ pub(crate) fn panel_bounds(app: &SolveApp, mut available: Rect) -> Rect {
|
||||
|
||||
/// One source of occlusion for navigation, picking and overlays.
|
||||
pub(crate) fn covered_rects(app: &SolveApp) -> Vec<Rect> {
|
||||
occluding_rects(app, false)
|
||||
occluding_rects(app, false, false, true)
|
||||
}
|
||||
|
||||
/// Selection controls follow the projected model, so they must not influence its fit.
|
||||
pub(crate) fn fit_rects(app: &SolveApp) -> Vec<Rect> {
|
||||
occluding_rects(app, true)
|
||||
occluding_rects(app, true, false, true)
|
||||
}
|
||||
|
||||
fn occluding_rects(app: &SolveApp, fitting: bool) -> Vec<Rect> {
|
||||
/// Actual persistent workspace footprints for the opt-in host. Transient menus
|
||||
/// remain input shields, without becoming targets for framing or control placement.
|
||||
pub(crate) fn host_usable(app: &SolveApp) -> solidcraft_engine::panels::PanelResult<crate::panel_runtime::HostUsableRegion> {
|
||||
use crate::panel_runtime::{MAX_USABLE_OBSTACLES, egui_rect, logical_rect, resolve_usable_region};
|
||||
use solidcraft_engine::panels::{Rule, error};
|
||||
let frame = app.universal_panel_frame().ok_or_else(|| error(Rule::Lifecycle, "universal host geometry is unavailable"))?;
|
||||
let windows = app.viewport.host_windows.as_ref().ok_or_else(|| error(Rule::CollectionLimit, "persistent window footprint limit"))?;
|
||||
let mut obstacles = frame.layout.usable.obstacles.clone();
|
||||
for bounds in occluding_rects(app, true, false, false).into_iter().chain(windows.iter().copied()).chain(app.viewport.host_confirm) {
|
||||
if !bounds.is_positive() || !bounds.is_finite() || !bounds.intersect(egui_rect(frame.layout.render_domain)).is_positive() {
|
||||
continue;
|
||||
}
|
||||
let bounds = logical_rect(bounds);
|
||||
bounds.validate()?;
|
||||
if !obstacles.contains(&bounds) {
|
||||
if obstacles.len() >= MAX_USABLE_OBSTACLES {
|
||||
return Err(error(Rule::CollectionLimit, "effective usable-space obstacle limit"));
|
||||
}
|
||||
obstacles.push(bounds);
|
||||
}
|
||||
}
|
||||
resolve_usable_region(frame.layout.render_domain, &obstacles)
|
||||
}
|
||||
|
||||
fn occluding_rects(app: &SolveApp, fitting: bool, input: bool, include_confirm: bool) -> Vec<Rect> {
|
||||
let mut rects = Vec::new();
|
||||
if let Some(frame) = app.universal_panel_frame() {
|
||||
let regions = if input { &frame.layout.input } else { &frame.layout.occlusion };
|
||||
rects.extend(regions.iter().copied().map(crate::panel_runtime::egui_rect));
|
||||
if !fitting {
|
||||
rects.extend(frame.menu_bounds.map(crate::panel_runtime::egui_rect));
|
||||
rects.extend(frame.owned_overlays.iter().map(|region| crate::panel_runtime::egui_rect(region.bounds)));
|
||||
}
|
||||
}
|
||||
rects.extend(app.shell.workspace_panels.iter().filter(|(id, _)| !fitting || **id != "render:selection").map(|(_, (rect, _))| *rect));
|
||||
if crate::render_workspace::active(app) || Container::for_layout(app.ui.layout, Surface::Panel).floating() {
|
||||
if app.universal_panel_host_enabled() || crate::render_workspace::active(app) || Container::for_layout(app.ui.layout, Surface::Panel).floating() {
|
||||
rects.extend(app.shell.cards.iter().copied());
|
||||
rects.extend(app.shell.panels.iter().copied());
|
||||
if crate::agent_chat::shown(app) && app.agent_chat.open && !app.preferences.agent_chat_popped {
|
||||
if !app.universal_panel_host_enabled() && crate::agent_chat::shown(app) && app.agent_chat.open && !app.preferences.agent_chat_popped {
|
||||
rects.extend(app.agent_chat.panel_rect);
|
||||
}
|
||||
}
|
||||
rects.extend(app.shell.history.filter(|_| app.ui.show_timeline));
|
||||
if app.ui.show_timeline && app.preferences.timeline_left {
|
||||
rects.extend(app.shell.history.map(|card| crate::ui_kit::HistorySeam::new(card).pill));
|
||||
if !app.universal_panel_host_enabled() {
|
||||
rects.extend(app.shell.history.filter(|_| app.ui.show_timeline));
|
||||
if app.ui.show_timeline && app.preferences.timeline_left {
|
||||
rects.extend(app.shell.history.map(|card| crate::ui_kit::HistorySeam::new(card).pill));
|
||||
}
|
||||
rects.extend(app.shell.browser.filter(|_| app.ui.show_browser));
|
||||
}
|
||||
rects.extend(app.viewport.palette_rect.filter(|_| app.universal_panel_host_enabled() || app.session.active_sketch.is_some()));
|
||||
// The host's persistent Window ledger supplies real feature/redefine
|
||||
// paint. This legacy cache is also written by transient modal warnings.
|
||||
if !fitting || !app.universal_panel_host_enabled() {
|
||||
rects.extend(app.viewport.dialog_rect.filter(|_| app.universal_panel_host_enabled() || app.dialog.is_some() || app.tree.redefine.is_some()));
|
||||
}
|
||||
if include_confirm {
|
||||
rects.extend(crate::view_confirm::rect(app));
|
||||
}
|
||||
rects.extend(app.shell.browser.filter(|_| app.ui.show_browser));
|
||||
rects.extend(app.viewport.palette_rect.filter(|_| app.session.active_sketch.is_some()));
|
||||
rects.extend(app.viewport.dialog_rect.filter(|_| app.dialog.is_some() || app.tree.redefine.is_some()));
|
||||
rects.extend(crate::view_confirm::rect(app));
|
||||
rects.extend(app.shell.status_bar.filter(|_| crate::status_bar::shown(app)));
|
||||
rects.retain(|r| r.is_finite() && r.is_positive());
|
||||
rects
|
||||
}
|
||||
|
||||
pub(crate) fn covered(app: &SolveApp, p: egui::Pos2) -> bool {
|
||||
covered_rects(app).iter().any(|r| r.contains(p))
|
||||
occluding_rects(app, false, true, true).iter().any(|r| r.contains(p))
|
||||
}
|
||||
|
||||
/// Space reserved below viewport overlays by the floating History card. Its rect is set before
|
||||
/// the viewport is painted, so showing or hiding History takes effect in the same frame. History
|
||||
/// docked as the left sidebar sits beside the viewport, not below it, so it reserves nothing.
|
||||
pub(crate) fn viewport_bottom_inset(app: &SolveApp, viewport: Rect) -> f32 {
|
||||
if app.universal_panel_host_enabled() {
|
||||
return 0.0;
|
||||
}
|
||||
if app.ui.layout != LayoutMode::Floating || (app.ui.show_timeline && app.preferences.timeline_left) {
|
||||
return 0.0;
|
||||
}
|
||||
@@ -221,6 +264,9 @@ pub(crate) fn within(v: f32, lo: f32, hi: f32) -> f32 {
|
||||
/// Free anchor space shared by both layouts. Compact edge hosts have already consumed
|
||||
/// their allocation; content-hugging Browser and floating overlays reserve their measured span.
|
||||
pub(crate) fn workspace_content(app: &SolveApp, mut content: Rect) -> Rect {
|
||||
if let Some(frame) = app.universal_panel_frame() {
|
||||
return frame.layout.viewport.map(crate::panel_runtime::egui_rect).map_or(content, |rect| rect.intersect(content));
|
||||
}
|
||||
if crate::render_workspace::active(app) {
|
||||
if crate::render_ui::focused(app) {
|
||||
return content;
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -179,7 +179,9 @@ pub fn panel(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
let command = spec.as_ref().map_or("", |s| crate::i18n::tr_label(s.label));
|
||||
let title = crate::i18n::format("sketch_panel.redefine_title", &[("command", command), ("name", name)]);
|
||||
let panel = ui_kit::Panel::new(&title, egui::Id::unique("sc_redefine"), anchor, drag_bounds, side, frame);
|
||||
let mut painted = false;
|
||||
let response = panel.window(ctx).show(ctx, |ui| {
|
||||
painted = ui.is_visible() && !ui.is_sizing_pass();
|
||||
let (closed, action) = panel.feature(
|
||||
ui,
|
||||
ui_kit::FeatureOptions {
|
||||
@@ -336,7 +338,7 @@ pub fn panel(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
cancel |= closed || action == ui_kit::Action::Cancel;
|
||||
apply |= action == ui_kit::Action::Ok;
|
||||
});
|
||||
app.viewport.dialog_rect = response.map(|r| r.response.rect);
|
||||
app.viewport.dialog_rect = response.filter(|_| !app.universal_panel_host_enabled() || painted).map(|r| r.response.rect);
|
||||
if let Some(rect) = app.viewport.dialog_rect {
|
||||
crate::scenario::publish_rect("dialog:outer", rect);
|
||||
crate::scenario::publish_rect("dialog:card", rect);
|
||||
|
||||
@@ -375,6 +375,80 @@ fn picked_top_face_of_a_stacked_join_extrude_takes_a_sketch() {
|
||||
assert!((plane.origin.z - 20.).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_redefine_editor_survives_host_toggles_and_reserves_only_its_current_visible_footprint() {
|
||||
fn assert_live(h: &Harness, sketch: u64, commands: &[(String, Value)]) -> egui::Rect {
|
||||
assert_eq!(h.app.tree.redefine, Some(sketch));
|
||||
assert_eq!(crate::sketch_attachment_ui::commands(&h.app).as_deref(), Some(commands));
|
||||
let rect = h.app.viewport.dialog_rect.expect("the live redefine editor must actually paint");
|
||||
assert!(rect.is_positive() && rect.is_finite());
|
||||
assert_eq!(crate::scenario::rect_of("dialog:outer"), Some(rect));
|
||||
if h.app.universal_panel_host_enabled() {
|
||||
let usable = crate::shell::host_usable(&h.app).unwrap();
|
||||
assert!(usable.obstacles.contains(&crate::panel_runtime::logical_rect(rect)));
|
||||
assert!(usable.free.iter().all(|piece| !crate::panel_runtime::egui_rect(*piece).intersect(rect).is_positive()));
|
||||
}
|
||||
rect
|
||||
}
|
||||
for scale in [1.0, 2.0] {
|
||||
let mut h = Harness::new();
|
||||
h.app.home.open = false;
|
||||
h.call("ui.resize", json!({"width":1400,"height":1000}));
|
||||
let sketch = h.app.run("sketch.create", json!({"plane":"XY"})).unwrap()["sketch"].as_u64().unwrap();
|
||||
h.app.run("sketch.rectangle.two_point", json!({"p0":[10,10],"p1":[30,20]})).unwrap();
|
||||
h.app.finish_sketch();
|
||||
h.settle();
|
||||
h.ctx.set_pixels_per_point(scale);
|
||||
crate::panel_runtime::enable_host_specimen(&mut h.app, "docks").unwrap();
|
||||
h.frames(3);
|
||||
h.ctx.options_mut(|options| options.max_passes = 1.try_into().unwrap());
|
||||
let document = h.app.session.doc.clone();
|
||||
let revision = h.app.session.revision;
|
||||
let undo = h.app.session.undo.len();
|
||||
let before = crate::shell::host_usable(&h.app).unwrap();
|
||||
crate::browser::redefine_sketch(&mut h.app, sketch);
|
||||
h.frame();
|
||||
assert_eq!(h.app.tree.redefine, Some(sketch));
|
||||
assert!(h.app.tree.redefine_draft.is_some());
|
||||
assert!(h.app.viewport.dialog_rect.is_none(), "the first invisible sizing pass cannot reserve a dialog footprint");
|
||||
assert!(crate::scenario::rect_of("dialog:outer").is_none());
|
||||
assert_eq!(crate::shell::host_usable(&h.app).unwrap(), before);
|
||||
h.frame();
|
||||
let initial = h.app.viewport.dialog_rect.expect("the next pass paints the actual editor");
|
||||
assert_eq!(crate::scenario::rect_of("dialog:outer"), Some(initial));
|
||||
h.step(&json!({"widget":"Use XZ plane"})).unwrap();
|
||||
let commands = crate::sketch_attachment_ui::commands(&h.app).unwrap();
|
||||
assert_eq!(commands, vec![("sketch.redefine".into(), json!({"sketch":sketch,"plane":"XZ"}))]);
|
||||
assert_live(&h, sketch, &commands);
|
||||
|
||||
h.app.disable_universal_panel_host().unwrap();
|
||||
h.frames(3);
|
||||
assert_live(&h, sketch, &commands);
|
||||
h.app.enable_universal_panel_host(crate::panel_runtime::HostOptions::default()).unwrap();
|
||||
h.frame();
|
||||
assert_live(&h, sketch, &commands);
|
||||
h.frames(3);
|
||||
let mounted = assert_live(&h, sketch, &commands);
|
||||
assert!(std::sync::Arc::ptr_eq(&h.app.session.doc, &document));
|
||||
assert_eq!(h.app.session.revision, revision);
|
||||
assert_eq!(h.app.session.undo.len(), undo, "host toggles cannot apply or cancel the pending redefine command");
|
||||
let cancel = crate::scenario::handle_at("dialog:cancel").unwrap();
|
||||
assert!(mounted.contains(cancel));
|
||||
h.step(&json!({"click":{"handle":"dialog:cancel"}})).unwrap();
|
||||
h.frames(2);
|
||||
assert!(h.app.tree.redefine.is_none() && h.app.tree.redefine_draft.is_none());
|
||||
assert!(h.app.viewport.dialog_rect.is_none());
|
||||
assert!(crate::scenario::rect_of("dialog:outer").is_none());
|
||||
assert!(
|
||||
!crate::shell::host_usable(&h.app).unwrap().obstacles.contains(&crate::panel_runtime::logical_rect(mounted)),
|
||||
"a producer that no longer paints cannot leave a phantom dialog reservation"
|
||||
);
|
||||
assert!(std::sync::Arc::ptr_eq(&h.app.session.doc, &document));
|
||||
assert_eq!(h.app.session.revision, revision);
|
||||
assert_eq!(h.app.session.undo.len(), undo);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plane_redefinition_uses_dense_card_and_keeps_command_preview_cancel_and_ok() {
|
||||
use crate::scenario;
|
||||
|
||||
@@ -13,6 +13,7 @@ fn step(h: &mut Harness, value: Value) {
|
||||
fn fixture() -> Harness {
|
||||
let mut h = Harness::new();
|
||||
h.app.preferences.look_at_anim = false;
|
||||
h.app.preferences.sketch_mirror_auto_line = false; // Exercise manual reference picking.
|
||||
for (command, params) in [
|
||||
("sketch.create", json!({"plane":"XY"})),
|
||||
("sketch.line", json!({"points":[[-30,10],[-15,10]]})),
|
||||
|
||||
@@ -204,6 +204,107 @@ fn the_toolbar_button_opens_a_window_with_both_picks_visible() {
|
||||
assert_eq!(curve_ids(&h).len(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mirror_uses_the_only_preselected_construction_line_among_multiple_lines() {
|
||||
for second_axis in [false, true] {
|
||||
let mut h = line_and_circle();
|
||||
let ids = curve_ids(&h);
|
||||
h.app.run("sketch.construction", json!({"curves": [ids[0]], "value": true})).unwrap();
|
||||
h.app.run("sketch.line", json!({"points": [[5, -20], [5, 20]], "construction": true, "ids": ["second_axis"]})).unwrap();
|
||||
let line = if second_axis { "second_axis" } else { &ids[0] };
|
||||
let mut picks = vec![Sel::SketchCurve { id: line.into(), sketch: None }, Sel::SketchCurve { id: ids[1].clone(), sketch: None }];
|
||||
if second_axis {
|
||||
picks.reverse();
|
||||
}
|
||||
h.app.session.selection = picks.clone();
|
||||
let before = h.app.session.doc.to_json();
|
||||
let undo = h.app.session.undo.len();
|
||||
h.step(&json!({"start": "sketch.mirror"})).unwrap();
|
||||
let d = h.app.dialog.as_ref().unwrap();
|
||||
assert_eq!(d.inputs[0].items, picks);
|
||||
assert_eq!(d.inputs[1].items, vec![Sel::SketchCurve { id: line.into(), sketch: None }]);
|
||||
assert_eq!(h.app.session.doc.to_json(), before, "opening Mirror only previews the result");
|
||||
assert_eq!(h.app.session.undo.len(), undo);
|
||||
h.frames(2);
|
||||
h.step(&json!({"key": "Enter"})).unwrap();
|
||||
h.settle();
|
||||
assert!(h.app.dialog.is_none(), "{:?}", h.app.status);
|
||||
let state = h.app.session.model.state();
|
||||
let sketch = &state.sketch(h.app.session.active_sketch.unwrap()).unwrap().sketch;
|
||||
assert_eq!(sketch.curves.len(), 4, "neither the reference nor the unselected construction line is copied");
|
||||
let solidcraft_engine::sketch::CurveKind::Circle { c, r } = &sketch.curves.last().unwrap().kind else { panic!("expected mirrored circle") };
|
||||
let at = sketch.point(*c).unwrap();
|
||||
let expected_x = if second_axis { 0.0 } else { -10.0 };
|
||||
assert!((at.x - expected_x).abs() < 1e-6 && at.y.abs() < 1e-6);
|
||||
assert!((*r - 3.0).abs() < 1e-6);
|
||||
h.app.run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(h.app.session.doc.to_json(), before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mirror_auto_line_requires_one_preselected_straight_construction_line_and_the_preference() {
|
||||
for (count, selected, enabled) in [(0, 1, true), (1, 0, true), (2, 0, true), (1, 1, true), (2, 1, true), (2, 2, true), (1, 1, false)] {
|
||||
let mut h = line_and_circle();
|
||||
let ids = curve_ids(&h);
|
||||
// A construction circle never qualifies, and ordinary lines do not count.
|
||||
h.app.run("sketch.construction", json!({"curves": [ids[1]], "value": true})).unwrap();
|
||||
if count > 0 {
|
||||
h.app.run("sketch.construction", json!({"curves": [ids[0]], "value": true})).unwrap();
|
||||
}
|
||||
if count > 1 {
|
||||
h.app.run("sketch.line", json!({"points": [[5, -20], [5, 20]], "construction": true, "ids": ["second_axis"]})).unwrap();
|
||||
}
|
||||
h.app.session.selection = vec![Sel::SketchCurve { id: ids[1].clone(), sketch: None }];
|
||||
h.app
|
||||
.session
|
||||
.selection
|
||||
.extend([ids[0].as_str(), "second_axis"].into_iter().take(selected).map(|id| Sel::SketchCurve { id: id.into(), sketch: None }));
|
||||
h.app.preferences.sketch_mirror_auto_line = enabled;
|
||||
h.step(&json!({"start": "sketch.mirror"})).unwrap();
|
||||
let d = h.app.dialog.as_ref().unwrap();
|
||||
let expected = if count > 0 && selected == 1 && enabled { vec![Sel::SketchCurve { id: ids[0].clone(), sketch: None }] } else { vec![] };
|
||||
assert_eq!(d.inputs[1].items, expected, "count={count}, selected={selected}, enabled={enabled}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mirror_auto_line_respects_manual_references_and_only_uses_the_active_sketch() {
|
||||
let mut h = line_and_circle();
|
||||
let ids = curve_ids(&h);
|
||||
h.app.run("sketch.construction", json!({"curves": [ids[0]], "value": true})).unwrap();
|
||||
h.app.session.selection.clear();
|
||||
h.step(&json!({"start": "sketch.mirror"})).unwrap();
|
||||
let d = h.app.dialog.as_ref().unwrap();
|
||||
assert!(d.inputs[0].items.is_empty() && d.inputs[1].items.is_empty(), "nothing is inferred without preselection");
|
||||
assert_eq!(d.active, 0);
|
||||
h.step(&json!({"key": "Escape"})).unwrap();
|
||||
let line = Sel::SketchCurve { id: ids[0].clone(), sketch: None };
|
||||
let axis = Sel::Axis { name: "X".into() };
|
||||
h.app.session.selection = vec![axis.clone(), line.clone()];
|
||||
h.step(&json!({"start": "sketch.mirror"})).unwrap();
|
||||
assert_eq!(h.app.dialog.as_ref().unwrap().inputs[1].items, vec![axis]);
|
||||
h.step(&json!({"key": "Escape"})).unwrap();
|
||||
h.app.session.selection = vec![line];
|
||||
h.step(&json!({"start": "sketch.mirror"})).unwrap();
|
||||
assert_eq!(h.app.dialog.as_ref().unwrap().inputs[1].items.len(), 1);
|
||||
h.step(&json!({"click": {"handle": "dialog:clear:Mirror line"}})).unwrap();
|
||||
h.frames(3);
|
||||
assert!(h.app.dialog.as_ref().unwrap().inputs[1].items.is_empty(), "a cleared reference stays empty");
|
||||
h.step(&json!({"key": "Escape"})).unwrap();
|
||||
let previous_sketch = h.app.session.active_sketch;
|
||||
h.app.run("sketch.finish", json!({})).unwrap();
|
||||
h.app.run("sketch.create", json!({"plane": "XZ"})).unwrap();
|
||||
h.app.run("sketch.line", json!({"points": [[0, -20], [0, 20]], "construction": true, "ids": [ids[0]]})).unwrap();
|
||||
h.app.session.selection = vec![Sel::SketchCurve { id: ids[0].clone(), sketch: previous_sketch }];
|
||||
h.step(&json!({"start": "sketch.mirror"})).unwrap();
|
||||
assert!(h.app.dialog.as_ref().unwrap().inputs[1].items.is_empty(), "another sketch's construction line is not used");
|
||||
h.step(&json!({"key": "Escape"})).unwrap();
|
||||
h.app.session.selection = vec![Sel::SketchCurve { id: ids[0].clone(), sketch: h.app.session.active_sketch }];
|
||||
h.step(&json!({"start": "sketch.mirror"})).unwrap();
|
||||
assert_eq!(h.app.dialog.as_ref().unwrap().inputs[1].items, vec![Sel::SketchCurve { id: ids[0].clone(), sketch: None }]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_two_picks_become_the_command() {
|
||||
let h = line_and_circle();
|
||||
|
||||
@@ -384,7 +384,9 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
frame,
|
||||
)
|
||||
.width(width(vp));
|
||||
let mut painted = false;
|
||||
let response = panel.window(ctx).show(ctx, |ui| {
|
||||
painted = ui.is_visible() && !ui.is_sizing_pass();
|
||||
panel.palette(ui, bottom, top, |ui, part| match part {
|
||||
crate::ui_kit::Part::Header => {
|
||||
let status = if !solved || !geometry || remaining == 0 {
|
||||
@@ -508,7 +510,8 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
}
|
||||
});
|
||||
});
|
||||
app.viewport.palette_rect = response.map(|r| r.response.rect.expand(frame.stroke.width));
|
||||
app.viewport.palette_rect =
|
||||
response.filter(|_| !app.universal_panel_host_enabled() || painted).map(|r| r.response.rect.expand(frame.stroke.width));
|
||||
if let Some(rect) = app.viewport.palette_rect {
|
||||
crate::scenario::publish_rect("sketch_palette:outer", rect);
|
||||
}
|
||||
@@ -538,6 +541,10 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {
|
||||
app.set_status(error, true);
|
||||
}
|
||||
if look {
|
||||
if app.universal_panel_host_enabled() {
|
||||
app.viewport.host_windows = crate::ui_kit::Container::host_window_regions(ctx);
|
||||
crate::viewport::refresh_layout(app, ctx);
|
||||
}
|
||||
crate::dialogs::look_at_sketch_again(app);
|
||||
}
|
||||
if finish {
|
||||
|
||||
@@ -11,6 +11,10 @@ mod palettes;
|
||||
use egui::{Color32, Stroke};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Expanded Wide hosts compose controls and content in one total row below
|
||||
/// this logical height. Independent of pixel density and user UI scaling.
|
||||
pub const PANEL_INLINE_MAX_HEIGHT: f32 = 88.0;
|
||||
|
||||
thread_local! {
|
||||
/// Theme state belongs to the UI thread drawing the frame. Concurrent app/test renderers
|
||||
/// must not change one another's palette while a frame or icon texture is being built.
|
||||
|
||||
@@ -226,17 +226,103 @@ impl BackingTooltipExt for egui::Response {
|
||||
}
|
||||
}
|
||||
|
||||
const MAX_LAYER_RAISES_PER_PASS: usize = 256;
|
||||
const MAX_HOST_WINDOWS_PER_PASS: usize = 256;
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct HostWindows {
|
||||
stamp: (u64, u64),
|
||||
windows: Vec<(Id, egui::Rect)>,
|
||||
exhausted: bool,
|
||||
}
|
||||
|
||||
fn host_windows_key(ctx: &Context) -> Id {
|
||||
Id::unique(("solidcraft_host_windows", ctx.viewport_id()))
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct LayerRaises {
|
||||
stamp: (egui::ViewportId, u64, u64),
|
||||
layers: Vec<egui::LayerId>,
|
||||
exhausted: bool,
|
||||
}
|
||||
|
||||
fn layer_raise_key(ctx: &Context) -> Id {
|
||||
Id::unique(("solidcraft_container_layer_raises", ctx.viewport_id()))
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct ModalBoundary {
|
||||
stamp: (u64, u64),
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct HostEscape {
|
||||
stamp: (u64, u64),
|
||||
event: egui::Event,
|
||||
}
|
||||
|
||||
fn modal_boundary_key(ctx: &Context) -> Id {
|
||||
Id::unique(("solidcraft_container_modal", ctx.viewport_id()))
|
||||
}
|
||||
fn host_escape_key(ctx: &Context) -> Id {
|
||||
Id::unique(("solidcraft_container_host_escape", ctx.viewport_id()))
|
||||
}
|
||||
|
||||
/// The shared modal show boundary, including its first invisible sizing pass.
|
||||
/// Constructing a modal alone never changes the input context.
|
||||
#[must_use]
|
||||
pub struct ModalHost {
|
||||
modal: BackingModal,
|
||||
}
|
||||
|
||||
impl ModalHost {
|
||||
pub fn backdrop_color(mut self, color: Color32) -> Self {
|
||||
self.modal = self.modal.backdrop_color(color);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn frame(mut self, frame: Frame) -> Self {
|
||||
self.modal = self.modal.frame(frame);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn show<T>(self, ctx: &Context, content: impl FnOnce(&mut egui::Ui) -> T) -> egui::ModalResponse<T> {
|
||||
let stamp = (ctx.cumulative_frame_nr(), ctx.cumulative_pass_nr());
|
||||
let modal_key = modal_boundary_key(ctx);
|
||||
let escape_key = host_escape_key(ctx);
|
||||
let reserved = ctx.data_mut(|data| {
|
||||
data.insert_temp(modal_key, ModalBoundary { stamp });
|
||||
let reserved = data.get_temp::<HostEscape>(escape_key);
|
||||
data.remove::<HostEscape>(escape_key);
|
||||
reserved.filter(|reserved| reserved.stamp == stamp)
|
||||
});
|
||||
// A modal can open after logic reserved Escape for a panel gesture.
|
||||
// Transfer the original event once to the modal, without replaying it
|
||||
// to ordinary windows or changing the pending panel layout state.
|
||||
if let Some(reserved) = reserved {
|
||||
ctx.input_mut(|input| {
|
||||
if !input.key_pressed(egui::Key::Escape) {
|
||||
input.events.push(reserved.event);
|
||||
}
|
||||
});
|
||||
}
|
||||
self.modal.show(ctx, content)
|
||||
}
|
||||
}
|
||||
|
||||
/// The feature sheet's deliberately restricted stock Window (no title, scrolling or fades).
|
||||
/// Keep its builder private: the marker's layer and host clip are owned here.
|
||||
pub(crate) struct FeatureWindow<'a> {
|
||||
window: egui::Window<'a>,
|
||||
id: Id,
|
||||
frame: Frame,
|
||||
open: Option<bool>,
|
||||
}
|
||||
|
||||
impl<'a> FeatureWindow<'a> {
|
||||
pub(super) fn new(window: egui::Window<'a>, id: Id, frame: Frame) -> Self {
|
||||
Self { window, id, frame }
|
||||
Self { window, id, frame, open: None }
|
||||
}
|
||||
|
||||
pub(crate) fn fixed_size(mut self, size: egui::Vec2) -> Self {
|
||||
@@ -249,8 +335,9 @@ impl<'a> FeatureWindow<'a> {
|
||||
where
|
||||
'a: 'open,
|
||||
{
|
||||
let is_open = *open;
|
||||
let window: egui::Window<'open> = self.window;
|
||||
FeatureWindow { window: window.open(open), id: self.id, frame: self.frame }
|
||||
FeatureWindow { window: window.open(open), id: self.id, frame: self.frame, open: Some(is_open) }
|
||||
}
|
||||
|
||||
pub(crate) fn show<R>(self, ctx: &Context, body: impl FnOnce(&mut egui::Ui) -> R) -> Option<egui::InnerResponse<Option<R>>> {
|
||||
@@ -264,11 +351,38 @@ impl<'a> FeatureWindow<'a> {
|
||||
background: Option<Background>,
|
||||
body: impl FnOnce(&mut egui::Ui) -> R,
|
||||
) -> Option<egui::InnerResponse<Option<R>>> {
|
||||
let Some(background) = background else { return self.window.show(ctx, body) };
|
||||
let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Middle, self.id));
|
||||
let slot = painter.add(egui::Shape::Noop);
|
||||
let backing = background.map(|background| {
|
||||
let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Middle, self.id));
|
||||
let slot = painter.add(egui::Shape::Noop);
|
||||
(background, slot)
|
||||
});
|
||||
// Window::show animates its open flag even with fade_out(false).
|
||||
// A closed feature must disappear before its body or footprint is produced.
|
||||
if self.open == Some(false) {
|
||||
Container::record_host_window(ctx, self.id, None);
|
||||
return None;
|
||||
}
|
||||
let Some((background, slot)) = backing else {
|
||||
let mut painted = false;
|
||||
let shown = self.window.show(ctx, |ui| {
|
||||
painted = ui.is_visible() && !ui.is_sizing_pass();
|
||||
body(ui)
|
||||
});
|
||||
let bounds = shown
|
||||
.as_ref()
|
||||
.filter(|shown| {
|
||||
painted
|
||||
|| shown.inner.is_none()
|
||||
&& egui::containers::AreaState::load(ctx, shown.response.layer_id.id).is_some_and(|area| area.interactable)
|
||||
})
|
||||
.map(|shown| shown.response.rect);
|
||||
Container::record_host_window(ctx, self.id, bounds);
|
||||
return shown;
|
||||
};
|
||||
let mut host_painter = None;
|
||||
let mut painted = false;
|
||||
let shown = self.window.show(ctx, |ui| {
|
||||
painted = ui.is_visible() && !ui.is_sizing_pass();
|
||||
// Resize's content clip omits the frame border/padding. This bounded Window
|
||||
// uses Area's default viewport clip, with no fades or native title bar.
|
||||
let mut painter = ui.painter().clone();
|
||||
@@ -276,6 +390,15 @@ impl<'a> FeatureWindow<'a> {
|
||||
host_painter = Some(painter);
|
||||
body(ui)
|
||||
});
|
||||
let bounds = shown
|
||||
.as_ref()
|
||||
.filter(|shown| {
|
||||
painted
|
||||
|| shown.inner.is_none()
|
||||
&& egui::containers::AreaState::load(ctx, shown.response.layer_id.id).is_some_and(|area| area.interactable)
|
||||
})
|
||||
.map(|shown| shown.response.rect);
|
||||
Container::record_host_window(ctx, self.id, bounds);
|
||||
if let (Some(shown), Some(painter)) = (&shown, host_painter) {
|
||||
// Window relocates inner_margin into an internal content Frame. Its final
|
||||
// Area response still includes all margins and the original stroke width.
|
||||
@@ -673,11 +796,19 @@ impl Container {
|
||||
/// Optional companion to a primary outline, painted inside the allocated surface.
|
||||
/// It consumes no layout space or input target. Tiny/collapsed surfaces omit it.
|
||||
pub(crate) fn paint_inset(painter: &egui::Painter, widget: egui::Rect, frame: Frame) {
|
||||
// Ordinary hosts supply a content well clip, which excludes their padding.
|
||||
// Their companion belongs to the whole surface instead of that well.
|
||||
Self::paint_inset_clipped(painter, widget, frame, painter.ctx().content_rect());
|
||||
}
|
||||
|
||||
/// Bounded hosts supply their inherited outer clip so decoration cannot
|
||||
/// escape a partially visible card. Geometry matches the ordinary companion.
|
||||
pub(crate) fn paint_inset_clipped(painter: &egui::Painter, widget: egui::Rect, frame: Frame, outer_clip: egui::Rect) {
|
||||
let mut painter = painter.clone();
|
||||
painter.set_clip_rect(widget.intersect(painter.ctx().content_rect()).intersect(outer_clip));
|
||||
let t = Tokens::get();
|
||||
if let Some(bevel) = t.borders.bevel {
|
||||
let mut chrome = painter.clone();
|
||||
chrome.set_clip_rect(widget.intersect(painter.ctx().content_rect()));
|
||||
bevel.paint(&chrome, widget, frame.corner_radius, false, true);
|
||||
bevel.paint(&painter, widget, frame.corner_radius, false, true);
|
||||
}
|
||||
let Some(inset) = t.borders.primary_inset else {
|
||||
return;
|
||||
@@ -689,10 +820,6 @@ impl Container {
|
||||
}
|
||||
let reduce = |r: u8| r.saturating_sub(distance.ceil() as u8);
|
||||
let radius = frame.corner_radius;
|
||||
// A host's content clip excludes its padding. The companion belongs to the whole
|
||||
// host, so clip to that known surface and the viewport instead of the content well.
|
||||
let mut painter = painter.clone();
|
||||
painter.set_clip_rect(widget.intersect(painter.ctx().content_rect()));
|
||||
painter.rect_stroke(
|
||||
rect,
|
||||
egui::CornerRadius { nw: reduce(radius.nw), ne: reduce(radius.ne), sw: reduce(radius.sw), se: reduce(radius.se) },
|
||||
@@ -734,6 +861,123 @@ impl Container {
|
||||
egui::Area::new(id).enabled(self.input_enabled()).order(order)
|
||||
}
|
||||
|
||||
/// Start collection only for the opt-in host, isolated to this native
|
||||
/// viewport and egui pass. Ordinary shared windows keep their old behavior.
|
||||
pub(crate) fn begin_host_windows(ctx: &Context) {
|
||||
let stamp = (ctx.cumulative_frame_nr(), ctx.cumulative_pass_nr());
|
||||
let key = host_windows_key(ctx);
|
||||
ctx.data_mut(|data| data.insert_temp(key, HostWindows { stamp, ..Default::default() }));
|
||||
}
|
||||
|
||||
/// Persistent Feature/Window wrappers declare actual paint here. Popup,
|
||||
/// Modal and model-following Area wrappers never enter this ledger.
|
||||
pub(crate) fn record_host_window(ctx: &Context, id: Id, bounds: Option<egui::Rect>) {
|
||||
let stamp = (ctx.cumulative_frame_nr(), ctx.cumulative_pass_nr());
|
||||
let key = host_windows_key(ctx);
|
||||
ctx.data_mut(|data| {
|
||||
let Some(mut windows) = data.get_temp::<HostWindows>(key).filter(|windows| windows.stamp == stamp) else {
|
||||
return;
|
||||
};
|
||||
if let Some(bounds) = bounds {
|
||||
if !bounds.is_positive() || !bounds.is_finite() {
|
||||
windows.exhausted = true;
|
||||
} else if let Some(entry) = windows.windows.iter_mut().find(|(existing, _)| *existing == id) {
|
||||
entry.1 = bounds;
|
||||
} else if windows.windows.len() < MAX_HOST_WINDOWS_PER_PASS {
|
||||
windows.windows.push((id, bounds));
|
||||
} else {
|
||||
windows.exhausted = true;
|
||||
}
|
||||
} else {
|
||||
windows.windows.retain(|(existing, _)| *existing != id);
|
||||
}
|
||||
data.insert_temp(key, windows);
|
||||
});
|
||||
}
|
||||
|
||||
/// None refuses framing/control placement when the bounded ledger failed.
|
||||
pub(crate) fn host_window_regions(ctx: &Context) -> Option<Vec<egui::Rect>> {
|
||||
let stamp = (ctx.cumulative_frame_nr(), ctx.cumulative_pass_nr());
|
||||
let key = host_windows_key(ctx);
|
||||
match ctx.data(|data| data.get_temp::<HostWindows>(key)) {
|
||||
Some(windows) if windows.stamp == stamp => (!windows.exhausted).then(|| windows.windows.into_iter().map(|(_, bounds)| bounds).collect()),
|
||||
_ => Some(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Raise an outer host through the shared kit. egui applies raises at the
|
||||
/// end of the pass; deferred host actions also need to observe that intent.
|
||||
/// Raised layers form a set: egui preserves their existing relative order.
|
||||
pub fn bring_to_front(ctx: &Context, layer: egui::LayerId) {
|
||||
let stamp = (ctx.viewport_id(), ctx.cumulative_frame_nr(), ctx.cumulative_pass_nr());
|
||||
let key = layer_raise_key(ctx);
|
||||
ctx.data_mut(|data| {
|
||||
let mut raises = data.get_temp::<LayerRaises>(key).unwrap_or_default();
|
||||
if raises.stamp != stamp {
|
||||
raises = LayerRaises { stamp, ..Default::default() };
|
||||
}
|
||||
if !raises.layers.contains(&layer) {
|
||||
if raises.layers.len() < MAX_LAYER_RAISES_PER_PASS {
|
||||
raises.layers.push(layer);
|
||||
} else {
|
||||
raises.exhausted = true;
|
||||
}
|
||||
}
|
||||
data.insert_temp(key, raises);
|
||||
});
|
||||
ctx.move_to_top(layer);
|
||||
}
|
||||
|
||||
/// None means the bounded raise ledger overflowed; consumers refuse their
|
||||
/// own pending actions rather than inventing a viewport-wide input shield.
|
||||
pub(crate) fn current_layer_raises(ctx: &Context) -> Option<Vec<egui::LayerId>> {
|
||||
let stamp = (ctx.viewport_id(), ctx.cumulative_frame_nr(), ctx.cumulative_pass_nr());
|
||||
let key = layer_raise_key(ctx);
|
||||
let raises = ctx.data(|data| data.get_temp::<LayerRaises>(key));
|
||||
match raises {
|
||||
Some(raises) if raises.stamp == stamp => (!raises.exhausted).then_some(raises.layers),
|
||||
_ => Some(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Current shared show intent supplements egui's previous-frame modal state.
|
||||
pub(crate) fn modal_input_blocked(ctx: &Context) -> bool {
|
||||
let stamp = (ctx.cumulative_frame_nr(), ctx.cumulative_pass_nr());
|
||||
let key = modal_boundary_key(ctx);
|
||||
ctx.data(|data| data.get_temp::<ModalBoundary>(key).is_some_and(|boundary| boundary.stamp == stamp))
|
||||
|| ctx.memory(|memory| memory.top_modal_layer().is_some())
|
||||
}
|
||||
|
||||
pub(crate) fn reserve_host_escape(ctx: &Context) -> bool {
|
||||
if Self::modal_input_blocked(ctx) {
|
||||
return false;
|
||||
}
|
||||
let event = ctx.input_mut(|input| {
|
||||
let event = input
|
||||
.events
|
||||
.iter()
|
||||
.find(|event| {
|
||||
matches!(event,
|
||||
egui::Event::Key { key: egui::Key::Escape, pressed: true, modifiers, .. }
|
||||
if modifiers.matches_logically(egui::Modifiers::NONE)
|
||||
)
|
||||
})
|
||||
.cloned();
|
||||
if event.is_some() {
|
||||
input.consume_key(egui::Modifiers::NONE, egui::Key::Escape);
|
||||
}
|
||||
event
|
||||
});
|
||||
if let Some(event) = event {
|
||||
let stamp = (ctx.cumulative_frame_nr(), ctx.cumulative_pass_nr());
|
||||
let key = host_escape_key(ctx);
|
||||
ctx.data_mut(|data| data.insert_temp(key, HostEscape { stamp, event }));
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// A panel on `edge`, keyed by `salt` within the Ui it is shown in.
|
||||
pub fn edge(self, salt: impl egui::AsIdSalt, edge: Edge) -> egui::Panel {
|
||||
let panel = match edge {
|
||||
@@ -832,8 +1076,8 @@ impl Container {
|
||||
.inner_margin(egui::Margin::symmetric(t.space_8 as i8, t.space_4 as i8))
|
||||
}
|
||||
|
||||
pub fn modal(self, id: Id) -> BackingModal {
|
||||
BackingModal { modal: egui::Modal::new(id).area(egui::Modal::default_area(id).fade_in(false)), id }
|
||||
pub fn modal(self, id: Id) -> ModalHost {
|
||||
ModalHost { modal: BackingModal { modal: egui::Modal::new(id).area(egui::Modal::default_area(id).fade_in(false)), id } }
|
||||
}
|
||||
|
||||
pub fn central(self) -> egui::CentralPanel {
|
||||
|
||||
@@ -1604,7 +1604,7 @@ pub(crate) fn text_area(ui: &mut Ui, label: &str, id: egui::Id, value: &mut Stri
|
||||
super::text_menu::menu(ui, &mut response, value, super::text_menu::Field::LINES.limited(limit));
|
||||
t.input_bevel(ui, &response);
|
||||
response.widget_info(|| {
|
||||
let mut info = egui::WidgetInfo::labeled(egui::Role::TextInput, ui.is_enabled(), label);
|
||||
let mut info = egui::WidgetInfo::labeled(egui::Role::MultilineTextInput, ui.is_enabled(), label);
|
||||
info.current_text_value = Some(value.clone());
|
||||
info
|
||||
});
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Table-driven layout/paint references in both themes. No window or GPU required.
|
||||
use super::preferences_figures::{ThemeSample, paint_theme_system, paint_theme_thumbnail};
|
||||
use super::preferences_figures::{ThemeSample, paint_theme_thumbnail};
|
||||
use super::*;
|
||||
use crate::ui_kit::{Container, Surface};
|
||||
use crate::{scenario, theme::Tokens};
|
||||
@@ -57,6 +57,128 @@ fn navigation_sample(ui: &mut Ui, size: crate::navigation_bar::Size) {
|
||||
|
||||
// One entry per element/variant: names, rendering and geometry expectations stay together.
|
||||
const ELEMENTS: &[Element] = &[
|
||||
element!("theme_mode_segments", |ui, _| {
|
||||
theme_segments(
|
||||
ui,
|
||||
"gallery_mode",
|
||||
&[ThemeSegment::new("One theme", ThemeGlyph::Monitor, None), ThemeSegment::new("Follow system", ThemeGlyph::Contrast, None)],
|
||||
Some(1),
|
||||
false,
|
||||
);
|
||||
}),
|
||||
element!("theme_imported_filter", |ui, _| {
|
||||
theme_segments(ui, "gallery_imported", &[ThemeSegment::new("Imported", ThemeGlyph::None, Some(2))], Some(0), false);
|
||||
}),
|
||||
element!("theme_toolbar", |ui, _| {
|
||||
theme_toolbar(
|
||||
ui,
|
||||
"gallery_toolbar",
|
||||
68.0,
|
||||
0.0,
|
||||
|ui| {
|
||||
theme_segments(
|
||||
ui,
|
||||
"gallery_tone",
|
||||
&[ThemeSegment::new("Light", ThemeGlyph::Sun, Some(9)), ThemeSegment::new("Dark", ThemeGlyph::Moon, Some(17))],
|
||||
Some(0),
|
||||
false,
|
||||
);
|
||||
},
|
||||
|ui| {
|
||||
theme_segments(
|
||||
ui,
|
||||
"gallery_view",
|
||||
&[ThemeSegment::new("Carousel", ThemeGlyph::Carousel, None), ThemeSegment::new("Grid", ThemeGlyph::Grid, None)],
|
||||
Some(0),
|
||||
true,
|
||||
);
|
||||
},
|
||||
);
|
||||
}),
|
||||
element!("theme_browser_grid", |ui, _| {
|
||||
theme_browser(ui, "gallery_grid", 14, true, None, |ui, _, width| {
|
||||
theme_card(
|
||||
ui,
|
||||
&ThemeCard {
|
||||
name: "Light",
|
||||
note: "Built in",
|
||||
options: None,
|
||||
sample: ThemeSample::from_tokens(&Tokens::light()),
|
||||
selected: false,
|
||||
dark: false,
|
||||
high: false,
|
||||
day: false,
|
||||
night: false,
|
||||
},
|
||||
width,
|
||||
);
|
||||
});
|
||||
}),
|
||||
element!("theme_segments", |ui, _| {
|
||||
theme_segments(
|
||||
ui,
|
||||
"gallery",
|
||||
&[ThemeSegment::new("Light", ThemeGlyph::Sun, Some(10)), ThemeSegment::new("Dark", ThemeGlyph::Moon, Some(17))],
|
||||
Some(0),
|
||||
false,
|
||||
);
|
||||
}),
|
||||
element!("theme_import_button", |ui, _| {
|
||||
theme_import_button(ui, "Import theme file…");
|
||||
}),
|
||||
element!("theme_slot", |ui, _| {
|
||||
theme_slot(
|
||||
ui,
|
||||
&ThemeSlot {
|
||||
title: "Day theme",
|
||||
name: "Light",
|
||||
hint: "Pick from below",
|
||||
aimed: true,
|
||||
night: false,
|
||||
width: ui.available_width(),
|
||||
sample: ThemeSample::from_tokens(&Tokens::light()),
|
||||
},
|
||||
);
|
||||
}),
|
||||
element!("theme_card", |ui, _| {
|
||||
theme_card(
|
||||
ui,
|
||||
&ThemeCard {
|
||||
name: "Dark",
|
||||
note: "Built in · High contrast",
|
||||
options: Some("Has options"),
|
||||
sample: ThemeSample::from_tokens(&Tokens::dark()),
|
||||
selected: true,
|
||||
dark: true,
|
||||
high: true,
|
||||
day: true,
|
||||
night: true,
|
||||
},
|
||||
118.0,
|
||||
);
|
||||
}),
|
||||
element!("theme_empty", |ui, _| {
|
||||
theme_empty(ui, "No theme matches these filters.", "Clear filters", || {});
|
||||
}),
|
||||
element!("theme_browser", |ui, _| {
|
||||
theme_browser(ui, "gallery_browser", 9, false, None, |ui, i, width| {
|
||||
theme_card(
|
||||
ui,
|
||||
&ThemeCard {
|
||||
name: if i % 2 == 0 { "Light" } else { "Dark" },
|
||||
note: "Built in",
|
||||
options: None,
|
||||
sample: ThemeSample::from_tokens(&Tokens::get()),
|
||||
selected: i == 0,
|
||||
dark: i % 2 != 0,
|
||||
high: false,
|
||||
day: false,
|
||||
night: false,
|
||||
},
|
||||
width,
|
||||
);
|
||||
});
|
||||
}),
|
||||
element!("viewport_status_item", "viewport_status:sample:item", Some("viewport_status:sample:close"), |ui, _| {
|
||||
let item = StatusItem {
|
||||
id: "sample".into(),
|
||||
@@ -586,35 +708,6 @@ const ELEMENTS: &[Element] = &[
|
||||
);
|
||||
settings_pointer_preview(ui, true, "Normal", true);
|
||||
}),
|
||||
element!("preference_theme_carousel", |ui, _| {
|
||||
let light = ThemeSample::from_tokens(&Tokens::light());
|
||||
let dark = ThemeSample::from_tokens(&Tokens::dark());
|
||||
carousel(ui, "gallery_theme_carousel", 4, 88.0, 96.0, |ui, index| {
|
||||
if index == 3 {
|
||||
theme_import_tile(ui, "Import…", "theme file");
|
||||
} else {
|
||||
let label = ["Light", "Dark", "System"][index];
|
||||
picture_card(
|
||||
ui,
|
||||
&Card {
|
||||
label,
|
||||
sub: Some(if index == 2 { "Follows the OS" } else { "Built in" }),
|
||||
selected: index == 0,
|
||||
enabled: true,
|
||||
options: None,
|
||||
check: false,
|
||||
aspect: 124.0 / 76.0,
|
||||
figure: &|p, rect| match index {
|
||||
0 => paint_theme_thumbnail(p, rect, &light),
|
||||
1 => paint_theme_thumbnail(p, rect, &dark),
|
||||
_ => paint_theme_system(p, rect, &light, &dark),
|
||||
},
|
||||
},
|
||||
88.0,
|
||||
);
|
||||
}
|
||||
});
|
||||
}),
|
||||
element!("picture_card", |ui, _| {
|
||||
use super::preferences_figure_data as figures;
|
||||
let gap = ui.spacing().item_spacing.x;
|
||||
@@ -742,36 +835,15 @@ const ELEMENTS: &[Element] = &[
|
||||
help_icon(ui, "Applies when SolidCraft restarts.");
|
||||
});
|
||||
}),
|
||||
element!("carousel", |ui, _| {
|
||||
let sample = ThemeSample::from_tokens(&Tokens::get());
|
||||
let width = Tokens::get().space_24 * 2.0 + Tokens::get().space_24;
|
||||
carousel(ui, "gallery_carousel", 6, width, width * 0.8, |ui, index| {
|
||||
let label = ["Light", "Dark", "System", "Gruvbox", "Studio", "Mono"][index % 6];
|
||||
picture_card(
|
||||
ui,
|
||||
&Card {
|
||||
label,
|
||||
sub: Some("Built in"),
|
||||
selected: index == 1,
|
||||
enabled: true,
|
||||
options: None,
|
||||
check: false,
|
||||
aspect: 124.0 / 76.0,
|
||||
figure: &|p, r| paint_theme_thumbnail(p, r, &sample),
|
||||
},
|
||||
width,
|
||||
);
|
||||
});
|
||||
}),
|
||||
element!("preference_theme_thumbnails", |ui, _| {
|
||||
let (light, dark) = (ThemeSample::from_tokens(&Tokens::light()), ThemeSample::from_tokens(&Tokens::dark()));
|
||||
ui.horizontal(|ui| {
|
||||
for kind in 0..3 {
|
||||
for kind in 0..2 {
|
||||
let (rect, _) = ui.allocate_exact_size(vec2(88.0, 88.0 * 76.0 / 124.0), egui::Sense::hover());
|
||||
match kind {
|
||||
0 => paint_theme_thumbnail(ui.painter(), rect, &light),
|
||||
1 => paint_theme_thumbnail(ui.painter(), rect, &dark),
|
||||
_ => paint_theme_system(ui.painter(), rect, &light, &dark),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -2361,6 +2433,7 @@ fn gallery_covers_every_inline_element() {
|
||||
"sphere.rs",
|
||||
"status.rs",
|
||||
"table.rs",
|
||||
"theme_picker.rs",
|
||||
"tree.rs",
|
||||
] {
|
||||
let source = std::fs::read_to_string(root.join(file)).unwrap();
|
||||
@@ -2986,19 +3059,14 @@ fn card_looks_follow_selected_hover_disabled_and_focus() {
|
||||
|
||||
#[test]
|
||||
fn cards_size_to_their_container_and_survive_hostile_sizes() {
|
||||
use super::preferences_cards::{card_width, carousel_window};
|
||||
use super::preferences_cards::card_width;
|
||||
assert_eq!(card_width(320.0, 4, 10.0), 72.5);
|
||||
assert_eq!(card_width(320.0, 0, 10.0), 320.0);
|
||||
for bad in [0.0, -5.0, f32::NAN, f32::INFINITY, f32::MAX] {
|
||||
let w = card_width(bad, 3, 10.0);
|
||||
assert!(w.is_finite() && w >= 0.0, "{bad}: {w}");
|
||||
let (first, visible) = carousel_window(5, 9, bad, 88.0, 8.0, 26.0);
|
||||
assert!(first + visible <= 5 && visible >= 1, "{bad}: {first} {visible}");
|
||||
}
|
||||
assert_eq!(carousel_window(0, 3, 400.0, 88.0, 8.0, 26.0), (0, 0));
|
||||
// 400 wide: two arrows and their gaps leave 332, which fits three 88-wide items with gaps.
|
||||
assert_eq!(carousel_window(6, 0, 400.0, 88.0, 8.0, 26.0), (0, 3));
|
||||
assert_eq!(carousel_window(6, 5, 400.0, 88.0, 8.0, 26.0), (3, 3), "the offset stops at the last full window");
|
||||
}
|
||||
|
||||
fn sample_card<'a>(label: &'a str, selected: bool, enabled: bool) -> super::preferences_cards::Card<'a> {
|
||||
@@ -3053,8 +3121,8 @@ fn picture_cards_and_tiles_click_only_when_enabled_and_never_panic() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preset_card_help_icon_and_carousel_behave() {
|
||||
use super::preferences_cards::{carousel, help_icon, preset_card};
|
||||
fn preset_card_and_help_icon_behave() {
|
||||
use super::preferences_cards::{help_icon, preset_card};
|
||||
let ctx = crate::fonts::test_context();
|
||||
let icon = |p: &egui::Painter, r: egui::Rect, ink: egui::Color32| crate::icons::paint_ink(p, r, "settings", ink);
|
||||
super::test_support::frame(&ctx, vec![], |ui| {
|
||||
@@ -3065,29 +3133,6 @@ fn preset_card_help_icon_and_carousel_behave() {
|
||||
let help = help_icon(ui, "Help text");
|
||||
assert!(help.rect.width() > 8.0 && help.rect.width() < 20.0);
|
||||
});
|
||||
// The next arrow moves the window by a page and stays inert at the end.
|
||||
let mut first = vec![];
|
||||
let mut at = None;
|
||||
for pass in 0..6 {
|
||||
let events = match (pass, at) {
|
||||
(2, Some(p)) => super::test_support::pointer(p, true),
|
||||
(3, Some(p)) => super::test_support::pointer(p, false),
|
||||
_ => vec![],
|
||||
};
|
||||
super::test_support::frame(&ctx, events, |ui| {
|
||||
let (f, visible) = carousel(ui, "carousel_test", 5, 60.0, 40.0, |ui, _| {
|
||||
ui.allocate_exact_size(egui::vec2(60.0, 40.0), egui::Sense::hover());
|
||||
});
|
||||
first.push((f, visible));
|
||||
if let Some(rect) = scenario::rect_of("prefs:carousel:Next") {
|
||||
at = Some(rect.center());
|
||||
}
|
||||
});
|
||||
}
|
||||
let (f0, visible) = first[0];
|
||||
assert_eq!(f0, 0);
|
||||
assert!((1..5).contains(&visible), "{visible}");
|
||||
assert!(first.last().unwrap().0 >= 1, "the next arrow advanced the window: {first:?}");
|
||||
}
|
||||
|
||||
/// Light and dark boards of the shared Preferences widgets and of every figure, rendered on the CPU.
|
||||
@@ -3100,7 +3145,7 @@ fn preference_widgets_and_figures_board_in_both_themes() {
|
||||
for dark in [false, true] {
|
||||
crate::theme::set_dark(dark);
|
||||
for (board, names) in [
|
||||
("widgets", &["picture_card", "toggle_tile", "preset_card", "help_icon", "carousel", "preference_theme_thumbnails"][..]),
|
||||
("widgets", &["picture_card", "toggle_tile", "preset_card", "help_icon", "theme_browser", "preference_theme_thumbnails"][..]),
|
||||
("figures", &["preference_figures"][..]),
|
||||
] {
|
||||
for scale in [1.0_f32, 2.0] {
|
||||
|
||||
@@ -4,6 +4,66 @@ use crate::ui_kit::*;
|
||||
use crate::{scenario, theme::Tokens};
|
||||
use egui::Ui;
|
||||
|
||||
#[test]
|
||||
fn theme_browser_has_equal_end_padding_and_screenful_arrows_without_selecting() {
|
||||
let ctx = crate::fonts::test_context();
|
||||
let clicked = std::cell::Cell::new(false);
|
||||
let draw = |ui: &mut Ui| {
|
||||
theme_browser(ui, "padding_browser", 10, false, None, |ui, i, width| {
|
||||
let card = theme_card(
|
||||
ui,
|
||||
&ThemeCard {
|
||||
name: "Example",
|
||||
note: "Built in",
|
||||
options: None,
|
||||
sample: ThemeSample::from_tokens(&Tokens::light()),
|
||||
selected: i == 0,
|
||||
dark: false,
|
||||
high: false,
|
||||
day: false,
|
||||
night: false,
|
||||
},
|
||||
width,
|
||||
);
|
||||
clicked.set(clicked.get() || card.clicked());
|
||||
scenario::publish_rect(&format!("test:theme_card:{i}"), card.rect);
|
||||
});
|
||||
};
|
||||
for _ in 0..3 {
|
||||
frame(&ctx, vec![], draw);
|
||||
}
|
||||
let viewport = scenario::rect_of("prefs:theme_viewport").unwrap();
|
||||
let first = scenario::rect_of("test:theme_card:0").unwrap();
|
||||
for gap in [first.left() - viewport.left(), first.top() - viewport.top(), viewport.bottom() - first.bottom()] {
|
||||
assert!((gap - Tokens::get().space_10).abs() < 0.1, "same padding on every resting side: {gap}");
|
||||
}
|
||||
assert!(scenario::handle_at("prefs:theme_previous").is_none());
|
||||
let advance = || {
|
||||
let at = scenario::handle_at("prefs:theme_next").unwrap();
|
||||
frame(&ctx, pointer(at, true), draw);
|
||||
frame(&ctx, pointer(at, false), draw);
|
||||
frame(&ctx, vec![], draw);
|
||||
};
|
||||
let stride = scenario::rect_of("test:theme_card:1").unwrap().left() - first.left();
|
||||
let page = ((viewport.width() / stride).floor() as usize).max(1);
|
||||
advance();
|
||||
let moved = scenario::rect_of(&format!("test:theme_card:{page}")).unwrap();
|
||||
assert!((moved.left() - first.left()).abs() < 0.1, "arrow moves a screenful of {page} cards");
|
||||
assert!(scenario::handle_at("prefs:theme_previous").is_some());
|
||||
assert!(scenario::handle_at("prefs:theme_next").is_some());
|
||||
for _ in 0..10 {
|
||||
if scenario::handle_at("prefs:theme_next").is_none() {
|
||||
break;
|
||||
}
|
||||
advance();
|
||||
}
|
||||
let viewport = scenario::rect_of("prefs:theme_viewport").unwrap();
|
||||
let last = scenario::rect_of("test:theme_card:9").unwrap();
|
||||
assert!((viewport.right() - last.right() - Tokens::get().space_10).abs() < 0.1);
|
||||
assert!(scenario::handle_at("prefs:theme_next").is_none());
|
||||
assert!(!clicked.get(), "floating arrows never select the card under them");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn navigation_cards_keep_their_proportions_and_native_targets_at_narrow_widths() {
|
||||
let previous = crate::theme::is_dark();
|
||||
@@ -272,16 +332,6 @@ fn status_lines_wrap_at_form_width_and_leave_room_for_the_next_row() {
|
||||
crate::theme::set_dark(previous_dark);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn carousel_window_clamps_offsets_and_keeps_a_card_on_narrow_pages() {
|
||||
use crate::ui_kit::preferences_cards::carousel_window;
|
||||
assert_eq!(carousel_window(0, 9, 280.0, 88.0, 8.0, 26.0), (0, 0));
|
||||
assert_eq!(carousel_window(6, 0, 280.0, 88.0, 8.0, 26.0), (0, 2));
|
||||
assert_eq!(carousel_window(6, 2, 280.0, 88.0, 8.0, 26.0), (2, 2));
|
||||
assert_eq!(carousel_window(6, 99, 280.0, 88.0, 8.0, 26.0), (4, 2));
|
||||
assert_eq!(carousel_window(6, 99, 100.0, 88.0, 8.0, 26.0), (5, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_picture_choices_wrap_inside_the_row_and_reserve_their_height() {
|
||||
let choices = [
|
||||
@@ -364,166 +414,6 @@ fn shared_picture_choices_return_clicks_and_respect_both_disabled_states() {
|
||||
}
|
||||
|
||||
/// #11434: an arrow moves by the cards that fit, not by one, and the last page ends on the last card.
|
||||
#[test]
|
||||
fn carousel_arrows_move_a_page_of_the_cards_that_fit_at_each_width() {
|
||||
let count = 11;
|
||||
for width in [280.0_f32, 480.0, 700.0] {
|
||||
let ctx = crate::fonts::test_context();
|
||||
let shown = || -> Vec<usize> { (0..count).filter(|i| scenario::rect_of(&format!("page:item:{i}")).is_some()).collect() };
|
||||
let draw = |events: Vec<egui::Event>| {
|
||||
scenario::clear_handles();
|
||||
crate::test_support::frame(
|
||||
&ctx,
|
||||
egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width + 40.0, 400.0))),
|
||||
events,
|
||||
..Default::default()
|
||||
},
|
||||
|ui| {
|
||||
ui.set_width(width);
|
||||
scope(ui, |ui| {
|
||||
carousel(ui, ("page_carousel", width as u32), count, 88.0, 96.0, |ui, i| {
|
||||
let (r, _) = ui.allocate_exact_size(egui::vec2(88.0, 90.0), egui::Sense::hover());
|
||||
scenario::publish_rect(&format!("page:item:{i}"), r);
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
};
|
||||
let click = |label: &str| {
|
||||
let at = scenario::handle_at(&format!("prefs:carousel:{}", crate::i18n::tr(label))).unwrap();
|
||||
draw(pointer(at, true));
|
||||
draw(pointer(at, false));
|
||||
draw(vec![]);
|
||||
};
|
||||
draw(vec![]);
|
||||
draw(vec![]);
|
||||
let page = shown().len();
|
||||
assert!(page > 1 && page < count, "width {width}: {page} cards fit");
|
||||
assert_eq!(shown(), (0..page).collect::<Vec<_>>());
|
||||
click("prefs.carousel_previous");
|
||||
assert_eq!(shown(), (0..page).collect::<Vec<_>>(), "width {width}: previous is inert at the start");
|
||||
click("prefs.carousel_next");
|
||||
let second = page.min(count - page);
|
||||
assert_eq!(shown(), (second..second + page).collect::<Vec<_>>(), "width {width}: next shows the cards that were hidden");
|
||||
for _ in 0..count {
|
||||
click("prefs.carousel_next");
|
||||
}
|
||||
let last: Vec<usize> = (count - page..count).collect();
|
||||
assert_eq!(shown(), last, "width {width}: the last page ends on the last card");
|
||||
click("prefs.carousel_previous");
|
||||
let back = (count - page).saturating_sub(page);
|
||||
assert_eq!(shown(), (back..back + page).collect::<Vec<_>>(), "width {width}: previous shows the cards before");
|
||||
for _ in 0..count {
|
||||
click("prefs.carousel_previous");
|
||||
}
|
||||
assert_eq!(shown(), (0..page).collect::<Vec<_>>(), "width {width}: previous stops at the first card");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn theme_carousel_moves_and_disables_its_ends_without_selecting() {
|
||||
let ctx = crate::fonts::test_context();
|
||||
let sample = ThemeSample::from_tokens(&Tokens::light());
|
||||
let draw = |ui: &mut Ui| {
|
||||
let bounds = ui.max_rect();
|
||||
carousel(ui, "test_themes", 3, 88.0, 96.0, |ui, index| {
|
||||
let label = ["Light", "Dark", "System"][index];
|
||||
let response = picture_card(
|
||||
ui,
|
||||
&Card {
|
||||
label,
|
||||
sub: Some("Built in"),
|
||||
selected: index == 0,
|
||||
enabled: true,
|
||||
options: (index == 2).then_some("Has options"),
|
||||
check: false,
|
||||
aspect: 124.0 / 76.0,
|
||||
figure: &|p, r| paint_theme_thumbnail(p, r, &sample),
|
||||
},
|
||||
88.0,
|
||||
);
|
||||
assert!(!response.clicked(), "scrolling must not select a card");
|
||||
assert!(bounds.contains_rect(response.rect));
|
||||
scenario::publish_target(&format!("test:theme:{index}"), response.rect);
|
||||
});
|
||||
};
|
||||
for _ in 0..3 {
|
||||
frame(&ctx, vec![], draw);
|
||||
}
|
||||
let previous = format!("prefs:carousel:{}", crate::i18n::tr("prefs.carousel_previous"));
|
||||
let next = format!("prefs:carousel:{}", crate::i18n::tr("prefs.carousel_next"));
|
||||
let click = |handle: &str| {
|
||||
let at = scenario::handle_at(handle).unwrap();
|
||||
frame(&ctx, pointer(at, true), draw);
|
||||
frame(&ctx, pointer(at, false), draw);
|
||||
frame(&ctx, vec![], draw);
|
||||
};
|
||||
let start = scenario::rect_of("test:theme:0").unwrap().left();
|
||||
click(&previous);
|
||||
assert_eq!(scenario::rect_of("test:theme:0").unwrap().left(), start, "previous is inert at the start");
|
||||
click(&next);
|
||||
assert!(scenario::rect_of("test:theme:0").is_none());
|
||||
assert!((scenario::rect_of("test:theme:1").unwrap().left() - start).abs() < 1.0, "the last page ends on the last card");
|
||||
assert!(scenario::rect_of("test:theme:2").is_some());
|
||||
click(&next);
|
||||
assert!((scenario::rect_of("test:theme:1").unwrap().left() - start).abs() < 1.0, "next is inert at the end");
|
||||
click(&previous);
|
||||
assert!(scenario::rect_of("test:theme:0").is_some());
|
||||
assert!(scenario::rect_of("test:theme:2").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn carousel_arrows_expose_disabled_state_hover_and_keyboard_focus() {
|
||||
let ctx = crate::fonts::test_context();
|
||||
ctx.enable_accesskit();
|
||||
let draw = |events| {
|
||||
scenario::clear_handles();
|
||||
crate::test_support::frame(
|
||||
&ctx,
|
||||
egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(320.0, 400.0))),
|
||||
events,
|
||||
focused: true,
|
||||
..Default::default()
|
||||
},
|
||||
|ui| {
|
||||
ui.set_width(280.0);
|
||||
scope(ui, |ui| {
|
||||
carousel(ui, "keyboard_carousel", 3, 88.0, 96.0, |ui, i| {
|
||||
let (r, _) = ui.allocate_exact_size(egui::vec2(88.0, 90.0), egui::Sense::hover());
|
||||
scenario::publish_rect(&format!("keyboard:item:{i}"), r);
|
||||
});
|
||||
});
|
||||
},
|
||||
)
|
||||
};
|
||||
let previous = crate::i18n::tr("prefs.carousel_previous");
|
||||
let next = crate::i18n::tr("prefs.carousel_next");
|
||||
draw(vec![]);
|
||||
let idle = draw(vec![]);
|
||||
let tree = idle.platform_output.accesskit_update.as_ref().unwrap();
|
||||
for (label, disabled) in [(previous, true), (next, false)] {
|
||||
let nodes: Vec<_> =
|
||||
tree.nodes.iter().filter(|(_, node)| node.role() == egui::accesskit::Role::Button && node.label() == Some(label)).collect();
|
||||
assert_eq!(nodes.len(), 1);
|
||||
assert_eq!(nodes[0].1.is_disabled(), disabled);
|
||||
}
|
||||
let at = scenario::handle_at(&format!("prefs:carousel:{next}")).unwrap();
|
||||
let hover = draw(vec![egui::Event::PointerMoved(at)]);
|
||||
assert_eq!(hover.platform_output.cursor_icon, egui::CursorIcon::PointingHand);
|
||||
draw(vec![egui::Event::PointerMoved(egui::pos2(310.0, 390.0))]);
|
||||
let focus = draw(key(egui::Key::Tab));
|
||||
assert!(
|
||||
focus.shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Rect(r) if r.stroke.color == Tokens::get().form_primary)),
|
||||
"keyboard focus uses the standard ring"
|
||||
);
|
||||
draw(key(egui::Key::Enter));
|
||||
draw(vec![]);
|
||||
assert!(scenario::rect_of("keyboard:item:0").is_none(), "keyboard activates Next");
|
||||
assert!(scenario::rect_of("keyboard:item:2").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layout_picture_choices_wrap_inside_the_indexed_row_and_keep_real_targets() {
|
||||
let previous = crate::theme::is_dark();
|
||||
|
||||
@@ -27,6 +27,7 @@ mod navigation;
|
||||
mod navigation_menu;
|
||||
mod navigation_settings;
|
||||
pub(crate) mod panel;
|
||||
mod panel_host;
|
||||
mod preferences;
|
||||
mod preferences_assistant;
|
||||
#[allow(dead_code, reason = "composed by the Preferences pages of #9875 to #9883")]
|
||||
@@ -50,6 +51,7 @@ mod status;
|
||||
mod table;
|
||||
mod text;
|
||||
mod text_menu;
|
||||
mod theme_picker;
|
||||
mod tree;
|
||||
mod value_focus;
|
||||
mod viewport_status;
|
||||
@@ -91,6 +93,7 @@ pub(crate) use panel::{
|
||||
pub use panel::{DialogButtons, Window};
|
||||
#[cfg(test)]
|
||||
pub(crate) use panel::{collapsible_header, header};
|
||||
pub(crate) use panel_host::*;
|
||||
pub(crate) use preferences::*;
|
||||
pub(crate) use preferences_assistant::*;
|
||||
#[allow(unused_imports, reason = "composed by the Preferences pages of #9875 to #9883")]
|
||||
@@ -99,7 +102,7 @@ pub(crate) use preferences_figure_data::{
|
||||
paint_aa_2x, paint_aa_4x, paint_aa_8x, paint_aa_off, paint_ao_on, paint_frame_rate, paint_quick_measure, paint_tess_coarse, paint_tess_fine,
|
||||
paint_tess_normal, paint_tess_ultra, paint_vertex_markers, paint_view_angles, paint_view_grid, paint_view_perspective, paint_view_shadow,
|
||||
};
|
||||
pub(crate) use preferences_figures::{ThemeSample, paint_theme_system, paint_theme_thumbnail};
|
||||
pub(crate) use preferences_figures::{ThemeSample, paint_theme_thumbnail_rounded};
|
||||
pub(crate) use preferences_navigation::*;
|
||||
pub(crate) use preferences_small::*;
|
||||
pub(crate) use radial::{RADIAL_RADIUS, radial_menu};
|
||||
@@ -117,6 +120,7 @@ pub(crate) use table::*;
|
||||
#[cfg(test)]
|
||||
pub(crate) use text::ellipsize_middle;
|
||||
pub(crate) use text_menu::menu_open as text_menu_open;
|
||||
pub(crate) use theme_picker::*;
|
||||
pub(crate) use tree::*;
|
||||
pub(crate) use value_focus::*;
|
||||
pub(crate) use viewport_status::*;
|
||||
|
||||
@@ -0,0 +1,396 @@
|
||||
//! Bounded universal workspace chrome. Placement and transactions are owned by
|
||||
//! panel_runtime; every outer surface here uses the common Container policy.
|
||||
use super::{Container, Surface};
|
||||
use crate::theme::Tokens;
|
||||
|
||||
pub(crate) struct HostChrome<'a> {
|
||||
pub label: &'a str,
|
||||
pub icon: Option<&'a str>,
|
||||
pub icon_only: bool,
|
||||
pub attention: bool,
|
||||
pub selected: bool,
|
||||
pub enabled: bool,
|
||||
pub drag: bool,
|
||||
pub title: bool,
|
||||
/// A tab group's header target paints only its section grip, retaining its label for accessibility.
|
||||
pub grip_only: bool,
|
||||
pub rtl: bool,
|
||||
}
|
||||
|
||||
fn panel_host_container(ctx: &egui::Context, floating: bool) -> Container {
|
||||
if floating { Container::floating_card(Surface::Panel) } else { Container::new(ctx, Surface::Panel) }
|
||||
}
|
||||
|
||||
/// The same adaptive frame supplies both paint and the content's safe clip.
|
||||
pub(crate) fn panel_host_frame(ctx: &egui::Context, floating: bool) -> egui::Frame {
|
||||
panel_host_container(ctx, floating).frame(ctx, Tokens::get().panel, crate::frame::Side::Left).inner_margin(0).outer_margin(0)
|
||||
}
|
||||
|
||||
pub(crate) fn panel_host_surface<R>(
|
||||
ui: &mut egui::Ui,
|
||||
id: egui::Id,
|
||||
bounds: egui::Rect,
|
||||
floating: bool,
|
||||
body: impl FnOnce(&mut egui::Ui, egui::Rect) -> R,
|
||||
) -> R {
|
||||
let container = panel_host_container(ui.ctx(), floating);
|
||||
let frame = panel_host_frame(ui.ctx(), floating);
|
||||
let clip = ui.clip_rect().intersect(bounds);
|
||||
// egui clips to rectangles. This inscribed rectangle keeps arbitrary content
|
||||
// fills inside the rounded frame without changing any header hit target.
|
||||
let radius = frame.corner_radius;
|
||||
let radius = f32::from(radius.nw.max(radius.ne).max(radius.sw).max(radius.se));
|
||||
let inset = frame.stroke.width + (radius - frame.stroke.width).max(0.0) * (1.0 - std::f32::consts::FRAC_1_SQRT_2);
|
||||
let content_clip = bounds.shrink(inset.min(bounds.width().min(bounds.height()).max(0.0) / 2.0)).intersect(clip);
|
||||
let paint = |ui: &mut egui::Ui| {
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().id_salt(id).max_rect(bounds));
|
||||
child.set_clip_rect(clip);
|
||||
container.paint_background(child.painter(), frame, bounds - frame.total_margin());
|
||||
let result = body(&mut child, content_clip);
|
||||
Container::paint_inset_clipped(child.painter(), bounds, frame, clip);
|
||||
result
|
||||
};
|
||||
if floating {
|
||||
let layer = egui::LayerId::new(egui::Order::Background, id.with("area"));
|
||||
Container::bring_to_front(ui.ctx(), layer);
|
||||
container
|
||||
.area(id.with("area"))
|
||||
.fixed_pos(bounds.min)
|
||||
.movable(false)
|
||||
.fade_in(false)
|
||||
.show(ui.ctx(), |ui| {
|
||||
ui.set_min_size(bounds.size());
|
||||
paint(ui)
|
||||
})
|
||||
.inner
|
||||
} else {
|
||||
paint(ui)
|
||||
}
|
||||
}
|
||||
|
||||
/// Actual accessible egui targets, with IDs independent of ordering and labels.
|
||||
pub(crate) fn panel_host_control(ui: &mut egui::Ui, id: egui::Id, bounds: egui::Rect, chrome: HostChrome<'_>) -> egui::Response {
|
||||
panel_host_control_label_opacity(ui, id, bounds, chrome, 1.0)
|
||||
}
|
||||
|
||||
/// Only the label ink changes; the grip, icons, fills and response stay intact.
|
||||
pub(crate) fn panel_host_control_label_opacity(
|
||||
ui: &mut egui::Ui,
|
||||
id: egui::Id,
|
||||
bounds: egui::Rect,
|
||||
chrome: HostChrome<'_>,
|
||||
label_opacity: f32,
|
||||
) -> egui::Response {
|
||||
let t = Tokens::get();
|
||||
let sense = if chrome.enabled { if chrome.drag { egui::Sense::click_and_drag() } else { egui::Sense::click() } } else { egui::Sense::hover() };
|
||||
let response = ui.interact(bounds, id, sense);
|
||||
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, chrome.enabled, chrome.label));
|
||||
let fill = if chrome.selected {
|
||||
Some(t.selected_bg)
|
||||
} else if response.hovered() && chrome.enabled {
|
||||
Some(t.hover)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let ink = if !chrome.enabled {
|
||||
t.form_dim
|
||||
} else if chrome.attention {
|
||||
t.form_primary
|
||||
} else {
|
||||
t.form_ink
|
||||
};
|
||||
let painter = ui.painter().with_clip_rect(ui.clip_rect().intersect(bounds));
|
||||
let paint_bounds = bounds.shrink2(egui::vec2(t.space_4.min(bounds.width() / 2.0), t.space_4.min(bounds.height() / 2.0)));
|
||||
if let Some(fill) = fill {
|
||||
if chrome.title {
|
||||
super::panel::panel_header_hover(&painter, paint_bounds);
|
||||
} else {
|
||||
painter.rect_filled(paint_bounds, t.control_radius, fill);
|
||||
}
|
||||
}
|
||||
if response.has_focus() {
|
||||
painter.rect_stroke(bounds.shrink(t.space_2), t.radius_sm, t.control_border_stroke(t.form_primary), egui::StrokeKind::Inside);
|
||||
}
|
||||
let text_inset = if chrome.title { t.space_12 } else { t.space_4 };
|
||||
let mut text = bounds.shrink2(egui::vec2(text_inset.min(bounds.width() / 2.0), 0.0));
|
||||
if chrome.title {
|
||||
let size =
|
||||
egui::vec2(t.space_10.min(if chrome.grip_only { bounds.width() } else { text.width() }), (t.space_16 + t.space_2).min(bounds.height()));
|
||||
let center = if chrome.grip_only {
|
||||
bounds.center()
|
||||
} else {
|
||||
egui::pos2(if chrome.rtl { text.right() - size.x / 2.0 } else { text.left() + size.x / 2.0 }, bounds.center().y)
|
||||
};
|
||||
let grip = egui::Rect::from_center_size(center, size);
|
||||
let mut grip_ui = ui.new_child(egui::UiBuilder::new().max_rect(grip));
|
||||
grip_ui.set_clip_rect(grip.intersect(ui.clip_rect()));
|
||||
super::panel_grip(&mut grip_ui);
|
||||
if chrome.rtl {
|
||||
text.max.x = (grip.left() - t.space_8).max(text.left());
|
||||
} else {
|
||||
text.min.x = (grip.right() + t.space_8).min(text.right());
|
||||
}
|
||||
}
|
||||
let icon = chrome.icon.filter(|icon| !icon.is_empty());
|
||||
if let Some(icon) = icon {
|
||||
let extent = if chrome.icon_only {
|
||||
(bounds.width().min(bounds.height()) - t.form_icon_inset * 2.0).max(0.0)
|
||||
} else {
|
||||
t.form_icon_size.min(bounds.height()).min(text.width())
|
||||
};
|
||||
let center = if chrome.icon_only {
|
||||
bounds.center()
|
||||
} else {
|
||||
egui::pos2(if chrome.rtl { text.right() - extent / 2.0 } else { text.left() + extent / 2.0 }, bounds.center().y)
|
||||
};
|
||||
let icon_rect = egui::Rect::from_center_size(center, egui::vec2(extent, extent));
|
||||
if chrome.icon_only {
|
||||
crate::icons::paint_ink(&painter, icon_rect, icon, ink);
|
||||
} else {
|
||||
crate::icons::paint_icon(&painter, icon_rect, icon, if chrome.enabled { 1.0 } else { 0.5 });
|
||||
}
|
||||
let gap = if chrome.title { t.space_8 } else { t.space_4 };
|
||||
if chrome.rtl {
|
||||
text.max.x = (icon_rect.left() - gap).max(text.left());
|
||||
} else {
|
||||
text.min.x = (icon_rect.right() + gap).min(text.right());
|
||||
}
|
||||
}
|
||||
if chrome.attention && !chrome.grip_only {
|
||||
painter.circle_filled(
|
||||
egui::pos2(if chrome.rtl { paint_bounds.left() } else { paint_bounds.right() }, paint_bounds.top()),
|
||||
t.space_2,
|
||||
t.form_primary,
|
||||
);
|
||||
}
|
||||
if !chrome.icon_only && !chrome.grip_only {
|
||||
let ink = ink.gamma_multiply(label_opacity);
|
||||
let font = if chrome.title {
|
||||
crate::fonts::semibold(t.font_heading)
|
||||
} else if chrome.selected {
|
||||
crate::fonts::semibold(t.font_label)
|
||||
} else {
|
||||
egui::FontId::proportional(t.font_label)
|
||||
};
|
||||
if chrome.rtl {
|
||||
let width = painter.layout_no_wrap(chrome.label.to_owned(), font.clone(), ink).size().x.min(text.width());
|
||||
text.min.x = text.right() - width;
|
||||
}
|
||||
super::text::paint_text(ui, text, chrome.label, font, ink, false);
|
||||
}
|
||||
if chrome.enabled && response.hovered() {
|
||||
ui.ctx().set_cursor_icon(if chrome.drag { egui::CursorIcon::Grab } else { egui::CursorIcon::PointingHand });
|
||||
}
|
||||
response.on_hover_text(chrome.label)
|
||||
}
|
||||
|
||||
/// The same full-header affordance collapses and restores with one click.
|
||||
/// Reuse the existing chevron master, with the kit's vertical mirror helper.
|
||||
pub(crate) fn panel_host_disclosure(
|
||||
ui: &mut egui::Ui,
|
||||
id: egui::Id,
|
||||
bounds: egui::Rect,
|
||||
label: &str,
|
||||
enabled: bool,
|
||||
collapsed: bool,
|
||||
) -> egui::Response {
|
||||
let response = panel_host_control(
|
||||
ui,
|
||||
id,
|
||||
bounds,
|
||||
HostChrome {
|
||||
label,
|
||||
icon: None,
|
||||
icon_only: true,
|
||||
attention: false,
|
||||
selected: false,
|
||||
enabled,
|
||||
drag: false,
|
||||
title: false,
|
||||
grip_only: false,
|
||||
rtl: false,
|
||||
},
|
||||
);
|
||||
let t = Tokens::get();
|
||||
let ink = if enabled { t.form_ink } else { t.form_dim };
|
||||
let extent = (bounds.width().min(bounds.height()) - t.form_icon_inset * 2.0).max(0.0);
|
||||
let icon = egui::Rect::from_center_size(bounds.center(), egui::vec2(extent, extent));
|
||||
let painter = ui.painter().with_clip_rect(ui.clip_rect().intersect(bounds));
|
||||
if collapsed {
|
||||
crate::icons::paint_ink(&painter, icon, "chevron", ink);
|
||||
} else {
|
||||
crate::icons::paint_ink_flipped(&painter, icon, "chevron", ink);
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
pub(crate) fn panel_host_sash(ui: &mut egui::Ui, id: egui::Id, bounds: egui::Rect, name: &str) -> egui::Response {
|
||||
let t = Tokens::get();
|
||||
let response = ui.interact(bounds, id, egui::Sense::click_and_drag());
|
||||
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::SpinButton, ui.is_enabled(), name));
|
||||
if response.hovered() || response.has_focus() || response.dragged() {
|
||||
ui.painter().rect_filled(bounds.intersect(ui.clip_rect()), t.radius_sm, t.form_primary);
|
||||
}
|
||||
if response.hovered() {
|
||||
ui.ctx().set_cursor_icon(if bounds.width() >= bounds.height() {
|
||||
egui::CursorIcon::ResizeVertical
|
||||
} else {
|
||||
egui::CursorIcon::ResizeHorizontal
|
||||
});
|
||||
}
|
||||
response.on_hover_text(name)
|
||||
}
|
||||
|
||||
/// A scrollbar owns only its narrow track. The surrounding canvas has no
|
||||
/// response or scroll area, so uncovered gaps remain available to navigation.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn panel_host_scrollbar(
|
||||
ui: &mut egui::Ui,
|
||||
id: egui::Id,
|
||||
bounds: egui::Rect,
|
||||
horizontal: bool,
|
||||
visible: f32,
|
||||
total: f32,
|
||||
offset: f32,
|
||||
name: &str,
|
||||
) -> (egui::Response, Option<f32>) {
|
||||
let t = Tokens::get();
|
||||
let response = ui.interact(bounds, id, egui::Sense::click_and_drag());
|
||||
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::SpinButton, ui.is_enabled(), name));
|
||||
let length = if horizontal { bounds.width() } else { bounds.height() };
|
||||
let maximum = (total - visible).max(0.0);
|
||||
if length <= 0.0 || maximum <= 0.0 {
|
||||
return (response, None);
|
||||
}
|
||||
let thumb_length = (length * visible / total).max(t.control_height.min(length)).min(length);
|
||||
let travel = length - thumb_length;
|
||||
let start = if horizontal { bounds.left() } else { bounds.top() };
|
||||
let thumb_start = start + travel * offset.clamp(0.0, maximum) / maximum;
|
||||
let thumb = if horizontal {
|
||||
egui::Rect::from_min_size(egui::pos2(thumb_start, bounds.top()), egui::vec2(thumb_length, bounds.height()))
|
||||
} else {
|
||||
egui::Rect::from_min_size(egui::pos2(bounds.left(), thumb_start), egui::vec2(bounds.width(), thumb_length))
|
||||
};
|
||||
let painter = ui.painter().with_clip_rect(ui.clip_rect().intersect(bounds));
|
||||
painter.rect_filled(bounds, t.radius_sm, t.panel_header);
|
||||
painter.rect_filled(thumb, t.radius_sm, if response.dragged() || response.hovered() { t.form_primary } else { t.form_dim });
|
||||
let mut next = None;
|
||||
if travel > 0.0
|
||||
&& let Some(pointer) = response.interact_pointer_pos()
|
||||
{
|
||||
let coordinate = if horizontal { pointer.x } else { pointer.y };
|
||||
let grab_id = id.with("scroll_grab");
|
||||
if response.drag_started() {
|
||||
ui.ctx().data_mut(|data| data.insert_temp(grab_id, (coordinate - thumb_start).clamp(0.0, thumb_length)));
|
||||
}
|
||||
if response.dragged() || response.clicked() {
|
||||
let grab = ui.ctx().data(|data| data.get_temp::<f32>(grab_id)).unwrap_or(thumb_length / 2.0);
|
||||
next = Some(((coordinate - start - grab) / travel * maximum).clamp(0.0, maximum));
|
||||
}
|
||||
if response.drag_stopped() {
|
||||
ui.ctx().data_mut(|data| data.remove::<f32>(grab_id));
|
||||
}
|
||||
}
|
||||
if response.has_focus() {
|
||||
let delta = ui.input(|input| {
|
||||
let back = if horizontal { egui::Key::ArrowLeft } else { egui::Key::ArrowUp };
|
||||
let forward = if horizontal { egui::Key::ArrowRight } else { egui::Key::ArrowDown };
|
||||
u8::from(input.key_pressed(forward)) as f32 - u8::from(input.key_pressed(back)) as f32
|
||||
});
|
||||
if delta != 0.0 {
|
||||
next = Some((offset + delta * t.control_height).clamp(0.0, maximum));
|
||||
}
|
||||
}
|
||||
(response.on_hover_text(name), next)
|
||||
}
|
||||
|
||||
pub(crate) fn panel_host_preview(ui: &egui::Ui, bounds: egui::Rect, valid: bool, reason: Option<&str>, opacity: f32) {
|
||||
let t = Tokens::get();
|
||||
let ink = if valid { t.form_primary } else { t.form_error };
|
||||
let painter =
|
||||
ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, ui.scope_id().with("panel_preview"))).with_clip_rect(ui.clip_rect());
|
||||
painter.rect_filled(bounds, t.radius_md, ink.gamma_multiply(0.12 * opacity));
|
||||
let mut stroke = t.control_border_stroke(ink);
|
||||
stroke.color = stroke.color.gamma_multiply(opacity);
|
||||
painter.rect_stroke(bounds, t.radius_md, stroke, egui::StrokeKind::Inside);
|
||||
if let Some(reason) = reason {
|
||||
let galley = painter.layout(
|
||||
reason.to_owned(),
|
||||
egui::FontId::proportional(t.font_small),
|
||||
t.form_ink,
|
||||
(bounds.width() - t.space_8 * 2.0).max(t.space_2),
|
||||
);
|
||||
// Keep the rejection legible over the retained content beneath it.
|
||||
// This is paint on the existing preview layer, never an input surface.
|
||||
let reason_painter = painter.with_clip_rect(bounds.intersect(ui.clip_rect()));
|
||||
let backing = egui::Rect::from_center_size(bounds.center(), galley.size()).expand2(egui::vec2(t.space_8, t.space_4)).intersect(bounds);
|
||||
reason_painter.rect_filled(backing, t.radius_sm, t.dialog_body.to_opaque());
|
||||
reason_painter.rect_stroke(backing, t.radius_sm, t.control_border_stroke(ink.gamma_multiply(0.65)), egui::StrokeKind::Inside);
|
||||
reason_painter.galley(bounds.center() - galley.size() / 2.0, galley, t.form_ink);
|
||||
}
|
||||
}
|
||||
|
||||
/// Paint identity on the existing preview layer without allocating a widget or
|
||||
/// registering an input/occlusion footprint. Titles are already in display order;
|
||||
/// never automatically wrap or reorder them. Oversized text clips to the badge.
|
||||
pub(crate) fn panel_host_drag_title(ui: &egui::Ui, title: &str, at: egui::Pos2, domain: egui::Rect, rtl: bool) {
|
||||
let clip = ui.clip_rect().intersect(domain);
|
||||
if !clip.is_finite() || !clip.is_positive() || !at.is_finite() || !clip.contains(at) {
|
||||
return;
|
||||
}
|
||||
let t = Tokens::get();
|
||||
let padding = egui::vec2(t.space_8.min(clip.width() / 4.0), t.space_4.min(clip.height() / 4.0));
|
||||
let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, ui.scope_id().with("panel_preview"))).with_clip_rect(clip);
|
||||
let galley = painter.layout_no_wrap(title.to_owned(), egui::FontId::proportional(t.font_label), t.form_ink);
|
||||
let size = (galley.size() + padding * 2.0).min(clip.size());
|
||||
let x = if rtl { at.x - t.space_12 - size.x } else { at.x + t.space_12 };
|
||||
let min = egui::pos2(
|
||||
x.clamp(clip.left(), (clip.right() - size.x).max(clip.left())),
|
||||
(at.y + t.space_12).clamp(clip.top(), (clip.bottom() - size.y).max(clip.top())),
|
||||
);
|
||||
let bounds = egui::Rect::from_min_size(min, size);
|
||||
painter.rect_filled(bounds, t.radius_sm, t.dialog_body.to_opaque());
|
||||
painter.rect_stroke(bounds, t.radius_sm, t.control_border_stroke(t.dialog_border), egui::StrokeKind::Inside);
|
||||
let text_at = egui::pos2(if rtl { bounds.right() - padding.x - galley.size().x } else { min.x + padding.x }, min.y + padding.y);
|
||||
painter.with_clip_rect(bounds.intersect(clip)).galley(text_at, galley, t.form_ink);
|
||||
}
|
||||
|
||||
pub(crate) fn panel_host_neighbour_preview(ui: &egui::Ui, bounds: egui::Rect, removed: bool, opacity: f32) {
|
||||
let t = Tokens::get();
|
||||
let painter =
|
||||
ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, ui.scope_id().with("panel_preview"))).with_clip_rect(ui.clip_rect());
|
||||
let stroke = egui::Stroke::new(1.0, t.form_primary.gamma_multiply(0.7 * opacity));
|
||||
painter.rect_stroke(bounds, t.radius_sm, stroke, egui::StrokeKind::Inside);
|
||||
if removed {
|
||||
painter.line_segment([bounds.left_top(), bounds.right_bottom()], stroke);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn panel_host_tab_insertion(ui: &egui::Ui, bounds: egui::Rect, opacity: f32) {
|
||||
let painter =
|
||||
ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, ui.scope_id().with("panel_preview"))).with_clip_rect(ui.clip_rect());
|
||||
painter.rect_filled(bounds, 0, Tokens::get().form_primary.gamma_multiply(opacity));
|
||||
}
|
||||
|
||||
/// Menus own only their measured bounded rectangle; there is no viewport shield.
|
||||
pub(crate) fn panel_host_popup<R>(ui: &mut egui::Ui, id: egui::Id, bounds: egui::Rect, body: impl FnOnce(&mut egui::Ui) -> R) -> R {
|
||||
let container = Container::new(ui.ctx(), Surface::Popup);
|
||||
let frame = Container::menu_frame();
|
||||
let clip = ui.clip_rect().intersect(bounds);
|
||||
container
|
||||
.area(id)
|
||||
.order(egui::Order::Foreground)
|
||||
.fixed_pos(bounds.min)
|
||||
.movable(false)
|
||||
.fade_in(false)
|
||||
.show(ui.ctx(), |ui| {
|
||||
ui.set_clip_rect(clip);
|
||||
ui.set_min_size(bounds.size());
|
||||
Container::paint_frame(ui.painter(), frame, bounds - frame.total_margin());
|
||||
let inner = bounds.shrink(Tokens::get().space_6);
|
||||
let mut content = ui.new_child(egui::UiBuilder::new().id_salt("content").max_rect(inner));
|
||||
content.set_clip_rect(inner.intersect(clip));
|
||||
body(&mut content)
|
||||
})
|
||||
.inner
|
||||
}
|
||||
@@ -4,6 +4,927 @@ use crate::ui_kit::*;
|
||||
use crate::{scenario, theme::Tokens};
|
||||
use egui::Ui;
|
||||
|
||||
#[test]
|
||||
fn closed_backing_window_noop_does_not_block_real_host_menu_but_visible_returning_window_does() {
|
||||
use crate::panel_runtime::{ContentServices, HostControlTarget, HostOptions, HostPointerTarget, PanelMountHarness, WorkspacePanelHost};
|
||||
use solidcraft_engine::panels::{
|
||||
ActionSink as _, Destination, InstanceId, LogicalRect, Mutation, PanelKind, Point, SectionId, SectionLocation, Size, Zone,
|
||||
};
|
||||
fn frame(
|
||||
ctx: &egui::Context,
|
||||
content: &mut PanelMountHarness,
|
||||
host: &mut WorkspacePanelHost,
|
||||
time: &mut f64,
|
||||
events: Vec<egui::Event>,
|
||||
position: egui::Pos2,
|
||||
open: bool,
|
||||
) -> (bool, bool) {
|
||||
content.tick().unwrap();
|
||||
host.capture_metrics(&content.runtime, &content.models).unwrap();
|
||||
host.capture_reservations(&content.runtime, &content.catalogue).unwrap();
|
||||
host.prepare(&content.runtime, LogicalRect { origin: Point { x: 0.0, y: 0.0 }, size: Size { width: 1400.0, height: 1000.0 } }).unwrap();
|
||||
*time += 1.0 / 60.0;
|
||||
let mut observed = (false, false);
|
||||
crate::test_support::frame(
|
||||
ctx,
|
||||
egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 1000.0))),
|
||||
focused: true,
|
||||
time: Some(*time),
|
||||
events,
|
||||
..Default::default()
|
||||
},
|
||||
|ui| {
|
||||
Container::begin_host_windows(ui.ctx());
|
||||
host.show_deferred(
|
||||
ui,
|
||||
&mut content.runtime,
|
||||
&mut content.native,
|
||||
&mut ContentServices { models: &content.models, commands: &mut content.commands, local: &mut content.local },
|
||||
)
|
||||
.unwrap();
|
||||
let source = host
|
||||
.frame()
|
||||
.unwrap()
|
||||
.controls
|
||||
.iter()
|
||||
.find(|control| {
|
||||
matches!(&control.target,
|
||||
HostControlTarget::Pointer(HostPointerTarget::Menu { instance }) if instance.0 == "source")
|
||||
})
|
||||
.unwrap();
|
||||
observed.0 = ui.ctx().read_response(source.id).unwrap().clicked();
|
||||
let id = egui::Id::unique("returning_backing_feature");
|
||||
let container = Container::new(ui.ctx(), Surface::Feature);
|
||||
let backing = Panel::feature_frame(ui.ctx(), crate::shell::LayoutMode::Floating, crate::frame::Side::Left);
|
||||
let stock = container
|
||||
.window("Returning independent feature")
|
||||
.id(id)
|
||||
.title_bar(false)
|
||||
.collapsible(false)
|
||||
.resizable(false)
|
||||
.scroll(false)
|
||||
.constrain(false)
|
||||
.fade_in(false)
|
||||
.fade_out(false)
|
||||
.fixed_pos(position)
|
||||
.frame(backing);
|
||||
let mut open_flag = open;
|
||||
let mut body_called = false;
|
||||
let windows_before = Container::host_window_regions(ui.ctx());
|
||||
// Exercise the real optional-backing allocation path without
|
||||
// manufacturing GPU support in this headless test.
|
||||
let shown =
|
||||
container::FeatureWindow::new(stock, id, backing).open(&mut open_flag).show_background(ui.ctx(), Some(host_marker), |ui| {
|
||||
body_called = true;
|
||||
ui.set_min_size(egui::vec2(180.0, 90.0));
|
||||
ui.label("Actual foreign feature content");
|
||||
ui.is_visible() && !ui.is_sizing_pass()
|
||||
});
|
||||
observed.1 = shown.as_ref().and_then(|shown| shown.inner).unwrap_or(false);
|
||||
if !open {
|
||||
assert!(shown.is_none());
|
||||
assert!(!body_called, "closing must skip the body on the first closed frame");
|
||||
assert_eq!(Container::host_window_regions(ui.ctx()), windows_before, "a closed window cannot leave a ghost footprint");
|
||||
let layer = egui::LayerId::new(egui::Order::Middle, id);
|
||||
assert!(
|
||||
ui.ctx().graphics(|graphics| graphics.get(layer).is_some_and(
|
||||
|paint| paint.all_entries().count() > 0 && paint.all_entries().all(|entry| matches!(&entry.shape, egui::Shape::Noop))
|
||||
)),
|
||||
"a closed backing wrapper must really leave only its reserved Noop"
|
||||
);
|
||||
} else if observed.1 {
|
||||
assert!(Container::host_window_regions(ui.ctx()).unwrap().contains(&shown.as_ref().unwrap().response.rect));
|
||||
}
|
||||
host.finish(
|
||||
ui,
|
||||
&mut content.runtime,
|
||||
&mut content.native,
|
||||
&mut ContentServices { models: &content.models, commands: &mut content.commands, local: &mut content.local },
|
||||
&mut content.catalogue,
|
||||
)
|
||||
.unwrap();
|
||||
},
|
||||
);
|
||||
observed
|
||||
}
|
||||
fn pointer(at: egui::Pos2, pressed: bool) -> Vec<egui::Event> {
|
||||
vec![
|
||||
egui::Event::PointerMoved(at),
|
||||
egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE },
|
||||
]
|
||||
}
|
||||
for scale in [1.0, 2.0] {
|
||||
let ctx = crate::fonts::test_context();
|
||||
ctx.set_pixels_per_point(scale);
|
||||
ctx.options_mut(|options| options.max_passes = 1.try_into().unwrap());
|
||||
let mut content = PanelMountHarness::new(false).unwrap();
|
||||
content
|
||||
.dispatch(vec![Mutation::Open {
|
||||
kind: PanelKind::new("fixture.log").unwrap(),
|
||||
instance: InstanceId::new("source").unwrap(),
|
||||
destination: Some(Destination::NewSection {
|
||||
section: SectionId::new("source-section").unwrap(),
|
||||
index: 0,
|
||||
location: SectionLocation::Dock { zone: Zone::Left },
|
||||
size: Size { width: 280.0, height: 240.0 },
|
||||
}),
|
||||
}])
|
||||
.unwrap();
|
||||
let before = content.runtime.layout().inspect();
|
||||
let commits = content.native.commits;
|
||||
let mut host = WorkspacePanelHost::new(HostOptions::default()).unwrap();
|
||||
let mut time = 0.0;
|
||||
let away = egui::pos2(1600.0, 1200.0);
|
||||
for _ in 0..3 {
|
||||
frame(&ctx, &mut content, &mut host, &mut time, Vec::new(), away, true);
|
||||
}
|
||||
let source = host
|
||||
.frame()
|
||||
.unwrap()
|
||||
.controls
|
||||
.iter()
|
||||
.find(|control| {
|
||||
matches!(&control.target,
|
||||
HostControlTarget::Pointer(HostPointerTarget::Menu { instance }) if instance.0 == "source")
|
||||
})
|
||||
.unwrap()
|
||||
.clone();
|
||||
let at = crate::panel_runtime::egui_rect(source.bounds).center();
|
||||
let cover = at - egui::vec2(12.0, 12.0);
|
||||
assert!(frame(&ctx, &mut content, &mut host, &mut time, Vec::new(), cover, true).1);
|
||||
frame(&ctx, &mut content, &mut host, &mut time, Vec::new(), cover, false);
|
||||
let retained = egui::containers::AreaState::load(&ctx, egui::Id::unique("returning_backing_feature")).unwrap();
|
||||
assert!(retained.interactable && retained.rect().contains(at), "the closed window must retain its old covering Area state");
|
||||
frame(&ctx, &mut content, &mut host, &mut time, pointer(at, true), cover, false);
|
||||
assert!(
|
||||
frame(&ctx, &mut content, &mut host, &mut time, pointer(at, false), cover, false).0,
|
||||
"the earlier actual Menu widget must complete its real click"
|
||||
);
|
||||
for _ in 0..2 {
|
||||
frame(&ctx, &mut content, &mut host, &mut time, Vec::new(), cover, false);
|
||||
}
|
||||
assert!(host.frame().unwrap().menu_bounds.is_some(), "Noop-only backing must not refuse the real underlying menu intent");
|
||||
for pressed in [true, false] {
|
||||
frame(
|
||||
&ctx,
|
||||
&mut content,
|
||||
&mut host,
|
||||
&mut time,
|
||||
vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }],
|
||||
cover,
|
||||
false,
|
||||
);
|
||||
}
|
||||
frame(&ctx, &mut content, &mut host, &mut time, Vec::new(), cover, false);
|
||||
frame(&ctx, &mut content, &mut host, &mut time, pointer(at, true), cover, false);
|
||||
let returned = frame(&ctx, &mut content, &mut host, &mut time, pointer(at, false), cover, true);
|
||||
assert!(returned.0 && returned.1, "the actual Window must return visibly after the earlier Menu click queues its intent");
|
||||
for _ in 0..3 {
|
||||
frame(&ctx, &mut content, &mut host, &mut time, Vec::new(), cover, false);
|
||||
}
|
||||
assert!(host.frame().unwrap().menu_bounds.is_none(), "actual visible foreign paint still rejects the source with no latent replay");
|
||||
assert_eq!(content.runtime.layout().inspect(), before);
|
||||
assert_eq!(content.native.commits, commits);
|
||||
assert_eq!(content.commands.calls, 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_window_ledger_is_opt_in_pass_scoped_identity_aware_and_fail_closed() {
|
||||
let ctx = crate::fonts::test_context();
|
||||
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0));
|
||||
let first = egui::Rect::from_min_size(egui::pos2(10.0, 20.0), egui::vec2(100.0, 80.0));
|
||||
let moved = first.translate(egui::vec2(30.0, 40.0));
|
||||
let id = egui::Id::unique("actual_window_identity");
|
||||
let mut passes = 0;
|
||||
crate::test_support::frame(&ctx, egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| {
|
||||
passes += 1;
|
||||
assert_eq!(Container::host_window_regions(ui.ctx()), Some(Vec::new()));
|
||||
Container::record_host_window(ui.ctx(), id, Some(first));
|
||||
assert_eq!(Container::host_window_regions(ui.ctx()), Some(Vec::new()), "a producer cannot activate collection without the host");
|
||||
Container::begin_host_windows(ui.ctx());
|
||||
Container::record_host_window(ui.ctx(), id, Some(first));
|
||||
Container::record_host_window(ui.ctx(), id, Some(moved));
|
||||
assert_eq!(Container::host_window_regions(ui.ctx()), Some(vec![moved]), "an identity update replaces its old footprint");
|
||||
Container::record_host_window(ui.ctx(), id, None);
|
||||
assert_eq!(Container::host_window_regions(ui.ctx()), Some(Vec::new()));
|
||||
Container::record_host_window(ui.ctx(), id, Some(first));
|
||||
if ui.ctx().current_pass_index() == 0 {
|
||||
ui.ctx().request_discard("prove persistent window footprints do not leak into a retry pass");
|
||||
}
|
||||
});
|
||||
assert!(passes >= 2);
|
||||
crate::test_support::frame(&ctx, egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| {
|
||||
assert_eq!(Container::host_window_regions(ui.ctx()), Some(Vec::new()), "a new frame cannot reuse the preceding footprint");
|
||||
});
|
||||
for bad in [
|
||||
egui::Rect::from_min_size(egui::pos2(f32::NAN, 0.0), egui::vec2(10.0, 10.0)),
|
||||
egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(f32::INFINITY, 10.0)),
|
||||
egui::Rect::from_min_size(egui::Pos2::ZERO, egui::Vec2::ZERO),
|
||||
] {
|
||||
crate::test_support::frame(&ctx, egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| {
|
||||
Container::begin_host_windows(ui.ctx());
|
||||
Container::record_host_window(ui.ctx(), id, Some(bad));
|
||||
assert!(Container::host_window_regions(ui.ctx()).is_none());
|
||||
Container::record_host_window(ui.ctx(), id, None);
|
||||
assert!(Container::host_window_regions(ui.ctx()).is_none(), "removal cannot erase a hostile-footprint failure in this pass");
|
||||
});
|
||||
}
|
||||
crate::test_support::frame(&ctx, egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| {
|
||||
Container::begin_host_windows(ui.ctx());
|
||||
for index in 0..256 {
|
||||
Container::record_host_window(ui.ctx(), egui::Id::unique(("bounded_window", index)), Some(first));
|
||||
}
|
||||
assert_eq!(Container::host_window_regions(ui.ctx()).unwrap().len(), 256);
|
||||
Container::record_host_window(ui.ctx(), egui::Id::unique(("bounded_window", 0)), Some(moved));
|
||||
assert_eq!(Container::host_window_regions(ui.ctx()).unwrap().len(), 256, "repainting a known window consumes no extra capacity");
|
||||
Container::record_host_window(ui.ctx(), egui::Id::unique(("bounded_window", 256)), Some(first));
|
||||
assert!(Container::host_window_regions(ui.ctx()).is_none(), "overflow must refuse the whole snapshot instead of truncating windows");
|
||||
Container::record_host_window(ui.ctx(), egui::Id::unique(("bounded_window", 0)), None);
|
||||
assert!(Container::host_window_regions(ui.ctx()).is_none());
|
||||
});
|
||||
let peer = egui::ViewportId::from_hash_of("independent_native_host");
|
||||
let mut input = egui::RawInput { viewport_id: peer, screen_rect: Some(screen), ..Default::default() };
|
||||
input.viewports.entry(peer).or_default().parent = Some(egui::ViewportId::ROOT);
|
||||
crate::test_support::frame(&ctx, input, |ui| {
|
||||
assert_eq!(ui.ctx().viewport_id(), peer);
|
||||
assert_eq!(Container::host_window_regions(ui.ctx()), Some(Vec::new()), "another viewport cannot inherit root's exhausted ledger");
|
||||
Container::begin_host_windows(ui.ctx());
|
||||
Container::record_host_window(ui.ctx(), id, Some(moved));
|
||||
assert_eq!(Container::host_window_regions(ui.ctx()), Some(vec![moved]));
|
||||
});
|
||||
crate::test_support::frame(&ctx, egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| {
|
||||
Container::begin_host_windows(ui.ctx());
|
||||
assert_eq!(Container::host_window_regions(ui.ctx()), Some(Vec::new()), "root's next pass recovers without peer footprints");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn actual_feature_and_system_windows_publish_visible_paint_but_popups_and_modals_do_not() {
|
||||
for scale in [1.0, 2.0] {
|
||||
for background in [false, true] {
|
||||
let ctx = crate::fonts::test_context();
|
||||
ctx.set_pixels_per_point(scale);
|
||||
ctx.options_mut(|options| options.max_passes = 1.try_into().unwrap());
|
||||
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 800.0));
|
||||
for visible in [false, true, true] {
|
||||
crate::test_support::frame(&ctx, egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| {
|
||||
Container::begin_host_windows(ui.ctx());
|
||||
let id = egui::Id::unique("actual_feature_ledger_producer");
|
||||
let container = Container::new(ui.ctx(), Surface::Feature);
|
||||
let frame = Panel::feature_frame(ui.ctx(), crate::shell::LayoutMode::Floating, crate::frame::Side::Left);
|
||||
let stock = container
|
||||
.window("Persistent feature")
|
||||
.id(id)
|
||||
.title_bar(false)
|
||||
.collapsible(false)
|
||||
.resizable(false)
|
||||
.scroll(false)
|
||||
.fade_in(false)
|
||||
.fade_out(false)
|
||||
.frame(frame)
|
||||
.fixed_pos(egui::pos2(20.0, 20.0));
|
||||
let shown = container::FeatureWindow::new(stock, id, frame)
|
||||
.show_background(ui.ctx(), background.then_some(host_marker), |ui| {
|
||||
let visible = ui.is_visible() && !ui.is_sizing_pass();
|
||||
ui.disable();
|
||||
ui.set_min_size(egui::vec2(160.0, 90.0));
|
||||
let leaf = ui.button("Disabled content still paints");
|
||||
assert!(!leaf.enabled());
|
||||
visible
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(shown.inner, Some(visible));
|
||||
let feature = Container::host_window_regions(ui.ctx()).unwrap();
|
||||
assert_eq!(feature, if visible { vec![shown.response.rect] } else { Vec::new() });
|
||||
Window::new(egui::Id::unique("actual_system_ledger_producer"), "", "Persistent system window")
|
||||
.placed(egui::Align2::LEFT_TOP, egui::pos2(400.0, 20.0))
|
||||
.surface(ui.ctx(), false, |ui| {
|
||||
ui.disable();
|
||||
ui.label("Visible system content");
|
||||
(false, Action::None)
|
||||
});
|
||||
let windows = Container::host_window_regions(ui.ctx()).unwrap();
|
||||
assert_eq!(windows.len(), if visible { 2 } else { 0 });
|
||||
if visible {
|
||||
assert!(windows.contains(&shown.response.rect));
|
||||
assert!(windows.contains(&scenario::rect_of("dialog:window").unwrap()));
|
||||
}
|
||||
Container::new(ui.ctx(), Surface::Popup)
|
||||
.area(egui::Id::unique("transient_popup_not_a_fit_obstacle"))
|
||||
.fixed_pos(egui::pos2(600.0, 400.0))
|
||||
.show(ui.ctx(), |ui| {
|
||||
ui.label("Transient popup");
|
||||
});
|
||||
Container::new(ui.ctx(), Surface::Canvas)
|
||||
.area(egui::Id::unique("model_following_area_not_a_fit_obstacle"))
|
||||
.fixed_pos(egui::pos2(600.0, 500.0))
|
||||
.show(ui.ctx(), |ui| {
|
||||
ui.label("Model-following value box");
|
||||
});
|
||||
Window::new(egui::Id::unique("modal_system_wrapper_not_a_fit_obstacle"), "", "Modal system window").surface(
|
||||
ui.ctx(),
|
||||
true,
|
||||
|ui| {
|
||||
ui.label("Modal system content");
|
||||
(false, Action::None)
|
||||
},
|
||||
);
|
||||
Container::new(ui.ctx(), Surface::Window).modal(egui::Id::unique("modal_not_a_persistent_fit_obstacle")).show(ui.ctx(), |ui| {
|
||||
ui.label("Modal content");
|
||||
});
|
||||
assert_eq!(
|
||||
Container::host_window_regions(ui.ctx()),
|
||||
Some(windows),
|
||||
"popup, modal and model-following wrappers cannot register persistent windows"
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn universal_chrome_controls_have_real_accessible_widgets_and_stable_ids_at_both_scales() {
|
||||
use crate::panel_runtime::{HostControlTarget, HostPointerTarget, enable_host_specimen};
|
||||
for scale in [1.0, 2.0] {
|
||||
for preset in ["docks", "tabs", "collapsed", "overflow", "floating", "inline"] {
|
||||
let mut h = crate::scenario::Harness::new();
|
||||
h.app.home.open = false;
|
||||
h.ctx.set_pixels_per_point(scale);
|
||||
h.call("ui.resize", serde_json::json!({"width":800,"height":600}));
|
||||
enable_host_specimen(&mut h.app, preset).unwrap();
|
||||
h.frames(3);
|
||||
let before = h.app.universal_panel_frame().unwrap().controls.clone();
|
||||
assert!(!before.is_empty(), "actual chrome at scale {scale}: {preset}");
|
||||
let tree = h.output.accesskit_update.as_ref().expect("real egui accessibility update");
|
||||
let mut ids = std::collections::HashSet::new();
|
||||
for control in &before {
|
||||
assert!(ids.insert(control.id), "semantic IDs cannot collide: {control:?}");
|
||||
assert!(!control.accessible_name.is_empty());
|
||||
control.bounds.validate().unwrap();
|
||||
let interactive = !matches!(&control.target, HostControlTarget::Pointer(HostPointerTarget::Surface { .. }));
|
||||
if interactive && control.enabled {
|
||||
let node = tree
|
||||
.nodes
|
||||
.iter()
|
||||
.find(|(id, _)| *id == control.id.accesskit_id())
|
||||
.map(|(_, node)| node)
|
||||
.unwrap_or_else(|| panic!("exported control needs its own actual widget: {control:?}"));
|
||||
assert_eq!(node.label(), Some(control.accessible_name.as_str()), "actual widget/metadata name parity: {control:?}");
|
||||
assert!(matches!(node.role(), egui::accesskit::Role::Button | egui::accesskit::Role::SpinButton | egui::accesskit::Role::Slider));
|
||||
if matches!(&control.target, HostControlTarget::Pointer(HostPointerTarget::Menu { .. })) {
|
||||
assert_eq!(control.accessible_name, crate::i18n::tr("ui.panel_host.menu"));
|
||||
}
|
||||
}
|
||||
}
|
||||
h.frames(2);
|
||||
let after = &h.app.universal_panel_frame().unwrap().controls;
|
||||
for control in before {
|
||||
let retained = after.iter().find(|other| other.target == control.target).expect("same semantic target on the next frame");
|
||||
assert_eq!(retained.id, control.id, "status/service update cannot change widget identity");
|
||||
assert_eq!(retained.bounds, control.bounds);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn universal_host_slots_and_menu_button_stay_bounded_at_minimum_and_small_window_sizes() {
|
||||
use crate::panel_runtime::enable_host_specimen;
|
||||
for scale in [1.0, 2.0] {
|
||||
for (width, height) in [(1280, 800), (800, 600), (480, 320)] {
|
||||
let mut h = crate::scenario::Harness::new();
|
||||
h.app.home.open = false;
|
||||
h.ctx.set_pixels_per_point(scale);
|
||||
h.call("ui.resize", serde_json::json!({"width":width,"height":height}));
|
||||
enable_host_specimen(&mut h.app, "tabs").unwrap();
|
||||
h.frames(3);
|
||||
let host = &h.app.universal_panel_frame().unwrap().layout;
|
||||
host.resolved.validate().unwrap();
|
||||
for section in &host.sections {
|
||||
assert!(section.outer.contains_rect(section.header));
|
||||
assert!(section.header.contains_rect(section.menu));
|
||||
if let Some(body) = section.body {
|
||||
assert!(section.outer.contains_rect(body));
|
||||
assert!(body.origin.y >= section.header.origin.y + section.header.size.height);
|
||||
}
|
||||
assert_eq!(section.header.size.height, host.metrics.header_height);
|
||||
if let Some(strip) = section.tab_strip {
|
||||
assert_eq!(strip.origin.y, section.header.origin.y);
|
||||
assert_eq!(strip.size.height, section.header.size.height);
|
||||
assert!(section.header.contains_rect(strip));
|
||||
assert!(section.outer.contains_rect(strip));
|
||||
if let Some(body) = section.body {
|
||||
assert!(body.origin.y >= strip.origin.y + strip.size.height);
|
||||
}
|
||||
}
|
||||
if let Some(footer) = section.footer {
|
||||
assert!(section.outer.contains_rect(footer));
|
||||
if let Some(body) = section.body {
|
||||
assert_eq!(footer.origin.y, body.origin.y + body.size.height);
|
||||
}
|
||||
assert_eq!(footer.size.height, host.metrics.footer_height);
|
||||
}
|
||||
assert!(section.menu.size.width > 0.0 && section.menu.size.height > 0.0, "shared actions remain reachable when content fits");
|
||||
}
|
||||
for overflow in &host.overflow {
|
||||
assert!(!overflow.sections.is_empty());
|
||||
if let Some(bounds) = overflow.bounds {
|
||||
assert!(host.capacity.contains_rect(bounds));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn universal_kit_chrome_uses_one_container_and_preserves_parent_clipping_and_focus_semantics() {
|
||||
use crate::ui_kit::panel_host::{HostChrome, panel_host_control, panel_host_sash, panel_host_surface};
|
||||
let mut t = Tokens::get();
|
||||
let bevel = crate::theme::Bevel { width: 1.0, highlight: t.form_ink, light: t.control_border, shadow: t.form_dim, dark_shadow: t.border };
|
||||
t.borders.primary = Some(egui::Stroke::new(1.0, t.border));
|
||||
t.borders.bevel = Some(bevel);
|
||||
t.borders.primary_inset = Some(crate::theme::InsetBorder { stroke: egui::Stroke::new(0.75, t.form_error), gap: 3.0 });
|
||||
let _tokens = crate::theme::scoped_tokens(t);
|
||||
let ctx = crate::fonts::test_context();
|
||||
ctx.enable_accesskit();
|
||||
let bounds = egui::Rect::from_min_size(egui::pos2(20.0, 30.0), egui::vec2(160.0, 120.0));
|
||||
let clip = egui::Rect::from_min_max(bounds.min + egui::vec2(5.0, 5.0), bounds.max);
|
||||
let header = egui::Rect::from_min_size(bounds.min, egui::vec2(bounds.width(), 32.0));
|
||||
let sash = egui::Rect::from_min_size(egui::pos2(bounds.left(), bounds.bottom() - 4.0), egui::vec2(bounds.width(), 4.0));
|
||||
let mut calls = 0;
|
||||
let output = crate::test_support::frame(&ctx, egui::RawInput::default(), |ui| {
|
||||
ui.set_clip_rect(clip);
|
||||
panel_host_surface(ui, egui::Id::unique("synthetic-section"), bounds, false, |ui, content_clip| {
|
||||
calls += 1;
|
||||
assert_eq!(ui.clip_rect(), clip);
|
||||
assert!(clip.contains_rect(content_clip));
|
||||
let outer_frames = ui.stack().iter().filter(|node| node.frame().fill != egui::Color32::TRANSPARENT).count();
|
||||
assert!(outer_frames <= 1, "a section must not introduce nested outer frames");
|
||||
let title = panel_host_control(
|
||||
ui,
|
||||
egui::Id::unique("synthetic-header"),
|
||||
header,
|
||||
HostChrome {
|
||||
label: "Synthetic long localized panel title",
|
||||
icon: Some("list"),
|
||||
icon_only: false,
|
||||
attention: true,
|
||||
selected: false,
|
||||
enabled: true,
|
||||
drag: true,
|
||||
title: true,
|
||||
grip_only: false,
|
||||
rtl: false,
|
||||
},
|
||||
);
|
||||
let resize = panel_host_sash(ui, egui::Id::unique("synthetic-sash"), sash, "Resize synthetic neighbours");
|
||||
assert!(title.sense.is_focusable());
|
||||
assert!(resize.sense.is_focusable());
|
||||
assert_eq!(title.rect, header);
|
||||
assert_eq!(resize.rect, sash);
|
||||
});
|
||||
});
|
||||
assert!(calls >= 1);
|
||||
let tree = output.platform_output.accesskit_update.as_ref().unwrap();
|
||||
for label in ["Synthetic long localized panel title", "Resize synthetic neighbours"] {
|
||||
assert!(tree.nodes.iter().any(|(_, node)| node.label() == Some(label)), "actual focusable widget: {label}");
|
||||
}
|
||||
let (mut bevel_edges, mut inset_borders) = (0, 0);
|
||||
for shape in &output.shapes {
|
||||
assert!(clip.contains_rect(shape.clip_rect), "chrome paint must not escape its inherited clip");
|
||||
crate::test_support::each_shape(&shape.shape, &mut |paint| match paint {
|
||||
egui::Shape::LineSegment { stroke, .. }
|
||||
if stroke.width == bevel.width && [bevel.highlight, bevel.light, bevel.shadow, bevel.dark_shadow].contains(&stroke.color) =>
|
||||
{
|
||||
bevel_edges += 1;
|
||||
}
|
||||
egui::Shape::Rect(rect) if rect.stroke.color == t.form_error => {
|
||||
assert!(!clip.contains_rect(rect.rect), "the partial clip must actually trim the inset border");
|
||||
inset_borders += 1;
|
||||
}
|
||||
_ => {}
|
||||
});
|
||||
}
|
||||
assert!(bevel_edges > 0 && inset_borders > 0, "exercise both decorations under the inherited partial clip");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn universal_surface_uses_adaptive_workspace_fill_and_rounding_with_safe_content_clip() {
|
||||
use crate::shell::LayoutMode;
|
||||
let bounds = egui::Rect::from_min_size(egui::pos2(40.0, 40.0), egui::vec2(320.0, 180.0));
|
||||
for dark in [false, true] {
|
||||
let mut tokens = if dark { Tokens::dark() } else { Tokens::light() };
|
||||
tokens.panel = tokens.panel.gamma_multiply(0.8);
|
||||
let _tokens = crate::theme::scoped_tokens(tokens);
|
||||
for layout in [LayoutMode::Floating, LayoutMode::Docked] {
|
||||
for free_card in [false, true] {
|
||||
let ctx = crate::fonts::test_context();
|
||||
layout.publish(&ctx);
|
||||
let shared = if free_card { Container::floating_card(Surface::Panel) } else { Container::new(&ctx, Surface::Panel) };
|
||||
let expected = shared.frame(&ctx, tokens.panel, crate::frame::Side::Left);
|
||||
if free_card {
|
||||
// A new floating Area first measures invisibly, even with fade disabled.
|
||||
crate::test_support::frame(&ctx, egui::RawInput { time: Some(0.0), ..Default::default() }, |ui| {
|
||||
panel_host_surface(ui, egui::Id::unique("adaptive-surface"), bounds, free_card, |_, _| {});
|
||||
});
|
||||
}
|
||||
for time in [1.0, 2.0] {
|
||||
let output = crate::test_support::frame(&ctx, egui::RawInput { time: Some(time), ..Default::default() }, |ui| {
|
||||
panel_host_surface(ui, egui::Id::unique("adaptive-surface"), bounds, free_card, |ui, clip| {
|
||||
assert!(ui.is_visible() && !ui.is_sizing_pass(), "assert the first visible paint and its subsequent frame");
|
||||
assert!(bounds.contains_rect(clip));
|
||||
let stroke = expected.stroke.width;
|
||||
for (corner, center, radius) in [
|
||||
(clip.left_top(), bounds.left_top(), expected.corner_radius.nw),
|
||||
(clip.right_top(), bounds.right_top(), expected.corner_radius.ne),
|
||||
(clip.left_bottom(), bounds.left_bottom(), expected.corner_radius.sw),
|
||||
(clip.right_bottom(), bounds.right_bottom(), expected.corner_radius.se),
|
||||
] {
|
||||
let radius = f32::from(radius);
|
||||
let inward = egui::vec2(
|
||||
if center.x == bounds.left() { radius } else { -radius },
|
||||
if center.y == bounds.top() { radius } else { -radius },
|
||||
);
|
||||
if radius > stroke {
|
||||
assert!(corner.distance(center + inward) <= radius - stroke + 0.001);
|
||||
}
|
||||
}
|
||||
// A controller may paint an oversized rectangular body;
|
||||
// its inherited content clip must still protect corners.
|
||||
ui.painter().with_clip_rect(clip).rect_filled(bounds, 0, tokens.control_fill);
|
||||
});
|
||||
});
|
||||
let mut backgrounds = 0;
|
||||
for shape in &output.shapes {
|
||||
crate::test_support::each_shape(&shape.shape, &mut |shape| {
|
||||
if let egui::Shape::Rect(rect) = shape
|
||||
&& rect.rect == bounds
|
||||
&& rect.stroke == expected.stroke
|
||||
{
|
||||
assert_eq!(rect.fill, expected.fill, "shared frame alpha is stable from the first visible paint");
|
||||
assert_eq!(rect.corner_radius, expected.corner_radius);
|
||||
assert!(rect.fill.a() < 255, "the host must retain the shared frame's alpha");
|
||||
backgrounds += 1;
|
||||
}
|
||||
});
|
||||
}
|
||||
assert!(backgrounds > 0, "actual bounded background must use the shared frame");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn universal_header_reuses_title_font_and_six_dot_grip_without_idle_control_tiles() {
|
||||
let t = Tokens::get();
|
||||
let title = egui::Rect::from_min_size(egui::pos2(30.0, 30.0), egui::vec2(300.0, t.form_header_height));
|
||||
let tab = title.translate(egui::vec2(0.0, title.height()));
|
||||
let group = tab.translate(egui::vec2(0.0, tab.height()));
|
||||
for rtl in [false, true] {
|
||||
let ctx = crate::fonts::test_context();
|
||||
let output = crate::test_support::frame(&ctx, egui::RawInput::default(), |ui| {
|
||||
for (bounds, is_title, label) in [(title, true, "Shared title"), (tab, false, "Shared tab")] {
|
||||
let response = panel_host_control(
|
||||
ui,
|
||||
egui::Id::unique(label),
|
||||
bounds,
|
||||
HostChrome {
|
||||
label,
|
||||
icon: None,
|
||||
icon_only: false,
|
||||
attention: false,
|
||||
selected: false,
|
||||
enabled: true,
|
||||
drag: true,
|
||||
title: is_title,
|
||||
grip_only: false,
|
||||
rtl,
|
||||
},
|
||||
);
|
||||
assert_eq!(response.rect, bounds, "paint insets must preserve the exact target");
|
||||
assert!(response.sense.is_focusable());
|
||||
}
|
||||
let grip = egui::Rect::from_center_size(
|
||||
egui::pos2(if rtl { group.right() - t.space_10 } else { group.left() + t.space_10 }, group.center().y),
|
||||
egui::vec2(t.space_10 + t.space_8, group.height()),
|
||||
);
|
||||
let response = panel_host_control(
|
||||
ui,
|
||||
egui::Id::unique("group-grip"),
|
||||
grip,
|
||||
HostChrome {
|
||||
label: "Accessible active panel",
|
||||
icon: None,
|
||||
icon_only: false,
|
||||
attention: false,
|
||||
selected: false,
|
||||
enabled: true,
|
||||
drag: true,
|
||||
title: true,
|
||||
grip_only: true,
|
||||
rtl,
|
||||
},
|
||||
);
|
||||
assert_eq!(response.rect, grip);
|
||||
assert!(response.sense.is_focusable());
|
||||
});
|
||||
let (mut titles, mut tabs, mut dots, mut group_dots) = (0, 0, 0, 0);
|
||||
for clipped in &output.shapes {
|
||||
crate::test_support::each_shape(&clipped.shape, &mut |shape| match shape {
|
||||
egui::Shape::Text(text) if text.galley.job.text == "Shared title" => {
|
||||
assert_eq!(text.galley.job.sections.first().unwrap().format.font_id, crate::fonts::semibold(t.font_heading));
|
||||
titles += 1;
|
||||
}
|
||||
egui::Shape::Text(text) if text.galley.job.text == "Shared tab" => {
|
||||
assert_eq!(text.galley.job.sections.first().unwrap().format.font_id, egui::FontId::proportional(t.font_label));
|
||||
tabs += 1;
|
||||
}
|
||||
egui::Shape::Text(text) => {
|
||||
assert_ne!(text.galley.job.text, "Accessible active panel", "grip accessibility name is not a duplicate painted title")
|
||||
}
|
||||
egui::Shape::Circle(dot) if title.contains(dot.center) && dot.fill == t.text_dim => {
|
||||
assert_eq!(dot.center.x > title.center().x, rtl, "grip follows the leading edge");
|
||||
dots += 1;
|
||||
}
|
||||
egui::Shape::Circle(dot) if group.contains(dot.center) && dot.fill == t.text_dim => {
|
||||
group_dots += 1;
|
||||
}
|
||||
egui::Shape::Rect(rect) => assert_ne!(rect.fill, t.panel_header, "idle controls share the outer background"),
|
||||
_ => {}
|
||||
});
|
||||
}
|
||||
assert_eq!((titles, tabs, dots, group_dots), (1, 1, 6, 6));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn universal_drag_source_changes_only_label_ink_and_keeps_existing_fonts() {
|
||||
let t = Tokens::get();
|
||||
for (title, selected, attention, enabled) in
|
||||
[(true, false, false, true), (false, true, true, true), (false, false, false, true), (false, false, false, false)]
|
||||
{
|
||||
let ctx = crate::fonts::test_context();
|
||||
let bounds = egui::Rect::from_min_size(egui::pos2(30.0, 30.0), egui::vec2(300.0, t.form_header_height));
|
||||
let other = bounds.translate(egui::vec2(0.0, bounds.height()));
|
||||
let ink = if !enabled {
|
||||
t.form_dim
|
||||
} else if attention {
|
||||
t.form_primary
|
||||
} else {
|
||||
t.form_ink
|
||||
};
|
||||
let font = if title {
|
||||
crate::fonts::semibold(t.font_heading)
|
||||
} else if selected {
|
||||
crate::fonts::semibold(t.font_label)
|
||||
} else {
|
||||
egui::FontId::proportional(t.font_label)
|
||||
};
|
||||
let output = crate::test_support::frame(&ctx, egui::RawInput::default(), |ui| {
|
||||
for (rect, label, opacity) in [(bounds, "Moved title", 0.5), (other, "Other title", 1.0)] {
|
||||
let response = panel_host_control_label_opacity(
|
||||
ui,
|
||||
egui::Id::unique(label),
|
||||
rect,
|
||||
HostChrome { label, icon: None, icon_only: false, attention, selected, enabled, drag: true, title, grip_only: false, rtl: false },
|
||||
opacity,
|
||||
);
|
||||
assert_eq!(response.rect, rect);
|
||||
assert_eq!(response.sense, if enabled { egui::Sense::click_and_drag() } else { egui::Sense::hover() });
|
||||
}
|
||||
});
|
||||
let (mut moved, mut others, mut dots) = (0, 0, 0);
|
||||
for clipped in &output.shapes {
|
||||
crate::test_support::each_shape(&clipped.shape, &mut |shape| match shape {
|
||||
egui::Shape::Text(text) if matches!(text.galley.job.text.as_str(), "Moved title" | "Other title") => {
|
||||
let dim = text.galley.job.text == "Moved title";
|
||||
for section in &text.galley.job.sections {
|
||||
assert_eq!(section.format.color, ink.gamma_multiply(if dim { 0.5 } else { 1.0 }));
|
||||
assert_eq!(section.format.font_id, font);
|
||||
}
|
||||
if dim {
|
||||
moved += 1;
|
||||
} else {
|
||||
others += 1;
|
||||
}
|
||||
}
|
||||
egui::Shape::Circle(dot) if title && (bounds.contains(dot.center) || other.contains(dot.center)) => {
|
||||
assert_eq!(dot.fill, t.text_dim, "grip ink remains unchanged");
|
||||
dots += 1;
|
||||
}
|
||||
egui::Shape::Rect(rect) if selected && (rect.rect.intersects(bounds) || rect.rect.intersects(other)) => {
|
||||
assert_eq!(rect.fill, t.selected_bg, "selection fill remains unchanged");
|
||||
}
|
||||
_ => {}
|
||||
});
|
||||
}
|
||||
assert_eq!((moved, others, dots), (1, 1, if title { 12 } else { 0 }));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn universal_drag_badge_keeps_display_order_on_one_line_and_clamps_without_allocating_input_or_layout() {
|
||||
let t = Tokens::get();
|
||||
let domain = egui::Rect::from_min_max(egui::pos2(20.0, 30.0), egui::pos2(440.0, 330.0));
|
||||
let logical = "אחד שניים שלושה ארבעה חמישה שישה שבעה שמונה תשעה עשרה אחרון";
|
||||
let hebrew = crate::bidi::visual(logical).into_owned();
|
||||
assert_ne!(hebrew, logical, "exercise an already display-ordered eleven-word Hebrew title");
|
||||
let narrow = egui::Rect::from_min_size(domain.min, egui::vec2(180.0, 600.0));
|
||||
for (scale, rtl) in [(1.0, false), (2.0, true)] {
|
||||
let ctx = crate::fonts::test_context();
|
||||
ctx.set_pixels_per_point(scale);
|
||||
for (title, domain) in
|
||||
[("Full title".to_owned(), domain), ("Full current presentation title without ellipsis ".repeat(5), domain), (hebrew.clone(), narrow)]
|
||||
{
|
||||
let clip = domain.shrink(20.0);
|
||||
for at in [
|
||||
clip.center(),
|
||||
clip.left_top() + egui::vec2(1.0, 1.0),
|
||||
clip.right_bottom() - egui::vec2(1.0, 1.0),
|
||||
egui::pos2(-20.0, -20.0),
|
||||
egui::pos2(f32::NAN, 100.0),
|
||||
] {
|
||||
let visible = at.is_finite() && clip.contains(at);
|
||||
let mut layer = None;
|
||||
let output = crate::test_support::frame(&ctx, egui::RawInput::default(), |ui| {
|
||||
ui.set_clip_rect(clip);
|
||||
layer = Some(egui::LayerId::new(egui::Order::Tooltip, ui.scope_id().with("panel_preview")));
|
||||
let before = ui.min_rect();
|
||||
panel_host_drag_title(ui, &title, at, domain, rtl);
|
||||
assert_eq!(ui.min_rect(), before, "paint-only feedback allocates no layout");
|
||||
});
|
||||
let (mut labels, mut backgrounds) = (0, 0);
|
||||
for clipped in &output.shapes {
|
||||
crate::test_support::each_shape(&clipped.shape, &mut |shape| match shape {
|
||||
egui::Shape::Text(text) if text.galley.job.text == title => {
|
||||
assert!(clip.contains_rect(clipped.clip_rect));
|
||||
let text_bounds = egui::Rect::from_min_size(text.pos, text.galley.size());
|
||||
assert!(text_bounds.intersects(clipped.clip_rect));
|
||||
let padding = t.space_8.min(clip.width() / 4.0);
|
||||
let aligned = if rtl {
|
||||
text_bounds.right() - (clipped.clip_rect.right() - padding)
|
||||
} else {
|
||||
text_bounds.left() - (clipped.clip_rect.left() + padding)
|
||||
};
|
||||
assert!(aligned.abs() < 0.01, "keep the reading start visible when the full galley exceeds its clip");
|
||||
assert!(
|
||||
text.galley.job.sections.iter().all(|section| section.format.color == t.form_ink
|
||||
&& section.format.font_id == egui::FontId::proportional(t.font_label))
|
||||
);
|
||||
assert_eq!(text.galley.rows.len(), 1, "never reflow already display-ordered words");
|
||||
if title == hebrew {
|
||||
assert_eq!(text.galley.job.text, hebrew, "preserve display order without a second bidi pass");
|
||||
assert!(text_bounds.width() > clipped.clip_rect.width(), "the narrow Hebrew case must exercise clipping");
|
||||
if rtl {
|
||||
assert!(text_bounds.left() < clipped.clip_rect.left());
|
||||
}
|
||||
}
|
||||
labels += 1;
|
||||
}
|
||||
egui::Shape::Rect(rect) if rect.fill == t.dialog_body.to_opaque() && rect.corner_radius == t.radius_sm.into() => {
|
||||
assert!(clip.contains_rect(rect.rect));
|
||||
assert_ne!(ctx.layer_id_at(rect.rect.center()), layer, "no tooltip Area or input shield");
|
||||
if title == "Full title" && at == clip.center() {
|
||||
assert_eq!(rect.rect.center().x < at.x, rtl, "cursor offset mirrors with direction");
|
||||
}
|
||||
backgrounds += 1;
|
||||
}
|
||||
_ => {}
|
||||
});
|
||||
}
|
||||
assert_eq!((labels, backgrounds), if visible { (1, 1) } else { (0, 0) });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn universal_collapsed_header_keeps_actions_and_one_click_restores_the_same_controller() {
|
||||
use crate::panel_runtime::{HostControlTarget, HostPointerTarget, enable_host_specimen, inspect_host_specimen};
|
||||
let mut h = crate::scenario::Harness::new();
|
||||
h.app.home.open = false;
|
||||
h.call("ui.resize", serde_json::json!({"width":1400,"height":900}));
|
||||
enable_host_specimen(&mut h.app, "collapsed").unwrap();
|
||||
h.frames(3);
|
||||
let before = inspect_host_specimen(&mut h.app).unwrap();
|
||||
let frame = h.app.universal_panel_frame().unwrap();
|
||||
assert!(frame.layout.sections.iter().all(|section| section.collapsed && section.body.is_none() && section.footer.is_none()));
|
||||
assert!(frame.controls.iter().any(|control| matches!(&control.target,
|
||||
HostControlTarget::Pointer(HostPointerTarget::HeaderAction { instance, action }) if instance.0 == "specimen-0" && action.0 == "apply")
|
||||
&& control.enabled));
|
||||
assert!(frame.controls.iter().any(|control| matches!(&control.target,
|
||||
HostControlTarget::Pointer(HostPointerTarget::Close { instance }) if instance.0 == "specimen-0")));
|
||||
assert!(!frame.controls.iter().any(|control| matches!(&control.target,
|
||||
HostControlTarget::Pointer(HostPointerTarget::Close { instance }) if instance.0 == "specimen-1")));
|
||||
let expand = frame
|
||||
.controls
|
||||
.iter()
|
||||
.find(|control| {
|
||||
matches!(&control.target,
|
||||
HostControlTarget::Pointer(HostPointerTarget::Collapse { instance }) if instance.0 == "specimen-0")
|
||||
})
|
||||
.unwrap();
|
||||
let at = crate::panel_runtime::egui_rect(expand.bounds).center();
|
||||
h.call("ui.click", serde_json::json!({"x":at.x,"y":at.y}));
|
||||
h.frames(2);
|
||||
let restored = h.app.universal_panel_frame().unwrap().layout.sections.iter().find(|section| section.instance.0 == "specimen-0").unwrap();
|
||||
assert!(!restored.collapsed);
|
||||
assert!(restored.body.is_some());
|
||||
let after = inspect_host_specimen(&mut h.app).unwrap();
|
||||
let controller = |value: &serde_json::Value| {
|
||||
value["runtime"]["probe"]["controllers"].as_array().unwrap().iter().find(|state| state["instance"] == "specimen-0").unwrap().clone()
|
||||
};
|
||||
let old = controller(&before);
|
||||
let new = controller(&after);
|
||||
assert_eq!(old["renders"], 0);
|
||||
assert!(new["renders"].as_u64().unwrap() > 0);
|
||||
assert_eq!(old["controller_identity"], new["controller_identity"]);
|
||||
assert_eq!(old["cancels"], new["cancels"]);
|
||||
assert_eq!(old["draft"], new["draft"]);
|
||||
assert_eq!(before["session"]["camera"], after["session"]["camera"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn universal_sole_content_gap_is_navigable_while_declared_fill_uses_the_column() {
|
||||
use crate::panel_runtime::{enable_host_specimen, logical_rect};
|
||||
let mut h = crate::scenario::Harness::new();
|
||||
h.app.home.open = false;
|
||||
h.call("ui.resize", serde_json::json!({"width":1400,"height":900}));
|
||||
enable_host_specimen(&mut h.app, "content_fill").unwrap();
|
||||
h.frames(3);
|
||||
let frame = h.app.universal_panel_frame().unwrap();
|
||||
let content = frame.layout.sections.iter().find(|section| section.instance.0 == "specimen-0").unwrap();
|
||||
let fill = frame.layout.sections.iter().find(|section| section.instance.0 == "specimen-1").unwrap();
|
||||
assert!(fill.outer.size.height > content.outer.size.height);
|
||||
let outer = crate::panel_runtime::egui_rect(content.outer);
|
||||
let gap = egui::Rect::from_center_size(egui::pos2(outer.center().x, outer.bottom() + 20.0), egui::vec2(4.0, 4.0));
|
||||
assert!(frame.layout.usable.contains_rect(logical_rect(gap)));
|
||||
assert!(!frame.layout.consumes_pointer(solidcraft_engine::panels::Point { x: gap.center().x, y: gap.center().y }));
|
||||
assert!(frame.layout.resolved.rails.is_empty() && frame.layout.overflow.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn universal_inline_specimen_uses_one_total_row_with_real_content_and_shared_controls() {
|
||||
use crate::panel_runtime::{HostControlTarget, HostPointerTarget, enable_host_specimen};
|
||||
let mut h = crate::scenario::Harness::new();
|
||||
h.app.home.open = false;
|
||||
h.call("ui.resize", serde_json::json!({"width":1400,"height":900}));
|
||||
enable_host_specimen(&mut h.app, "inline").unwrap();
|
||||
h.frames(3);
|
||||
let frame = h.app.universal_panel_frame().unwrap();
|
||||
let section = frame.layout.sections.first().unwrap();
|
||||
assert!(section.inline && !section.collapsed);
|
||||
assert_eq!(section.header, section.outer);
|
||||
assert!(section.outer.size.height <= crate::theme::PANEL_INLINE_MAX_HEIGHT);
|
||||
assert!(section.body.is_none() && section.footer.is_none());
|
||||
assert!(!frame.controls.iter().any(|control| matches!(control.target, HostControlTarget::Pointer(HostPointerTarget::HeaderAction { .. }))));
|
||||
let runtime = h.app.panel_runtime().unwrap();
|
||||
let instance = runtime.layout().layout().instance(§ion.instance).unwrap();
|
||||
assert!(runtime.layout().registry().get(&instance.kind).unwrap().header_actions.is_empty(), "the inline log declares no custom or debug actions");
|
||||
assert!(frame.controls.iter().any(|control| matches!(control.target, HostControlTarget::Pointer(HostPointerTarget::Menu { .. }))));
|
||||
assert!(frame.controls.iter().any(|control| matches!(control.target, HostControlTarget::Pointer(HostPointerTarget::Collapse { .. }))));
|
||||
assert!(h.widget(crate::i18n::tr("ui.panel_fixture.inline")).is_some());
|
||||
assert!(h.widget(crate::i18n::tr("ui.panel_fixture.caption")).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn universal_registered_header_command_invokes_only_the_declared_synthetic_binding() {
|
||||
use crate::panel_runtime::{enable_host_specimen, inspect_host_specimen};
|
||||
let mut h = crate::scenario::Harness::new();
|
||||
h.app.home.open = false;
|
||||
h.call("ui.resize", serde_json::json!({"width":1400,"height":900}));
|
||||
enable_host_specimen(&mut h.app, "collapsed").unwrap();
|
||||
h.frames(3);
|
||||
let before = inspect_host_specimen(&mut h.app).unwrap();
|
||||
h.app.run_panel_command("panel.action", &serde_json::json!({"target":{"type":"instance","id":"specimen-0"},"action":"apply"})).unwrap();
|
||||
let after = inspect_host_specimen(&mut h.app).unwrap();
|
||||
let applies = |value: &serde_json::Value| {
|
||||
value["runtime"]["probe"]["controllers"].as_array().unwrap().iter().find(|state| state["instance"] == "specimen-0").unwrap()["applies"]
|
||||
.as_u64()
|
||||
.unwrap()
|
||||
};
|
||||
assert_eq!(applies(&after), applies(&before) + 1);
|
||||
assert_eq!(after["runtime"]["probe"]["content_command_calls"], before["runtime"]["probe"]["content_command_calls"].as_u64().unwrap() + 1);
|
||||
assert_eq!(before["session"], after["session"]);
|
||||
let rejected = h.app.run_panel_command("panel.action", &serde_json::json!({"target":{"type":"instance","id":"specimen-1"},"action":"apply"}));
|
||||
assert_eq!(rejected.unwrap_err().rule, solidcraft_engine::panels::Rule::Capability);
|
||||
let undeclared = h.app.run_panel_command("panel.action", &serde_json::json!({"target":{"type":"instance","id":"specimen-0"},"action":"cancel"}));
|
||||
assert_eq!(undeclared.unwrap_err().rule, solidcraft_engine::panels::Rule::Capability, "a content action is not automatically a header action");
|
||||
let refused = inspect_host_specimen(&mut h.app).unwrap();
|
||||
assert_eq!(applies(&after), applies(&refused));
|
||||
assert_eq!(after["runtime"]["probe"]["content_command_calls"], refused["runtime"]["probe"]["content_command_calls"]);
|
||||
let editor = |value: &serde_json::Value| {
|
||||
value["runtime"]["probe"]["controllers"].as_array().unwrap().iter().find(|state| state["instance"] == "specimen-0").unwrap().clone()
|
||||
};
|
||||
assert_eq!(editor(&after)["cancels"], editor(&refused)["cancels"]);
|
||||
assert_eq!(editor(&after)["transaction_live"], editor(&refused)["transaction_live"]);
|
||||
assert_eq!(before["session"], refused["session"]);
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum BlurHost {
|
||||
Frame,
|
||||
@@ -146,9 +1067,11 @@ fn blur_stock_window_open_flag_preserves_closed_close_and_reopen_behavior() {
|
||||
let id = egui::Id::unique("open flag fixture");
|
||||
let mut recorded = Vec::new();
|
||||
for (index, mut keep) in [false, false, true, true, true, false, false, false, true, true, true].into_iter().enumerate() {
|
||||
let initially_open = keep;
|
||||
let mut observation = String::new();
|
||||
let mut called = false;
|
||||
let output = crate::test_support::frame(&ctx, egui::RawInput { time: Some(index as f64), ..Default::default() }, |_| {
|
||||
Container::begin_host_windows(&ctx);
|
||||
let window = container
|
||||
.window("Open flag fixture")
|
||||
.id(id)
|
||||
@@ -169,22 +1092,25 @@ fn blur_stock_window_open_flag_preserves_closed_close_and_reopen_behavior() {
|
||||
}
|
||||
};
|
||||
let shown = if mode == 0 {
|
||||
window.open(&mut keep).show(&ctx, &mut body)
|
||||
// Compare open windows with stock geometry and close handling;
|
||||
// explicitly closed features skip stock's animated showing.
|
||||
if initially_open { window.open(&mut keep).show(&ctx, &mut body) } else { None }
|
||||
} else {
|
||||
// A long-lived builder must accept this frame-local mutable borrow.
|
||||
let window: container::FeatureWindow<'static> = container::FeatureWindow::new(window, id, frame);
|
||||
let window = window.open(&mut keep);
|
||||
if mode == 1 { window.show(&ctx, &mut body) } else { window.show_background(&ctx, Some(host_marker), &mut body) }
|
||||
};
|
||||
if index == 0 || index == 7 {
|
||||
assert!(shown.is_none(), "initially closed and settled closed windows stay hidden");
|
||||
if !initially_open {
|
||||
assert!(shown.is_none(), "initially closed and newly closed windows stay hidden immediately");
|
||||
assert_eq!(Container::host_window_regions(&ctx), Some(Vec::new()), "closed windows publish no geometry");
|
||||
}
|
||||
if index == 4 {
|
||||
assert!(shown.as_ref().is_some_and(|shown| shown.response.should_close()), "the Window response carries the close request");
|
||||
}
|
||||
observation = format!("{:?}", (keep, shown.map(|shown| (shown.response.id, shown.response.rect, shown.inner))));
|
||||
});
|
||||
if index == 0 || index == 7 {
|
||||
if !initially_open {
|
||||
assert!(!called);
|
||||
}
|
||||
if index == 4 {
|
||||
@@ -211,8 +1137,8 @@ fn blur_stock_window_open_flag_preserves_closed_close_and_reopen_behavior() {
|
||||
}
|
||||
recorded
|
||||
}
|
||||
assert_eq!(record(0, false), record(1, false), "zero keeps stock shapes, including Noop counts and hidden windows");
|
||||
assert_eq!(record(0, true), record(2, true), "positive markers preserve stock visibility, close handling, geometry and IDs");
|
||||
assert_eq!(record(0, false), record(1, false), "zero keeps open stock shapes and Noop counts, with immediate closed visibility");
|
||||
assert_eq!(record(0, true), record(2, true), "positive markers preserve close handling, geometry and IDs, with immediate closed visibility");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -566,15 +566,18 @@ fn settings_section_count_spaced<R>(
|
||||
pub(crate) fn settings_card<R>(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> egui::InnerResponse<R> {
|
||||
let t = Tokens::get();
|
||||
let container = super::Container::new(ui.ctx(), super::Surface::Navigation);
|
||||
let frame = container
|
||||
.frame(ui.ctx(), t.dialog_footer, crate::frame::Side::Left)
|
||||
.inner_margin(egui::Margin::symmetric(t.space_12 as i8, t.space_10 as i8));
|
||||
let frame = settings_card_frame(ui).inner_margin(egui::Margin::symmetric(t.space_12 as i8, t.space_10 as i8));
|
||||
container.show_frame(ui, frame, ui.max_rect(), |ui| {
|
||||
ui.set_min_width(dimension(ui.available_width()));
|
||||
add(ui)
|
||||
})
|
||||
}
|
||||
|
||||
/// The theme browser and its options panel share exactly the same themed backing.
|
||||
pub(super) fn settings_card_frame(ui: &Ui) -> egui::Frame {
|
||||
super::Container::new(ui.ctx(), super::Surface::Navigation).frame(ui.ctx(), Tokens::get().dialog_footer, crate::frame::Side::Left)
|
||||
}
|
||||
|
||||
/// Controls and one explanatory specimen side by side, stacked on narrow viewports.
|
||||
pub(crate) fn settings_pair<R>(ui: &mut Ui, controls: impl FnOnce(&mut Ui) -> R, preview: impl FnOnce(&mut Ui, R)) {
|
||||
if crate::prefs_search::suppress_chrome(ui) {
|
||||
@@ -602,44 +605,6 @@ pub(crate) fn settings_pair<R>(ui: &mut Ui, controls: impl FnOnce(&mut Ui) -> R,
|
||||
}
|
||||
}
|
||||
|
||||
/// Dashed import tile, bounded by its carousel cell.
|
||||
pub(crate) fn theme_import_tile(ui: &mut Ui, label: &str, note: &str) -> Response {
|
||||
if crate::prefs_search::suppress_chrome(ui) && !crate::prefs_search::texts_hit(ui, &[label, note]) {
|
||||
return crate::prefs_search::hidden_response(ui);
|
||||
}
|
||||
let t = Tokens::get();
|
||||
let width = t.space_24 * 3.0 + t.space_16;
|
||||
let height = t.space_24 * 4.0;
|
||||
let (r, response) = ui.allocate_exact_size(vec2(width.min(dimension(ui.available_width())), height), Sense::click());
|
||||
if response.hovered() {
|
||||
ui.painter().rect_filled(r, t.radius_lg, t.hover);
|
||||
}
|
||||
let mut outline = rounded_perimeter(r.shrink(t.space_2 / 2.0), f32::from(t.radius_lg));
|
||||
if let Some(first) = outline.first().copied() {
|
||||
outline.push(first);
|
||||
}
|
||||
ui.painter().extend(egui::Shape::dashed_line(&outline, Stroke::new(t.space_3 / 2.0, t.control_border), t.space_3, t.space_3));
|
||||
let icon = Rect::from_center_size(pos2(r.center().x, r.top() + t.space_16), vec2(t.space_16, t.space_16));
|
||||
crate::icons::paint_ink(ui.painter(), icon, "import_tray", t.form_dim);
|
||||
centred_text(
|
||||
ui.painter(),
|
||||
Rect::from_min_size(pos2(r.left(), r.top() + t.space_24 + t.space_4), vec2(r.width(), t.space_16)),
|
||||
label,
|
||||
FontId::proportional(t.font_label),
|
||||
t.form_dim,
|
||||
);
|
||||
centred_text(
|
||||
ui.painter(),
|
||||
Rect::from_min_size(pos2(r.left(), r.top() + t.space_24 + t.space_4 + t.space_16), vec2(r.width(), t.space_16)),
|
||||
note,
|
||||
FontId::proportional(t.font_small),
|
||||
t.form_dim,
|
||||
);
|
||||
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), label));
|
||||
scenario::publish_target(&format!("dialog:{label}"), r);
|
||||
response.on_hover_cursor(egui::CursorIcon::PointingHand)
|
||||
}
|
||||
|
||||
/// Compact informational state badge for settings; never an interactive control.
|
||||
pub(crate) fn settings_badge(ui: &mut Ui, text: &str, warning: bool) {
|
||||
if crate::prefs_search::suppress_chrome(ui) && !crate::prefs_search::texts_hit(ui, &[text]) {
|
||||
|
||||
@@ -392,79 +392,6 @@ pub(crate) fn help_icon(ui: &mut Ui, text: &str) -> Response {
|
||||
response.backing_on_hover_text(text)
|
||||
}
|
||||
|
||||
/// Which items of a carousel are shown: the first one and how many fit between the two arrows.
|
||||
pub(super) fn carousel_window(count: usize, offset: usize, available: f32, item_width: f32, gap: f32, arrow: f32) -> (usize, usize) {
|
||||
if count == 0 {
|
||||
return (0, 0);
|
||||
}
|
||||
let room = dimension(available) - 2.0 * (arrow + gap);
|
||||
let unit = dimension(item_width).max(1.0) + gap.max(0.0);
|
||||
let visible = (((room + gap) / unit).floor() as usize).clamp(1, count);
|
||||
(offset.min(count - visible), visible)
|
||||
}
|
||||
|
||||
/// A row of items with a previous and a next arrow; an arrow is dimmed and inert at its end.
|
||||
/// An arrow moves by the items that fit (#11434); the last page ends on the last item.
|
||||
/// `item` paints the item at an index into a column `item_width` wide and `item_height` high.
|
||||
pub(crate) fn carousel(
|
||||
ui: &mut Ui,
|
||||
id: impl std::hash::Hash + std::fmt::Debug,
|
||||
count: usize,
|
||||
item_width: f32,
|
||||
item_height: f32,
|
||||
mut item: impl FnMut(&mut Ui, usize),
|
||||
) -> (usize, usize) {
|
||||
let t = Tokens::get();
|
||||
let key = ui.make_persistent_id(id);
|
||||
let gap = t.space_8;
|
||||
let arrow = t.space_24 + 2.0;
|
||||
let offset = ui.data(|d| d.get_temp::<usize>(key)).unwrap_or(0);
|
||||
let (first, visible) = carousel_window(count, offset, ui.available_width(), item_width, gap, arrow);
|
||||
let height = dimension(item_height);
|
||||
let mut next_offset = first;
|
||||
ui.horizontal_top(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = gap;
|
||||
let can_back = first > 0;
|
||||
if carousel_arrow(ui, vec2(arrow, height), -1.0, can_back, crate::i18n::tr("prefs.carousel_previous")).clicked() {
|
||||
next_offset = first.saturating_sub(visible);
|
||||
}
|
||||
for index in first..first + visible {
|
||||
ui.allocate_ui_with_layout(vec2(dimension(item_width), height), egui::Layout::top_down(egui::Align::Min), |ui| {
|
||||
ui.set_width(dimension(item_width));
|
||||
item(ui, index);
|
||||
});
|
||||
}
|
||||
let can_forward = first + visible < count;
|
||||
if carousel_arrow(ui, vec2(arrow, height), 1.0, can_forward, crate::i18n::tr("prefs.carousel_next")).clicked() {
|
||||
next_offset = (first + visible).min(count.saturating_sub(visible));
|
||||
}
|
||||
});
|
||||
ui.data_mut(|d| d.insert_temp(key, next_offset));
|
||||
(first, visible)
|
||||
}
|
||||
|
||||
fn carousel_arrow(ui: &mut Ui, size: egui::Vec2, direction: f32, enabled: bool, label: &str) -> Response {
|
||||
let t = Tokens::get();
|
||||
let (rect, response) = ui.allocate_exact_size(size, if enabled { Sense::click() } else { Sense::hover() });
|
||||
let alpha = if enabled { 1.0 } else { 0.35 };
|
||||
let p = ui.painter();
|
||||
let fill = if enabled && response.hovered() { t.hover } else { t.control_fill };
|
||||
p.rect(rect, f32::from(t.radius_lg), fill.gamma_multiply(alpha), Stroke::new(1.0, t.dialog_border.gamma_multiply(alpha)), StrokeKind::Inside);
|
||||
let icon = Rect::from_center_size(rect.center(), vec2(t.space_16, t.space_16));
|
||||
let ink = t.form_ink.gamma_multiply(alpha);
|
||||
if direction < 0.0 {
|
||||
crate::icons::paint_ink_mirrored(p, icon, "chevron_right", ink);
|
||||
} else {
|
||||
crate::icons::paint_ink(p, icon, "chevron_right", ink);
|
||||
}
|
||||
if enabled && response.has_focus() {
|
||||
p.rect_stroke(rect.expand(t.space_2), f32::from(t.radius_lg) + t.space_2, Stroke::new(t.space_2, t.form_primary), StrokeKind::Outside);
|
||||
}
|
||||
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, label));
|
||||
scenario::publish_target(&format!("prefs:carousel:{label}"), rect);
|
||||
if enabled { response.on_hover_cursor(egui::CursorIcon::PointingHand) } else { response }
|
||||
}
|
||||
|
||||
/// Installed add-on row: 12 pt padding, 36 pt mark and centred, unframed folder action.
|
||||
pub(crate) fn settings_plugin_card(
|
||||
ui: &mut Ui,
|
||||
|
||||
Loaded 100 of 132 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user