diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 58b10239d..c7cb555b0 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -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 diff --git a/apps/solidcraft-web/src/main.rs b/apps/solidcraft-web/src/main.rs index f55f0d447..4f8818ba8 100644 --- a/apps/solidcraft-web/src/main.rs +++ b/apps/solidcraft-web/src/main.rs @@ -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) { diff --git a/assets/locales/ar.json b/assets/locales/ar.json index f8ccab84f..1f259d7ee 100644 --- a/assets/locales/ar.json +++ b/assets/locales/ar.json @@ -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": "حدد قطعة قياسية مُدرجة (برغي أو صامولة أو حلقة مسطحة أو مسمار) لتغيير مقاسها. لتكبير جسم أو تصغيره، استخدم «تحجيم».", diff --git a/assets/locales/bg.json b/assets/locales/bg.json new file mode 100644 index 000000000..c9f098ea0 --- /dev/null +++ b/assets/locales/bg.json @@ -0,0 +1,3660 @@ +{ + "0 turns it off": "0 turns it off", + "1. Open GitHub draft below, then paste the report copied to your clipboard.": "1. Open GitHub draft below, then paste the report copied to your clipboard.", + "1. Open GitHub draft below. Your title and report will be filled in.": "1. Open GitHub draft below. Your title and report will be filled in.", + "2. Attach your screenshot: copy and paste it, or save and upload the PNG.": "2. Attach your screenshot: copy and paste it, or save and upload the PNG.", + "2D": "2D", + "3. Click Submit new issue on GitHub to send your report.": "3. Click Submit new issue on GitHub to send your report.", + "A Single hole snaps to the middle of its face and to the centres of its round edges": "A Single hole snaps to the middle of its face and to the centres of its round edges", + "A new configuration, a copy of the active one": "A new configuration, a copy of the active one", + "A placed Single hole has a handle to drag it, and picking its face again moves the hole there instead of taking it out": "A placed Single hole has a handle to drag it, and picking its face again moves the hole there instead of taking it out", + "A short title for the problem (optional)": "A short title for the problem (optional)", + "ARRANGE": "ARRANGE", + "About SolidCraft": "Относно SolidCraft", + "Acceleration": "Acceleration", + "Access": "Access", + "Actions": "Actions", + "Active": "Active", + "Active rule": "Active rule", + "Add": "Добави", + "Add Column": "Добави колона", + "Add Key": "Add Key", + "Add Mid Radius": "Add Mid Radius", + "Add Row": "Add Row", + "Add a tool": "Add a tool", + "Add all bodies": "Add all bodies", + "Add bend": "Add bend", + "Add condition": "Add condition", + "Add or edit rule": "Add or edit rule", + "Add to New Folder": "Add to New Folder", + "Add visible bodies": "Add visible bodies", + "Advanced": "Advanced", + "Against": "Against", + "Alignment": "Alignment", + "All Lines": "All Lines", + "All Sketch Points": "All Sketch Points", + "All components": "All components", + "All open designs": "All open designs", + "Allowed expressions, separated by semicolons": "Allowed expressions, separated by semicolons", + "Also deletes": "Also deletes", + "Anchor": "Anchor", + "Angle 2": "Angle 2", + "Angle Display": "Angle Display", + "Animate": "Animate", + "Another bend on the far edge of the last flange": "Another bend on the far edge of the last flange", + "App/system information and command settings are included. Review private details before sharing.": "App/system information and command settings are included. Review private details before sharing.", + "Appearance name": "Appearance name", + "Applied Radius": "Applied Radius", + "Apply To": "Apply To", + "Apply library appearance": "Apply library appearance", + "Apply to selection": "Apply to selection", + "Apply your appearance first. Exports assigned appearances and materials created in this design.": "Apply your appearance first. Exports assigned appearances and materials created in this design.", + "Arc length": "Arc length", + "Area": "Площ", + "As-Built": "As-Built", + "Assign Rule": "Assign Rule", + "Attachment": "Attachment", + "BLEND SURFACE": "BLEND SURFACE", + "BOUNDARY SURFACE": "BOUNDARY SURFACE", + "BROWSER": "BROWSER", + "Bar": "Bar", + "Base Center": "Base Center", + "Bend": "Bend", + "Bend Edges": "Bend Edges", + "Bend Line Position": "Bend Line Position", + "Bend Position": "Bend Position", + "Bend Radius": "Bend Radius", + "Bend Table": "Bend Table", + "Bends": "Bends", + "Bodies": "Bodies", + "Bodies (optional)": "Bodies (optional)", + "Body": "Body", + "Body (last if none)": "Body (last if none)", + "Body to split": "Body to split", + "Body, or faces to take out": "Body, or faces to take out", + "Bottom Left": "Bottom Left", + "Bottom Middle": "Bottom Middle", + "Bottom Right": "Bottom Right", + "Boundary": "Boundary", + "Bounding box": "Bounding box", + "CHECK": "CHECK", + "COMPONENTS": "COMPONENTS", + "CONFIGURATIONS": "CONFIGURATIONS", + "CONSTRAIN": "CONSTRAIN", + "CONTACT": "CONTACT", + "CONVERT": "CONVERT", + "CSV or JSON: updates existing parameters, adds new ones": "CSV or JSON: updates existing parameters, adds new ones", + "Capture All Positions": "Capture All Positions", + "Capture Pos.": "Capture Pos.", + "Catch Depth": "Catch Depth", + "Catch Direction": "Catch Direction", + "Catch Length": "Catch Length", + "Cells": "Cells", + "Center X": "Center X", + "Center Y": "Center Y", + "Center of mass": "Center of mass", + "Centre to centre": "Centre to centre", + "Centroid": "Centroid", + "Chamfer Type": "Chamfer Type", + "Channel": "Channel", + "Check collisions": "Check collisions", + "Checked": "Checked", + "Choose Variable radius or Spline in Type.": "Choose Variable radius or Spline in Type.", + "Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.": "Choose a new plane. Sketch geometry and dimensions stay unchanged in its two-dimensional coordinates.", + "Choose…": "Choose…", + "Circle center": "Circle center", + "Circular": "Circular", + "Circumference": "Circumference", + "Clockwise": "Clockwise", + "Close draft": "Close draft", + "Collapse": "Collapse", + "Collisions": "Collisions", + "Colour": "Colour", + "Command": "Command", + "Comment": "Comment", + "Component 1": "Component 1", + "Component 2": "Component 2", + "Component1": "Component1", + "Components": "Components", + "Config Table": "Config Table", + "Configuration": "Configuration", + "Configuration rules": "Configuration rules", + "Contact": "Contact", + "Contact Sets": "Contact Sets", + "Contact sets": "Contact sets", + "Continue on GitHub": "Continue on GitHub", + "Continuity": "Continuity", + "Control Radius": "Control Radius", + "Copies the definition only. Assign it from Physical Material when ready.": "Copies the definition only. Assign it from Physical Material when ready.", + "Copy Error Message": "Copy Error Message", + "Copy Warning Message": "Copy Warning Message", + "Copy all licences": "Copy all licences", + "Copy diagnostic information": "Copy diagnostic information", + "Copy report": "Copy report", + "Copy screenshot": "Copy screenshot", + "Corner Relief": "Corner Relief", + "Corner Relief Shape": "Corner Relief Shape", + "Corner radius": "Corner radius", + "Counterbore depth": "Counterbore depth", + "Counterbore Ø": "Counterbore Ø", + "Countersink angle": "Countersink angle", + "Countersink Ø": "Countersink Ø", + "Create Hole": "Create Hole", + "Create Issue — review draft": "Create Issue — review draft", + "Create Issue…": "Create Issue…", + "Cross curves": "Cross curves", + "Ctrl+Enter continues on GitHub.": "Ctrl+Enter continues on GitHub.", + "Cube": "Cube", + "Current orthographic view (1:1 mm)": "Current orthographic view (1:1 mm)", + "Current perspective view": "Current perspective view", + "Current plane": "Current plane", + "Curv. Comb": "Curv. Comb", + "Curvature (G2)": "Curvature (G2)", + "Curvature change (G3)": "Curvature change (G3)", + "Custom": "Custom", + "Customize Toolbar": "Customize Toolbar", + "Customize…": "Customize…", + "Cylindrical face": "Cylindrical face", + "Delete": "Изтрий", + "Delete Folders and Features…": "Delete Folders and Features…", + "Delete Selected Features…": "Delete Selected Features…", + "Delete Selected Folders": "Delete Selected Folders", + "Delete all": "Delete all", + "Delete rule": "Delete rule", + "Delete the row": "Delete the row", + "Delete the set": "Delete the set", + "Density": "Density", + "Dependents": "Dependents", + "Describe the problem you saw": "Describe the problem you saw", + "Describe what happened before continuing.": "Describe what happened before continuing.", + "Designs you open or save appear here.": "Designs you open or save appear here.", + "Determined by To Object. Choose Angle to edit the angular extent.": "Determined by To Object. Choose Angle to edit the angular extent.", + "Diameter": "Диаметър", + "Direction": "Direction", + "Discard": "Discard", + "Distance": "Distance", + "Distance 1": "Distance 1", + "Do not export hidden edges": "Do not export hidden edges", + "Don't ask again": "Don't ask again", + "Double-click to rename": "Double-click to rename", + "Double-clicking the middle button in the view: Home (the home view, framing what is shown), Fit (frame what is shown, keeping the orientation) or nothing": "Double-clicking the middle button in the view: Home (the home view, framing what is shown), Fit (frame what is shown, keeping the orientation) or nothing", + "Drag to move the boss across the model. It snaps to sketch points on the face.": "Drag to move the boss across the model. It snaps to sketch points on the face.", + "Drag to move the hole; click to remove it": "Drag to move the hole; click to remove it", + "Drag to move the rest across the model. It snaps to sketch points on the face.": "Drag to move the rest across the model. It snaps to sketch points on the face.", + "Drag to move the snap fit across the model. It snaps to sketch points on the face.": "Drag to move the snap fit across the model. It snaps to sketch points on the face.", + "Drag to point the catch in another direction.": "Drag to point the catch in another direction.", + "Drag to turn the rest in 5° steps. Hold Alt or Ctrl to turn it freely.": "Drag to turn the rest in 5° steps. Hold Alt or Ctrl to turn it freely.", + "Drive Joint": "Drive Joint", + "Duration": "Duration", + "Edges": "Edges", + "Edit": "Редактирай", + "Edit Profile Sketch": "Edit Profile Sketch", + "Enable rule": "Enable rule", + "Enabled": "Enabled", + "End Radius": "End Radius", + "End bulge": "End bulge", + "End continuity": "End continuity", + "Expand": "Expand", + "Expected result (optional)": "Expected result (optional)", + "Explode": "Explode", + "Explode Text": "Explode Text", + "Export Animation…": "Export Animation…", + "Export Bend Table…": "Export Bend Table…", + "Export CSV…": "Export CSV…", + "Export Current View as DXF": "Export Current View as DXF", + "Export Current View as DXF…": "Export Current View as DXF…", + "Export DXF": "Export DXF", + "Export DXF…": "Export DXF…", + "Export JSON…": "Export JSON…", + "Export design library...": "Export design library...", + "Export hidden edges as dashed lines": "Export hidden edges as dashed lines", + "Exported by SolidWorks, which usually saves Y up": "Exported by SolidWorks, which usually saves Y up", + "Expression": "Expression", + "Extend to meet": "Extend to meet", + "Extents": "Extents", + "FILES": "FILES", + "FLAT": "FLAT", + "Face": "Face", + "Face Appearance": "Face Appearance", + "Face attachment lost": "Face attachment lost", + "Face center": "Face center", + "Faces": "Faces", + "Faces / edges / vertices": "Faces / edges / vertices", + "Faces to split": "Faces to split", + "Fastener": "Fastener", + "Favorites": "Favorites", + "Favourite": "Favourite", + "Feature": "Елемент", + "Files from many CAD programs have Y up, so they open lying on their back here (Z up).": "Files from many CAD programs have Y up, so they open lying on their back here (Z up).", + "Filter": "Filter", + "Filter…": "Filter…", + "Find in Browser": "Find in Browser", + "Finish": "Finish", + "First plane": "First plane", + "Fit and G2 corners require Constant radius.": "Fit and G2 corners require Constant radius.", + "Fixed Face": "Fixed Face", + "Flange thickness": "Flange thickness", + "Flanges": "Flanges", + "Flat Pattern": "Flat Pattern", + "Flat size": "Flat size", + "Follow camera (Look At sketches)": "Follow camera (Look At sketches)", + "Follow the camera (Look At sketches)": "Follow the camera (Look At sketches)", + "Font": "Font", + "From": "From", + "From Bodies": "From Bodies", + "From edges": "From edges", + "Full Length": "Full Length", + "Full thread depth": "Full thread depth", + "Further Bends": "Further Bends", + "G2 corners require a constant radius and Exact fit. G2 corner construction is not supported yet.": "G2 corners require a constant radius and Exact fit. G2 corner construction is not supported yet.", + "Gap": "Gap", + "Grid": "Мрежа", + "HISTORY": "HISTORY", + "Halo under sketch curves": "Halo under sketch curves", + "Height": "Височина", + "Height From": "Height From", + "Hidden edges": "Hidden edges", + "History layout": "History layout", + "History names": "History names", + "Hole (optional)": "Hole (optional)", + "Holes": "Holes", + "Holes (edges on them)": "Holes (edges on them)", + "Home view": "Home view", + "Horiz./Vert.": "Horiz./Vert.", + "I-Beam": "I-Beam", + "IMAGES": "IMAGES", + "Import material into design": "Import material into design", + "Import…": "Import…", + "In This Design": "In This Design", + "In place (surfaces)": "In place (surfaces)", + "In plane": "In plane", + "Included": "Included", + "Inner Sharp": "Inner Sharp", + "Inside": "Inside", + "Instant": "Instant", + "Interface font": "Interface font", + "Interferes": "Interferes", + "Invert": "Invert", + "Isocurve": "Isocurve", + "Issue title": "Issue title", + "Items": "Items", + "JOINTS": "JOINTS", + "Joint Origin1": "Joint Origin1", + "Keep (points on it)": "Keep (points on it)", + "Keep Tools": "Keep Tools", + "Keep of the other surface": "Keep of the other surface", + "Key a joint's value at this step": "Key a joint's value at this step", + "Keys": "Keys", + "L-Angle": "L-Angle", + "LIBRARY": "LIBRARY", + "LINKS": "LINKS", + "Later": "Later", + "Leave it": "Leave it", + "Left Middle": "Left Middle", + "Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Legacy face attachment. Rebinding to a certified face creates an exact attachment.", + "Length": "Дължина", + "Length units": "Length units", + "Letter Spacing": "Letter Spacing", + "Library": "Library", + "Library file": "Library file", + "Limits": "Limits", + "Line Spacing": "Line Spacing", + "Line Type": "Line Type", + "Lines": "Lines", + "Listing the installed fonts…": "Listing the installed fonts…", + "Load library": "Load library", + "Local library": "Local library", + "Loop": "Loop", + "M5 or M5x0.5": "M5 or M5x0.5", + "M5, M5x0.5, 1/4-20 UNC": "M5, M5x0.5, 1/4-20 UNC", + "MANAGE": "MANAGE", + "MATERIALS": "MATERIALS", + "MODEL": "MODEL", + "MOTION": "MOTION", + "Margin": "Margin", + "Mass": "Маса", + "Mass Center": "Mass Center", + "Matched restrictions check the final values.": "Matched restrictions check the final values.", + "Material": "Материал", + "Material Outside": "Material Outside", + "Material copied. Existing body assignments are unchanged.": "Material copied. Existing body assignments are unchanged.", + "Max": "Max", + "Maximum": "Maximum", + "Mesh body": "Mesh body", + "Mid Radius": "Mid Radius", + "Middle double-click": "Middle double-click", + "Min": "Min", + "Minimum": "Minimum", + "Mirror Plane": "Mirror Plane", + "Mitre": "Mitre", + "Model Parameters": "Model Parameters", + "Modeled": "Modeled", + "More toolbar panels": "More toolbar panels", + "Motion": "Motion", + "Mouse gestures": "Mouse gestures", + "Mouse gestures only work with the SolidWorks mouse mode (the wheel orbits, Ctrl + wheel pans).": "Mouse gestures only work with the SolidWorks mouse mode (the wheel orbits, Ctrl + wheel pans).", + "Move / Copy": "Move / Copy", + "Move Type": "Move Type", + "Move down": "Move down", + "Move earlier": "Move earlier", + "Move holes by clicking or dragging": "Move holes by clicking or dragging", + "Move later": "Move later", + "Move up": "Move up", + "Name": "Name", + "Name on import": "Name on import", + "Nearest": "Nearest", + "New": "Нов", + "New Comp.": "New Comp.", + "New Sketch": "New Sketch", + "New rule…": "New rule…", + "New study": "New study", + "No crash reports.": "No crash reports.", + "No matching appearance presets.": "No matching appearance presets.", + "No matching appearances": "No matching appearances", + "No matching physical materials.": "No matching physical materials.", + "No visible bodies or sketches to export.": "No visible bodies or sketches to export.", + "Nominal diameter": "Nominal diameter", + "None": "None", + "Not available yet": "Not available yet", + "Not saved yet": "Not saved yet", + "Notch": "Notch", + "OUTPUT": "OUTPUT", + "Of": "Of", + "On your computer": "On your computer", + "Opacity": "Opacity", + "Open GitHub draft": "Open GitHub draft", + "Open bodies (no volume)": "Open bodies (no volume)", + "Open library...": "Open library...", + "Open local libraries in the desktop app. You can export this design's library here.": "Open local libraries in the desktop app. You can export this design's library here.", + "Open surface — no volume": "Open surface — no volume", + "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.": "Open-source parametric 3D CAD in Rust. Licensed MIT OR Apache-2.0.", + "Opens your browser and copies the report text for you to paste into GitHub.": "Opens your browser and copies the report text for you to paste into GitHub.", + "Opens your browser. Review and submit your report on GitHub.": "Opens your browser. Review and submit your report on GitHub.", + "Operator": "Operator", + "Orbit (right drag)": "Orbit (right drag)", + "Other side": "Other side", + "Other surface (mutual trim)": "Other surface (mutual trim)", + "Other way": "Other way", + "Outer Sharp": "Outer Sharp", + "Outer radius": "Outer radius", + "Outside": "Outside", + "Overall length": "Overall length", + "Param. Graph": "Param. Graph", + "Parameter": "Parameter", + "Parts": "Parts", + "Pass through": "Pass through", + "Path": "Path", + "Pattern": "Pattern", + "Per Edge": "Per Edge", + "Physical material definitions": "Physical material definitions", + "Pick the tool bodies": "Pick the tool bodies", + "Picked": "Picked", + "Picked point": "Picked point", + "Pitch": "Pitch", + "Pivot": "Pivot", + "Place at the origin instead": "Place at the origin instead", + "Plastic Rules": "Plastic Rules", + "Play the joint's motion in the view": "Play the joint's motion in the view", + "Playback": "Playback", + "Plot": "Plot", + "Position": "Position", + "Position (0 to 1)": "Position (0 to 1)", + "Position (G0)": "Position (G0)", + "Position along the edge, 0 at the start end, 1 at the other": "Position along the edge, 0 at the start end, 1 at the other", + "Preferences › Design turns the offer back on": "Preferences › Design turns the offer back on", + "Preview": "Preview", + "Preview Row": "Preview Row", + "Preview leaves the current design unchanged.": "Preview leaves the current design unchanged.", + "Profile / Edges": "Profile / Edges", + "Profiles or curves": "Profiles or curves", + "Profiles/Curves": "Profiles/Curves", + "Quantity": "Quantity", + "RECENT": "RECENT", + "REFERENCE": "REFERENCE", + "RULED SURFACE": "RULED SURFACE", + "RULES": "RULES", + "Radius": "Радиус", + "Radius Fit": "Radius Fit", + "Ratio": "Ratio", + "Reattach selected face": "Reattach selected face", + "Recover": "Recover", + "Recover unsaved design?": "Recover unsaved design?", + "Rectangular": "Rectangular", + "Rectangular Tube": "Rectangular Tube", + "Reference face": "Reference face", + "Remove Tools": "Remove Tools", + "Remove condition": "Remove condition", + "Remove from Folder": "Remove from Folder", + "Remove from list": "Remove from list", + "Remove override": "Remove override", + "Remove private design details or paths before sharing.": "Remove private design details or paths before sharing.", + "Remove screenshot": "Remove screenshot", + "Remove the column": "Remove the column", + "Remove the track": "Remove the track", + "Remove this bend": "Remove this bend", + "Remove this point": "Remove this point", + "Rename Feature": "Rename Feature", + "Rename Folder": "Rename Folder", + "Render Stage": "Render Stage", + "Reopen designs": "Reopen designs", + "Reopen the designs that were open when SolidCraft was last closed": "Reopen the designs that were open when SolidCraft was last closed", + "Replace existing library file": "Replace existing library file", + "Report a bug — review a screenshot and open a GitHub draft": "Report a bug — review a screenshot and open a GitHub draft", + "Report text copied. Paste it into GitHub and submit your report there.": "Report text copied. Paste it into GitHub and submit your report there.", + "Reports are public. A GitHub account is required.": "Reports are public. A GitHub account is required.", + "Reset Toolbar": "Reset Toolbar", + "Resize Part": "Resize Part", + "Restore View": "Restore View", + "Restore outer boundary": "Restore outer boundary", + "Restore the inherited component or physical material appearance": "Restore the inherited component or physical material appearance", + "Restore this studio's tools": "Restore this studio's tools", + "Result": "Result", + "Retake screenshot": "Retake screenshot", + "Reverse": "Reverse", + "Reverse Direction": "Reverse Direction", + "Revert": "Revert", + "Revert All Positions": "Revert All Positions", + "Revert Pos.": "Revert Pos.", + "Revert Position": "Revert Position", + "Review the report and screenshot before opening GitHub.": "Review the report and screenshot before opening GitHub.", + "Review your report on GitHub and click Submit new issue to publish it.": "Review your report on GitHub and click Submit new issue to publish it.", + "Rib Length": "Rib Length", + "Rib Offset": "Rib Offset", + "Rib Thickness": "Rib Thickness", + "Ribs": "Ribs", + "Right Middle": "Right Middle", + "Rim Edge": "Rim Edge", + "Ring of tools on the right button": "Ring of tools on the right button", + "Roll Back Here": "Roll Back Here", + "Roll History Marker Here": "Roll History Marker Here", + "Root radius": "Root radius", + "Round": "Round", + "Round Bar": "Round Bar", + "Round Tube": "Round Tube", + "Rule": "Rule", + "Rule name": "Rule name", + "Rules run from top to bottom. Matched drives change effective values.": "Rules run from top to bottom. Matched drives change effective values.", + "SECTION": "SECTION", + "SURFACE QUALITY": "SURFACE QUALITY", + "Same way": "Same way", + "Save Rule": "Save Rule", + "Save View": "Save View", + "Save screenshot…": "Save screenshot…", + "Save the study as an animated GIF, seen as the viewport shows it": "Save the study as an animated GIF, seen as the viewport shows it", + "Saved preview. Geometry is being checked before editing.": "Saved preview. Geometry is being checked before editing.", + "Scale factor": "Scale factor", + "Scene": "Scene", + "Screenshot (optional)": "Screenshot (optional)", + "Search": "Търси", + "Search commands": "Search commands", + "Search this library": "Search this library", + "Second plane": "Second plane", + "Section": "Section", + "Section (optional)": "Section (optional)", + "Section position": "Section position", + "Sections (one sketch each)": "Sections (one sketch each)", + "Select Other": "Select Other", + "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).", + "Select Same Look": "Select Same Look", + "Select bodies (a face picks its body)": "Select bodies (a face picks its body)", + "Select bodies or faces instead": "Select bodies or faces instead", + "Select edges": "Select edges", + "Selection filter": "Selection filter", + "Semantic faces share their appearance across instances.": "Semantic faces share their appearance across instances.", + "Send your report on GitHub": "Send your report on GitHub", + "Shaded": "Shaded", + "Shape": "Shape", + "Sheet Rules": "Sheet Rules", + "Show Agent Cursor": "Show Agent Cursor", + "Show ghost": "Show ghost", + "Show in folder": "Show in folder", + "Show the pointer an AI agent moves (#35)": "Show the pointer an AI agent moves (#35)", + "Show tool at cursor": "Show tool at cursor", + "Signed axes": "Signed axes", + "Size": "Size", + "Sketch constraints": "Sketch constraints", + "Sketch curves": "Sketch curves", + "Sketch dimensions": "Sketch dimensions", + "Sketch geometry and profiles": "Sketch geometry and profiles", + "Sketch plane has no body-face attachment.": "Sketch plane has no body-face attachment.", + "Sketch points": "Sketch points", + "Slot width": "Slot width", + "Snap to face and edge centres": "Snap to face and edge centres", + "SolidCraft closed before these designs were saved. Their last autosave can be opened.": "SolidCraft closed before these designs were saved. Their last autosave can be opened.", + "Specialise": "Specialise", + "Speed": "Speed", + "Splitting tool": "Splitting tool", + "Square": "Square", + "Stand it up": "Stand it up", + "Stand it up: a quarter turn about X, as one Move feature you can undo.": "Stand it up: a quarter turn about X, as one Move feature you can undo.", + "Stand this part up?": "Stand this part up?", + "Start angle": "Start angle", + "Start bulge": "Start bulge", + "Start continuity": "Start continuity", + "Step": "Step", + "Steps": "Steps", + "Steps to reproduce (optional)": "Steps to reproduce (optional)", + "Stitch the kept pieces": "Stitch the kept pieces", + "Stitch to both bodies": "Stitch to both bodies", + "Studio": "Studio", + "Study": "Study", + "Style": "Style", + "Summary": "Summary", + "Suppress": "Suppress", + "Suppress Selected Folders": "Suppress Selected Folders", + "Suppressed": "Suppressed", + "Surface": "Surface", + "Surface, or faces to turn over": "Surface, or faces to turn over", + "Swap Ends": "Swap Ends", + "TRIM": "TRIM", + "Tangent": "Tangent", + "Tangent (G1)": "Tangent (G1)", + "Tangent Chain": "Tangent Chain", + "Tangent chain": "Tangent chain", + "Tangent to Edge": "Tangent to Edge", + "Tap drill diameter": "Tap drill diameter", + "Target": "Target", + "Target Body": "Target Body", + "Tear": "Tear", + "Technical details": "Technical details", + "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.": "The dashed sketch is a saved plane guide. Select a new face to repair the attachment.", + "The saved author occurrence is missing. Select a valid author placement before rebinding.": "The saved author occurrence is missing. Select a valid author placement before rebinding.", + "Then": "Then", + "These features will be deleted:": "These features will be deleted:", + "These features will fail:": "These features will fail:", + "Thickness Outside": "Thickness Outside", + "Thin": "Thin", + "Thin Extrude": "Thin Extrude", + "This child is shared. Deleting it removes it from every copy of its parent.": "This child is shared. Deleting it removes it from every copy of its parent.", + "This child is shared. Position changes apply to every copy of its parent.": "This child is shared. Position changes apply to every copy of its parent.", + "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.": "This face cannot provide a durable attachment. Choose another face or explicitly use a fixed plane.", + "This image is not attached to GitHub yet. Copy or save it, then attach it on GitHub.": "This image is not attached to GitHub yet. Copy or save it, then attach it on GitHub.", + "Thread depth": "Thread depth", + "Thread diameter": "Thread diameter", + "To": "To", + "To Offset": "To Offset", + "To edges": "To edges", + "Toe radius": "Toe radius", + "Tolerance": "Tolerance", + "Too close": "Too close", + "Tool Bodies": "Tool Bodies", + "Tools": "Инструменти", + "Tools, clockwise from the top": "Tools, clockwise from the top", + "Top Left": "Top Left", + "Top Middle": "Top Middle", + "Top Right": "Top Right", + "Trimming tool (plane, face or curves)": "Trimming tool (plane, face or curves)", + "Turn off section analysis before exporting the view.": "Turn off section analysis before exporting the view.", + "Type": "Type", + "UNTRIM": "UNTRIM", + "Unit": "Unit", + "Unsuppress": "Unsuppress", + "Unsuppress Selected Folders": "Unsuppress Selected Folders", + "Updating the preview": "Updating the preview", + "Use active author placement": "Use active author placement", + "Use fixed plane": "Use fixed plane", + "Use saved fixed plane": "Use saved fixed plane", + "Use selected face as fixed plane": "Use selected face as fixed plane", + "Use the SolidWorks mouse mode": "Use the SolidWorks mouse mode", + "User Parameters": "User Parameters", + "VIEW": "VIEW", + "VIEWS": "VIEWS", + "Value": "Value", + "Variable Radius": "Variable Radius", + "Velocity": "Velocity", + "Vertices": "Vertices", + "View navigator": "View navigator", + "Volume": "Обем", + "Wall": "Wall", + "Wall Location": "Wall Location", + "Wall Thickness": "Wall Thickness", + "Web thickness": "Web thickness", + "What did you do just before the problem? A short list is enough": "What did you do just before the problem? A short list is enough", + "What did you expect to see?": "What did you expect to see?", + "What happened?": "What happened?", + "When": "When", + "Width": "Широчина", + "Will fail": "Will fail", + "With gestures on, the right button no longer orbits the view: hold it and move to open the ring, then touch a tool's zone. A plain right-click still opens the menu.": "With gestures on, the right button no longer orbits the view: hold it and move to open the ring, then touch a tool's zone. A plain right-click still opens the menu.", + "X": "X", + "X Angle": "X Angle", + "X angle": "X angle", + "X distance": "X distance", + "Y": "Y", + "Y Angle": "Y Angle", + "Y angle": "Y angle", + "Y distance": "Y distance", + "Z": "Z", + "Z Angle": "Z Angle", + "Z Distance": "Z Distance", + "Z angle": "Z angle", + "Z distance": "Z distance", + "Zebra": "Zebra", + "ai.connected_toast": "SolidCraft is now available in {clients}. Restart them to use it (Settings > Assistant).", + "ai.prefs.allow_control": "Let AI agents connect (control channel / MCP)", + "ai.prefs.allow_control_note": "Opens a control channel on this computer only (127.0.0.1, port 27878 or the next free one). A program that connects must also show a secret token that only your user account can read, made fresh at every start. Takes effect the next time SolidCraft starts. Off: nothing listens unless you start SolidCraft with --control.", + "ai.prefs.availability": "Assistant controls", + "ai.prefs.background_commands": "Run agent commands in the background", + "ai.prefs.connect_apps": "Make SolidCraft available to AI apps on this computer", + "ai.prefs.connect_apps_note": "When SolidCraft starts, adds it as an MCP server to the AI apps found on this computer (OpenCode, Claude Desktop, Claude Code, Cursor, Codex, Gemini CLI, Copilot CLI, Windsurf, Zed, VS Code), so an agent can use it without any setup. Only the solidcraft entry is added or its path refreshed; an entry you changed is left alone, and the file is backed up first. Off: the entries it added are removed. Help > Connect AI assistants… does this by hand.", + "ai.prefs.connect_at_start": "Connect the last-used agent when SolidCraft starts", + "ai.prefs.connect_at_start_note": "Starts the agent you connected last (or the default one) in the background each time SolidCraft starts, so it is ready for chatting. Not when SolidCraft is started with --control. If it cannot connect, the Assistant shows Connection failed and a Retry button.", + "ai.prefs.follow_camera": "Turn the camera to sketches", + "ai.prefs.follow_camera_off": "Automatic camera following is off.", + "ai.prefs.follow_camera_on": "The camera turns to face sketches the agent creates.", + "ai.prefs.intro": "Agents, permissions and how their work appears.", + "ai.prefs.make_default": "Use by default", + "ai.prefs.no_agents": "No agents yet. Add an agent or refresh to find installed agents.", + "ai.prefs.no_saved_approvals": "No saved approvals.", + "ai.prefs.open_at_start": "Open the Assistant panel when SolidCraft starts", + "ai.prefs.open_at_start_note": "Shows the Assistant panel (or its own window) each time SolidCraft starts. Not when SolidCraft is started with --control.", + "ai.prefs.override_all_warning": "This agent may save, overwrite, export or replace the design without asking.", + "ai.prefs.permission_all": "Allow everything", + "ai.prefs.permission_all_summary": "Available SolidCraft tools run without asking.", + "ai.prefs.permission_ask": "Ask before changes", + "ai.prefs.permission_ask_summary": "Approve every design change and file action.", + "ai.prefs.permission_edits": "Allow model edits", + "ai.prefs.permission_edits_summary": "Model edits run; file and destructive actions still ask.", + "ai.prefs.permission_scope": "For SolidCraft tools only. The agent’s shell and file edits use its own permissions.", + "ai.prefs.pointer_preview_hidden": "Pointer hidden", + "ai.prefs.pointer_preview_speed": "Agent pointer · {speed}", + "ai.prefs.pointer_speed": "Motion speed", + "ai.prefs.privacy_note": "Only your chosen agent or endpoint receives the conversation. Endpoint keys are stored in your system keychain.", + "ai.prefs.show_pointer": "Show agent pointer", + "ai.prefs.turn_limit_hint": "Maximum design-changing tool calls the Assistant may make for one message.", + "angle, height": "angle, height", + "appearance.dielectric_ior": "Dielectric IOR", + "appearance.metallic": "Metallic", + "appearance.only_available": "Available appearances only", + "appearance.pbr_help": "View this surface in Render or a product PNG. No refraction or transmission.", + "appearance.pbr_opaque": "Opaque PBR", + "appearance.roughness": "Roughness", + "appearance.surface_response": "Surface response", + "browser.body_name": "Body{number}", + "browser.calibrate_title": "Calibrate: {name}", + "browser.capture_many": "{count} components were moved but their positions aren't captured.", + "browser.capture_note": "Capture keeps the new position; Revert puts it back.", + "browser.capture_one": "A component was moved but its position isn't captured.", + "browser.component_name": "Component{number}", + "browser.edit_canvas_title": "Edit Canvas: {name}", + "browser.move_title": "Move: {name}", + "browser.parameters": "Parameters ({count})", + "browser.precision": "Precision: {precision}", + "browser.sketch_name": "Sketch{number}", + "browser.units": "Units: {units}", + "cam.flat": "Flat face", + "cam.follower": "Follower", + "cam.knife": "Knife edge", + "cam.needs_joints": "needs a joint that turns and one that slides or swings", + "cam.roller": "Roller", + "cam.roller_pick": "Roller (optional)", + "cam.tip_pick": "Tip (optional)", + "cmd.appearance_assign": "Appearance", + "cmd.appearance_chain": "Appearance Chain", + "cmd.appearance_library": "Appearance Library", + "cmd.appearance_list": "List Appearances", + "cmd.appearance_paint": "Paint Appearance", + "cmd.appearance_pick_up": "Pick Up Appearance", + "cmd.appearance_replace": "Replace Appearance", + "cmd.assembly_bom": "Bill of Materials", + "cmd.body_rename": "Rename Body", + "cmd.browser_collapse_all": "Collapse All", + "cmd.browser_expand_all": "Expand All", + "cmd.browser_group": "New Group", + "cmd.browser_move": "Move Browser Items", + "cmd.browser_order": "Order Browser Items", + "cmd.browser_rename_group": "Rename Group", + "cmd.browser_ungroup": "Ungroup", + "cmd.browser_visibility": "Show/Hide", + "cmd.canvas_calibrate": "Calibrate Canvas", + "cmd.canvas_decal": "Decal", + "cmd.canvas_delete": "Delete Canvas", + "cmd.canvas_edit": "Edit Canvas", + "cmd.canvas_insert": "Canvas", + "cmd.canvas_to_sketch": "Canvas to Sketch", + "cmd.component_activate": "Activate Component", + "cmd.component_break_link": "Break Link", + "cmd.component_capture_position": "Capture Position", + "cmd.component_copies": "Find Identical Copies", + "cmd.component_copy_bodies": "Paste Bodies", + "cmd.component_create": "New Component", + "cmd.component_cycle_color": "Cycle Component Color", + "cmd.component_delete": "Delete Component", + "cmd.component_extract": "Extract to File", + "cmd.component_from_bodies": "Create Components from Bodies", + "cmd.component_insert_design": "Insert Design", + "cmd.component_links": "List Links", + "cmd.component_list": "List Components", + "cmd.component_metadata": "Part Properties", + "cmd.component_metadata_set": "Change Part Properties", + "cmd.component_move_bodies": "Move Bodies to Component", + "cmd.component_move_sketches": "Move Sketches to Component", + "cmd.component_paste_new": "Paste New", + "cmd.component_properties": "Component Physical Properties", + "cmd.component_relink": "Relink Source", + "cmd.component_rename": "Rename Component", + "cmd.component_replace_with_link": "Replace with Link", + "cmd.component_revert_position": "Revert Position", + "cmd.component_unlock": "Unlock Contents", + "cmd.component_update_links": "Update Links", + "cmd.config_activate": "Activate Configuration", + "cmd.config_column": "Configuration Column", + "cmd.config_configure": "Configure", + "cmd.config_preview": "Preview Configuration", + "cmd.config_row": "Configuration Row", + "cmd.config_rule": "Configuration Rule", + "cmd.config_rules": "Configuration Rules", + "cmd.config_table": "Display Configuration Table", + "cmd.construct_axis_edge": "Axis Through Edge", + "cmd.construct_axis_normal_to_face": "Axis Perpendicular To Face", + "cmd.construct_axis_through_cylinder": "Axis Through Cylinder/Cone/Torus", + "cmd.construct_axis_two_planes": "Axis Through Two Planes", + "cmd.construct_axis_two_points": "Axis Through Two Points", + "cmd.construct_plane_along_path": "Plane Along Path", + "cmd.construct_plane_midplane": "Midplane", + "cmd.construct_plane_perpendicular": "Perpendicular Plane", + "cmd.construct_plane_tangent": "Tangent Plane", + "cmd.construct_plane_three_points": "Plane Through Three Points", + "cmd.construct_plane_two_edges": "Plane Through Two Edges", + "cmd.construct_point_along_path": "Point Along Path", + "cmd.construct_point_center": "Point At Center Of Circle/Sphere/Torus", + "cmd.construct_point_edge_plane": "Point At Edge And Plane", + "cmd.construct_point_three_planes": "Point Through Three Planes", + "cmd.construct_point_two_edges": "Point Through Two Edges", + "cmd.construct_point_vertex": "Point At Vertex", + "cmd.contact_check": "Check Contact", + "cmd.contact_create": "New Contact Set", + "cmd.contact_disable_all": "Disable Contact", + "cmd.contact_edit": "Edit Contact Set", + "cmd.contact_enable_all": "Enable All Contact", + "cmd.contact_enable_sets": "Enable Contact Sets", + "cmd.contact_list": "List Contact Sets", + "cmd.diagnostics_crash_report": "Crash Report", + "cmd.diagnostics_crash_reports": "Crash Reports", + "cmd.diagnostics_crash_reports_clear": "Delete Crash Reports", + "cmd.diagnostics_crash_test": "Crash Test", + "cmd.doc_recover": "Recover Design", + "cmd.doc_recovery_discard": "Discard Recovered Design", + "cmd.doc_recovery_list": "Recoverable Designs", + "cmd.document_inspect": "Inspect Design", + "cmd.document_metadata": "Design Properties", + "cmd.document_metadata_remove": "Remove Design Property", + "cmd.document_metadata_set": "Change Design Properties", + "cmd.document_revision": "Design Revision", + "cmd.document_units": "Change Design Units", + "cmd.edit_checkpoint": "Checkpoint", + "cmd.edit_repeat": "Repeat Last Command", + "cmd.edit_restore_checkpoint": "Restore Checkpoint", + "cmd.engine_commands": "List Commands", + "cmd.engine_describe": "Describe Command", + "cmd.explode_create": "Exploded View", + "cmd.explode_delete": "Delete Exploded View", + "cmd.explode_list": "List Exploded Views", + "cmd.explode_show": "Show Exploded View", + "cmd.expr_evaluate": "Evaluate Expression", + "cmd.face_delete": "Delete Face", + "cmd.file_export": "Export", + "cmd.file_insert_mesh": "Insert Mesh", + "cmd.file_insert_step": "Insert STEP", + "cmd.file_open_in_easyprint": "Open with EasyPrint", + "cmd.file_save_mesh": "Save As Mesh", + "cmd.file_send_to_slicer": "Send to Slicer", + "cmd.file_slicers": "Installed Slicers", + "cmd.frame_member": "Frame Member", + "cmd.frame_profile_insert": "Insert Profile", + "cmd.frame_profile_list": "Profile Library", + "cmd.frame_profile_properties": "Profile Properties", + "cmd.inspect_accessibility": "Accessibility Analysis", + "cmd.inspect_center_of_mass": "Center of Mass", + "cmd.inspect_clearance": "Clearance", + "cmd.inspect_colored_components": "Enable Component Colors", + "cmd.inspect_compare": "Compare Bodies", + "cmd.inspect_continuity": "Continuity Analysis", + "cmd.inspect_curvature_comb": "Curvature Comb Analysis", + "cmd.inspect_curvature_map": "Curvature Map Analysis", + "cmd.inspect_draft": "Draft Analysis", + "cmd.inspect_environment_map": "Environment Map Analysis", + "cmd.inspect_interference": "Interference", + "cmd.inspect_isocurve": "Isocurve Analysis", + "cmd.inspect_minimum_radius": "Minimum Radius Analysis", + "cmd.inspect_parameter_sweep": "Parameter Sweep", + "cmd.inspect_silhouette": "Silhouette", + "cmd.inspect_zebra": "Zebra Analysis", + "cmd.joint_as_built": "As-Built Joint", + "cmd.joint_cam": "Cam", + "cmd.joint_create": "Joint", + "cmd.joint_delete": "Delete Joint", + "cmd.joint_drive": "Drive Joints", + "cmd.joint_edit": "Edit Joint", + "cmd.joint_gear": "Gear", + "cmd.joint_inspect": "Inspect Joint", + "cmd.joint_limits": "Joint Limits", + "cmd.joint_list": "List Joints", + "cmd.joint_motion_link": "Motion Link", + "cmd.joint_origin": "Joint Origin", + "cmd.joint_rack_pinion": "Rack and Pinion", + "cmd.joint_reach": "Reach Point", + "cmd.joint_rigid_group": "Rigid Group", + "cmd.joint_screw": "Screw", + "cmd.joint_solve": "Solve Joints", + "cmd.joint_sweep": "Sweep Joint", + "cmd.library_apply": "Apply Local Library Entry", + "cmd.library_export": "Export Design Library", + "cmd.library_inspect": "Inspect Local Library", + "cmd.material_assign": "Physical Material", + "cmd.material_create": "New Physical Material", + "cmd.material_delete": "Delete Physical Material", + "cmd.material_edit": "Edit Physical Material", + "cmd.material_inspect": "Inspect Physical Material", + "cmd.material_list": "List Materials", + "cmd.material_properties_directional": "Directional Elastic Modulus", + "cmd.material_properties_validate": "Validate Physical Material Data", + "cmd.mesh_convert": "Convert Mesh", + "cmd.model_edges": "List Edges", + "cmd.model_faces": "List Faces", + "cmd.model_threads": "List Threads", + "cmd.motion_delete": "Delete Motion Study", + "cmd.motion_export": "Export Motion Study", + "cmd.motion_export_animation": "Export Motion Animation", + "cmd.motion_interference": "Motion Interference", + "cmd.motion_list": "List Motion Studies", + "cmd.motion_play": "Play Motion Study", + "cmd.motion_plot": "Plot Motion Study", + "cmd.motion_study": "Motion Study", + "cmd.motion_trace": "Motion Trace", + "cmd.motion_trace_edit": "Edit Motion Trace", + "cmd.motion_trace_keep": "Keep Motion Trace", + "cmd.occurrence_copy": "Paste (Instance)", + "cmd.occurrence_drag": "Drag Occurrence", + "cmd.occurrence_ground": "Ground", + "cmd.occurrence_move": "Move Occurrence", + "cmd.occurrence_properties": "Occurrence Physical Properties", + "cmd.occurrence_reparent": "Move to Component", + "cmd.parameters_add": "Add User Parameter", + "cmd.parameters_change": "Change Parameters", + "cmd.parameters_comment": "Comment Parameter", + "cmd.parameters_complete": "Complete Expression", + "cmd.parameters_delete": "Delete Parameter", + "cmd.parameters_export": "Export Parameters", + "cmd.parameters_favorite": "Favourite Parameter", + "cmd.parameters_graph": "Parameter Graph", + "cmd.parameters_import": "Import Parameters", + "cmd.parameters_list": "List Parameters", + "cmd.parameters_move": "Move Parameter", + "cmd.parameters_rename": "Rename Parameter", + "cmd.parameters_users": "Parameter Users", + "cmd.parts_fastener": "Insert Fastener", + "cmd.parts_insert": "Insert Part", + "cmd.parts_library": "Standard Parts", + "cmd.parts_resize": "Change Part Size", + "cmd.plastic_assign_rule": "Assign Plastic Rule", + "cmd.plastic_boss": "Boss", + "cmd.plastic_lip": "Lip", + "cmd.plastic_manage_rules": "Manage Plastic Rules", + "cmd.plastic_rest": "Rest", + "cmd.plastic_rules": "List Plastic Rules", + "cmd.plastic_snap_fit": "Snap Fit", + "cmd.render_aging_describe": "Layered Surface Aging", + "cmd.render_backends": "Render Backends", + "cmd.render_batch": "Render All Shots", + "cmd.render_camera_fit": "Frame Render Subject", + "cmd.render_camera_get": "Inspect Render Camera", + "cmd.render_cancel": "Cancel Render", + "cmd.render_compare": "Compare Images", + "cmd.render_effects_describe": "Lens and Creative Effects", + "cmd.render_export": "Export Render Image", + "cmd.render_hdr_inspect": "Inspect HDR Source", + "cmd.render_library_appearance_apply": "Apply Library Opaque Appearance", + "cmd.render_library_describe": "Inspect Render Library Resource", + "cmd.render_library_environment_apply": "Apply Built-in HDR Environment", + "cmd.render_library_list": "Browse Render Library", + "cmd.render_library_physical_prepare": "Prepare Physical Reference", + "cmd.render_library_preview": "Inspect Original Surface Map", + "cmd.render_library_studio_apply": "Apply Authored Studio Lights", + "cmd.render_library_studio_prepare": "Prepare Authored Studio Lights", + "cmd.render_library_surface_bind": "Save Surface Binding", + "cmd.render_library_surface_prepare": "Prepare Authored Surface Maps", + "cmd.render_library_surface_unbind": "Remove Surface Binding", + "cmd.render_library_targets": "Find Render Library Targets", + "cmd.render_lights_solo": "Solo Light", + "cmd.render_optics_bind": "Save Optical Binding", + "cmd.render_optics_unbind": "Remove Optical Binding", + "cmd.render_preflight": "Check Render Request", + "cmd.render_preset_apply": "Apply Native Studio", + "cmd.render_preset_resolve": "Review Native Studio", + "cmd.render_quality_prepare": "Review Fixed Sampling Budget", + "cmd.render_result_pin": "Retain Displayed Render Result", + "cmd.render_result_regrade": "Regrade Linear Master", + "cmd.render_scene": "Inspect Render Scene", + "cmd.render_settings_apply": "Apply Render Camera", + "cmd.render_settings_capture_hdr": "Save Render Settings with HDR", + "cmd.render_settings_get": "Render Settings", + "cmd.render_settings_set": "Save Render Settings", + "cmd.render_shot_duplicate": "Duplicate Render Shot", + "cmd.render_shot_remove": "Remove Render Shot", + "cmd.render_shot_rename": "Rename Render Shot", + "cmd.render_stage_backdrop": "Save Physical Render Background", + "cmd.render_stage_clear": "Remove Render Stage", + "cmd.render_stage_ground": "Save Render Ground", + "cmd.render_start": "Render Image", + "cmd.render_status": "Render Progress", + "cmd.select_clear": "Clear Selection", + "cmd.sheet_convert": "Convert to Sheet Metal", + "cmd.sheet_export_bend_table": "Export Bend Table", + "cmd.sheet_export_dxf": "Export Flat Pattern as DXF", + "cmd.sheet_flange": "Flange", + "cmd.sheet_flat_pattern": "Create Flat Pattern", + "cmd.sheet_fold": "Fold", + "cmd.sheet_hem": "Hem", + "cmd.sheet_manage_rules": "Sheet Metal Rules", + "cmd.sheet_path_flange": "Path Flange", + "cmd.sheet_perforate": "Perforate", + "cmd.sheet_refold": "Refold", + "cmd.sheet_rules": "List Sheet Metal Rules", + "cmd.sheet_unfold": "Unfold", + "cmd.sketch.construction_line": "Помощна права", + "cmd.sketch.construction_line.angle": "Помощна права под ъгъл", + "cmd.sketch.construction_line.bisector": "Ъглополовяща", + "cmd.sketch.construction_line.horizontal": "Хоризонтална помощна права", + "cmd.sketch.construction_line.parallel": "Успоредна помощна права", + "cmd.sketch.construction_line.perpendicular": "Перпендикулярна помощна права", + "cmd.sketch.construction_line.tangent_at": "Допирателна в точка на крива", + "cmd.sketch.construction_line.tangent_external": "Допирателна през външна точка", + "cmd.sketch.construction_line.tangent_two": "Обща допирателна", + "cmd.sketch.construction_line.vertical": "Вертикална помощна права", + "cmd.sketch_arc3d": "3D Arc", + "cmd.sketch_arc_center_point": "Center Point Arc", + "cmd.sketch_arc_tangent": "Tangent Arc", + "cmd.sketch_arc_three_point": "3-Point Arc", + "cmd.sketch_auto_constrain": "AutoConstrain", + "cmd.sketch_auto_constrain_from_datum": "AutoConstrain from datum", + "cmd.sketch_auto_project": "Auto-Project Edges on Reference", + "cmd.sketch_blend_curve": "Blend Curve", + "cmd.sketch_cancel": "Cancel Sketch", + "cmd.sketch_chain": "Chain", + "cmd.sketch_chamfer_distance_angle": "Distance and Angle Chamfer", + "cmd.sketch_chamfer_equal_distance": "Equal Distance Chamfer", + "cmd.sketch_chamfer_two_distance": "Two Distance Chamfer", + "cmd.sketch_circle_center": "Center Diameter Circle", + "cmd.sketch_circle_three_point": "3-Point Circle", + "cmd.sketch_circle_three_tangent": "3-Tangent Circle", + "cmd.sketch_circle_two_point": "2-Point Circle", + "cmd.sketch_circle_two_tangent": "2-Tangent Circle", + "cmd.sketch_constrainer": "Sketch Constrainer", + "cmd.sketch_constraint_fix": "Fix/UnFix", + "cmd.sketch_constraint_midpoint": "MidPoint", + "cmd.sketch_construction": "Normal/Construction", + "cmd.sketch_copy": "Copy Sketch Entities", + "cmd.sketch_cut": "Cut Sketch Entities", + "cmd.sketch_delete": "Delete Sketch Entities", + "cmd.sketch_dimension_text": "Move Dimension Text", + "cmd.sketch_drag": "Drag Sketch Geometry", + "cmd.sketch_drag_end": "End Sketch Drag", + "cmd.sketch_draw_dimensioned": "Draw Dimensioned Sketch Geometry", + "cmd.sketch_drawing_bounds": "Drawing Size", + "cmd.sketch_edit": "Edit Sketch", + "cmd.sketch_edit_text": "Edit Text", + "cmd.sketch_export_dxf": "Save As DXF", + "cmd.sketch_finish_auto_constrain": "Finish with AutoConstrain", + "cmd.sketch_fit_curves_to_section": "Fit Curves to Mesh Section", + "cmd.sketch_glyphs": "Constraint Glyphs", + "cmd.sketch_include_3d": "Include 3D Geometry", + "cmd.sketch_infinite": "Infinite Line", + "cmd.sketch_insert_dxf": "Insert DXF", + "cmd.sketch_insert_svg": "Insert SVG", + "cmd.sketch_inspect": "Inspect Sketch", + "cmd.sketch_intersection_curve": "Intersection Curve", + "cmd.sketch_isoparametric_curve": "Isoparametric Curve", + "cmd.sketch_line3d": "3D Line", + "cmd.sketch_line_midpoint": "Midpoint Line", + "cmd.sketch_loose_ends": "Loose Ends", + "cmd.sketch_loose_ends_tie": "Tie Loose Ends", + "cmd.sketch_move": "Move/Copy Sketch Entities", + "cmd.sketch_move3d": "Move 3D Point", + "cmd.sketch_move_point": "Drag Sketch Point", + "cmd.sketch_offset_break": "Break Offset Association", + "cmd.sketch_options": "Sketch Palette Options", + "cmd.sketch_paste": "Paste Sketch Entities", + "cmd.sketch_point3d": "3D Point", + "cmd.sketch_polygon_circumscribed": "Circumscribed Polygon", + "cmd.sketch_polygon_edge": "Edge Polygon", + "cmd.sketch_polygon_inscribed": "Inscribed Polygon", + "cmd.sketch_project_to_surface": "Project To Surface", + "cmd.sketch_rectangle_center": "Center Rectangle", + "cmd.sketch_rectangle_rounded": "Rounded Rectangle", + "cmd.sketch_rectangle_three_point": "3-Point Rectangle", + "cmd.sketch_rectangle_two_point": "2-Point Rectangle", + "cmd.sketch_redefine": "Redefine Sketch Plane", + "cmd.sketch_slot_arc_center": "Center Point Arc Slot", + "cmd.sketch_slot_arc_three_point": "Three Point Arc Slot", + "cmd.sketch_slot_center_point": "Center Point Slot", + "cmd.sketch_slot_center_to_center": "Center to Center Slot", + "cmd.sketch_slot_overall": "Overall Slot", + "cmd.sketch_snap": "Snap Inference", + "cmd.sketch_solve": "Solve Sketch", + "cmd.sketch_spline3d": "3D Spline", + "cmd.sketch_spline_control_point": "Control Point Spline", + "cmd.sketch_spline_control_point_5": "Control Point Spline (Degree 5)", + "cmd.sketch_spline_fit_point": "Fit Point Spline", + "cmd.sketch_spline_insert_point": "Add Spline Point", + "cmd.sketch_spun_profile": "Spun Profile", + "cmd.sketch_toggle_diameter": "Toggle Radius / Diameter", + "cmd.sketch_toggle_driven": "Toggle Driven Dimension", + "cmd.sketch_transform": "Transform", + "cmd.sketch_trim_path": "Trim Along Path", + "cmd.solid_align": "Align", + "cmd.solid_boundary_fill": "Boundary Fill", + "cmd.solid_bounding_solid": "Bounding Solid", + "cmd.solid_emboss": "Emboss", + "cmd.solid_move": "Move/Copy", + "cmd.solid_offset_face": "Offset Face", + "cmd.solid_press_pull": "Press Pull", + "cmd.solid_remove": "Remove", + "cmd.solid_replace_face": "Replace Face", + "cmd.solid_rib": "Rib", + "cmd.solid_split_face": "Split Face", + "cmd.solid_web": "Web", + "cmd.surface_blend": "Blend Surface", + "cmd.surface_boundary": "Boundary Surface", + "cmd.surface_extrude": "Surface Extrude", + "cmd.surface_fair": "Fair Surface", + "cmd.surface_fillet": "Surface Fillet", + "cmd.surface_loft": "Surface Loft", + "cmd.surface_match": "Match Surface", + "cmd.surface_offset": "Offset Surface", + "cmd.surface_patch": "Patch", + "cmd.surface_reverse_normal": "Reverse Normal", + "cmd.surface_revolve": "Surface Revolve", + "cmd.surface_ruled": "Ruled Surface", + "cmd.surface_stitch": "Stitch", + "cmd.surface_sweep": "Surface Sweep", + "cmd.surface_thicken": "Thicken", + "cmd.surface_unstitch": "Unstitch", + "cmd.surface_untrim": "Untrim", + "cmd.timeline_add": "Add Recorded Feature", + "cmd.timeline_compute_all": "Compute All", + "cmd.timeline_copy": "Copy Features", + "cmd.timeline_dependents": "Feature Dependents", + "cmd.timeline_export_script": "Export Command Script", + "cmd.timeline_inspect": "Inspect Feature", + "cmd.timeline_paste": "Paste Features", + "cmd.timeline_redefine": "Edit Feature", + "cmd.timeline_rename": "Rename", + "cmd.timeline_reorder": "Reorder Feature", + "cmd.timeline_roll_to": "Roll History Marker", + "cmd.timeline_rollback": "Move Timeline Marker", + "cmd.timeline_suppress": "Suppress Feature", + "cmd.view.render_browser": "Render Browser", + "cmd.view.render_dock": "Move Render Dock", + "cmd.view.render_focus": "Render Focus View", + "cmd.view_ambient_occlusion": "Ambient Occlusion", + "cmd.view_apply": "Restore Named View", + "cmd.view_back": "Back View", + "cmd.view_bottom": "Bottom View", + "cmd.view_delete": "Delete Named View", + "cmd.view_fit": "Fit", + "cmd.view_front": "Front View", + "cmd.view_graphics_preset": "Graphics Preset", + "cmd.view_grid": "Grid", + "cmd.view_ground_shadow": "Ground shadow", + "cmd.view_home": "Home view", + "cmd.view_isometric": "Isometric View", + "cmd.view_left": "Left View", + "cmd.view_list": "List Named Views", + "cmd.view_navigate": "Navigate View", + "cmd.view_navigation_bar": "Navigation bar", + "cmd.view_normal_to": "Normal to Selection", + "cmd.view_rename": "Rename Named View", + "cmd.view_right": "Right View", + "cmd.view_save": "New Named View", + "cmd.view_shots_strip": "Shots Strip", + "cmd.view_spin": "Continuous orbit", + "cmd.view_tool": "Navigation tool", + "cmd.view_top": "Top View", + "cmd.view_visual_style": "Visual style", + "color.copy": "Click to copy color values", + "color.edit": "Click to edit color", + "color.gamma": "Showing color values in 0-255 gamma space", + "color.hue": "Hue", + "color.linear": "Showing color values in 0-1 linear space", + "color.saturation_value": "Saturation and value", + "color.selected": "Selected color", + "contact.components_count": "{count} components", + "contact.enabled_label": "enabled", + "coupling.gear_1": "Gear 1", + "coupling.gear_1_pick": "Gear 1 (optional)", + "coupling.gear_2": "Gear 2", + "coupling.gear_2_pick": "Gear 2 (optional)", + "coupling.internal": "Internal gear", + "coupling.needs_turn_and_slide": "needs a joint that turns and one that slides", + "coupling.needs_turns": "needs two joints that turn", + "coupling.not_round": "not a round face", + "coupling.nut": "Nut", + "coupling.picked": "picked", + "coupling.pinion": "Pinion", + "coupling.pinion_pick": "Pinion (optional)", + "coupling.pitch": "Pitch", + "coupling.rack": "Rack", + "coupling.radius_1": "Radius 1", + "coupling.radius_2": "Radius 2", + "crash.announce": "SolidCraft closed unexpectedly or hit an internal error last time. A crash report was saved (Help > Crash Reports…).", + "crash.copy_folder": "Copy folder path", + "crash.copy_path": "Copy path", + "crash.deleted": "Deleted {count} report(s).", + "crash.detected_time": "Detected {time} UTC", + "crash.intro": "Crash reports stay on this computer and are never sent anywhere. Report… opens a draft you review before anything is shared.", + "crash.kind_command": "Internal error in a command", + "crash.kind_internal": "Internal error", + "crash.kind_kernel": "Kernel error (recovered)", + "crash.kind_unclean": "Closed unexpectedly", + "crash.previous_session": "An earlier SolidCraft session ended unexpectedly or hit an internal error. Reports from unclean exits are detected at startup. See Help > Crash Reports… for details.", + "crash.replayable": "replayable", + "crash.report": "Report…", + "crash.unclean_explanation": "Detected on a later launch; the exact exit time was not recorded. A system shutdown or forced stop can also cause an unclean exit.", + "delete.and_more": "… and {count} more", + "diagnostic.empty_boolean_component": "there is no body to cut or intersect in component '{component}'; the tool may overlap '{body}' in component '{other}' — activate that component or pick the body as a target", + "dialog.bodies_count": "{count} bodies", + "dialog.clearance_invalid": "the clearance must be a length of 0 or more", + "dialog.compute": "Compute", + "dialog.compute_again": "Compute again", + "dialog.computing": "Computing… {seconds} s", + "dialog.could_not_be_checked": "could not be checked", + "dialog.custom_axis": "↖ Custom Axis", + "dialog.dimension_insert_hint": "Click another driving dimension to insert its name", + "dialog.dimension_name": "Dimension: {name}", + "dialog.edit_title": "EDIT {title}", + "dialog.select": "↖ Select", + "dialog.selected_count": "↖ {count} selected", + "dialog.selection_guidance": "Select an input to change it. Click selected objects to remove them; Ctrl/Cmd-click also toggles them. Review the preview, then press OK.", + "dialog.selection_step": "{step} of {total}: Select {input}", + "dialog.step": "Step", + "document.changed_on_disk": "{name} changed on disk", + "document.changed_on_disk_detail": "{name} was changed by another program or computer since you opened or last saved it. Overwrite replaces those changes with yours; Save a Copy keeps both.", + "document.copy_name": "{name} copy", + "document.open_anyway": "Open Anyway", + "document.open_elsewhere": "{name} is already open", + "document.open_elsewhere_detail": "{name} is open in SolidCraft {app} on {who}, opened {when}. If you both save, one of you loses work. Open it read-only to look at it without saving over it.", + "document.open_read_only": "Open Read-Only", + "document.opened_read_only": "Opened read-only: Save asks for a new file", + "document.overwrite": "Overwrite", + "document.read_only_save": "This design was opened read-only: save it as a new file", + "document.save_changes": "Save changes to {name}?", + "document.save_copy": "Save a Copy…", + "document.unsaved_changes": "{name} has unsaved changes. If you don't save, they are lost.", + "drive.rigid": "{joint} is a rigid joint: it holds its parts still, so it has nothing to drive. To let them move, change its type in Edit Joint: Revolute to rotate, Slider to slide, Cylindrical for both.", + "drive.stopped_by_contact": "Stopped at {value}: {a} would pass through {b}", + "drive.stopped_by_loop": "Stopped at {value}: the loop through {joint} can't close any further", + "drive.unconnected": "Moves nothing: {part} is not connected to anything grounded", + "dxf.cancel_wait": "Waiting for the export to stop…", + "dxf.cancelled": "DXF export cancelled", + "dxf.cancelling": "Cancelling DXF export", + "dxf.exporting": "Exporting DXF", + "dxf.invalid_tolerance": "Curve tolerance must be between 0.0001 and 1 mm.", + "dxf.progress.index": "Preparing surfaces (2/5)", + "dxf.progress.meshes": "Preparing meshes (1/5)", + "dxf.progress.occlusion": "Resolving hidden lines (4/5)", + "dxf.progress.projection": "Projecting geometry (3/5)", + "dxf.progress.write": "Writing DXF (5/5)", + "dxf.tolerance": "Curve tolerance", + "dxf.tolerance_help": "Visible bodies and shown sketches only. Curves use straight segments. Smaller tolerance gives finer curves and uses more time and memory.", + "file.open.drawing_filter": "Designs, CAD files, meshes and drawings", + "file_load.built": "Built so far: {built} of {total} features.", + "file_load.converting": "Converting solid {done} of {total}", + "file_load.inserting": "Inserting geometry", + "file_load.link_item": "{name} ({done} of {total})", + "file_load.opening": "Opening design", + "file_load.preparing_thumbnail": "Preparing the thumbnail...", + "file_load.preparing_view": "Preparing the view...", + "file_load.preview_note": "Saved preview. Geometry is being checked before editing.", + "file_load.reading": "Reading the file...", + "file_load.reading_percent": "Reading the file... {percent}%", + "file_load.rebuilding": "Rebuilding feature {done} of {total}", + "file_load.recovering": "Recovering design", + "file_load.stopping": "Waiting for the previous operation to stop...", + "file_load.updating_links": "Updating links", + "file_load.waiting": "Waiting for file operation", + "fits the face, e.g. M8": "fits the face, e.g. M8", + "from the profile": "from the profile", + "from the rule": "from the rule", + "help.apache": "Apache licence 2.0", + "help.appearance.assign": "Gives the selected bodies, faces or components a colour or a material look, without changing their weight. Use it to tell parts apart or to preview a finish.", + "help.attributions": "Attributions (ATTRIBUTION.md)", + "help.build": "Version {version} · commit {commit} · built {date}", + "help.connect_note": "Restart each assistant to load the SolidCraft server. Each file was backed up as .bak before it changed.", + "help.connect_title": "Connect AI assistants", + "help.face.delete": "Removes the selected faces and lets the neighbouring faces close the gap, or leaves the gap open as a surface. Use it to take off a rounded edge, a hole or a boss that is in the way.", + "help.font_details": "The interface uses egui's built-in fonts (Ubuntu Light and Hack, under the Ubuntu Font Licence and the MIT/Bitstream Vera licence; Noto Emoji and the emoji icon font, under the OFL and MIT). Sketch text uses Liberation Sans (SIL OFL 1.1). The Crafting Apps' optional font pack, craft-fonts (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC, Noto Sans Arabic; SIL OFL 1.1), is not bundled in SolidCraft builds.", + "help.fonts": "Fonts", + "help.licences": "Licences", + "help.material.assign": "Sets what the selected bodies are made of, such as steel, aluminium or ABS. Use it so that the mass and weight match the real part.", + "help.mit": "MIT licence", + "help.notice": "NOTICE", + "help.parameters.change": "Opens the table of named values and expressions that drive the dimensions of the design. Use it to change a size in one place and let every feature that uses it follow.", + "help.solid.align": "Moves the selected bodies so that a point, face or plane on them meets a point, face or plane elsewhere. Use it to place a part against another one without measuring the offset.", + "help.solid.chamfer": "Cuts the selected edges with a flat bevel of the distance you set. Use it to break sharp edges or to ease the entry of a pin or screw.", + "help.solid.combine": "Joins bodies, cuts them out of a target body, or keeps only the volume they share, and can keep the tool bodies. Use it to merge parts, to cut one shape with another or to find where two bodies overlap.", + "help.solid.draft": "Tilts the selected faces by the angle you set, measured from a neutral plane. Use it on moulded or cast parts so that they slide out of the mould.", + "help.solid.extrude": "Pushes a sketch profile into 3D along a distance, adding or removing material. Use it to turn a flat outline into a block, a boss or a pocket.", + "help.solid.fillet": "Rounds the selected edges with a smooth circular blend of the radius you set. Use it to soften sharp edges for strength, comfort or looks.", + "help.solid.hole": "Drills a round hole of the diameter you set at a chosen point on a face. Use it for screw clearances, pins and other simple round openings.", + "help.solid.loft": "Blends a smooth solid between two or more sketch profiles, or from a profile to a point. Use it for transitions, funnels, handles and any shape that changes section along its length.", + "help.solid.mirror": "Makes a mirrored copy of the selected bodies or features across a plane, and can merge it with the original. Use it for symmetric parts, so that you model one half and get both.", + "help.solid.move": "Moves or rotates the selected bodies, or a copy of them, by the distance and angle you set. Use it to reposition a body or to make a second one in another place.", + "help.solid.offset_face": "Pushes the selected faces in or out by the distance you set, and the faces around them follow. Use it to make a wall thicker, a pocket deeper or a boss taller without editing the sketch.", + "help.solid.pattern.circular": "Repeats the selected objects around an axis, for the count and total angle you set. Use it for bolt circles, spokes, fins and teeth.", + "help.solid.pattern.rectangular": "Repeats the selected objects in one or two directions with the count and spacing you set. Use it for rows and grids of holes, ribs, pins or feet.", + "help.solid.press_pull": "Adds or removes material as you drag a face, or rounds edges as you drag them. Use it for quick changes straight on the model.", + "help.solid.remove": "Takes the selected bodies out of the design from this point in the timeline on; earlier steps keep them. Use it to drop a helper body, such as a cutting tool you no longer need.", + "help.solid.replace_face": "Moves the selected flat faces onto a plane or onto a parallel face, and the body grows or shrinks to meet it. Use it to bring a face flush with another part or a construction plane.", + "help.solid.revolve": "Spins a sketch profile around an axis to make a round solid. Use it for shafts, knobs, bowls and any part that is round about a centre line.", + "help.solid.scale": "Makes the selected bodies larger or smaller by a factor, the same in every direction or one per axis. Use it to resize an imported shape or to allow for shrinkage.", + "help.solid.shell": "Hollows out a solid, leaving walls of the thickness you set, and can open the faces you pick. Use it for boxes, covers and other thin-walled parts.", + "help.solid.split_body": "Cuts a body into separate bodies with a plane, the face of another body or a sketch line. Use it to make parts that are printed, machined or coloured on their own.", + "help.solid.split_face": "Divides the selected faces along a plane, the face of another body or sketch curves, without cutting the body. Use it to give part of a face its own draft, colour or offset.", + "help.solid.sweep": "Drags a sketch profile along a path to make a solid. Use it for pipes, rails, handles and any part of constant section that follows a curve.", + "help.third_party": "Third-party licences", + "help.timeline.compute_all": "Rebuilds every feature in the timeline from the start. Use it to refresh the model and to see which features fail.", + "help.timeline.delete": "Deletes the selected features from the timeline; deleting a sketch also deletes the features built from it. Use it to remove a step that is no longer wanted.", + "hole_presets.confirm_delete": "Confirm delete", + "hole_presets.delete": "Delete", + "hole_presets.delete_prompt": "Delete this personal preset? Existing holes are unchanged.", + "hole_presets.full": "The personal library already contains 64 presets.", + "hole_presets.invalid_name": "Enter a short name without line breaks or control characters.", + "hole_presets.invalid_parameters": "Complete the hole parameters using valid expressions of reasonable length.", + "hole_presets.missing": "The selected preset is no longer available.", + "hole_presets.name": "Preset name", + "hole_presets.name_exists": "A preset with this name already exists. Use a different name.", + "hole_presets.name_hint": "A unique name", + "hole_presets.overwrite": "Save changes to selected preset", + "hole_presets.preset": "Preset", + "hole_presets.recall": "Recall", + "hole_presets.rename": "Rename", + "hole_presets.save": "Save new", + "hole_presets.scope": "Saved in your profile for all projects.", + "hole_presets.select": "Select a preset", + "hole_presets.title": "Personal presets", + "hole_presets.unsupported_options": "This preset uses thread options that this version cannot recall.", + "hole_presets.unsupported_overwrite": "This preset contains options that cannot be overwritten safely.", + "home.back": "Back to {name}", + "home.crashes": "Crash reports", + "home.design_workspace": "Design", + "home.documentation": "Documentation", + "home.export": "Export", + "home.export_hint": "Choose a format for the current design.", + "home.export_json_hint": "Editable design and command history", + "home.export_mesh_hint": "Mesh for printing or sharing", + "home.export_step_hint": "Precise solid geometry", + "home.import": "Import…", + "home.import_hint": "STEP, IGES or mesh into a new design", + "home.in_this_browser": "in this browser", + "home.missing": "missing", + "home.month_01": "Jan", + "home.month_02": "Feb", + "home.month_03": "Mar", + "home.month_04": "Apr", + "home.month_05": "May", + "home.month_06": "Jun", + "home.month_07": "Jul", + "home.month_08": "Aug", + "home.month_09": "Sep", + "home.month_10": "Oct", + "home.month_11": "Nov", + "home.month_12": "Dec", + "home.new_inches": "New design, inches", + "home.new_inches_hint": "Inches · opens in Design", + "home.new_mm": "New design", + "home.new_mm_hint": "Millimetres · opens in Design", + "home.open": "Open…", + "home.open_hint": "A .sc design ({shortcut})", + "home.open_now": "Open now", + "home.opened_days_ago": "{count} days ago", + "home.opened_hours_ago": "{count} h ago", + "home.opened_just_now": "Just now", + "home.opened_minutes_ago": "{count} min ago", + "home.opening": "opening…", + "home.properties": "Design properties", + "home.recent": "Recent", + "home.recent_empty": "Designs you open or save appear here.", + "home.recovery_count": "Recoverable designs: {count}", + "home.recovery_empty": "No recoverable designs.", + "home.recovery_hint": "SolidCraft closed before these designs were saved.", + "home.report_issue": "Report an Issue", + "home.samples": "Samples", + "home.settings": "Settings", + "home.short_date": "{day} {month}", + "home.shortcuts": "Keyboard shortcuts", + "home.start_hint": "Create a design, open a recent file, or explore a sample.", + "home.whats_new": "What's new", + "home.yesterday": "Yesterday", + "install.button_tip": "Install SolidCraft as an app: it opens in its own window and works offline", + "install.dock_1": "Choose File › Add to Dock.", + "install.dock_2": "Click Add.", + "install.dock_after": "SolidCraft then opens in its own window from the Dock, and works offline.", + "install.done": "Done", + "install.home_screen_1": "Tap Share (in the … menu if it isn't on the toolbar).", + "install.home_screen_2": "Choose Add to Home Screen.", + "install.home_screen_3": "Tap Add.", + "install.home_screen_after": "SolidCraft then opens from its icon on the Home Screen, without Safari's toolbars, and works offline.", + "install.menu": "Install app…", + "install.steps_intro": "Safari installs web apps from its own menus:", + "install.title": "Install SolidCraft", + "issue.body_label": "Report text", + "issue.note_changed_while_waiting": "Settings or model changed while waiting for the preview. Retake the screenshot to update the technical details for the current view.", + "issue.note_details_kept": "Screenshot captured locally. Your edited technical details were kept: check that they still match the current view.", + "issue.note_details_updated": "Technical details updated to match the current view. Screenshot captured locally. Review it before attaching it on GitHub.", + "issue.note_image_copied": "Paste the image into the GitHub draft, or save the PNG if image copying is unavailable.", + "issue.note_opened": "Review the GitHub draft and attach the screenshot. GitHub's Submit new issue button publishes it.", + "issue.note_opened_copied": "Report copied. Paste into the GitHub draft, attach the screenshot, then click Submit new issue on GitHub.", + "issue.note_removed": "Screenshot removed from this draft.", + "issue.note_report_copied": "Report copied. Paste it into the GitHub draft if needed.", + "issue.note_save_failed": "Could not save screenshot: {error}", + "issue.note_saved": "Screenshot saved. Attach the PNG in the GitHub draft.", + "issue.save_screenshot": "Save screenshot…", + "joint.from_bodies_hint": "Each picked body moves into a new component of its own and stays where it is.", + "joint.one_body": "Both picks are on {body}. Pick the second one on another part.", + "joint.one_component": "These parts are bodies of one component: {bodies}. A joint moves one component against another, so each part needs a component of its own.", + "joint.rigid_group_one_component": "These {count} bodies are all in one component (or in the design itself): use {command} first.", + "joint.rigid_group_select_components": "Select two or more components.", + "keymap.command_id": "Command ID", + "keymap.empty": "No matching commands", + "keymap.use_anyway": "Use {key} here anyway", + "label.move_to_left_side": "Move to left side", + "label.move_to_right_side": "Move to right side", + "manage.appearance_hint": "Choose a look for the selection, or drag a swatch onto a body or face.", + "manage.assign_hint": "Select bodies and choose their plastic design rule.", + "manage.config_hint": "Edit configuration rows, columns and rules, then activate or preview a row.", + "manage.empty": "No matching rows.", + "manage.material_hint": "Select bodies and choose their physical material.", + "manage.parameters_hint": "Edit expressions and units. Changes apply on Enter or when leaving a field.", + "manage.rules_hint": "Choose a rule to edit, or create a new rule. Confirm to save the rule.", + "material.editor.add_property": "Add property", + "material.editor.add_source": "Add source", + "material.editor.assigned_density": "Assigned density", + "material.editor.axes": "Material axes", + "material.editor.axes_numeric": "1 / 2 / 3", + "material.editor.axes_wood": "L / R / T", + "material.editor.copy_name": "Copy of {name}", + "material.editor.density_range": "Assigned density must be above 0 and at most 1000 g/cm³.", + "material.editor.designation": "Designation", + "material.editor.duplicate": "Duplicate", + "material.editor.engineering_card": "Engineering property card", + "material.editor.family": "Material family", + "material.editor.glass": "Glass", + "material.editor.illustrative": "Illustrative", + "material.editor.invalid_property": "Unsupported property type.", + "material.editor.isotropic": "Isotropic", + "material.editor.measurement": "Measurement", + "material.editor.metal": "Metal", + "material.editor.moisture": "Moisture, dry basis", + "material.editor.name_required": "Enter a name with 1–128 characters.", + "material.editor.no_draft": "No material draft is open.", + "material.editor.number_required": "Enter a finite numeric value.", + "material.editor.orthotropic": "Orthotropic", + "material.editor.other": "Other", + "material.editor.polymer": "Polymer", + "material.editor.preserved_appearance": "Preserved appearance", + "material.editor.public_reference": "Public reference", + "material.editor.reference": "Reference", + "material.editor.save_or_discard": "Save or discard the material draft before assigning a material.", + "material.editor.saved": "Material saved. Body assignments are unchanged.", + "material.editor.scope": "Save stores this material without assigning it to bodies. Blank properties and conditions remain unknown. Card density does not change assigned density or mass.", + "material.editor.source_id": "Source ID", + "material.editor.source_kind": "Source type", + "material.editor.source_title": "Source title", + "material.editor.sources": "Sources", + "material.editor.stale": "This material changed while the draft was open. Discard and reopen it before saving.", + "material.editor.state": "Material state", + "material.editor.strain_rate": "Strain rate", + "material.editor.symmetry": "Elastic symmetry", + "material.editor.temperature": "Temperature", + "material.editor.unknown_card": "Engineering properties are unknown. Save may keep only the assigned density and existing appearance.", + "material.editor.user_supplied": "User supplied", + "material.editor.wood": "Wood", + "material.selection.choose": "Choose a material", + "material.selection.mixed": "Different materials", + "measure.at": "At", + "measure.item": "Item {number}", + "messages.ago_h": "{n} h ago", + "messages.ago_min": "{n} min ago", + "messages.ago_s": "{n} s ago", + "messages.chip_hint": "Click for all messages of this session", + "messages.clear": "Clear", + "messages.copy_all": "Copy all", + "messages.menu": "Messages…", + "messages.none": "No messages yet.", + "messages.title": "Messages", + "motion.checked_to": "Checked to step {step} only: the check ran out of its work budget", + "motion.collision": "{a} · {b}: steps {steps}", + "motion.delete_key": "Delete key", + "motion.duration_hint": "seconds (empty: per step)", + "motion.key_here": "Key here", + "motion.key_here_hint": "Add a key at this step with the joint's value now", + "motion.no_collisions": "No collisions over the study", + "motion.plot_quantity": "Quantity", + "motion.step_back": "Step back", + "motion.step_forward": "Step on", + "motion.to_end": "To the end", + "motion.to_start": "To the start", + "motion.track_name": "Track {number}", + "nav.alias.help": "Shift+Alt+left drag orbits, Shift+Alt+middle pans, Shift+Alt+right zooms; middle drag also pans and right drag orbits", + "nav.blender.help": "Middle drag orbits, Shift+middle pans, Ctrl+middle zooms; right drag leaves the camera alone", + "nav.free_orbit.help": "Mouse and 3D mouse rotate through both poles and preserve roll. Shift axis snapping is disabled.", + "nav.free_orbit.label": "Free orbit", + "nav.free_orbit.snap_help": "Mouse and 3D mouse rotate through both poles and preserve roll. Hold Shift during an orbit drag to snap the view direction and roll.", + "nav.free_orbit_upright.help": "Sideways mouse drags spin the model around the world's vertical axis; up and down drags tilt over the top without a limit.", + "nav.free_orbit_upright.label": "Turn around the vertical axis", + "nav.fusion.help": "Middle drag pans, Shift+middle orbits, right drag orbits", + "nav.hfss.help": "Alt+left drag pans, Shift+Alt+left zooms, Ctrl+left drag on empty space orbits", + "nav.inventor.help": "Middle drag pans, Shift+middle orbits, Ctrl+middle zooms, right drag orbits", + "nav.maya.help": "Alt+left drag orbits, Alt+middle pans, Alt+right zooms; middle drag also pans", + "nav.openscad.help": "Left drag on empty space orbits, Shift+left drag box-selects, sketch geometry drags edit; right or middle drag pans, Shift+right or Shift+middle drag zooms", + "nav.perspective.sketch": "Sketch editing uses orthographic view. Finish the sketch to switch perspective.", + "nav.solidworks.help": "Middle drag orbits, Ctrl+middle pans, Shift+middle zooms, right drag orbits", + "nav.tinkercad.help": "Right drag orbits, middle or Shift+right drag pans", + "nav.touchpad.help": "Hold Shift and move the pointer to pan; hold Alt/Option and move it to orbit. No mouse button is needed. Vertical scroll zooms.", + "nav.touchpad.label": "Touchpad", + "nav.touchpad.orbit": "Orbit (hold Alt/Option and move; no mouse button)", + "nav.touchpad.pan": "Pan (hold Shift and move; no mouse button)", + "nav.touchpad.scroll": "Touchpad uses vertical scroll to zoom. Your two-finger pan setting is kept for other presets.", + "nav.touchpad.zoom": "Zoom (vertical scroll or pinch)", + "navbar.agent_chat": "Assistant chat panel", + "navbar.agent_cursor": "Show agent cursor", + "navbar.ambient_occlusion": "Ambient occlusion", + "navbar.assistant": "Assistant", + "navbar.custom.add_slot": "Add {slot}", + "navbar.custom.always": "Always visible", + "navbar.custom.available": "{available} · drag onto the bar, or press Add", + "navbar.custom.buttons": "Buttons", + "navbar.custom.compact": "Compact", + "navbar.custom.count": "{count} of 16 slots", + "navbar.custom.customise": "Customise navigation bar…", + "navbar.custom.design": "Design", + "navbar.custom.duplicate": "This slot is already on the bar.", + "navbar.custom.fade": "Fade", + "navbar.custom.full": "Remove a slot to add another.", + "navbar.custom.hidden_design": "Hidden in Design", + "navbar.custom.hidden_render": "Hidden in Render", + "navbar.custom.hide": "Hide navigation bar", + "navbar.custom.hide_idle": "Hide until hovered", + "navbar.custom.icon_only": "Icon only", + "navbar.custom.icon_value": "Icon and value", + "navbar.custom.icons": "Icons", + "navbar.custom.idle": "When idle", + "navbar.custom.intro": "Choose the controls on the bar at the bottom of the 3D view, and in what order. Drag a slot to move it, or drag it off the bar to remove it.", + "navbar.custom.labels": "Icons and labels", + "navbar.custom.left": "Move left", + "navbar.custom.position": "Position", + "navbar.custom.position_centre": "Centre", + "navbar.custom.position_left": "Left", + "navbar.custom.position_right": "Right", + "navbar.custom.preview_as": "Preview as", + "navbar.custom.regular": "Regular", + "navbar.custom.remove": "Remove", + "navbar.custom.remove_bar": "Remove from bar", + "navbar.custom.render": "Render", + "navbar.custom.reset": "Reset navigation bar", + "navbar.custom.reset_default": "Reset to default", + "navbar.custom.right": "Move right", + "navbar.custom.select": "No slot selected. Select a slot on the bar to move it, remove it or change how it looks.", + "navbar.custom.separators_full": "The bar already has four separators.", + "navbar.custom.show": "Show navigation bar", + "navbar.custom.shows": "Shows", + "navbar.custom.size": "Size", + "navbar.custom.stale": "The bar changed. Select the slot again.", + "navbar.custom.title": "Navigation bar", + "navbar.custom.unknown": "This slot is not available.", + "navbar.description.ambient_occlusion": "Darkens creases and corners to add depth.", + "navbar.description.display": "Holds the view settings: graphics preset, grid, ground shadow, ambient occlusion and projection.", + "navbar.description.fit": "Frames the selection, or the whole model if nothing is selected.", + "navbar.description.grid": "Shows or hides the ground grid.", + "navbar.description.ground_shadow": "Shows or hides the shadow under the model.", + "navbar.description.home": "Returns to the isometric view of the whole model.", + "navbar.description.look_at": "Turns the view to face the selected face, plane or open sketch.", + "navbar.description.orbit": "Turns the view around the model.", + "navbar.description.pan": "Slides the view sideways, up or down.", + "navbar.description.projection": "Switches between orthographic and perspective views.", + "navbar.description.separator": "A thin line that groups neighbouring slots.", + "navbar.description.spin": "Keeps the view turning until you click or press a key.", + "navbar.description.visual_style": "Switches how the model is drawn: shaded, wireframe or with hidden edges.", + "navbar.description.zoom": "Moves the view closer to or further from the model.", + "navbar.display": "Display", + "navbar.fit": "Fit", + "navbar.graphics": "Graphics", + "navbar.grid": "Grid", + "navbar.ground_shadow": "Ground shadow", + "navbar.home": "Home", + "navbar.later": "Later", + "navbar.look_at": "Look at", + "navbar.more": "More", + "navbar.orbit": "Orbit", + "navbar.orthographic": "Orthographic", + "navbar.pan": "Pan", + "navbar.perspective": "Perspective", + "navbar.preset": "Preset", + "navbar.projection": "Projection", + "navbar.projection_heading": "Projection", + "navbar.separator": "Separator", + "navbar.show": "Show", + "navbar.spin": "Spin", + "navbar.style.shaded": "Shaded", + "navbar.style.shaded_with_edges": "Shaded with edges", + "navbar.style.shaded_with_hidden_edges": "Shaded with hidden edges", + "navbar.style.wireframe": "Wireframe", + "navbar.translucent": "Translucent", + "navbar.value_tip": "{name} · {value}", + "navbar.visual_style": "Visual style", + "navbar.zoom": "Zoom", + "needs two joints": "needs two joints", + "network.allow_once": "Allow once", + "network.always_allow": "Always allow this server", + "network.prompt_detail": "This design links to a file on network location {host}. Opening it connects to that computer and may send your Windows sign-in to it. Only allow servers you trust.", + "network.prompt_title": "Network location", + "new configuration": "new configuration", + "new parameter": "new parameter", + "no hole": "no hole", + "no interference": "no interference", + "no joint that moves yet": "no joint that moves yet", + "no picture": "no picture", + "none": "none", + "parts.automatic_name": "automatic", + "pattern.alignment_2": "Alignment 2", + "pattern.alignment_hint": "Counts include the original. Center balances copies; Flip chooses the extra side for even totals.", + "pattern.direction_1": "Direction 1", + "pattern.direction_2": "Direction 2", + "pattern.flip_direction": "Flip direction", + "perf.click_for_details": "Click for details: frame-time graph, histogram and what the GPU drew", + "perf.draw_calls": "Draw calls", + "perf.line_segments": "Line segments", + "perf.low_1": "1% low", + "perf.renderer": "Renderer", + "perf.scene_build": "Scene build", + "perf.triangles": "Triangles", + "perf.ui_time": "UI time", + "perf.viewport": "Viewport", + "perf.worst": "worst", + "pick a hole to seat it, or OK places it at the origin": "pick a hole to seat it, or OK places it at the origin", + "pick one or two vertices, edges or faces": "pick one or two vertices, edges or faces", + "pick the path": "pick the path", + "prefs.add_item": "Add the item", + "prefs.alt_frees_manipulators": "Alt / Option also frees manipulator arrows", + "prefs.anti_aliasing_amd_dx12": "Anti-aliasing uses 1× because the startup check drew nothing with multisampling and passed at 1×. You can choose another setting above; restart to apply it if the check passes.", + "prefs.anti_aliasing_note": "Smooths jagged edges.", + "prefs.applies_on_restart": "Applies on restart", + "prefs.assistant": "Assistant", + "prefs.axes": "Axes", + "prefs.axis": "Axis", + "prefs.bodies_folders": "Bodies folders", + "prefs.bodies_folders_always": "Always", + "prefs.bodies_folders_never": "Never", + "prefs.bodies_folders_several": "Several bodies only", + "prefs.bottom": "Bottom", + "prefs.browser": "Browser", + "prefs.built_in": "Built in", + "prefs.button_left": "Left drag", + "prefs.button_middle": "Middle drag", + "prefs.button_right": "Right drag", + "prefs.choose_font": "Choose font file…", + "prefs.click": "Click", + "prefs.contact_shading": "Soft contact shading", + "prefs.contact_shading_note": "Soft shading where parts come close.", + "prefs.context_menu": "Context menu", + "prefs.context_menu_ring": "Context menu · hold for the radial menu", + "prefs.cpu": "CPU (software)", + "prefs.crash_reports": "Open crash reports…", + "prefs.crash_reports_note": "Reports are kept on this computer, with the design and commands that reproduce the problem.", + "prefs.ctrl_cmd": "Ctrl / Cmd", + "prefs.curved_surfaces": "Curved surfaces", + "prefs.curves": "Curved surfaces", + "prefs.dead_zone_note": "The hatched band is the dead zone: motion inside it is ignored.", + "prefs.default": "default", + "prefs.design": "Design defaults", + "prefs.design_note": "What new designs start with. Open designs keep their own.", + "prefs.devices": "3D mouse", + "prefs.dialog_buttons": "Dialog buttons", + "prefs.dialogs": "Dialogs", + "prefs.dialogs_edge": "At the view's edge", + "prefs.dialogs_left_column": "In the left column", + "prefs.dialogs_note": "Where command dialogs open: docked at the view's edge, or in the left column in place of the browser and the History, which come back as they were when the dialog closes.", + "prefs.display": "Display", + "prefs.edges": "Edges and shading", + "prefs.extend": "Extend", + "prefs.extra_navigation": "Ctrl+left drag on empty space orbits; hold Space to pan.", + "prefs.follows_os": "Follows the OS", + "prefs.font": "Font", + "prefs.font_fallback": "Glyphs the chosen font lacks fall back to the built-in font, so no label shows an empty box.", + "prefs.font_sample": "The quick brown fox · Ø12.50 mm · 45.0° · 0123456789", + "prefs.font_unreadable": "The selected font could not be read.", + "prefs.general": "General", + "prefs.general_note": "Language, saving and updates.", + "prefs.gesture_orbit": "Orbit", + "prefs.gesture_pan": "Pan", + "prefs.gesture_zoom": "Zoom", + "prefs.graphics": "Graphics", + "prefs.graphics_card": "Graphics card", + "prefs.graphics_card_auto": "Automatic", + "prefs.graphics_card_missing": "The saved graphics card is unavailable; Automatic is used.", + "prefs.graphics_card_restart": "Takes effect after restarting SolidCraft. WGPU_ADAPTER_NAME overrides this choice.", + "prefs.graphics_note": "Trade speed for smoothness. Each choice shows its effect on a sample.", + "prefs.graphics_presets_note": "Presets set the choices below together.", + "prefs.history": "History", + "prefs.history_origin_bodies": "Show origin and bodies at the top", + "prefs.history_origin_bodies_note": "The History on the left or under the browser starts with the active component's Bodies folder and the Origin, with their eyes and menus as in the browser. The History at the bottom is unchanged.", + "prefs.history_sketches": "Sketches", + "prefs.history_sketches_in_order": "In order", + "prefs.history_sketches_note": "With Sketches set to Under their feature, the History at the left lists each sketch one level in, under the first feature built from it, whenever it is wide enough for names. The timeline at the bottom always keeps the creation order.", + "prefs.history_sketches_under_feature": "Under their feature", + "prefs.hold_stop_snapping": "Hold to stop snapping", + "prefs.icons_only": "Icons only", + "prefs.imported_file": "Imported file", + "prefs.input": "Input", + "prefs.interface": "Interface", + "prefs.interface_language": "Interface language", + "prefs.interface_note": "How SolidCraft looks and where its parts sit.", + "prefs.interval_minutes": "{n} min", + "prefs.labels": "Labels", + "prefs.layout": "Layout", + "prefs.layout_note": "Compact docks panels to the window edges. Browser translucency is available in Floating. Change the Assistant side on the Assistant page.", + "prefs.left": "Left", + "prefs.left_click": "Left click", + "prefs.live_input": "Live input", + "prefs.live_preview": "Live preview", + "prefs.minutes": "minutes", + "prefs.minutes_suffix": " min", + "prefs.mouse": "Mouse and trackpad", + "prefs.mouse_heading": "Mouse", + "prefs.mouse_mapping": "Mouse mapping", + "prefs.navigation": "Navigation", + "prefs.navigation_note": "How the mouse, trackpad and 3D mouse move the view.", + "prefs.network_host_remove": "Remove", + "prefs.network_locations": "Allow network locations in designs", + "prefs.network_locations_note": "Off: a design's linked files on another computer (\\\\server\\share) are opened only from the servers listed here, or after you allow one when asked.", + "prefs.network_locations_section": "Network locations", + "prefs.not_on_gpu": "not on this GPU", + "prefs.on": "On", + "prefs.opaque": "Opaque", + "prefs.orbit_snap": "Hold Shift during orbit to snap to an axis.", + "prefs.orientation": "Orientation", + "prefs.origin_plane_names": "Origin plane names", + "prefs.origin_plane_names_note": "Names shown in the browser, dialogs and lists. {top} is XY, {front} is XZ and {right} is YZ, with Z up. Commands, scripts and saved designs keep XY, XZ and YZ.", + "prefs.overall_speed": "Overall speed", + "prefs.placement": "Placement", + "prefs.prefer_free_sketch_points": "Prefer movable sketch points when points overlap", + "prefs.preview_choices": "Preview of your choices", + "prefs.quality_default": "default", + "prefs.quality_fastest": "fastest", + "prefs.quality_slowest": "slowest", + "prefs.quality_smoother": "smoother", + "prefs.reports_saved": "{n} saved", + "prefs.right_click": "Right click", + "prefs.saving": "Autosave and recovery", + "prefs.scale_note": "Also Ctrl + / Ctrl − in the window. Buttons are 28 px at 100%.", + "prefs.scale_text": "Scale and text", + "prefs.search": "Search settings", + "prefs.search_empty": "No matching settings", + "prefs.select": "Select", + "prefs.select_one_item": "Select one item", + "prefs.selecting": "Selecting", + "prefs.shift": "Shift", + "prefs.shift_add_ctrl_toggle": "Shift adds only; Ctrl / Cmd toggles", + "prefs.shift_add_note": "On: Shift adds, Ctrl / Cmd toggles. Off (default): both toggle.", + "prefs.shortcuts": "Shortcuts", + "prefs.sketch_exit_view": "When a sketch ends", + "prefs.sketch_exit_view.keep": "Keep the current view", + "prefs.sketch_exit_view.previous": "Return to the previous view", + "prefs.sketch_exit_view.unless_rotated": "Return unless rotated", + "prefs.sketch_exit_view_note": "Where the view goes after Finish Sketch, Cancel or a double Esc.", + "prefs.sketch_selection": "Sketch & selection", + "prefs.sketch_selection_heading": "Sketch and selection", + "prefs.sketch_selection_note": "How sketches snap and how clicks select.", + "prefs.sketching": "Sketching", + "prefs.snap_drawing_note": "While drawing or dragging a sketch point.", + "prefs.source": "Source", + "prefs.speed": "Speed", + "prefs.stand_up_note": "After a STEP or IGES file opens with Z up, offer a quarter turn about X.", + "prefs.status_done": "Done", + "prefs.status_error": "Error", + "prefs.status_selected": "Selected", + "prefs.status_warning": "Warning", + "prefs.supersampling_brief": "Draws the view larger and filters it down: very crisp, and heavier.", + "prefs.tab_accent_note": "The accent follows the active tab", + "prefs.theme_file": "theme file", + "prefs.theme_follow": "Follow a theme file", + "prefs.theme_follow_error": "Not applied: {error}. The last good theme stays on.", + "prefs.theme_follow_launch": "Followed for this run only (--theme-file); reloaded whenever another tool rewrites it.", + "prefs.theme_follow_note": "Reloaded whenever another tool rewrites it. Choosing a theme stops following it.", + "prefs.theme_follow_off": "Off", + "prefs.theme_follow_stop": "Stop following", + "prefs.timeline_half_hour": "−30 min", + "prefs.timeline_now": "now", + "prefs.timeline_quarter_hour": "−15", + "prefs.toggle_item": "Add the item, or take it out again", + "prefs.toolbar": "Toolbar", + "prefs.top": "Top", + "prefs.translucent": "Translucent", + "prefs.under_browser": "Under browser", + "prefs.under_cursor": "Under cursor", + "prefs.units_precision": "Units and precision", + "prefs.updates": "Updates", + "prefs.view": "View behavior", + "prefs.view_confirm_corner": "OK and Cancel in the view's corner", + "prefs.view_confirm_corner_note": "While a dialog or a sketch is open, a check and a cross at the top right of the view do what the dialog's OK and Cancel do, or finish and cancel the sketch. The view navigator moves down below them.", + "prefs.viewport": "Viewport", + "prefs.wheel": "Wheel", + "prefs.wheel_trackpad": "Wheel and trackpad", + "prefs.workspace": "Workspace", + "prefs.zoom_toward_cursor": "Zoom, toward the cursor", + "properties.title": "Properties: {name}", + "recovery.days_ago": "{count} days ago", + "recovery.detail": "{file} · {features} features · autosaved {when}", + "recovery.hours_ago": "{count} h ago", + "recovery.just_now": "just now", + "recovery.min_ago": "{count} min ago", + "recovery.never_saved": "never saved", + "render.adaptive_absolute": "Absolute RGB error floor", + "render.adaptive_coverage": "Coverage error target", + "render.adaptive_enable": "Allocate samples with independent pilots", + "render.adaptive_help": "GPU only. Independent pilot samples are discarded, then allocate 16 or more production samples per pixel up to Samples per pixel. RGB and coverage variance guide allocation; rare paths may be missed and capped pixels may remain noisy. The final report counts actual work. No certified noise or time guarantee.", + "render.adaptive_minimum": "Minimum production samples", + "render.adaptive_pending": "GPU independent-pilot adaptive allocation and conditional Fresnel strata are available. Certified convergence, rare-event guarantees and CPU adaptive transport remain unavailable.", + "render.adaptive_pilots": "Pilot samples per pixel", + "render.adaptive_relative": "Relative RGB error target", + "render.add_ground": "Add fitted ground to setup", + "render.advanced_material_scope": "One finite homogeneous GPU medium is available under explicit limits. Density grids, nested glass/volume combinations, subsurface surfaces, displacement, spectral transport and unbound advanced material concepts remain unavailable.", + "render.aging_add": "Add aging layer", + "render.aging_airborne": "Airborne dust / participating medium", + "render.aging_airborne_help": "Airborne dust is a separate finite homogeneous scattering volume. It changes transport and raw EXR, not the surface-aging stack. Existing volume/glass/denoising restrictions remain explicit; no atmosphere is added automatically.", + "render.aging_all_bodies": "All eligible opaque bodies", + "render.aging_chips": "Chipped paint", + "render.aging_class_any": "All opaque material classes", + "render.aging_class_dielectric": "Nonmetallic surfaces only", + "render.aging_class_metal": "Metallic surfaces only", + "render.aging_color": "Layer colour · sRGB", + "render.aging_coverage": "Coverage", + "render.aging_dust": "Deposited dust", + "render.aging_empty": "No aging layers: the original surfaces remain unchanged.", + "render.aging_fading": "Faded coating", + "render.aging_grime": "Grime & staining", + "render.aging_help": "Combine up to eight optical layers, in order. Rust and patina are authored appearances, not age/corrosion simulations. Scale is in world millimetres. No geometry, mass or engineering property is changed; glass and passive stages are excluded.", + "render.aging_metallic": "Layer metallic fraction", + "render.aging_origin": "Field origin · world mm", + "render.aging_patina": "Copper-green patina", + "render.aging_refresh_targets": "Inspect current bodies", + "render.aging_roughness": "Layer roughness", + "render.aging_rust": "Oxidized iron / rust", + "render.aging_scale": "Pattern scale", + "render.aging_scratches": "Fine scratches", + "render.aging_target": "Target & coordinates", + "render.aging_target_help": "A named target must still match its captured index and name. Global masks are world-anchored; they do not follow moving parts. This is neither cavity detection nor true edge wear. Filter the list to reach additional bodies.", + "render.aging_target_search": "Filter body names", + "render.aging_upward": "Upward-facing deposition", + "render.all_controls_help": "Dense inspection of all current controls. Section pages provide focused editing without changing the underlying request.", + "render.all_shots_label": "All Shots", + "render.appearance_physics_separate": "Visual appearance does not assign density, thermal data or other engineering properties.", + "render.availability_native": "Native composition; review before applying", + "render.availability_projection": "Supported projection; see scope and omissions", + "render.availability_reference": "Reference data; not an automatic assignment", + "render.backdrop_alpha_conflict": "Choose this backdrop or transparent PNG output; the renderer will not silently ignore either setting.", + "render.backdrop_enable": "Use camera-only gradient backdrop", + "render.backdrop_first": "Start / center color", + "render.backdrop_help": "This screen-space backdrop does not illuminate, cast shadows, reflect or represent terrain. It is excluded from raw EXR. Geometry, lights and the HDR environment stay independent.", + "render.backdrop_horizontal": "Horizontal gradient", + "render.backdrop_radial": "Radial gradient", + "render.backdrop_radius": "Radius", + "render.backdrop_second": "End / edge color", + "render.backdrop_vertical": "Vertical gradient", + "render.backdrop_x": "Center X", + "render.backdrop_y": "Center Y", + "render.background": "Scene background", + "render.background_camera_section": "Camera background · PNG presentation", + "render.background_completed_frozen": "The displayed result is a frozen completed image. Editing a background does not repaint that result automatically. Use Regrade for camera-only changes, or Render for a new physical stage.", + "render.background_hdr_separate": "The current HDR resources illuminate and reflect on surfaces; they are not automatically displayed as a panorama behind the subject. Changing a gradient does not rotate or recolour the lighting.", + "render.background_lighting_section": "HDR illumination · separate from camera background", + "render.background_no_alpha_override": "A camera background is not added to transparent output silently. Raw-master regrading uses captured coverage and does not reapply denoising; the source EXR remains unchanged.", + "render.background_not_light": "Background color is presentation, not an additional lighting source.", + "render.background_regrade": "Apply to retained raw master", + "render.background_stage_occlusion": "This shot includes physical stage geometry. A large floor or wall can fill the frame and hide a camera-only background. Clear or resize the stage deliberately, or change its physical reflectance. Regrading cannot remove captured geometry.", + "render.background_workflow": "Choose the background you intend: a camera-only colour/gradient, a physical stage that receives light, or HDR illumination. They are independent. Live Preview is a modelling view; render a new image or regrade a retained master to see camera finishing.", + "render.base_appearance": "Editable body appearance", + "render.base_apply": "Apply body appearance", + "render.base_apply_help": "One undoable visual assignment to the reviewed exact body. Existing face-specific looks and engineering materials remain separate.", + "render.base_color": "Base color · sRGB", + "render.base_metallic": "Metallic fraction", + "render.base_opaque_only": "This editor preserves opaque body semantics. Use the explicit glass controls for optical transmission.", + "render.bloom_enable": "Display bloom", + "render.bloom_help": "Creative output-only glow from positive linear highlights, spread with three normalized box passes. Radius is in output pixels. Added in linear display light before sRGB; not a lens, volumetric effect or convergence improvement. The raw EXR is unchanged.", + "render.bloom_opaque": "Bloom requires opaque output. Transparent PNG is refused, not silently flattened.", + "render.bloom_radius": "Bloom radius", + "render.bloom_strength": "Bloom strength", + "render.bloom_threshold": "Linear highlight threshold", + "render.browse_capabilities": "Inspect complete capability catalog", + "render.browse_environments": "Browse original HDR environments", + "render.browse_native_scenes": "Browse native studios", + "render.browse_physical": "Inspect physical references", + "render.browse_quality": "Inspect quality specifications", + "render.browse_rigs": "Browse authored light rigs", + "render.browse_scene_specs": "Browse advanced scene specifications", + "render.browse_surfaces": "Browse authored surfaces", + "render.browser_library": "Library", + "render.browser_model": "Model", + "render.camera_distance": "Eye-to-target distance", + "render.camera_exact_help": "World millimeters; angles are displayed in degrees and saved as radians. Navigation uses the same camera as the viewport.", + "render.camera_fov": "Vertical field of view", + "render.camera_pitch": "Camera pitch", + "render.camera_roll": "Roll", + "render.camera_set": "Set Render Camera", + "render.camera_target": "Target position · mm", + "render.camera_yaw": "Yaw", + "render.chromatic_offset": "Chromatic edge offset", + "render.clear_stage": "Remove saved stage", + "render.copy_request": "Copy JSON", + "render.cpu_aa_help": "Spatial samples: more samples improve edges and increase render time.", + "render.cpu_area_add": "Add rectangular CPU light", + "render.cpu_area_editor": "CPU rectangular lights", + "render.cpu_area_editor_help": "Full side vectors in millimeters; U cross V points towards the emitting side. This differs from GPU half-edge vectors.", + "render.cpu_area_full_u": "Full U side · mm", + "render.cpu_area_full_v": "Full V side · mm", + "render.cpu_area_samples": "Area-light samples", + "render.cpu_binding_confirm": "Confirm this body", + "render.cpu_binding_stale": "The scene changed. Confirm this reflection target again before rendering.", + "render.cpu_body_choose": "Choose a body", + "render.cpu_body_filter": "Filter bodies by name", + "render.cpu_body_filter_more": "Refine the filter to see more bodies.", + "render.cpu_body_missing": "A reflection target is missing, hidden, ambiguous or has a name longer than 128 bytes. Choose it again.", + "render.cpu_budget": "CPU resource profile", + "render.cpu_budget_bodies": "Body ceiling", + "render.cpu_budget_compact": "Compact (legacy limits)", + "render.cpu_budget_details": "Resource limits", + "render.cpu_budget_help": "Choose larger limits explicitly. Resolution and samples are never reduced automatically.", + "render.cpu_budget_memory": "Job memory ceiling", + "render.cpu_budget_not_guarantee": "These are admission ceilings, not a RAM reservation or a speed guarantee. Geometry, film and retained previews share the memory budget; rendering remains cancellable.", + "render.cpu_budget_resize": "The draft exceeds this CPU profile or its camera-sample budget. Accept smaller dimensions explicitly or select a larger profile.", + "render.cpu_budget_studio": "Studio (large images)", + "render.cpu_budget_triangles": "Triangle ceiling", + "render.cpu_budget_workstation": "Workstation (heavy scenes)", + "render.cpu_captured_hdr": "HDR captured for this image", + "render.cpu_check_capture_help": "Check and Start verify the same file digest or use the embedded HDR. Each image keeps its captured source.", + "render.cpu_check_changed": "The controls or model changed after this check. Check again before rendering.", + "render.cpu_constant_help": "Constant radiance is visible to reflected or transmitted rays. It does not provide direct diffuse lighting.", + "render.cpu_custom_directions": "Replace preset with custom directional lights", + "render.cpu_direction": "Direction toward light (X, Y, Z)", + "render.cpu_directional": "Directional light", + "render.cpu_directional_add": "Add directional light", + "render.cpu_environment": "CPU environment", + "render.cpu_environment_background": "The image background stays separate from environment lighting.", + "render.cpu_environment_bounds": "CPU intensity must be 0–64, HDR rotation finite within ±1,000,000 radians, and HDR samples 1, 4, 16 or 64.", + "render.cpu_environment_constant": "Constant secondary-ray environment", + "render.cpu_environment_none": "No CPU environment", + "render.cpu_environment_samples": "HDR lighting samples", + "render.cpu_exposure_help": "CPU exposure must be between −16 and 16 EV. A GPU exposure outside that range is retained until you change it.", + "render.cpu_fixed": "Single image", + "render.cpu_hdr_help": "Radiance .hdr, 2:1 panorama, up to 2048 × 1024 and 16 MiB. CPU requires explicit sRGB/D65 primaries in the file; unspecified primaries and EXR are refused.", + "render.cpu_hdr_reflection_help": "HDR rough reflections require fully metallic body and face surfaces. Check reports unsupported combinations.", + "render.cpu_key_rim": "Key and rim", + "render.cpu_last_check": "Last CPU check", + "render.cpu_light_help": "Up to eight directional lights. An empty custom list turns them off; selecting a preset restores its lights. Colors are linear RGB and intensity is relative, not watts.", + "render.cpu_light_intensity": "Relative intensity (0–64)", + "render.cpu_light_minimum": "Minimum distance for attenuation", + "render.cpu_light_position": "World position (X, Y, Z)", + "render.cpu_light_reference": "Reference distance for intensity", + "render.cpu_light_remove": "Remove light", + "render.cpu_lighting": "Lighting preset", + "render.cpu_lights": "CPU lights", + "render.cpu_linear_color": "Linear color (R, G, B)", + "render.cpu_neutral": "Neutral", + "render.cpu_opaque_required": "CPU ray tracing needs an opaque background. Clear Transparent background to continue.", + "render.cpu_options_pending": "This CPU panel cannot edit emission, surface effects, glass or anisotropy yet. Clear those API options before using it.", + "render.cpu_point": "Point light", + "render.cpu_point_add": "Add point light", + "render.cpu_point_help": "Up to eight point lights, added to the selected directional lighting. Distances are in mm; the minimum must not exceed the reference distance.", + "render.cpu_primary_samples": "Edge samples per pixel", + "render.cpu_progressive": "CPU progressive", + "render.cpu_progressive_help": "Accumulate the existing CPU integrator in passes of one primary sample. Selected reflections require one sample; area lights, dielectrics and anisotropy require Single image.", + "render.cpu_progressive_limits": "At most 1,048,576 pixels and 16,777,216 pixel × sample evaluations. Changing samples never resizes the image automatically.", + "render.cpu_progressive_seed": "CPU sampling seed", + "render.cpu_progressive_spp": "samples per pixel", + "render.cpu_reflection_add": "Add rough reflection", + "render.cpu_reflection_depth": "Reflection depth (1–8)", + "render.cpu_reflection_empty": "No bodies selected: scene reflections are off.", + "render.cpu_reflection_help": "Choose bodies and set Off, Mirror or Rough. Rough uses the assigned surface roughness. More samples and bounces increase time; this is bounded specular transport, not global illumination.", + "render.cpu_reflection_limit": "Up to 64 reflected bodies are supported.", + "render.cpu_reflection_mirror": "Mirror", + "render.cpu_reflection_off": "Off", + "render.cpu_reflection_rough": "Rough", + "render.cpu_reflection_samples": "Reflection samples (1–64)", + "render.cpu_reflections": "CPU reflections", + "render.cpu_runtime_help": "Numeric light and environment settings are saved with the setup. Body reflections and HDR files remain temporary. Existing area-light and spot-cone values are retained.", + "render.cpu_sampling_mode": "CPU sampling mode", + "render.cpu_shadows": "Cast shadows", + "render.cpu_summary": "CPU ray tracing · reflections · HDR · directional and point lights", + "render.cpu_warm_cool": "Warm and cool", + "render.diag_bodies": "Visible bodies", + "render.diag_job_details": "Captured job details", + "render.diag_last_check": "Last preflight", + "render.diag_memory": "Logical admission estimate", + "render.diag_not_implemented": "Explicit capability boundaries", + "render.diag_preflight_details": "Preflight details", + "render.diag_request": "Exact current request", + "render.diag_triangles": "Triangles", + "render.discard_continue": "Discard draft and continue", + "render.draft_confirm_help": "The current render draft has unapplied edits. Save them before switching, discard them explicitly, or keep editing.", + "render.draft_confirm_title": "Preserve edited render settings", + "render.effects_gpu_only": "These effects require GPU path tracing. Changing the page never switches the renderer automatically.", + "render.effects_help": "Combine ordered colour looks and image-space lens effects. Rendering and raw-master regrading use the same saved settings. Raw EXR stays unchanged. These are original artistic controls, not calibrated lens or branded-film emulations.", + "render.effects_reset_lens": "Reset lens effects", + "render.effects_seed": "Pattern seed", + "render.emitted_axis": "Emitted axis", + "render.error_area_samples": "area_samples must be 1, 4, 16 or 64", + "render.error_binding_allocation": "could not reserve material binding", + "render.error_body_bound": "product preview exceeds its captured-body bound", + "render.error_checkpoint_dimensions": "checkpoint dimensions differ from the captured request", + "render.error_decode_budget": "image decode budget overflow", + "render.error_denoise_setting": "invalid native denoise setting", + "render.error_display_dimensions": "invalid image display dimensions", + "render.error_display_fit": "image display cannot fit this device", + "render.error_display_height": "display height overflow", + "render.error_display_width": "display width overflow", + "render.error_duplicate_face": "duplicate product face appearance", + "render.error_export_document": "The render export document changed while choosing its destination", + "render.error_face_cap": "product preview exceeds the face-appearance admission cap", + "render.error_finish_gesture": "finish the modelling gesture before previewing", + "render.error_finish_operation": "finish the current modelling operation before entering Render", + "render.error_fixed_preview": "fixed studio preview requires exposure 0, environment rotation 0 and intensity 1", + "render.error_geometry_size": "product geometry size overflow", + "render.error_glass_recipe": "unknown glass recipe", + "render.error_gpu_preview": "GPU product preview is unavailable on this host. Saved setups remain available.", + "render.error_gpu_samples": "unsupported GPU sample count", + "render.error_image_dimensions": "render image dimensions do not match its job", + "render.error_image_profile": "render image exceeds its captured resource profile", + "render.error_interactive_command": "unbound interactive Render command", + "render.error_job_action": "not an interactive image-job action", + "render.error_job_identity": "invalid render job identity: {error}", + "render.error_library_reply": "invalid render-library response", + "render.error_material_binding": "missing material binding", + "render.error_no_completed_image": "render has no completed image", + "render.error_no_geometry": "no product geometry", + "render.error_no_scene": "no product scene", + "render.error_opacity": "invalid product appearance opacity", + "render.error_pbr_opacity": "opaque PBR requires opacity 1", + "render.error_physical_glass": "the selected recipe is not physical glass", + "render.error_preview_device": "product preview requires an installed device with a depth buffer", + "render.error_product_triangle": "invalid product triangle", + "render.error_provisional_identity": "invalid provisional render identity or sample count", + "render.error_quality_bounds": "quality projection exceeds native bounds", + "render.error_quality_method": "quality projection requires the same explicit GPU method", + "render.error_quality_projection": "invalid native quality projection", + "render.error_regrade_identity": "invalid regrade identity: {error}", + "render.error_scene_bodies": "missing render scene bodies", + "render.error_scene_body_limit": "render scene exceeds its body limit", + "render.error_scene_identity": "invalid render scene identity", + "render.error_setup_panicked": "GPU path tracer setup panicked", + "render.error_setup_stopped": "setup worker stopped without returning a host", + "render.error_setup_worker": "could not start setup worker: {error}", + "render.error_source_preview": "source preview exceeds its byte envelope", + "render.error_surface_normals": "PBR requires nonzero surface normals", + "render.error_surface_reply": "invalid authored surface reply", + "render.error_triangle_bound": "product preview exceeds its eight-million-triangle source bound", + "render.error_triangle_count": "product triangle count overflow", + "render.error_upload_slot": "product preview upload slot unavailable", + "render.error_vertex_allocation": "product preview vertex allocation failed", + "render.error_vertex_envelope": "product preview exceeds its {limit} MiB vertex payload envelope; geometry was not simplified", + "render.error_vertex_packing": "product preview packing differs from its admitted vertex payload", + "render.error_visible_solid": "Create a visible solid in Design to preview it here.", + "render.exit_focus": "Exit focus", + "render.export_display": "Export: display PNG", + "render.export_image_label": "Export Image", + "render.export_linear": "Export: raw linear EXR", + "render.exr_pending": "GPU can retain raw linear EXR. Compression, multilayer images and auxiliary render passes remain unavailable.", + "render.film_grain": "Photographic grain", + "render.fit": "Fit Product", + "render.fixed_camera": "Camera", + "render.fixed_world": "World", + "render.flare_ghosts": "Ghost rings per source", + "render.flare_halo": "Flare halo", + "render.flare_streak": "Anamorphic-style streak", + "render.flare_strength": "Highlight flare strength", + "render.flare_threshold": "Scene-linear flare threshold", + "render.fold_browser": "Fold Browser", + "render.gpu_depth": "Maximum path depth", + "render.gpu_options_help": "Samples, depth, seed and exposure are saved with this setup. Only the active image method is saved.", + "render.gpu_path_failed": "GPU path tracer unavailable", + "render.gpu_path_first_setup": "The first setup on this GPU can take several minutes; SolidCraft stays usable meanwhile. Later starts reuse the compiled shaders where the driver keeps them.", + "render.gpu_path_preparing": "GPU path tracer: compiling shaders…", + "render.gpu_seed": "Random seed", + "render.gpu_unavailable": "GPU path tracing is not ready on this device.", + "render.ground_apply": "Fit and save ground", + "render.ground_gap": "Explicit clearance gap", + "render.ground_linear_rgb": "Diffuse reflectance · linear RGB", + "render.ground_margin": "Ground extent margin", + "render.hdr_details": "HDR source details", + "render.hdr_embedded": "HDR saved inside this design", + "render.hdr_embedded_help": "Rendering uses the bytes included in the design; the original file is no longer needed.", + "render.hdr_file_captured": "HDR file checked. Save will embed these bytes; if the file changes, check it again explicitly.", + "render.hdr_inspect": "Check HDR file", + "render.hdr_inspect_required": "Select and check an HDR file before saving or rendering.", + "render.hdr_primaries_declared": "The source declares its color primaries.", + "render.hdr_primaries_srgb": "Color primaries: sRGB/D65", + "render.hdr_primaries_undeclared": "The source does not declare primaries; review the renderer color requirements.", + "render.hdr_resource_missing": "This design is missing the saved HDR resource.", + "render.heading_batch": "BATCH", + "render.heading_frame": "FRAME", + "render.heading_lens": "LENS", + "render.heading_results": "RESULTS", + "render.heading_shots": "SHOTS", + "render.hide_shots_label": "Hide Shots strip", + "render.image_advanced": "Advanced GPU controls", + "render.image_cancelled": "Render cancelled", + "render.image_cancelling": "Cancelling", + "render.image_completed": "Image ready to export", + "render.image_encoding": "Encoding PNG", + "render.image_export": "Export completed image", + "render.image_exposure": "Exposure", + "render.image_failed": "Render failed", + "render.image_height": "Height", + "render.image_help": "CPU preview image · PNG · approximate transparency", + "render.image_host_missing": "No image host is installed.", + "render.image_method": "Image method", + "render.image_overwrite": "Replace existing file", + "render.image_preparing": "Preparing image", + "render.image_progressive": "Progressive rendering", + "render.image_queued": "Waiting to render", + "render.image_reduce": "Try a smaller image or simpler scene.", + "render.image_running": "Rendering image", + "render.image_samples": "Samples per pixel", + "render.image_scene_stale": "Finish the modelling gesture or refresh the scene before checking or starting an image.", + "render.image_stale": "This image uses the scene captured before subsequent changes.", + "render.image_start": "Start Render", + "render.image_supported": "Render request is supported; the queue and memory pool are checked again at start.", + "render.image_title": "Render Image", + "render.image_too_large": "Over the image limit: 4096 pixels per side and 4,194,304 pixels in all.", + "render.image_transparent": "Transparent background", + "render.image_unknown": "Render status unavailable", + "render.image_use_largest": "Use the largest size at this aspect:", + "render.image_width": "Width", + "render.include_rig_cards": "Include passive cards and flags", + "render.inner_half_angle": "Inner half angle", + "render.inspect_scene": "Refresh captured scene summary", + "render.inspector": "Inspector", + "render.keep_editing": "Keep editing", + "render.layer_down": "Move down", + "render.layer_enabled": "Layer enabled", + "render.layer_off_suffix": " (off)", + "render.layer_remove": "Remove layer", + "render.layer_strength": "Layer strength", + "render.layer_up": "Move up", + "render.lens_effects_help": "Flare uses up to four separated bright sources in the actual linear image. Ghosts, halo, streaks, chromatic offsets and radial distortion are artistic image-space approximations. Spatial effects need opaque output; outside samples extend the image edge. Grain is deterministic. No physics, EXR or geometry is altered.", + "render.lens_effects_title": "Lens-inspired & photographic", + "render.library_all": "Catalog", + "render.library_all_states": "All availability states", + "render.library_applied": "Resource projection applied. Check the complete render request before starting.", + "render.library_apply_hdr": "Save with this HDR environment", + "render.library_apply_maps": "Use authored GPU surface maps", + "render.library_apply_studio": "Save authored studio projection", + "render.library_apply_uniform": "Apply uniform opaque appearance", + "render.library_authored_help": "Original authored resources are illustrative, not measured engineering data. Each action applies only its stated projection.", + "render.library_blocked": "Blocked / requires calibration", + "render.library_capabilities": "Capability specifications", + "render.library_center": "Rig center", + "render.library_clear_search": "Clear", + "render.library_details": "Specification and provenance", + "render.library_emitters_only_ack": "Use emitters only; omit the documented passive cards", + "render.library_empty": "No matching resources. Try a different query or availability filter.", + "render.library_environment_concepts": "Environment concepts", + "render.library_extent": "Subject extent", + "render.library_favorite": "Add favorite", + "render.library_favorites": "Favorites", + "render.library_hdr": "Built-in HDR environments", + "render.library_hdr_help": "Embeds the original HDR in the saved setup. The authored longitude origin is converted explicitly; no external file is needed after saving.", + "render.library_inspect_only": "Select to inspect; nothing is applied automatically. Favorites and recent history belong to this open document session.", + "render.library_light_concepts": "Lighting concepts", + "render.library_maps_help": "Built-in maps can be saved with pinned sources and local occurrence mapping. Temporary optical overrides remain a separate mode.", + "render.library_material_concepts": "Material concepts", + "render.library_native_scenes": "Native studios", + "render.library_next": "Next page", + "render.library_omitted": "Not included", + "render.library_physical_profiles": "Physical reference profiles", + "render.library_previous": "Previous page", + "render.library_quality_concepts": "Quality specifications", + "render.library_recent": "Recent", + "render.library_replace_environment": "Replace the existing environment explicitly", + "render.library_replace_studio": "Replace saved lighting, environment and stage", + "render.library_results": "Matching resources", + "render.library_rig_help": "Fit once at an explicit center and physical extent. Complete rigs include passive cards; calibration blockers still refuse. Conservative emitter/card clearance is checked before saving.", + "render.library_rigs": "Authored lighting rigs", + "render.library_save_maps": "Save maps to this setup", + "render.library_scene_bounds": "Use captured scene bounds", + "render.library_scenes": "Scene specifications", + "render.library_search": "Search library", + "render.library_select_hint": "Choose a resource in the Library to inspect its supported actions and limitations.", + "render.library_selene": "SELENE opaque appearances", + "render.library_selene_shots": "SELENE shot specifications", + "render.library_short_blocked": "Unavailable", + "render.library_short_native": "Native composition", + "render.library_short_projection": "Supported projection", + "render.library_short_reference": "Reference only", + "render.library_short_specification": "Specification only", + "render.library_source_preview": "Load source-map preview", + "render.library_source_preview_help": "Authored base-color source map. This is not a rendered or measured material preview.", + "render.library_specification_only": "Specification only: not a complete executable preset. Required effects, resources and subject roles still need explicit implementation and binding.", + "render.library_specs": "Specifications only", + "render.library_status": "Availability", + "render.library_surfaces": "Authored PBR surfaces", + "render.library_target": "Target body", + "render.library_title": "Render resource library", + "render.library_unfavorite": "Remove favorite", + "render.library_uniform_ack": "Use the uniform approximation without spatial or advanced effects", + "render.library_usable": "Executable projections", + "render.light_anchor_pending": "Changing the light coordinate frame is not supported yet.", + "render.lights_fixed_to": "Lights fixed to", + "render.linear_help": "Keeps a 32-bit float RGBA master before denoising, exposure, tone mapping, filters and backdrop. Linear sRGB/D65; coverage-premultiplied. Additional memory is admitted explicitly. No compression or extra passes.", + "render.linear_retain": "Retain raw linear EXR", + "render.linear_unavailable": "The selected completed frame has no retained EXR. Enable retention before rendering; an older PNG cannot recover raw radiance.", + "render.look_add": "Add colour look", + "render.look_bleach": "Bleach-bypass-inspired", + "render.look_cool": "Cool", + "render.look_cyanotype": "Cyanotype-inspired", + "render.look_faded": "Faded print", + "render.look_mono": "Monochrome", + "render.look_sepia": "Sepia", + "render.look_strength": "Look strength", + "render.look_teal_orange": "Teal / orange", + "render.look_title": "Creative look stack", + "render.look_warm": "Warm", + "render.mapping_scale": "Physical repeat multiplier", + "render.material_absorption": "Absorption R · G · B (per mm)", + "render.material_add": "Add or edit this body", + "render.material_assignments": "Body assignments", + "render.material_binding_enable": "Include this body override", + "render.material_box": "Axis-aligned box", + "render.material_browse": "Choose image…", + "render.material_certification": "Closed glass uses geometric distance. Topology, orientation, overlap and optical boundaries are checked during GPU preparation; Check only admits the request.", + "render.material_choose_body": "Choose a scene body", + "render.material_closed": "Closed solid mesh", + "render.material_coat": "Clear coat over the base material", + "render.material_coat_enable": "Enable clear coat", + "render.material_coat_help": "Illustrative dielectric coating over the existing opaque appearance. Zero weight leaves the base unchanged.", + "render.material_color_map": "Base color image (sRGB)", + "render.material_color_replace": "Base map replaces body color", + "render.material_custom": "Custom illustrative optics", + "render.material_enable": "Use these GPU material overrides", + "render.material_filter": "Filter scene bodies…", + "render.material_filter_help": "Up to 128 matching bodies are shown. Refine the filter for large scenes.", + "render.material_glass": "Glass and optical absorption", + "render.material_glass_enable": "Use physical glass on this body", + "render.material_glass_exclusive": "Glass cannot share a body with clear coat or runtime maps in this renderer.", + "render.material_glass_help": "Original illustrative recipes. Swatches show transmittance, not a rendered preview. Absorption is −ln(linear transmittance) / reference distance; alpha is unchanged.", + "render.material_gpu_required": "These active material overrides require GPU path tracing. Select GPU or disable the overrides before Check or Start.", + "render.material_ior": "Index of refraction (IOR)", + "render.material_limits": "At most 128 body overrides, 32 disjoint glass bodies, 64 coats and 128 texture bindings. Identical maps share storage; actual device and total memory limits still apply.", + "render.material_map_invalid": "Map paths must be bounded local paths; normal strength must be finite and between 0 and 1.", + "render.material_map_required": "Choose a color image or a normal image before using maps.", + "render.material_maps": "Planar color and normal maps", + "render.material_maps_enable": "Enable maps for this opaque body", + "render.material_maps_help": "PNG/JPEG up to 1024×1024; 16 MiB encoded total. U and V are orthogonal world-mm repeat vectors (maximum 128 repeats). Color is sRGB; normal data uses OpenGL +Y. Files are captured at Check/Start.", + "render.material_metallic_map": "Metallic map (linear)", + "render.material_normal_map": "Normal image (OpenGL, +Y)", + "render.material_normal_strength": "Normal strength (0–1)", + "render.material_origin": "Mapping origin X · Y · Z (mm)", + "render.material_refresh": "Refresh scene bodies", + "render.material_refresh_needed": "Scene changed. Refresh the body list before adding a target.", + "render.material_remove": "Remove this assignment", + "render.material_repeat_u": "One U repeat X · Y · Z (mm)", + "render.material_repeat_v": "One V repeat X · Y · Z (mm)", + "render.material_revalidate": "Revalidate this body", + "render.material_revalidate_needed": "This assignment belongs to an earlier scene revision. Revalidate its exact body identity before rendering.", + "render.material_roughness": "Coat roughness (0.045–1)", + "render.material_roughness_map": "Roughness map (linear)", + "render.material_shadow": "Transmit straight shadow rays", + "render.material_target_missing": "The body ordinal and name no longer match. Remove this assignment and explicitly choose the intended body again.", + "render.material_thickness": "Thin-sheet thickness (mm)", + "render.material_thin": "Thin sheet", + "render.material_title": "GPU image materials", + "render.material_transient": "Temporary optical overrides for this document tab. They are not saved in the design, render setup or material library.", + "render.material_v_up": "Texture V points upward in the image", + "render.material_weight": "Coat weight (0–1)", + "render.method_cpu": "CPU ray tracing", + "render.method_gpu": "GPU path tracing", + "render.method_limit_raster": "Raster uses the fixed opaque studio preview. Select an explicit raytracing method for supported optical controls.", + "render.method_raster": "CPU raster", + "render.navigation_help": "The camera moves as in Design (Preferences › Navigation). Save Setup records the current camera.", + "render.nested_enable": "Certified nested dielectrics", + "render.nested_help": "Up to 16 containing layers; every parent must be convex and every child strictly inside it. Intersections, touching surfaces, thin sheets and straight-shadow transmission refuse. Camera-inside state follows the certified hierarchy. Does not create a liquid surface or merge touching CAD boundaries.", + "render.opaque_image_summary": "Preview PNG · opaque PBR · blended transparency", + "render.opaque_preview_help": "Opaque PBR and simple colors; blended transparency. Refraction, HDRI and final rendering are not available yet.", + "render.optics_remove": "Remove saved optics", + "render.optics_replace": "Replace this target’s saved optics explicitly", + "render.optics_save": "Save these optics to the setup", + "render.optics_saved": "Saved optical targets", + "render.optics_saved_help": "Exact definition, feature and occurrence identity survives offline reopen. Missing/replaced/hidden targets refuse; engineering materials are unchanged. Save or discard numeric edits before removing a saved target.", + "render.outer_half_angle": "Outer half angle", + "render.output_format_status": "PNG is the exact completed display image. Optional GPU EXR retains raw scene-linear FLOAT32 radiance before display filters. Export never substitutes the preview cache or a different job.", + "render.output_lock_ratio": "Lock aspect ratio", + "render.output_over_budget": "The requested image exceeds the selected resource envelope. Choose a compatible size or profile explicitly; no automatic downgrade occurs.", + "render.output_ratio_refused": "The linked dimension exceeds this method’s size limit. The previous size is retained; unlock the ratio or choose a smaller value.", + "render.output_swap_orientation": "Swap width and height", + "render.output_tools_inspector": "Edit size and format in the Output inspector.", + "render.page_aging": "Aging & contamination", + "render.page_all": "All controls", + "render.page_appearance": "Appearance", + "render.page_background": "Backgrounds", + "render.page_camera": "Camera", + "render.page_diagnostics": "Diagnostics", + "render.page_effects": "Lens & finishing effects", + "render.page_environment": "Environment", + "render.page_lighting": "Lighting", + "render.page_output": "Output", + "render.page_scene": "Scene", + "render.paint_label": "Paint", + "render.passive_stage": "Ground and passive stage", + "render.passive_stage_help": "Finite passive panels belong only to rendered images. They do not add CAD bodies or mass. Placement is fixed after applying; intersecting product bounds refuse. CPU does not provide diffuse bounce lighting.", + "render.perspective": "Perspective camera", + "render.physical_acknowledge": "I understand this partial reference needs grade, condition and source review", + "render.physical_associations": "Physical candidates and roles", + "render.physical_background_help": "Real passive floor and wall, separate from the camera backdrop. Cyclorama uses 24 polygonal strips; it is not an infinite or analytically smooth surface. Replaces the saved stage only with your consent.", + "render.physical_copy_plan": "Copy plan with sources and omissions", + "render.physical_cyclorama": "Fit polygonal cyclorama", + "render.physical_floor_wall": "Fit physical floor and wall", + "render.physical_material_name": "Proposed reference material name", + "render.physical_omissions": "Properties not representable in the native card", + "render.physical_plan_only": "Read-only plan prepared. No material was created or assigned. Keep its extended profile and omissions when reviewing the native card.", + "render.physical_prepare_plan": "Prepare creation plan (does not apply)", + "render.physical_separate": "Appearance is not material identification. These are sourced references, not certified effective properties. Existing mass, engineering materials and optics are unchanged.", + "render.physical_unknown": "No numerical candidate is established. Grade, formulation or construction must be specified; unknown is not zero.", + "render.pick_body": "Body", + "render.pick_component": "Component", + "render.pick_face": "Face", + "render.pick_help": "Choose Body, Face or Component. Click empty space to clear; Shift or Ctrl adds or toggles. Highlights appear only in the live product view.", + "render.pick_label": "Pick", + "render.pick_up_label": "Pick Up", + "render.pick_waiting": "Product picking is not supported yet.", + "render.post_contrast": "Contrast", + "render.post_gain_b": "Blue gain", + "render.post_gain_g": "Green gain", + "render.post_gain_r": "Red gain", + "render.post_help": "Creative presentation only. RGB gains precede tone mapping; contrast, saturation and vignette follow in display-linear light. Start Render creates new transport samples. Regrade uses the selected retained raw master without denoising or new rays.", + "render.post_reset": "Reset presentation filters", + "render.post_saturation": "Saturation", + "render.post_title": "Presentation filters", + "render.post_vignette": "Vignette", + "render.preview": "Integrated preview", + "render.preview_help": "Raster shading and blended transparency. Refraction, HDRI and final rendering are not available yet.", + "render.preview_image_settings_help": "Live Preview keeps fixed studio lighting. Exposure and image lighting apply to the image job when you Check or Start.", + "render.preview_lighting_help": "The live preview shows direct light only and no shadows.", + "render.preview_retry": "Retry live preview", + "render.preview_unavailable_help": "The live preview is unavailable. Saved setups and image-job controls remain accessible. Change the scene or explicitly retry; a refused scene is not rebuilt on every frame.", + "render.preview_upload": "Live-preview vertex payload", + "render.preview_upload_help": "Exact preview vertex bytes, not total GPU or process memory. Geometry is not simplified. Image jobs use their own admission and lighting.", + "render.progressive_image_summary": "Preview PNG · PBR and glass · progressive samples", + "render.property_conditions": "Conditions: {value}", + "render.property_fallback": "property", + "render.property_qualifier": "Qualifier: {value}", + "render.property_source": "Source: {id} - {locator}", + "render.property_uncertainty": "Uncertainty: {value}", + "render.property_unknown": "unknown", + "render.quality_ack": "Acknowledge the fixed-budget projection and omissions", + "render.quality_apply": "Use this fixed sampling budget", + "render.quality_projection_help": "Q presets include future requirements. This action projects only a supported fixed-sample PNG budget and explicitly omits adaptive stopping, raw linear output and independent transmission limits.", + "render.quality_review": "Review sampling budget", + "render.queue_pending": "There is no automatic production queue or animation renderer in this UI. Completed still images remain separately exportable.", + "render.radial_distortion": "Radial distortion", + "render.regrade_action": "Regrade raw master (no denoising)", + "render.regrade_help": "Creates a separate PNG from the selected completed raw master, using these presentation controls. Does not trace rays, change the captured size/camera/lights, or overwrite the EXR. Denoising is not reapplied: raw masters do not retain its guides. The derivative remains exportable through the same job controls.", + "render.regrade_label": "Regrade", + "render.reload_settings": "Reload Saved Settings", + "render.replace_ground": "Confirm replacement of existing stage", + "render.replace_label": "Replace", + "render.replace_saved_surface": "Replace an existing saved binding for this target", + "render.restore_camera": "Restore Saved Camera", + "render.result_actual_help": "One image pixel per display pixel.", + "render.result_actual_size": "100%", + "render.result_capture": "Captured revision", + "render.result_current": "The captured model revision is current.", + "render.result_empty": "No completed image yet. Check the settings, then start a render.", + "render.result_fit": "Fit Image", + "render.result_job": "Job", + "render.result_navigation": "Pan and zoom use Navigation preferences. Space + drag pans.", + "render.result_open": "Open the completed image in the main canvas.", + "render.result_preview": "Live Preview", + "render.result_provisional": "Provisional CPU image", + "render.result_provisional_help": "This checkpoint is not exportable. Export keeps the last completed result; cancellation returns to that result.", + "render.result_reduced_display": "Display preview reduced to the viewport device/cache limit. The retained PNG and export keep full resolution; native 100% inspection is unavailable for this reduced view.", + "render.result_retained": "Showing the last completed image; a newer render has not replaced it.", + "render.result_sequence": "Checkpoint", + "render.result_title": "Render Result", + "render.return_design": "Return to Design", + "render.review_stale": "This review is stale. Resolve or check again before applying.", + "render.ribbon_aging": "Aging", + "render.ribbon_backgrounds": "Backgrounds", + "render.ribbon_check": "Check", + "render.ribbon_check_help": "Validate the exact current draft that Render will submit. No renderer fallback, silent resize or resource replacement.", + "render.ribbon_edit_lights": "Edit Lights", + "render.ribbon_effects": "Effects", + "render.ribbon_environment_help": "HDR illumination, camera-only backgrounds and physical stage surfaces are separate controls with explicit replacement consent.", + "render.ribbon_finish_dialog": "Finish the current file or confirmation dialog first.", + "render.ribbon_frame": "Frame", + "render.ribbon_hdr_library": "HDR Library", + "render.ribbon_job_active": "A render is already running; cancel it explicitly before starting another.", + "render.ribbon_light_rigs": "Light Rigs", + "render.ribbon_lights_help": "Inspect authored rigs or edit supported lights without replacing the current setup until you explicitly apply the change.", + "render.ribbon_materials": "Materials", + "render.ribbon_materials_help": "Open the shared appearance inspector and original surface library. Optical edits never silently change engineering properties.", + "render.ribbon_no_active_job": "There is no active render to cancel.", + "render.ribbon_no_result": "Complete a render before exporting its exact image.", + "render.ribbon_no_saved_camera": "Save a shot before restoring its camera.", + "render.ribbon_saved_camera": "Saved Camera", + "render.ribbon_shots": "Shots", + "render.ribbon_studios": "Studios", + "render.ribbon_studios_help": "Browse implemented studio compositions and review their replacements before applying. Concept-only scenes remain labelled.", + "render.ribbon_surface_maps": "Surface Maps", + "render.sampling_title": "Adaptive and transmission sampling", + "render.save_continue": "Save and continue", + "render.save_setup": "Save Setup", + "render.save_shot": "Save Shot", + "render.saved_maps_runtime_conflict": "Saved surface bindings cannot be mixed with temporary optical overrides or an unsaved HDR. Save the HDR or remove the temporary inputs explicitly.", + "render.saved_surface_remove": "Remove saved binding", + "render.saved_surfaces": "Saved surface bindings", + "render.saved_surfaces_help": "Pinned built-in maps follow the selected occurrence in local millimeters. A replaced or missing target is an error, never an automatic reassignment.", + "render.scene_apply": "Apply reviewed studio", + "render.scene_consent": "Confirm lighting, environment, exposure and stage replacement", + "render.scene_preserved_fields": "Camera, sampling, dimensions, optical bindings, CAD geometry and engineering materials are preserved.", + "render.scene_preserves_design": "Compose lighting and a passive stage for the visible subject. Geometry, engineering materials and the camera remain separate.", + "render.scene_replaces": "Replaces", + "render.scene_review": "Resolve and review", + "render.scene_review_help": "Review the complete native composition before applying. Unbound advanced SCENE specifications are not substituted.", + "render.scene_scope_details": "Composition scope", + "render.setup_legacy_environment": "This older setup uses legacy environment rotation or intensity. Those values are retained; convert them explicitly before saving a full image job.", + "render.setup_name": "Setup name", + "render.setup_numeric_help": "Save records the active image method and all its numeric settings. Reload or choosing another setup replaces this draft; restore the camera separately.", + "render.setup_offline_help": "You can edit and save this method without its renderer. Check and Start require an available host.", + "render.setup_runtime_unsupported": "This full job cannot be saved yet: it contains maps or scene-body bindings. Remove those temporary inputs before saving a portable setup.", + "render.setup_save_missing": "The saved render configuration could not be found after the command completed.", + "render.sharpening": "Detail sharpening", + "render.shell_tab_appearance": "RENDER APPEARANCE", + "render.shell_tab_camera": "RENDER CAMERA", + "render.shell_tab_scene": "RENDER SCENE", + "render.shot_duplicate": "Duplicate saved shot", + "render.shot_manager": "Saved shots", + "render.shot_new_name": "New shot name", + "render.shot_remove": "Remove saved shot", + "render.shot_remove_help": "Remove only this saved setup. Source geometry and completed images are preserved; the action can be undone.", + "render.shot_remove_title": "Remove saved shot?", + "render.shot_rename": "Rename saved shot", + "render.shot_saved_only": "Save the current draft first. Duplicate and rename preserve exact saved options and resource references.", + "render.show_shots_label": "Show Shots strip", + "render.size_4k_uhd": "4K UHD", + "render.size_full_hd": "Full HD", + "render.size_hd": "HD", + "render.sky_ground": "Ground · linear RGB", + "render.sky_horizon": "Horizon · linear RGB", + "render.sky_zenith": "Zenith · linear RGB", + "render.soft_focus": "Soft focus", + "render.spot_cone": "Spot cone", + "render.stage_frame": "Frame", + "render.stage_light": "Light", + "render.stage_look": "Look", + "render.stage_orthographic": "Orthographic", + "render.stage_output": "Output", + "render.stage_panel_count": "Saved panels", + "render.stage_preview_note": "Integrated preview · direct light", + "render.strip_label": "Strip", + "render.studio_add_area": "Add area light", + "render.studio_ambient": "Constant environment radiance", + "render.studio_ambient_rgb": "Constant environment radiance (linear RGB)", + "render.studio_aperture": "Aperture radius", + "render.studio_area": "Area light", + "render.studio_area_help": "Up to four one-sided rectangles. Orthogonal half-edges U and V define size; U × V faces the lit side. Coordinates are world-space millimetres.", + "render.studio_center": "Center X, Y, Z (mm)", + "render.studio_denoise": "Reduce noise in the finished image", + "render.studio_denoise_help": "Final edge-aware filter; fine detail can soften. Glass and sharp specular surfaces bypass the filter.", + "render.studio_direction": "Direction toward sun (X, Y, Z)", + "render.studio_environment": "Environment", + "render.studio_environment_bounds": "Environment rotation must be finite within ±1,000,000 radians and intensity between 0 and 100.", + "render.studio_environment_none": "No environment map", + "render.studio_focus": "Axial focus distance", + "render.studio_half_u": "Half-edge U (mm)", + "render.studio_half_v": "Half-edge V (mm)", + "render.studio_hdr": "Radiance HDR file", + "render.studio_hdr_browse": "Choose HDR…", + "render.studio_hdr_help": "Radiance .hdr, 2:1 panorama, up to 2048 × 1024. EXR is unavailable. The color assumption applies only when primaries are unspecified.", + "render.studio_hdr_required": "Choose a local .hdr file.", + "render.studio_hdr_srgb": "Interpret unspecified primaries as linear sRGB", + "render.studio_intensity": "Environment intensity", + "render.studio_lens": "Depth of field", + "render.studio_lens_perspective": "Depth of field requires a perspective camera.", + "render.studio_lighting": "Studio lighting", + "render.studio_lighting_enable": "Use custom studio lighting", + "render.studio_needs_review": "Review method and settings", + "render.studio_radiance": "Linear RGB radiance", + "render.studio_ready": "Ready to check", + "render.studio_remove_area": "Remove area light", + "render.studio_rotation": "Environment rotation", + "render.studio_runtime_help": "Numeric studio settings and checked HDR sources can be saved with the setup. Body optical/material overrides remain temporary and do not change saved appearances.", + "render.studio_saved": "Saved setup / current camera", + "render.studio_sky": "Artistic sky", + "render.studio_sky_help": "Original sky gradient for lighting; not a calibrated atmospheric model.", + "render.studio_sun": "Sun", + "render.studio_sun_radius": "Angular radius", + "render.studio_title": "Render studio", + "render.studio_tone_map": "Tone mapping", + "render.subsurface_enable": "Interior scattering random walk", + "render.subsurface_help": "Closed dielectric only. Scattering and RGB absorption are separate per-mm coefficients. Paths scatter inside actual geometry, then refract or reflect at the boundary. Disable straight shadow transmission, surface denoising and exterior volume; use one Fresnel stratum. Not a diffusion shader, density grid or measured material. Dense media may need more samples and path depth.", + "render.subsurface_rate": "Scattering collision rate", + "render.tone_aces_fitted": "ACES fitted", + "render.tone_reinhard": "Reinhard", + "render.transmission_scope": "GPU glass supports certified disjoint media. Unrestricted nested media and a noise-free transmission estimator are not provided.", + "render.transmission_strata": "Conditional Fresnel strata", + "render.transmission_strata_help": "1 preserves the original stream. 2 or 4 subpaths stratify the first glass reflection/transmission choice with unchanged Snell and absorption laws. More paths cost more work; this is not denoising, nested-media support or a promise of faster rendering.", + "render.tree_add_light": "Add light", + "render.tree_add_shot": "Add shot", + "render.tree_browser": "Render Browser", + "render.tree_by_look": "By look", + "render.tree_by_object": "By object", + "render.tree_constant": "Constant environment", + "render.tree_default": "Default", + "render.tree_directional": "Directional", + "render.tree_environment": "Environment", + "render.tree_environment_values": "{rotation}° · {intensity}×", + "render.tree_face_count": "{count} faces", + "render.tree_face_one": "{count} face", + "render.tree_fixed_studio": "Fixed studio", + "render.tree_hdr": "HDR", + "render.tree_lights": "Lights", + "render.tree_lights_pending": "Named light commands are not available yet.", + "render.tree_mixed": "Mixed", + "render.tree_more": "{count} more", + "render.tree_mute": "Mute light", + "render.tree_no_environment": "No environment", + "render.tree_objects": "Objects", + "render.tree_output": "Output", + "render.tree_point": "Point", + "render.tree_rectangle": "Rectangle", + "render.tree_search": "Search objects", + "render.tree_selection": "Render selection", + "render.tree_shots": "Shots", + "render.tree_sky": "Sky", + "render.tree_solo": "Solo light", + "render.tree_spot": "Spot", + "render.tree_sun": "Sun", + "render.tree_switch": "Switch", + "render.tree_user_one": "{count} object", + "render.tree_users": "{count} objects", + "render.unavailable_preview": "This setup requests an unavailable preview profile.", + "render.unsaved": "Unsaved preview changes", + "render.use_preview": "Use Integrated Preview", + "render.volume_albedo": "Scattering albedo · linear RGB", + "render.volume_anisotropy": "Phase mean cosine", + "render.volume_enable": "Enable participating medium", + "render.volume_extinction": "Extinction coefficient", + "render.volume_help": "GPU transport inside one finite box, with Beer attenuation and HG scattering on camera and indirect paths. Uses explicit studio/HDR/sky lighting, including shadow attenuation. Positive phase cosine scatters forward. Glass boundaries and surface denoising must be disabled explicitly. Zero extinction leaves transport unchanged. Not a physical lunar atmosphere, density grid, volume emission, spectral transport or certified material property.", + "render.volume_max": "Maximum bounds · world mm", + "render.volume_min": "Minimum bounds · world mm", + "render.volume_title": "Bounded homogeneous volume", + "render.wait_batch": "not supported yet: the saved-shot render queue", + "render.wait_compare": "not supported yet: retained image comparison", + "render.wait_paint": "not supported yet: product picking and appearance painting", + "render.wait_pick_up": "not supported yet: product picking and appearance sampling", + "render.wait_replace": "not supported yet: replacing all uses of an appearance", + "render.wait_solo": "not supported yet: light visibility and solo controls", + "sample.bracket.about": "Base flange with edge flanges and a hem on a 2 mm rule", + "sample.bracket.name": "Sheet Metal Bracket", + "sample.enclosure.about": "Shelled box with a lip, screw bosses, a rest and a snap fit", + "sample.enclosure.name": "Plastic Enclosure", + "sample.flange.about": "Hub and flange with a circular pattern driven by a parameter", + "sample.flange.name": "Bolted Flange", + "sample.hinge.about": "Two components and a revolute joint, driven to 60°", + "sample.hinge.name": "Hinge Assembly", + "sample.plate.about": "Parametric plate with fillets, holes and a bored boss", + "sample.plate.name": "Sample Plate", + "sample.vents.about": "Slots in a rectangular pattern: rows, columns and pitch are parameters", + "sample.vents.name": "Vent Plate", + "search.command_keys": "Enter run Shift+Enter run and keep open Esc close", + "search.commands": "Commands", + "search.design": "In this design", + "search.feature": "Feature", + "search.invalid": "Not valid", + "search.keys": "↑ ↓ choose Enter run Tab fill name Esc close", + "search.no_match": "No command matches '{query}'", + "search.parameter": "Parameter", + "search.recent": "Recent", + "search.run": "Run command", + "search.suggest": "Did you mean {label}?", + "search.try": "Type a command name, a feature in this design, or a parameter. To run a command with values, type its id and a JSON object: {example}", + "search.valid": "Valid", + "section.off_hint": "No plane picked: OK turns the section off.", + "set by the sketch's lines": "set by the sketch's lines", + "settings.display_quality_note": "Only the display. Designs and exports are not affected.", + "settings.frame_rate_details_note": "Adds a graph of the last frames' times with the triangles drawn over it, a histogram of frame times and what the GPU drew. Click the frame rate in the view to show or hide them.", + "settings.frame_rate_note": "Shows frames per second in the view's bottom-right corner.", + "settings.measure_axis_distances": "Show X/Y/Z distances", + "settings.measure_axis_distances_help": "Show world-axis component dimensions alongside the total distance while Measure is open.", + "settings.msaa_applies_on_restart": "Anti-aliasing applies the next time SolidCraft starts", + "settings.msaa_reset": "{setting}: {requested}× isn't supported by this graphics device; it is now {reset}× (supported: {supported}).", + "settings.msaa_unsupported": "Not supported by this graphics device", + "settings.reference_geometry_through_bodies": "Show reference geometry through bodies", + "settings.reference_geometry_through_bodies_help": "Draw inactive sketch contours and datum planes over shaded bodies", + "settings.reset_intro": "These settings don't work on this computer and would keep SolidCraft from starting, so they were changed:", + "settings.reset_title": "Settings were changed", + "settings.supersampling_note": "Draws the view at a higher resolution and filters it down: smoother edges, lines and grid on screens below 4K. It costs GPU time: about 2.25× the pixels at 1.5× and 4× at 2×.", + "settings.window_system_details": "Details", + "settings.window_system_note_now": "Applies after a restart. Now: {now}.", + "settings.window_system_wayland_limited": "Some features are limited on native Wayland.", + "sheet.no_body": "there is no sheet metal body: start one with Flange > Base, or turn a plate into sheet metal with Convert to Sheet Metal (pick its large flat face)", + "shortcut.json_error": "parameters must be JSON: {error}", + "shortcut.no_command": "no command `{id}`; the text before the JSON must be a command id", + "shortcut.pin": "Pin to the top of the S box", + "shortcut.unpin": "Unpin", + "sketch.degrees_of_freedom": "{count} degrees of freedom", + "sketch.dof_left": "{count} degrees of freedom left", + "sketch.dof_left_one": "{count} degree of freedom left", + "sketch.draw_curves": "Draw as {linetype}", + "sketch.make_selection": "Convert the selection to {linetype}", + "sketch.open_ends": "Open {count}", + "sketch.untied_ends": "Untied {count}", + "sketch_panel.attached": "Attached to {body} / {path}", + "sketch_panel.author": "Author placement: {path}", + "sketch_panel.dimension_hint": "Enter a value or expression, then press OK.", + "sketch_panel.move_hint": "Enter distances and an angle, then press OK.", + "sketch_panel.plane_angle": "{plane}, turned by {angle}", + "sketch_panel.plane_fixed": "A fixed plane", + "sketch_panel.plane_flipped": "{plane}, from its other side", + "sketch_panel.plane_offset": "{plane}, offset by {distance}", + "sketch_panel.plane_origin": "The {plane} plane", + "sketch_panel.redefine_title": "{command}: {name}", + "sketch_panel.sheet_attachment": "Attached to a flat face of a sheet metal body; it follows that panel when the sheet changes.", + "sketch_panel.text_hint": "Edit the text and its placement, then press OK.", + "sketch_panel.use_plane": "Use {plane} plane", + "sketch_text.align_center": "Center", + "sketch_text.align_left": "Left", + "sketch_text.align_right": "Right", + "sketch_text.bold": "Bold", + "sketch_text.builtin_font": "{family} (built-in)", + "sketch_text.italic": "Italic", + "sketch_text.loading_fonts": "Looking for installed fonts…", + "sketch_text.on_path": "The text follows its path: the curve places it", + "sketch_text.path_clear": "Take the text off its curve", + "sketch_text.path_hint": "A curve of the sketch the text follows: click here, then the curve", + "sketch_text.use_font_file": "Use the font file {path}", + "solid": "solid", + "the parts library is not available": "the parts library is not available", + "thread.automatic_size": "Automatic size", + "thread.designation": "Designation", + "thread.iso_metric": "ISO metric", + "thread.select_size": "Select size", + "timeline.delete_after_marker_one": "Delete 1 Feature After History Marker", + "timeline.delete_after_marker_other": "Delete {count} Features After History Marker", + "timeline.delete_folders_tip": "Keep their features and nested folders in the history", + "timeline.delete_folders_with_features_tip": "Delete the folders with every feature in them and their nested folders", + "timeline.delete_many": "Delete {count} Selected Features", + "timeline.feature_error": "Error: {message}", + "timeline.feature_hint": "Double-click to edit · drag to reorder · right-click for more", + "timeline.feature_warning": "Warning: {message}", + "timeline.group": "New Feature Folder", + "timeline.move_many": "Move Timeline Items", + "timeline.move_to_group": "Move Features to Folder", + "timeline.rename_group": "Rename Feature Folder", + "timeline.reorder_many": "Reorder Features", + "timeline.suppress_folders_tip": "Suppress or unsuppress every feature in the folders and their nested folders", + "timeline.ungroup": "Remove Feature Folders", + "to the face": "to the face", + "to the next face": "to the next face", + "toolbar.customize_note": "{tab} tab. Tick a command to give it a toolbar button. You can also drag a row of a panel's drop-down onto the toolbar, drag a button off the toolbar to remove it, or use the pin on a drop-down row.", + "toolbar.image": "IMAGE", + "toolbar.render": "RENDER", + "toolbar.render_appearance": "APPEARANCE", + "toolbar.render_camera": "CAMERA", + "toolbar.render_environment": "ENVIRONMENT", + "toolbar.render_lighting": "LIGHTING", + "toolbar.render_lights": "LIGHTS", + "toolbar.render_result": "RESULT", + "toolbar.render_scene": "SCENE", + "toolbar.render_stage": "STAGE", + "toolbar.render_studio": "STUDIO", + "trace.points": "{count} points along the path", + "trace.stopped_by_contact": "Ends at sample {sample}: {a} would pass through {b}", + "trace.stopped_by_loop": "Ends at sample {sample}: the loop through {joint} can't close any further", + "ui.1_degree_of_freedom": "1 degree of freedom", + "ui.3d_mouse_axes_reassigned": "Axes are reassigned in Preferences, and that still applies on top of this calibration.", + "ui.3d_mouse_button": "Button {number}", + "ui.3d_mouse_button_nothing": "Nothing", + "ui.3d_mouse_button_settings": "3D mouse settings", + "ui.3d_mouse_buttons": "Buttons", + "ui.3d_mouse_buttons_hint": "Press a button on your 3D mouse to find it here, then pick what it does.", + "ui.3d_mouse_buttons_no_device": "Connect a 3D mouse to set what its buttons do.", + "ui.3d_mouse_buttons_reset": "Restore default buttons", + "ui.3d_mouse_calibrate": "Calibrate…", + "ui.3d_mouse_calibrate_tip": "Move the cap as the window asks, so SolidCraft learns which way each axis of this 3D mouse goes and how far. Saved for this 3D mouse.", + "ui.3d_mouse_calibrate_title": "Calibrate 3D mouse", + "ui.3d_mouse_calibrate_wait": "Move the 3D mouse once so SolidCraft can see it.", + "ui.3d_mouse_calibrated": "Calibrated", + "ui.3d_mouse_calibration": "Calibration", + "ui.3d_mouse_calibration_done": "Done. Save it to use it whenever this 3D mouse is connected.", + "ui.3d_mouse_calibration_no_response": "One axis barely moved, so it can't be calibrated. Start over and move the cap further each time.", + "ui.3d_mouse_circles_help": "The circles show what the device sends, after calibration. The test model shows what the view does with it, after invert, speed and the axis assignment.", + "ui.3d_mouse_dead_zone": "Dead zone", + "ui.3d_mouse_dead_zone_tip": "How far the cap has to move before the view does, as a share of its full travel. Raise it if the view drifts while the cap is at rest.", + "ui.3d_mouse_denied": "SolidCraft can see a 3D mouse but isn't allowed to read it. See the 3D mouse setup notes for the udev rule.", + "ui.3d_mouse_denied_short": "Found, but not readable", + "ui.3d_mouse_driven_by": "Which calibrated motion of the device drives this axis. Picking a motion another axis already uses swaps the two.", + "ui.3d_mouse_driven_by_label": "driven by", + "ui.3d_mouse_driver": "Driver", + "ui.3d_mouse_driver_auto": "Automatic", + "ui.3d_mouse_driver_direct": "Direct (hidraw)", + "ui.3d_mouse_driver_fallback": "Reading through spacenavd for now: the device itself could not be opened.", + "ui.3d_mouse_driver_only_direct": "Reading the device directly; spacenavd is not running", + "ui.3d_mouse_driver_only_spacenavd": "Reading through spacenavd, the only way available", + "ui.3d_mouse_forget": "Forget calibration", + "ui.3d_mouse_ghost_left_viewport": "Left viewport", + "ui.3d_mouse_ghost_left_window": "Left window", + "ui.3d_mouse_ghost_position": "Position", + "ui.3d_mouse_ghost_right_viewport": "Right viewport", + "ui.3d_mouse_hint": "Move and rotate the view together; sketches use pan and zoom only.", + "ui.3d_mouse_kind_cap": "Return to Center", + "ui.3d_mouse_kind_question": "What kind of 3D mouse is it?", + "ui.3d_mouse_kind_trackball": "Trackball", + "ui.3d_mouse_looks_like_cap": "The reading stays put while you hold it, the way a Return to Center device does.", + "ui.3d_mouse_looks_like_trackball": "The reading keeps dropping back as soon as you stop moving, the way a trackball's does.", + "ui.3d_mouse_motion_rotation_x": "Rotation X", + "ui.3d_mouse_motion_rotation_y": "Rotation Y", + "ui.3d_mouse_motion_rotation_z": "Rotation Z", + "ui.3d_mouse_motion_translation_x": "Translation X", + "ui.3d_mouse_motion_translation_y": "Translation Y", + "ui.3d_mouse_motion_translation_z": "Translation Z", + "ui.3d_mouse_navigate": "Navigate with the 3D mouse", + "ui.3d_mouse_none": "No 3D mouse found", + "ui.3d_mouse_not_calibrated": "Not calibrated", + "ui.3d_mouse_offer": "Calibrating your 3D mouse fixes swapped or reversed axes and sets its speed and feel.", + "ui.3d_mouse_offer_never": "Never show again", + "ui.3d_mouse_offer_swap": "Swap to Hidraw (Direct Driver)", + "ui.3d_mouse_reading": "Reading", + "ui.3d_mouse_reset_axes": "Reset axis assignment", + "ui.3d_mouse_reset_view": "Reset view", + "ui.3d_mouse_restore": "Restore defaults", + "ui.3d_mouse_restore_ask": "Set the 3D mouse settings back to their defaults? Your calibration and button mapping stay.", + "ui.3d_mouse_section": "3D mouse", + "ui.3d_mouse_show_in_view": "Show the 3D mouse in the 3D view", + "ui.3d_mouse_show_in_view_tip": "A picture of your 3D mouse in the lower left corner, moving as you move it.", + "ui.3d_mouse_skip": "My device can't do this", + "ui.3d_mouse_skip_tip": "Skips this motion both ways, and the calibration leaves it out.", + "ui.3d_mouse_speed": "3D mouse speed", + "ui.3d_mouse_step_lift": "Lift the cap up, hold it, then let go.", + "ui.3d_mouse_step_press": "Press the cap down, hold it, then let go.", + "ui.3d_mouse_step_pull": "Pull the cap toward you, hold it, then let go.", + "ui.3d_mouse_step_push": "Push the cap away from you, hold it, then let go.", + "ui.3d_mouse_step_rest": "Take your hand off the cap and leave it still.", + "ui.3d_mouse_step_rest_trackball": "Take your hand off the ball and leave it still.", + "ui.3d_mouse_step_ring_clockwise": "Turn the scroll ring clockwise a few clicks.", + "ui.3d_mouse_step_ring_counterclockwise": "Turn the scroll ring anticlockwise a few clicks.", + "ui.3d_mouse_step_roll_away": "Roll the ball away from you a few times, then let it stop.", + "ui.3d_mouse_step_roll_left": "Roll the ball left a few times, then let it stop.", + "ui.3d_mouse_step_roll_right": "Roll the ball right a few times, then let it stop.", + "ui.3d_mouse_step_roll_toward": "Roll the ball toward you a few times, then let it stop.", + "ui.3d_mouse_step_slide_left": "Slide the cap left, hold it, then let go.", + "ui.3d_mouse_step_slide_right": "Slide the cap right, hold it, then let go.", + "ui.3d_mouse_step_spin_clockwise": "Spin the ball clockwise a few times, then let it stop.", + "ui.3d_mouse_step_spin_counterclockwise": "Spin the ball anticlockwise a few times, then let it stop.", + "ui.3d_mouse_step_tilt_away": "Tilt the top of the cap away from you (the edge nearest you goes up), hold it, then let go.", + "ui.3d_mouse_step_tilt_left": "Tilt the cap left (left edge down), hold it, then let go.", + "ui.3d_mouse_step_tilt_right": "Tilt the cap right (right edge down), hold it, then let go.", + "ui.3d_mouse_step_tilt_toward": "Tilt the top of the cap toward you (the edge nearest you goes down), hold it, then let go.", + "ui.3d_mouse_step_touch": "Rest your hand on the cap without pushing it.", + "ui.3d_mouse_step_twist_clockwise": "Twist the cap clockwise, hold it, then let go.", + "ui.3d_mouse_step_twist_counterclockwise": "Twist the cap anticlockwise, hold it, then let go.", + "ui.3d_mouse_switch_cap": "Calibrate as Return to Center", + "ui.3d_mouse_switch_trackball": "Calibrate as a trackball", + "ui.3d_mouse_view_axis": "View axis", + "ui.3d_mouse_view_off": "Off", + "ui.3d_mouse_view_off_tip": "The 3D mouse driver's profile turns this axis off, so its motion doesn't move the view. Picking another axis's motion here swaps the two, and that motion stops moving the view.", + "ui.3d_mouse_view_orbit_sideways": "Orbit Y", + "ui.3d_mouse_view_orbit_up_down": "Orbit X", + "ui.3d_mouse_view_pan_sideways": "Pan X", + "ui.3d_mouse_view_pan_up_down": "Pan Y", + "ui.3d_mouse_view_roll": "Roll", + "ui.3d_mouse_view_unmapped": "Axis {n}", + "ui.3d_mouse_view_zoom": "Zoom", + "ui.3d_mouse_waiting": "Waiting for Movement", + "ui.3d_mouse_wiggle": "If you have one plugged in, wiggle it.", + "ui.3d_sketch": "3D Sketch", + "ui.activate": "Activate", + "ui.active_component": "Active component", + "ui.add_configuration": "Add configuration", + "ui.add_parameter": "Add parameter", + "ui.agent_chat": "Agent chat", + "ui.agent_chat_add": "Attach files", + "ui.agent_chat_add_file": "Choose a file…", + "ui.agent_chat_allow": "Allow", + "ui.agent_chat_allow_once": "Allow once", + "ui.agent_chat_allowed": "Allowed", + "ui.agent_chat_answered": "Answer: {option}", + "ui.agent_chat_approval": "Allow the agent to do this?", + "ui.agent_chat_attach_selection": "Attach selection", + "ui.agent_chat_attach_selection_tip": "Send what is selected in the model (faces, edges, features, bodies) with the message, so the agent knows what you mean", + "ui.agent_chat_attach_view": "Attach view", + "ui.agent_chat_attach_view_tip": "Send a picture of the current view with the message", + "ui.agent_chat_attachable": "Pictures, PDFs, text and CAD files", + "ui.agent_chat_auth_agent": "Sign in with {name}", + "ui.agent_chat_auth_env": "Set {vars} in your environment and restart SolidCraft.", + "ui.agent_chat_auth_needed": "The agent asks you to sign in. You sign in with the agent itself; SolidCraft never sees your password or keys.", + "ui.agent_chat_auth_none": "The agent offers no sign-in method here: sign in the way its own documentation describes.", + "ui.agent_chat_auth_retry": "I've signed in: connect again", + "ui.agent_chat_auth_terminal": "Run this in a terminal, then press Connect again:", + "ui.agent_chat_auth_title": "Sign in to the agent", + "ui.agent_chat_cancel": "Cancel", + "ui.agent_chat_changes": "Changes: {n}, one undo step", + "ui.agent_chat_changes_n": "{n} changes", + "ui.agent_chat_changes_of": "{n}/{limit} changes", + "ui.agent_chat_choose_model": "Choose a model", + "ui.agent_chat_close": "Close", + "ui.agent_chat_command": "Agent command", + "ui.agent_chat_connect": "Connect", + "ui.agent_chat_copy": "Copy", + "ui.agent_chat_ctx_bodies": "Bodies", + "ui.agent_chat_ctx_elements": "Elements", + "ui.agent_chat_ctx_features": "Features", + "ui.agent_chat_ctx_more": "+{n} more", + "ui.agent_chat_ctx_other": "Other", + "ui.agent_chat_custom_hint": "Any program that speaks the Agent Client Protocol on stdin and stdout. No shell runs it.", + "ui.agent_chat_denied": "Denied", + "ui.agent_chat_deny": "Deny", + "ui.agent_chat_desktop_only": "The agent chat needs the desktop app.", + "ui.agent_chat_detecting": "Looking for agents…", + "ui.agent_chat_dock": "Dock in the side panel", + "ui.agent_chat_dock_left": "Dock on the left", + "ui.agent_chat_dock_right": "Dock on the right", + "ui.agent_chat_drop_hint": "Drop to attach to your next message", + "ui.agent_chat_edit": "Edit", + "ui.agent_chat_exited": "The agent stopped.", + "ui.agent_chat_failed_start": "The agent could not start: {error}", + "ui.agent_chat_file_cad_not_read": "{name}: a CAD file is imported into the design, not read", + "ui.agent_chat_file_empty_picture": "{name}: an empty picture", + "ui.agent_chat_file_error": "{name}: {error}", + "ui.agent_chat_file_heic": "{name}: HEIC pictures can't be read here; export it as JPEG or PNG first", + "ui.agent_chat_file_importing": "Importing into the design…", + "ui.agent_chat_file_kinds": "{name}: pictures (PNG, JPEG, GIF, WebP, BMP, TIFF), text files (SVG too) and CAD files (STEP, IGES, FreeCAD, Rhino, STL, 3MF, OBJ, glTF) can be attached", + "ui.agent_chat_file_loading": "Reading the file…", + "ui.agent_chat_file_not_a_file": "{name}: not a file", + "ui.agent_chat_file_not_a_picture": "{name}: not a picture", + "ui.agent_chat_file_not_utf8": "{name}: not UTF-8 text", + "ui.agent_chat_file_picture_too_big": "{name}: a picture can be at most {max} MB", + "ui.agent_chat_file_text_too_big": "{name}: a text file can be at most {max} KB", + "ui.agent_chat_file_too_large": "{name}: too large", + "ui.agent_chat_file_too_large_to_send": "{name}: too large to send, even scaled down", + "ui.agent_chat_file_unreadable_picture": "{name}: not a picture this can read", + "ui.agent_chat_files": "Files: {files}", + "ui.agent_chat_files_left_out": "At most {max} files go with one message; left out: {files}", + "ui.agent_chat_files_loading": "Waiting for the files to be read", + "ui.agent_chat_files_max": "At most {max} files on one message", + "ui.agent_chat_flatpak_none_found": "No coding agent found. The Flatpak sandbox cannot see agents installed in your home folder and has no network access by default. To allow Claude Code and its ACP adapter installed through nvm or ~/.local/bin, run this command in a terminal, then restart SolidCraft. It grants access to the listed program and sign-in files, plus network access:", + "ui.agent_chat_import_failed": "{name}: the import failed: {error}", + "ui.agent_chat_intro": "Chat with a coding agent you already use, or a model endpoint you choose. It works on the open design through SolidCraft's tools: its changes show as it makes them and undo as one step per message. What it may do without asking is set in Preferences > AI.", + "ui.agent_chat_key_in_env": "key set", + "ui.agent_chat_last_missing": "The agent used last ({agent}) is not available any more. Pick an agent, then press Retry.", + "ui.agent_chat_left": "Left", + "ui.agent_chat_limit": "The agent reached the limit of {limit} changes for one message. Send another message to let it go on.", + "ui.agent_chat_login_found": "login found", + "ui.agent_chat_minimize": "Minimise to a strip", + "ui.agent_chat_mode_all": "All", + "ui.agent_chat_mode_ask": "Ask", + "ui.agent_chat_mode_edits": "Edits", + "ui.agent_chat_model_no_tools": "{model} can't use SolidCraft's tools, so it can only chat. Pick a model with tool support.", + "ui.agent_chat_model_tip": "The model the agent uses. Your choice is remembered for this agent.", + "ui.agent_chat_new": "New chat", + "ui.agent_chat_new_confirm": "Start a new chat? The current one is cleared.", + "ui.agent_chat_next_picture": "Next picture", + "ui.agent_chat_no_cli": "solidcraft-cli was not found next to the app, so the agent can't reach the design.", + "ui.agent_chat_no_control": "The agent chat's endpoint did not start, so the agent can't reach the design.", + "ui.agent_chat_no_images": "This agent doesn't take pictures", + "ui.agent_chat_no_picture": "There is no picture on the clipboard", + "ui.agent_chat_no_tool_call": "The model didn't use SolidCraft's tools, so the design wasn't changed. Choose a model that supports tool calling; see Local models in the agent chat guide.", + "ui.agent_chat_none_found": "No coding agent found. Install one of these, then press Refresh:", + "ui.agent_chat_none_found_short": "No agent found", + "ui.agent_chat_not_installed": "Not installed", + "ui.agent_chat_not_signed_in": "not signed in", + "ui.agent_chat_open_settings": "Open Preferences", + "ui.agent_chat_own_window": "Own window", + "ui.agent_chat_paste_picture": "Paste a picture", + "ui.agent_chat_permission": "The agent asks to run: {title}", + "ui.agent_chat_pick": "Agent", + "ui.agent_chat_pick_context": "Pick context", + "ui.agent_chat_pick_context_tip": "Choose faces, edges, features and bodies in the model for the agent to look at, then press OK", + "ui.agent_chat_placeholder": "Ask the agent to change the design…", + "ui.agent_chat_placeholder_busy": "Queue a message for when the agent is done (Ctrl+Enter: send now)", + "ui.agent_chat_pop_out": "Open in its own window, which you can move to another screen", + "ui.agent_chat_previous_picture": "Previous picture", + "ui.agent_chat_privacy": "Nothing goes anywhere except to the agent you run, under your own account.", + "ui.agent_chat_privacy_note": "The chat itself sends nothing anywhere: the agent you run talks to its own service under your own account. SolidCraft never sees or stores a key or password.", + "ui.agent_chat_provider_models": "{count} models", + "ui.agent_chat_provider_other": "Other", + "ui.agent_chat_provider_tip": "The provider whose models the next list shows.", + "ui.agent_chat_queue": "Queue", + "ui.agent_chat_queue_full": "Too many messages are waiting: remove one or wait for the agent.", + "ui.agent_chat_queued": "Queued", + "ui.agent_chat_queued_stopped": "Queued (stopped, not sent)", + "ui.agent_chat_refresh": "Refresh", + "ui.agent_chat_refused": "Not allowed for the agent: {reason}", + "ui.agent_chat_remove": "Remove from the queue", + "ui.agent_chat_remove_file": "Take it off this message", + "ui.agent_chat_remove_imported": "Take it off this message; the part stays in the design (Undo removes it)", + "ui.agent_chat_retry": "Retry", + "ui.agent_chat_right": "Right", + "ui.agent_chat_save": "Save", + "ui.agent_chat_send": "Send", + "ui.agent_chat_send_now": "Send now", + "ui.agent_chat_send_now_tip": "Stop the agent's current step and send this next (Ctrl+Enter)", + "ui.agent_chat_setup_body": "SolidCraft talks to a coding agent installed on this computer. Pick one in Preferences › AI.", + "ui.agent_chat_setup_title": "Set up an assistant", + "ui.agent_chat_side": "Agent chat side", + "ui.agent_chat_signed_in": "signed in", + "ui.agent_chat_state_auth": "Sign-in needed", + "ui.agent_chat_state_busy": "Working…", + "ui.agent_chat_state_exited": "Agent stopped", + "ui.agent_chat_state_failed": "Connection failed", + "ui.agent_chat_state_off": "Not connected", + "ui.agent_chat_state_ready": "Ready", + "ui.agent_chat_state_starting": "Starting…", + "ui.agent_chat_stop": "Stop", + "ui.agent_chat_stop_tip": "Stop the agent and everything it started", + "ui.agent_chat_stop_turn_tip": "Stop the agent (Esc). Queued messages stay queued.", + "ui.agent_chat_turn_limit": "Changes per message", + "ui.agent_chat_turn_unlimited": "Unlimited", + "ui.agent_chat_undo_changes": "Undo these changes", + "ui.agent_chat_undo_label": "Agent chat: {message}", + "ui.agent_chat_undone": "(undone)", + "ui.agent_chat_view_attached": "View attached", + "ui.agent_chat_waiting": "Waiting for you", + "ui.agent_cursor": "Agent cursor", + "ui.agent_cursor_speed": "Agent cursor speed", + "ui.agent_off_thread": "Keep the window responsive while agents run commands", + "ui.agent_off_thread_note": "An agent's slow commands (from the AI panel or an MCP client) compute beside the window: you can keep turning and inspecting the view, and stop one from the chip in the view. Off: each runs on the window's thread and the window waits for it.", + "ui.ai_add": "Add", + "ui.ai_add_agent": "Add agent…", + "ui.ai_add_agent_title": "Add agent", + "ui.ai_add_anthropic": "Anthropic-compatible API", + "ui.ai_add_api": "OpenAI-compatible API", + "ui.ai_add_custom": "Custom command", + "ui.ai_add_endpoint": "API endpoint", + "ui.ai_add_installed": "Installed agent", + "ui.ai_add_installed_note": "An entry of your own for an installed agent, for example with other arguments. Installed agents are listed by themselves.", + "ui.ai_added": "added", + "ui.ai_agent_mode_tip": "The agent's own mode: its own tools (shell, file edits) follow it. SolidCraft's tools follow the permissions in Preferences > AI.", + "ui.ai_agents": "Agents", + "ui.ai_always_allow": "Always allow", + "ui.ai_always_allow_tip": "Allow {tool} for this agent from now on, without asking", + "ui.ai_always_allowed": "Always allowed", + "ui.ai_always_allowed_none": "Nothing is always allowed yet. \"Always allow\" answers you give in the chat are listed here.", + "ui.ai_auto_allowed": "Auto-allowed: {title} ({why})", + "ui.ai_auto_mode": "your permission setting", + "ui.ai_auto_ours": "SolidCraft checks its own tools itself", + "ui.ai_auto_remembered": "you chose Always allow", + "ui.ai_bad_url": "Enter a URL that starts with http:// or https://", + "ui.ai_base_url": "Base URL", + "ui.ai_button": "AI", + "ui.ai_command_hint": "my-agent --acp", + "ui.ai_copy_suffix": "copy", + "ui.ai_custom_url": "Custom URL", + "ui.ai_default": "Default", + "ui.ai_http_busy": "the endpoint is busy or over its limit; try again later", + "ui.ai_http_key": "the endpoint refused the key: check it in Preferences > AI", + "ui.ai_http_not_found": "no such endpoint or model: check the base URL and the model name", + "ui.ai_http_too_large": "the conversation is too large for this endpoint; start a new chat", + "ui.ai_key": "API key", + "ui.ai_key_hint": "optional; kept in the system keychain", + "ui.ai_key_needs_https": "A key is only sent over HTTPS, or to this computer.", + "ui.ai_key_note": "Stored in the system keychain, never in SolidCraft's settings. Leave it empty for a local server.", + "ui.ai_keychain_error": "The system keychain refused: {error}", + "ui.ai_kind": "Kind", + "ui.ai_mode_all": "Allow everything", + "ui.ai_mode_all_note": "Nothing asks first. Crash reports stay off limits and the folder limits still apply.", + "ui.ai_mode_all_warning": "The agent can save, overwrite, export and replace your design without asking. Use this only with an agent you trust, on designs you have saved.", + "ui.ai_mode_ask": "Ask every time", + "ui.ai_mode_ask_note": "Every change to the design, and every file action, waits for your Allow.", + "ui.ai_mode_edits": "Auto-allow model edits", + "ui.ai_mode_edits_note": "Modelling commands run without asking; saving, opening, exporting and other file or destructive actions still ask.", + "ui.ai_mode_global": "As set above", + "ui.ai_model": "Model", + "ui.ai_model_hint": "qwen3:14b", + "ui.ai_modes_scope": "These settings cover SolidCraft's tools. An agent's own tools (its shell, its file edits) follow the agent's own mode, which you pick in the chat panel's header when the agent has modes.", + "ui.ai_name": "Name", + "ui.ai_name_hint": "My agent", + "ui.ai_need_command": "Enter the command that starts the agent", + "ui.ai_need_model": "Enter the model name", + "ui.ai_no_answer": "The agent did not answer in time", + "ui.ai_no_http": "This build can't reach API endpoints", + "ui.ai_no_keychain": "The system keychain isn't available, so a key can't be stored. A local server without a key still works.", + "ui.ai_panel": "Panel", + "ui.ai_permissions": "Permissions", + "ui.ai_preset": "Preset", + "ui.ai_protocol": "Protocol", + "ui.ai_remove": "Remove", + "ui.ai_request_timed_out": "The model took longer than {seconds} s. You can raise the request timeout for this endpoint in Preferences › Assistant.", + "ui.ai_request_timeout": "Request timeout", + "ui.ai_request_timeout_hint": "How long one model request to this endpoint may take, from 30 s to an hour. Raise it for a slow local model.", + "ui.ai_reset": "Reset", + "ui.ai_settings": "AI settings…", + "ui.ai_show_features": "Show AI features", + "ui.ai_show_features_note": "The agent chat: a panel where a coding agent you already use, or a model endpoint you choose, works on the open design. Off: no AI button, shortcut, menu entry or panel, and nothing is looked for or started.", + "ui.ai_switch_tip": "Change the agent for this conversation", + "ui.ai_test": "Test", + "ui.ai_test_acp_ok": "Answers: {agent}", + "ui.ai_test_acp_tip": "Starts the agent briefly and asks it for a session; ends it again", + "ui.ai_test_answered": "Reached: {model} answered", + "ui.ai_test_anthropic_tip": "Sends a short message to the endpoint", + "ui.ai_test_api_tip": "Asks the endpoint for its models", + "ui.ai_test_no_model": "Reached: {count} models, but not {model}", + "ui.ai_test_ok": "Reached: {count} models", + "ui.ai_testing": "Testing…", + "ui.ai_tool_arguments": "Arguments", + "ui.ai_tool_details": "Details", + "ui.ai_tool_done": "done", + "ui.ai_tool_failed": "failed", + "ui.ai_tool_result": "Result", + "ui.ai_tool_running": "running", + "ui.ai_tool_sum_bodies_one": "{count} body", + "ui.ai_tool_sum_bodies_other": "{count} bodies", + "ui.ai_tool_sum_by": "by {value}", + "ui.ai_tool_sum_edges_one": "{count} edge", + "ui.ai_tool_sum_edges_other": "{count} edges", + "ui.ai_tool_sum_faces_one": "{count} face", + "ui.ai_tool_sum_faces_other": "{count} faces", + "ui.ai_tool_sum_features_one": "{count} feature", + "ui.ai_tool_sum_features_other": "{count} features", + "ui.ai_tool_sum_measured": "Measured {what}", + "ui.ai_tool_sum_more": "{steps}, and {count} more", + "ui.ai_tool_sum_radius": "r {value}", + "ui.ai_tool_sum_saved": "Saved {file}", + "ui.ai_tool_sum_screenshot": "Screenshot", + "ui.ai_tool_sum_then": "{first}, then {next}", + "ui.ai_tool_unfold": "Click to show what it returned", + "ui.ai_tool_waiting": "waiting", + "ui.ai_toolbar_button": "Show Assistant button in application bar", + "ui.ai_toolbar_button_note": "The Assistant button in the application bar. Ctrl+Shift+A and the View menu still open the panel.", + "ui.ai_undo_tip": "Undo everything the agent changed for this message, as one step", + "ui.ai_url_hint": "https://example.com/v1", + "ui.all": "All", + "ui.ambient_occlusion": "Ambient occlusion", + "ui.ambient_occlusion_help": "Soft shading where opaque surfaces meet. Requires the GPU viewport.", + "ui.analysis": "Analysis", + "ui.angle": "Angle", + "ui.angle_decimals": "Angle decimals", + "ui.animateJoint": "Animate Joint", + "ui.animate_view_changes": "Animate view changes", + "ui.animation": "Animation", + "ui.animation_speed": "Animation speed", + "ui.anti_aliasing": "Anti-aliasing", + "ui.apply": "Apply", + "ui.arc": "Arc", + "ui.assistant": "Assistant", + "ui.assistant_waiting": "{count} approvals waiting", + "ui.autosave_every": "Autosave every", + "ui.axes": "Axes", + "ui.axis": "Axis", + "ui.back": "Back", + "ui.base_point": "Base point", + "ui.blocked": "Blocked", + "ui.bodies": "Bodies", + "ui.bodies_all_if_none": "Bodies (all if none)", + "ui.bottom": "Bottom", + "ui.box": "Box", + "ui.break": "Break", + "ui.browser_bodies_one": "{count} body", + "ui.browser_bodies_other": "{count} bodies", + "ui.browser_collapse": "Collapse the browser", + "ui.browser_expand": "Expand the browser", + "ui.browser_title": "Browser", + "ui.calibrate": "Calibrate", + "ui.cancel": "Cancel", + "ui.canvases": "Canvases", + "ui.center": "Center", + "ui.centerline": "Centerline", + "ui.chain": "Chain", + "ui.chamfer": "Chamfer", + "ui.chamfer_type": "Chamfer Type", + "ui.change_workspace": "Change workspace", + "ui.circle": "Circle", + "ui.circular_pattern": "Circular Pattern", + "ui.clear": "Clear", + "ui.clear_recent": "Clear Recent", + "ui.clear_the_selection": "Clear the selection", + "ui.click_selects_whole_bodies": "Click selects whole bodies", + "ui.click_then_press_key": "Click, then press the new key", + "ui.close": "Close", + "ui.coil": "Coil", + "ui.coincident": "Coincident", + "ui.collapse": "Collapse", + "ui.collinear": "Collinear", + "ui.colour_vision": "Colour vision", + "ui.colour_vision_deutan": "Deutan", + "ui.colour_vision_deutan_tip": "For a weak or missing green sense", + "ui.colour_vision_failed": "Failed", + "ui.colour_vision_fixed": "Fixed", + "ui.colour_vision_mode": "Mode", + "ui.colour_vision_note": "Changes the colours that carry a meaning: sketch states, axes, bends, analyses and icons. If you use Windows colour filters, keep this Off.", + "ui.colour_vision_off": "Off", + "ui.colour_vision_off_tip": "The theme's own colours", + "ui.colour_vision_projected": "Projected", + "ui.colour_vision_protan": "Protan", + "ui.colour_vision_protan_tip": "For a weak or missing red sense", + "ui.colour_vision_sample": "Sample", + "ui.colour_vision_tritan": "Tritan", + "ui.colour_vision_tritan_tip": "For a weak or missing blue sense", + "ui.combine": "Combine", + "ui.coming_later": "coming later", + "ui.command_done": "{command} done", + "ui.command_palette_hint": "Type a command, e.g. {example} — or press S to search", + "ui.concentric": "Concentric", + "ui.cone": "Cone", + "ui.conic_curve": "Conic Curve", + "ui.constant": "Constant", + "ui.constraints_conflict": "Constraints conflict", + "ui.construction": "Construction", + "ui.construction.ribbon_label": "Помощни прави", + "ui.context_menu": "Context menu", + "ui.continuity_g0": "G0 crease", + "ui.continuity_g1": "G1 tangent", + "ui.continuity_g2": "G2 curvature", + "ui.continuity_gap": "Gap", + "ui.copy": "Copy", + "ui.corner": "Corner", + "ui.corners": "Corners", + "ui.cosmetic_thread_markings": "Cosmetic thread markings", + "ui.cosmetic_thread_markings_help": "Show schematic markings on threaded cylindrical walls. Changes only the display, never the design or exports.", + "ui.counterbore": "Counterbore", + "ui.countersink": "Countersink", + "ui.create": "Create", + "ui.create_copy": "Create Copy", + "ui.create_sketch": "Create Sketch", + "ui.current": "current", + "ui.curvature": "Curvature", + "ui.curvature_g2": "Curvature (G2)", + "ui.curves": "Curves", + "ui.custom_program": "Custom…", + "ui.custom_program_tip": "Choose a slicer program to add to the list", + "ui.customizeToolbar": "Customize Toolbar…", + "ui.cut": "Cut", + "ui.cylinder": "Cylinder", + "ui.dark": "Dark", + "ui.default_modelling_orientation": "Default modelling orientation", + "ui.delete": "Delete", + "ui.depth": "Depth", + "ui.design": "Design", + "ui.design_properties.author": "Author", + "ui.design_properties.description": "Description", + "ui.design_properties.exports": "STEP, IGES and 3MF exports carry these where the format has a place for them.", + "ui.design_properties.license": "License", + "ui.design_properties.not_text": "Saved as something other than text; typing here replaces it.", + "ui.design_properties.organization": "Organization", + "ui.design_properties.others": "Other tools' data", + "ui.design_properties.others_note": "Kept in the design as it is and never exported.", + "ui.design_properties.part_number": "Part number", + "ui.design_properties.project": "Project", + "ui.design_properties.revision": "Revision", + "ui.diameter": "Diameter", + "ui.dimension": "Dimension", + "ui.direction": "Direction", + "ui.display_quality": "Display quality", + "ui.display_quality_coarse": "Coarse", + "ui.display_quality_fine": "Fine", + "ui.display_quality_normal": "Normal", + "ui.display_quality_ultra": "Ultra", + "ui.distance": "Distance", + "ui.distance_1": "Distance 1", + "ui.distance_2": "Distance 2", + "ui.document_settings": "Document Settings", + "ui.don_t_save": "Don't Save", + "ui.draft": "Draft", + "ui.drawing": "Drawing", + "ui.drill_point": "Drill Point", + "ui.easyprint_consent": "EasyPrint is Printables' slicer in the browser. To open the model there, SolidCraft uploads it to Printables' servers. The link expires after 30 minutes, and you'll need to be signed in to Printables. Continue?", + "ui.easyprint_failed": "EasyPrint upload failed: {error}", + "ui.easyprint_opened": "Opened in EasyPrint", + "ui.easyprint_row": "EasyPrint (Printables, in the browser)", + "ui.easyprint_uploading": "Uploading to Printables…", + "ui.edit": "Edit", + "ui.editJointLimits": "Edit Joint Limits", + "ui.edit_section_analysis": "Edit Section Analysis", + "ui.ellipse": "Ellipse", + "ui.end_radius": "End Radius", + "ui.end_scale": "End Scale", + "ui.entities": "Entities", + "ui.equal": "Equal", + "ui.equivalent_radius": "Equivalent Radius", + "ui.expand": "Expand", + "ui.exportDxf": "Export DXF…", + "ui.export_ellipsis_keymap": "Export…", + "ui.export_keymap_tip": "Keys, S box favourites and the toolbar, as a file", + "ui.extend": "Extend", + "ui.extent_type": "Extent Type", + "ui.extract_component": "Extract to File…", + "ui.extract_design_changed": "The design changed while choosing a file. Start Extract to File again.", + "ui.extract_done": "The component is now its own design, linked here.", + "ui.extrude": "Extrude", + "ui.extrude_auto_to_object": "Extrude to a picked target", + "ui.extrude_auto_to_object_tip": "In Extrude, with a profile picked, picking a face, vertex or parallel plane off its plane switches the extent to To Object", + "ui.factor": "Factor", + "ui.feature_history": "Feature history", + "ui.feature_options": "Feature Options", + "ui.features": "Features", + "ui.file": "File", + "ui.fillet": "Fillet", + "ui.filter_commands_or_keys": "Filter commands or keys", + "ui.findInTimeline": "Find in Timeline", + "ui.findInWindow": "Find in Window", + "ui.fine": "Fine", + "ui.finest": "Finest", + "ui.finish_sketch": "Finish Sketch", + "ui.fit": "Fit", + "ui.fix_unfix": "Fix/Unfix", + "ui.flat": "Flat", + "ui.flip": "Flip", + "ui.format": "Format", + "ui.frame_rate": "Frame rate", + "ui.frame_rate_details": "Frame rate details", + "ui.front": "Front", + "ui.fully_constrained": "Fully constrained", + "ui.function": "Function", + "ui.general": "General", + "ui.gpu_memory_lowered": "The graphics card is out of memory: the view is drawn at a lower quality.", + "ui.graphics": "Graphics", + "ui.graphics_custom": "Custom", + "ui.graphics_performance": "Performance", + "ui.graphics_preset": "Graphics Preset", + "ui.graphics_preset_help": "Quality: ambient occlusion, Fine display quality and adaptive 2× supersampling. Performance: no ambient occlusion, Normal display quality and supersampling off. Manual changes show Custom. MSAA stays unchanged.", + "ui.graphics_quality": "Quality", + "ui.grid_follows_view": "Grid follows the view", + "ui.grid_follows_view_hint": "Side views show the grid on the upright plane facing them instead of the ground", + "ui.ground_shadow": "Ground shadow", + "ui.groupSelected": "Group Selected", + "ui.hatch": "Hatch", + "ui.heading_add_ins": "ADD-INS", + "ui.heading_assemble": "ASSEMBLE", + "ui.heading_box": "BOX", + "ui.heading_chamfer": "CHAMFER", + "ui.heading_circular_pattern": "CIRCULAR PATTERN", + "ui.heading_coil": "COIL", + "ui.heading_combine": "COMBINE", + "ui.heading_cone": "CONE", + "ui.heading_configure": "CONFIGURE", + "ui.heading_constraints": "CONSTRAINTS", + "ui.heading_construct": "CONSTRUCT", + "ui.heading_create": "CREATE", + "ui.heading_create_sketch": "CREATE SKETCH", + "ui.heading_cylinder": "CYLINDER", + "ui.heading_design": "DESIGN", + "ui.heading_draft": "DRAFT", + "ui.heading_edit": "EDIT", + "ui.heading_extrude": "EXTRUDE", + "ui.heading_fillet": "FILLET", + "ui.heading_finish_sketch": "FINISH SKETCH", + "ui.heading_front": "FRONT", + "ui.heading_hole": "HOLE", + "ui.heading_home": "HOME", + "ui.heading_insert": "INSERT", + "ui.heading_inspect": "INSPECT", + "ui.heading_interference": "INTERFERENCE", + "ui.heading_loft": "LOFT", + "ui.heading_make": "MAKE", + "ui.heading_measure": "MEASURE", + "ui.heading_mesh": "MESH", + "ui.heading_mirror": "MIRROR", + "ui.heading_modify": "MODIFY", + "ui.heading_move": "MOVE", + "ui.heading_move_copy": "MOVE/COPY", + "ui.heading_offset": "OFFSET", + "ui.heading_offset_plane": "OFFSET PLANE", + "ui.heading_ok": "OK", + "ui.heading_parameters": "PARAMETERS", + "ui.heading_pattern": "PATTERN", + "ui.heading_pattern_on_path": "PATTERN ON PATH", + "ui.heading_pipe": "PIPE", + "ui.heading_plane_at_angle": "PLANE AT ANGLE", + "ui.heading_plastic": "PLASTIC", + "ui.heading_position": "POSITION", + "ui.heading_prepare": "PREPARE", + "ui.heading_rectangular_pattern": "RECTANGULAR PATTERN", + "ui.heading_revolve": "REVOLVE", + "ui.heading_right": "RIGHT", + "ui.heading_save_mesh": "SAVE AS MESH", + "ui.heading_scale": "SCALE", + "ui.heading_section_analysis": "SECTION ANALYSIS", + "ui.heading_select": "SELECT", + "ui.heading_setup": "SETUP", + "ui.heading_sheet_metal": "SHEET METAL", + "ui.heading_shell": "SHELL", + "ui.heading_sketch": "SKETCH", + "ui.heading_sketch_scale": "SKETCH SCALE", + "ui.heading_solid": "SOLID", + "ui.heading_sphere": "SPHERE", + "ui.heading_split_body": "SPLIT BODY", + "ui.heading_surface": "SURFACE", + "ui.heading_sweep": "SWEEP", + "ui.heading_thread": "THREAD", + "ui.heading_top": "TOP", + "ui.heading_torus": "TORUS", + "ui.heading_utilities": "UTILITIES", + "ui.heading_utility": "UTILITY", + "ui.heading_weldments": "WELDMENTS", + "ui.height": "Height", + "ui.help": "Help", + "ui.hide": "Hide", + "ui.hideAxes": "Hide Axes", + "ui.hideDimension": "Hide Dimension", + "ui.hideOrigin": "Hide Origin", + "ui.hidePlanes": "Hide Planes", + "ui.hideProfile": "Hide Profile", + "ui.hide_origin_by_default": "Hide origin by default", + "ui.hide_origin_note": "New designs start with the Origin folder hidden. A design keeps its own Origin setting once you show or hide it.", + "ui.history_back": "Go back one step", + "ui.history_below_browser": "Below browser", + "ui.history_edge_hint": "double-click the edge", + "ui.history_first": "Go to beginning", + "ui.history_forward": "Go forward one step", + "ui.history_hide_names": "Hide names", + "ui.history_last": "Go to end", + "ui.history_marker_tip": "History marker: drag to roll the model back; new features go here", + "ui.history_names": "Names", + "ui.history_play": "Play to the end", + "ui.history_show_names": "Show names", + "ui.history_sketch_listed_under": "Listed under {feature}", + "ui.history_title": "History", + "ui.history_toggle_names": "Show or hide feature names", + "ui.hole": "Hole", + "ui.hole_tap_type": "Hole Tap Type", + "ui.hole_type": "Hole Type", + "ui.home": "Home", + "ui.homeView": "Home View", + "ui.horizontal_constraint": "Horizontal Constraint", + "ui.horizontal_vertical": "Horizontal/Vertical", + "ui.import_ellipsis": "Import…", + "ui.infinite": "Infinite", + "ui.insert": "Insert", + "ui.inspect": "Inspect", + "ui.intersect": "Intersect", + "ui.isolate": "Isolate", + "ui.join": "Join", + "ui.joints": "Joints", + "ui.keyboard_shortcuts": "Keyboard Shortcuts", + "ui.language": "Language", + "ui.layout_compact": "Compact", + "ui.layout_floating": "Floating", + "ui.length": "Length", + "ui.length_decimals": "Length decimals", + "ui.light": "Light", + "ui.line": "Line", + "ui.link_copies": "Link Identical Copies", + "ui.link_copies_keep": "Keep", + "ui.link_copies_link": "Link", + "ui.link_copies_text": "These components build the same bodies as {name}. Make them placements of its link?", + "ui.lock": "Lock", + "ui.loft": "Loft", + "ui.look_at": "Look At", + "ui.look_at_anim_desc": "Axis view, Look At, Home and Fit", + "ui.major_radius": "Major radius", + "ui.manipulator_free_alt": "Manipulator free drag also on Alt/Option", + "ui.manipulator_free_alt_tip": "On: Alt/Option or Ctrl/Cmd on extrude / gizmo arrows disables value snapping. Off: Ctrl/Cmd only.", + "ui.manufacture": "Manufacture", + "ui.material_review.axes": "Material-local axes; no body orientation is assigned.", + "ui.material_review.claims": "Sources and licences are unverified claims. Missing values remain unknown.", + "ui.material_review.compressive_strength": "Compressive strength", + "ui.material_review.conditions": "Stated conditions", + "ui.material_review.density": "Density", + "ui.material_review.derived": "Derived isotropic moduli", + "ui.material_review.elasticity": "Elasticity", + "ui.material_review.input": "Paste a schema-1 material card (JSON)", + "ui.material_review.limit": "The card exceeds the 256 KiB input limit.", + "ui.material_review.moisture_unit": "kg water / kg dry material", + "ui.material_review.properties": "Properties", + "ui.material_review.review": "Review card", + "ui.material_review.scope": "Candidate only: not assigned or saved. Numerical validation is not engineering certification.", + "ui.material_review.shear_strength": "Shear strength", + "ui.material_review.source": "Source", + "ui.material_review.specific_heat": "Specific heat", + "ui.material_review.tensile_strength": "Tensile strength", + "ui.material_review.thermal_conductivity": "Thermal conductivity", + "ui.material_review.thermal_expansion": "Thermal expansion", + "ui.material_review.title": "Review Physical Material Data", + "ui.material_review.unknown": "Unknown", + "ui.material_review.yield_strength": "Yield strength", + "ui.measure": "Measure", + "ui.mesh_format_3mf": "3MF", + "ui.mesh_format_3mf_tagged": "3MF with face tags", + "ui.mesh_format_stl": "STL", + "ui.minor_radius": "Minor radius", + "ui.mirror": "Mirror", + "ui.mirror_line": "Mirror line", + "ui.move": "Move", + "ui.multiple": "Multiple", + "ui.named_views": "Named Views", + "ui.nav_bridge": "Navigate with a device app on this computer", + "ui.nav_bridge_connected": "Connected", + "ui.nav_bridge_port": "Port", + "ui.nav_bridge_tip": "A 3D input device's own program (for example a homemade 3D mouse's driver) moves the view over a local connection, so the mouse pointer stays yours. SolidCraft connects to it on this port on this computer only.", + "ui.nav_bridge_waiting": "Waiting for the device app", + "ui.navigation": "Navigation", + "ui.needs_design": "{command}: първо отворете дизайн", + "ui.newSketchGroup": "New Sketch Group", + "ui.new_body": "New Body", + "ui.new_design": "New Design", + "ui.no_geometry_yet": "No geometry yet", + "ui.no_slicer_found": "No slicer found", + "ui.normal": "Normal", + "ui.normalConstruction": "Normal / Construction", + "ui.not_a_program": "{path} is not a program that can be started", + "ui.object_type": "Object Type", + "ui.objects": "Objects", + "ui.offer_to_stand_up_y_up_files": "Offer to stand up Y-up files", + "ui.offset": "Offset", + "ui.offset_plane": "Offset Plane", + "ui.one_side": "One Side", + "ui.open": "Open", + "ui.open_ends_tip": "Touches nothing", + "ui.open_linked_design": "Open Linked Design", + "ui.open_preferences": "Open Preferences", + "ui.open_recent": "Open Recent", + "ui.operation": "Operation", + "ui.options": "Options", + "ui.orbit": "Orbit", + "ui.orbit_around": "Orbit around", + "ui.orientation": "Orientation", + "ui.origin": "Origin", + "ui.palette_construction_mode": "Construction mode (X)", + "ui.palette_more": "More", + "ui.palette_sketch_options": "Sketch options", + "ui.pan": "Pan", + "ui.pan_zoom_orbit": "Pan, zoom, orbit", + "ui.parallel": "Parallel", + "ui.parameters": "Parameters", + "ui.part_size_shared": "Rebuilds the part, replacing any added features. All occurrences of this component update.", + "ui.paste": "Paste", + "ui.path": "Path", + "ui.pattern_on_path": "Pattern on Path", + "ui.perforate_margin_default": "from the diameter", + "ui.perforate_pitch": "Pitch", + "ui.perforate_square": "Square", + "ui.perforate_staggered": "Staggered (60°)", + "ui.perforate_title": "PERFORATE", + "ui.perpendicular": "Perpendicular", + "ui.perspective_view": "Perspective view", + "ui.pinToShortcuts": "Pin to Shortcuts", + "ui.pinToToolbar": "Pin to Toolbar", + "ui.pipe": "Pipe", + "ui.pitch": "Pitch", + "ui.placement": "Placement", + "ui.placement_handles": "Placement handles", + "ui.placement_handles_tip": "Handles on the preview of a Rest, Boss or Snap Fit: drag the marker to move it across the model, turn it by its ring", + "ui.plane": "Plane", + "ui.plane_at_angle": "Plane at Angle", + "ui.plugins": "Plugins", + "ui.plugins_desktop": "Plugins are available in the desktop app.", + "ui.plugins_empty": "No plugins installed.", + "ui.plugins_none": "No plugins match this search.", + "ui.plugins_note": "Each plugin is a folder inside {path} with a plugin.json. SolidCraft reads that file and does not run any code from the folder. Turning a plugin off keeps it installed.", + "ui.plugins_search": "Search plugins", + "ui.plugins_skipped": "{count} folder(s) could not be read.", + "ui.plugins_version": "{version}", + "ui.point": "Point", + "ui.point_under_the_cursor": "Point under the cursor", + "ui.points": "Points", + "ui.polygon": "Polygon", + "ui.preferences": "Настройки", + "ui.press_a_key": "press a key…", + "ui.profile": "Profile", + "ui.profile_plane": "Profile Plane", + "ui.profiles": "Profiles", + "ui.project": "Project", + "ui.project_face_edges_sketch": "Project face edges into new sketches", + "ui.properties": "Properties", + "ui.pull_direction": "Pull direction", + "ui.quality": "Quality", + "ui.quantity": "Quantity", + "ui.quantity_2": "Quantity 2", + "ui.quit": "Quit", + "ui.radial_context_menu": "Radial context menu", + "ui.radius": "Radius", + "ui.rail": "Rail", + "ui.rail_fit": "Rail Fit", + "ui.reachable": "Reachable", + "ui.rectangle": "Rectangle", + "ui.rectangular_pattern": "Rectangular Pattern", + "ui.redo": "Redo", + "ui.reference_1": "Reference 1", + "ui.reference_2": "Reference 2", + "ui.reference_distance": "Reference distance", + "ui.relink_design_changed": "The assembly changed while choosing a source. Start Relink Source again.", + "ui.relink_done": "Source relinked for all instances.", + "ui.relink_not_linked": "This component is not linked to a source design.", + "ui.relink_select_one": "Select one linked component or one of its instances first.", + "ui.relink_source_all": "Relink Source (All Instances)…", + "ui.removeFromToolbar": "Remove from Toolbar", + "ui.removeSection": "Remove Section", + "ui.render": "Render", + "ui.renderer": "Renderer", + "ui.repeat": "Repeat", + "ui.repeat_nothing": "Nothing to repeat yet: start a tool or dialog first.", + "ui.replace_with_link_done": "The copies are now placements of the linked design.", + "ui.report_a_bug": "Report a bug", + "ui.reset": "Reset", + "ui.reset_all": "Reset All", + "ui.reset_the_settings_on_this_page": "Reset the settings on this page", + "ui.restore": "Restore", + "ui.restore_defaults": "Restore Defaults", + "ui.reverse_horizontal_pan_direction": "Reverse horizontal pan direction", + "ui.reverse_horizontal_pan_tip": "Horizontal two-finger scrolling and the thumb wheel pan the other way", + "ui.reverse_zoom_direction": "Reverse zoom direction", + "ui.revolutions": "Revolutions", + "ui.revolve": "Revolve", + "ui.ribbon_exit": "Exit", + "ui.ribbon_labels": "Show text under ribbon icons", + "ui.ribbon_pin_footer": "Pinned commands show on the ribbon. Hover a row to pin or unpin it.", + "ui.ribbon_workspace": "Workspace", + "ui.right": "Right", + "ui.save": "Save", + "ui.save_as": "Save As", + "ui.save_mesh_no_slicer_open": "No slicer found: choose Custom… and pick your slicer program", + "ui.save_mesh_pick_bodies": "Select the bodies to save", + "ui.saved_to": "Saved {path}", + "ui.sbox_pin": "Pin to the top of the S box", + "ui.sbox_unpin": "Unpin", + "ui.scale": "Scale", + "ui.second_rail": "Second Rail", + "ui.section_analysis": "Section Analysis", + "ui.section_size": "Section size", + "ui.select": "Select", + "ui.selectOther": "Select Other…", + "ui.selectTangentChain": "Select Tangent Chain", + "ui.selection": "Selection", + "ui.selection_modifiers": "Selection modifiers", + "ui.selection_shift_add_only": "Shift+click adds without removing", + "ui.selection_shift_add_only_tip": "On: Shift adds items, Ctrl/Cmd toggles. Off (default): Shift and Ctrl/Cmd both toggle.", + "ui.send": "Send", + "ui.send_to_slicer_unavailable": "Send to Slicer needs the desktop app: a browser can't start a program", + "ui.sent_to_slicer": "Sent to {slicer}", + "ui.sent_to_slicer_copy": "Sent to {slicer} as {file}, because the first file is still open there", + "ui.sheet_gap": "Gap", + "ui.shell": "Shell", + "ui.shortcut_capture_add_key": "Add one ordinary key. Escape cancels.", + "ui.shortcut_capture_hint": "Click a binding, then press modifiers and one key. Add modifiers within one second; release all keys to confirm. Escape cancels.", + "ui.shortcut_capture_press": "Press modifiers and one key. Escape cancels.", + "ui.shortcut_capture_release": "Release all keys to confirm. Escape cancels.", + "ui.shortcut_capture_settling": "Confirming shortcut… Escape cancels.", + "ui.shortcut_cycles_modes": "Pressing a tool's shortcut again switches its mode", + "ui.shortcut_cycles_modes_tip": "Before the first point, pressing a sketch tool's shortcut again steps through its creation modes. Off: it starts the tool again.", + "ui.shortcut_multiple_keys": "Use modifiers and only one other key. Click the binding to try again.", + "ui.show": "Show", + "ui.showAll": "Show All", + "ui.showAllBodies": "Show All Bodies", + "ui.showAxes": "Show Axes", + "ui.showDimension": "Show Dimension", + "ui.showOrigin": "Show Origin", + "ui.showPlanes": "Show Planes", + "ui.show_constraints": "Constraints", + "ui.show_construction_geometries": "Construction Geometries", + "ui.show_dimensions": "Dimensions", + "ui.show_profile": "Show Profile", + "ui.show_projected_geometries": "Projected Geometries", + "ui.simple": "Simple", + "ui.simulation": "Simulation", + "ui.single": "Single", + "ui.sketch": "Sketch", + "ui.sketch_dimension": "Sketch Dimension", + "ui.sketch_grid": "Sketch Grid", + "ui.sketch_modifiers": "Sketch modifiers", + "ui.sketch_scale": "Sketch Scale", + "ui.sketches": "Sketches", + "ui.slice": "Slice", + "ui.slicer": "Slicer", + "ui.slicer_delete_tip": "{program}\nPress Delete to remove it from the list", + "ui.slicer_lost": "{slicer} was started but can't be found again to send it the file. The file is saved at {path}: open it from there.", + "ui.slicer_no_file": "{slicer} is ready, but there is no file to send to it.", + "ui.slicer_no_response": "{slicer} didn't respond in time. The file is already saved at {path}: send it again once the slicer has started.", + "ui.slicer_resend_hint": "Sending again replaces the file the slicer has open.", + "ui.slicer_single_instance": "Open files in a slicer that is already running", + "ui.slicer_single_instance_tip": "PrusaSlicer, SuperSlicer and Cura load the file in the window that is open instead of starting another. Other slicers are started as they are. PrusaSlicer 3.0 always does this: its launcher can't take a file any other way.", + "ui.slicer_starting": "Starting {slicer}…", + "ui.slicer_still_starting": "Still waiting for {slicer} to start. Nothing else was sent.", + "ui.slicer_stl_fallback": "The 3MF could not be written, so this is an STL.", + "ui.slot": "Slot", + "ui.smooth": "Smooth", + "ui.smooth_wheel_zoom": "Smooth wheel zoom", + "ui.smooth_wheel_zoom_tip": "Turn off to apply each wheel event immediately, without a smoothing tail", + "ui.snap": "Snap", + "ui.spacing": "Spacing", + "ui.spacing_2": "Spacing 2", + "ui.sphere": "Sphere", + "ui.spline": "Spline", + "ui.split_body": "Split Body", + "ui.stand_up_tip": "After a STEP or IGES file opens with Z up, offer a quarter turn about X", + "ui.standard": "Standard", + "ui.start": "Start", + "ui.start_over": "Start over", + "ui.start_page": "Start page", + "ui.step_values": "Step values with the arrow keys and the wheel", + "ui.step_values_tip": "In a value field you are typing in, Up/Down change a plain number by 1 (Shift: 10, Alt: 0.1), and so does the mouse wheel over the field. Expressions are left as typed.", + "ui.stretch": "Stretch", + "ui.supersampling": "Supersampling (SSAA)", + "ui.supersampling_adaptive": "Only when the view is still", + "ui.supersampling_off": "Off (1×)", + "ui.suppress": "Suppress", + "ui.suppress_auto_snap": "Suppress auto-snap while drawing / dragging", + "ui.suppress_auto_snap_note": "Default: Ctrl/Cmd or Alt/Option each suppress sketch snapping. Choose a single key to narrow it.", + "ui.sweep": "Sweep", + "ui.sweep_follow_direction": "Follow Direction", + "ui.sweep_keep_as_drawn": "Keep as Drawn", + "ui.sweep_turn_with_path": "Turn with Path", + "ui.symmetric": "Symmetric", + "ui.symmetry": "Symmetry", + "ui.system": "System", + "ui.tangent": "Tangent", + "ui.taper_angle": "Taper Angle", + "ui.tapped": "Tapped", + "ui.text": "Text", + "ui.theme": "Theme", + "ui.thickness": "Thickness", + "ui.thread": "Thread", + "ui.tie_ends": "Tie", + "ui.tie_ends_tip": "Constrain all untied ends", + "ui.timeline_bottom": "Bottom timeline", + "ui.timeline_left_note": "The vertical history sits to the left of the browser. Toggle feature names on the strip.", + "ui.timeline_left_sidebar": "Left sidebar", + "ui.tip_angle": "Tip Angle", + "ui.to_object": "To Object", + "ui.tool_direction": "Tool direction", + "ui.top": "Top", + "ui.top_diameter": "Top diameter", + "ui.top_radius": "Top radius", + "ui.torus": "Torus", + "ui.total_angle": "Total angle", + "ui.trackpad_pan_tip": "Two-finger scroll pans; in Fusion, Shift + two fingers orbits. Off: scroll zooms. Mouse wheel and pinch zoom; thumb wheel pans sideways.", + "ui.trim": "Trim", + "ui.turn_up_axis": "Turn Up Axis", + "ui.twist": "Twist", + "ui.two_finger_scroll_pans": "Two-finger scroll pans", + "ui.two_sides": "Two Sides", + "ui.ui_scale": "UI scale", + "ui.undo": "Undo", + "ui.unground": "Unground", + "ui.unisolate": "Unisolate", + "ui.units": "Units", + "ui.units_of_new_designs": "Units of new designs", + "ui.unlock": "Unlock", + "ui.unsuppress": "Unsuppress", + "ui.untied_ends_tip": "Touches by position only", + "ui.untitled": "Untitled", + "ui.up_axis_note": "Which axis points up in the views (axis view, Home, Look At). Designs are unchanged.", + "ui.updateToCurrentView": "Update to Current View", + "ui.upload": "Upload", + "ui.vertical_constraint": "Vertical Constraint", + "ui.view_centre": "View centre", + "ui.viewport_theme_follow": "Follow theme", + "ui.visual_shaded_hidden_edges": "Shaded with hidden edges", + "ui.visual_shaded_with_edges": "Shaded with edges", + "ui.visual_style": "Visual style", + "ui.visual_wireframe": "Wireframe", + "ui.width": "Width", + "ui.window_system": "Window system", + "ui.window_system_auto": "Automatic", + "ui.window_system_wayland": "Wayland", + "ui.window_system_x11": "X11", + "ui.workspace": "workspace", + "ui.workspace_animation_description": "Exploded views, motion studies and storyboards", + "ui.workspace_available": "Available", + "ui.workspace_current": "Current", + "ui.workspace_design_description": "Sketch, model, assemble and inspect", + "ui.workspace_design_tabs": "Model · Surface · Assemble · Insert · Inspect · Manage · View", + "ui.workspace_drawing_description": "2D drawings with views, dimensions and title blocks", + "ui.workspace_footer": "Every workspace works on the same design, history and selection; only the ribbon tabs change. The switcher is locked while a sketch or feature is being edited.", + "ui.workspace_layout": "Workspace layout", + "ui.workspace_manufacture_description": "Slicing, toolpaths and setup", + "ui.workspace_planned": "Planned", + "ui.workspace_render_description": "Product preview, scene settings and rendered images", + "ui.workspace_render_tabs": "Scene · Image", + "ui.workspace_simulation_description": "Loads, constraints and results", + "ui.x_distance": "X Distance", + "ui.y_distance": "Y Distance", + "ui.y_up": "Y up", + "ui.z_up": "Z up", + "ui.zoom": "Zoom", + "ui.zoom_to_cursor_tip": "The wheel zooms toward the point under the cursor (off: toward the view's centre)", + "ui.zoom_to_the_cursor": "Zoom to the cursor", + "update.available": "SolidCraft {version} is available", + "update.button": "Update", + "update.button_version": "Update to {version}", + "update.check_automatically": "Check for updates automatically", + "update.check_now": "Check now", + "update.checking": "Checking…", + "update.copy": "Copy", + "update.dmg_opened": "The disk image is open and verified: drag SolidCraft to Applications, replacing the old copy, then restart SolidCraft.", + "update.download": "Download", + "update.download_open": "Download and open", + "update.downloading": "Downloading and verifying… {done} of {total} MB", + "update.failed": "Couldn't check: {error}", + "update.file": "Download gets {file}.", + "update.install_failed": "The update didn't install: {error}. Nothing was changed; Download gets the package instead.", + "update.install_msi": "Install (closes SolidCraft)", + "update.installed": "SolidCraft {version} is installed. Restart to use it.", + "update.installer_started": "The installer starts when SolidCraft closes.", + "update.later": "Remind me later", + "update.no_notes": "This release has no notes.", + "update.package_hint": "This copy came from a {kind}. Download the new package, then install it with:", + "update.prefs_dev": "This is a development build ({version}): it doesn't check for updates.", + "update.prefs_flatpak": "Flatpak updates this copy ({version}): run {command} or use your software center. SolidCraft doesn't check.", + "update.prefs_label": "Updates", + "update.prefs_note": "This is SolidCraft {version} ({kind}). A check asks GitHub for the latest release and sends nothing else.", + "update.prefs_web": "Reload the page to get the latest web app. If the network is unavailable or the update cannot finish downloading in time, the saved version opens instead; a download in progress continues for the next reload.", + "update.release_page": "Open release page", + "update.restart": "Restart now", + "update.restart_later": "Later", + "update.show": "Show the update to {version}", + "update.skip": "Skip this version", + "update.system_hint": "This copy is a {kind}. Update it with:", + "update.title": "Update available", + "update.up_to_date": "SolidCraft is up to date.", + "update.update_now": "Update now", + "update.you_have": "You have {version}.", + "view.auto_ortho_faces": "Perspective while orbiting, ortho on faces", + "web.files.insert_drawings_hint": "CAD files, meshes, DXF or SVG into the open design", + "web.files.insert_stored_drawings_hint": "Into the open design (CAD files, meshes, DXF, SVG)", + "web.open_full": "Open in SolidCraft", + "web.open_link": "Open linked design?", + "web.open_link_confirm": "There are unsaved changes. Open the linked design in a new tab?", + "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ choose · Enter / Tab complete · Esc dismiss", + "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ choose · Enter applies what you typed · Esc dismiss", + "⌘Enter continues on GitHub.": "⌘Enter continues on GitHub." +} diff --git a/assets/locales/de.json b/assets/locales/de.json index 538eb3030..68ab1c84e 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -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.", diff --git a/assets/locales/en.json b/assets/locales/en.json index c8c8963cf..7a827328a 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -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.", diff --git a/assets/locales/es.json b/assets/locales/es.json index 3647140f5..2203f817d 100644 --- a/assets/locales/es.json +++ b/assets/locales/es.json @@ -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", diff --git a/assets/locales/fr.json b/assets/locales/fr.json index cb258042b..e4860f299 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -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", diff --git a/assets/locales/he.json b/assets/locales/he.json index fd0ce4522..fc26a8cfa 100644 --- a/assets/locales/he.json +++ b/assets/locales/he.json @@ -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": "בחרו חלק סטנדרטי שהוכנס (בורג, אום, דסקית או פין) כדי לשנות את גודלו. כדי להגדיל או להקטין גוף, השתמשו בשינוי קנה מידה.", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 5bc8cd527..e8f128020 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -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": "サイズを変更する挿入済みの標準パーツ(ねじ、ナット、座金、ピン)を選択してください。ボディを拡大・縮小するには尺度を使います。", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index d58036e16..1b6a9f1e5 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -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": "크기를 바꿀 삽입된 표준 부품(나사, 너트, 와셔 또는 핀)을 선택하십시오. 바디를 키우거나 줄이려면 축척을 사용하십시오.", diff --git a/assets/locales/vi.json b/assets/locales/vi.json index e6672f456..242010b70 100644 --- a/assets/locales/vi.json +++ b/assets/locales/vi.json @@ -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ệ.", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 37e33a1ea..d55fcf32e 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -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": "请选择已插入的标准零件(螺钉、螺母、垫圈或销)以更改其尺寸。要放大或缩小实体,请使用缩放。", diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index ecd65b077..05114ff7e 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -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")] diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 808ba6044..ed986edc2 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -6083,15 +6083,28 @@ fn from_profile_on_closed_path(segs: Vec, 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, 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), diff --git a/crates/doc/src/format.rs b/crates/doc/src/format.rs index 60054b1c9..f8708c629 100644 --- a/crates/doc/src/format.rs +++ b/crates/doc/src/format.rs @@ -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))), diff --git a/crates/doc/src/format/pending/two-sided-extrude-fixed-sides.rs b/crates/doc/src/format/pending/two-sided-extrude-fixed-sides.rs new file mode 100644 index 000000000..cb03d7da5 --- /dev/null +++ b/crates/doc/src/format/pending/two-sided-extrude-fixed-sides.rs @@ -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 = 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"})); + } +} diff --git a/crates/doc/src/format_offsets.rs b/crates/doc/src/format_offsets.rs index b96f20c53..d3edece52 100644 --- a/crates/doc/src/format_offsets.rs +++ b/crates/doc/src/format_offsets.rs @@ -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, diff --git a/crates/doc/src/placement_reuse.rs b/crates/doc/src/placement_reuse.rs index 8a61b4b85..723763e3e 100644 --- a/crates/doc/src/placement_reuse.rs +++ b/crates/doc/src/placement_reuse.rs @@ -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: _, diff --git a/crates/doc/src/profile_refs.rs b/crates/doc/src/profile_refs.rs index 461703c1d..549f5df51 100644 --- a/crates/doc/src/profile_refs.rs +++ b/crates/doc/src/profile_refs.rs @@ -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, diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 091bd2468..2cd078d9b 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -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, diff --git a/crates/engine/src/cmd/extrude_convention_tests.rs b/crates/engine/src/cmd/extrude_convention_tests.rs index 97845aa51..04c49b0d5 100644 --- a/crates/engine/src/cmd/extrude_convention_tests.rs +++ b/crates/engine/src/cmd/extrude_convention_tests.rs @@ -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); + } +} diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index 32acb1d6c..71b26e0e0 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -39,7 +39,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .key("E") .contract(&EXTRUDE_CONTRACT) .output(output_schema_for::) - .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 distance2, start_offset, through_all, + second_follows_first: false, taper, corner, to: p.get("to").and_then(vec3).map(FacePick), diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index e458e0a63..06a46dc9f 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -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 { /// 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) -> Result { +fn add_mesh(s: &mut Session, path: &str, name: Option<&str>, y_up: Option, unit: Option<(&'static str, f64)>) -> Result { 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) } (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) 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> { 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> { + let names = || solidcraft_doc::point_cloud::UNITS.iter().map(|(n, _)| *n).collect::>().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 { let cmd = "file.insert_mesh"; let path = path_arg(p, cmd)?; @@ -298,7 +322,8 @@ fn insert_mesh(s: &mut Session, p: &Value) -> Result { 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 { @@ -375,7 +400,7 @@ fn open(s: &mut Session, p: &Value) -> Result { 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() { diff --git a/crates/engine/src/cmd/joints.rs b/crates/engine/src/cmd/joints.rs index d6e65871f..875b03a03 100644 --- a/crates/engine/src/cmd/joints.rs +++ b/crates/engine/src/cmd/joints.rs @@ -895,11 +895,27 @@ fn kind_param(p: &Value, cmd: &str) -> Result { .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 { 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 { 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, diff --git a/crates/engine/src/cmd/joints_tests.rs b/crates/engine/src/cmd/joints_tests.rs index 6ecf6a3d8..2d4e677e9 100644 --- a/crates/engine/src/cmd/joints_tests.rs +++ b/crates/engine/src/cmd/joints_tests.rs @@ -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"); +} diff --git a/crates/engine/src/cmd/motion_trace.rs b/crates/engine/src/cmd/motion_trace.rs index dad460307..cdd00f207 100644 --- a/crates/engine/src/cmd/motion_trace.rs +++ b/crates/engine/src/cmd/motion_trace.rs @@ -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 { diff --git a/crates/engine/src/cmd/panels.rs b/crates/engine/src/cmd/panels.rs index 67badaf06..e7fb645fc 100644 --- a/crates/engine/src/cmd/panels.rs +++ b/crates/engine/src/cmd/panels.rs @@ -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", diff --git a/crates/engine/src/cmd/revolve_convention_tests.rs b/crates/engine/src/cmd/revolve_convention_tests.rs index f3cc54c7e..30a9374e8 100644 --- a/crates/engine/src/cmd/revolve_convention_tests.rs +++ b/crates/engine/src/cmd/revolve_convention_tests.rs @@ -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 [ diff --git a/crates/engine/src/cmd/sketch_clipboard.rs b/crates/engine/src/cmd/sketch_clipboard.rs index 8497a0d68..1752c2d4d 100644 --- a/crates/engine/src/cmd/sketch_clipboard.rs +++ b/crates/engine/src/cmd/sketch_clipboard.rs @@ -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 = TypedContract::new(); +const CUT_CONTRACT: TypedContract = TypedContract::new(); +const PASTE_CONTRACT: TypedContract = 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::) .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::) .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::) + .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 { 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::(), - "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::(), + 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 { + serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string())) } fn cut(s: &mut Session, p: &Value) -> Result { @@ -361,7 +381,7 @@ fn paste(s: &mut Session, p: &Value) -> Result { .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)] diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 050bb40ee..21a52ce72 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -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(), diff --git a/crates/engine/src/panels/commands.rs b/crates/engine/src/panels/commands.rs index 486d23841..0621dc88a 100644 --- a/crates/engine/src/panels/commands.rs +++ b/crates/engine/src/panels/commands.rs @@ -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::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, id: &Option) -> 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 { + 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 { + 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>, + next: CatalogueState, +) -> PanelResult { + 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>, mut next: CatalogueState, -) -> PanelResult<(LayoutReply, CatalogueState)> { - let projected = context.sink.project(action.clone())?; + preparation: &LayoutPreparationContext, +) -> PanelResult { + 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 { + 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 { @@ -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, 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 { + 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 { + 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 { + 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 { + 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 { diff --git a/crates/engine/src/panels/fixtures.rs b/crates/engine/src/panels/fixtures.rs index e32888746..3485f6efd 100644 --- a/crates/engine/src/panels/fixtures.rs +++ b/crates/engine/src/panels/fixtures.rs @@ -19,7 +19,7 @@ pub fn synthetic_registry() -> PanelResult { 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 { 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) diff --git a/crates/engine/src/panels/geometry.rs b/crates/engine/src/panels/geometry.rs index 475855a68..a639fc55d 100644 --- a/crates/engine/src/panels/geometry.rs +++ b/crates/engine/src/panels/geometry.rs @@ -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) -> 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) -> 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, pub painted: Vec, pub input: Vec, } @@ -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, + pub content: Vec, + 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, + 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, + 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 { + 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::()).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>> { + 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> { + 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 { + 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 { + 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 = 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 { + 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::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::from(env.gap) * columns.len().saturating_sub(1) as f64) as f32; + let bottom_width = + (widths.iter().map(|width| f64::from(*width)).sum::() + 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 { - 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 = 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::())?, + 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::>() }; + 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 { + 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) -> 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 + } } diff --git a/crates/engine/src/panels/model.rs b/crates/engine/src/panels/model.rs index c9525b503..488d18ed6 100644 --- a/crates/engine/src/panels/model.rs +++ b/crates/engine/src/panels/model.rs @@ -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::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, 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, + #[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, + #[serde(default)] + pub column: Option, + #[serde(default)] + pub column_index: usize, + #[serde(default)] + pub column_width: Option, + #[serde(default = "default_weight")] + pub weight: f32, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub preferred_extent: Option, + #[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, + /// 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, + #[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, + #[serde(default)] + pub column_index: usize, + #[serde(default)] + pub column_width: Option, + #[serde(default = "default_weight")] + pub weight: f32, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub preferred_extent: Option, + #[serde(default, skip_serializing_if = "is_zero_extent_priority")] + pub extent_priority: u16, +} + +pub fn dock_stack_extent(zone: Zone, size: Size) -> Option { + 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) -> 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, 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, index: usize, width: Option, 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, + pub stored_priority: u16, + pub priority: u16, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ExtentPriorityContext { + pub records: Vec, + 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 { + 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>, + pub columns: BTreeMap>, +} + +impl ReplacementIdentityOwnership { + /// Capture only typed ownership, never quarantine or snapshot reservations. + pub fn from_layout(layout: &Layout) -> PanelResult { + 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, + pub columns: BTreeSet, + pub extent_priorities: ExtentPriorityContext, + pub replacement_ownership: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] pub struct Layout { pub version: u32, pub workspace: WorkspaceId, pub instances: Vec, /// Stable order, outermost first within each logical dock edge. pub sections: Vec
, + /// Outer-to-inner within each side, including retained dormant identities. + #[serde(default)] + pub columns: Vec, + #[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 { + 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 { + 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) -> PanelResult { + 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 { + next_column_id_with_reservations(layout, &BTreeSet::new()) +} + +pub fn next_column_id_with_reservations(layout: &Layout, reserved: &BTreeSet) -> PanelResult { + 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; +/// 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::::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) { diff --git a/crates/engine/src/panels/persistence.rs b/crates/engine/src/panels/persistence.rs index 43446e9bc..68133adb6 100644 --- a/crates/engine/src/panels/persistence.rs +++ b/crates/engine/src/panels/persistence.rs @@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize}; use super::*; pub const ENVELOPE_FORMAT: &str = "solidcraft.panel-layout"; -pub const ENVELOPE_VERSION: u32 = 1; +pub const ENVELOPE_VERSION: u32 = 2; /// Unknown panel wire values are retained verbatim as JSON values, including /// fields a future content adapter understands. Total encoded envelope is capped. @@ -28,7 +28,7 @@ pub struct SectionSnapshot { pub projected: Option
, } -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] pub struct LayoutEnvelope { pub format: String, pub version: u32, @@ -47,6 +47,30 @@ pub struct LayoutEnvelope { /// alone must not erase a future field that this foundation cannot interpret. #[serde(default)] pub retained_data: std::collections::BTreeMap, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub extent_priority_overrides: Vec, + /// Bounded residual unknown keys, matched by record identity during encoding. + /// Not serialized as a second copy beside the original extension fields. + #[serde(skip)] + pub recovery_wire: Option, + /// Provenance of an admitted bounded v1 record, even when its expanded v2 + /// representation cannot be staged. Never used to bypass write validation. + #[serde(skip)] + retained_v1: Option>, +} +impl PartialEq for LayoutEnvelope { + fn eq(&self, other: &Self) -> bool { + // Original source bytes are provenance, not current layout semantics. + self.format == other.format + && self.version == other.version + && self.layout == other.layout + && self.quarantine == other.quarantine + && self.section_snapshots == other.section_snapshots + && self.section_order == other.section_order + && self.retained_data == other.retained_data + && self.recovery_wire == other.recovery_wire + && self.extent_priority_overrides == other.extent_priority_overrides + } } impl LayoutEnvelope { pub fn new(layout: Layout) -> Self { @@ -59,8 +83,404 @@ impl LayoutEnvelope { section_snapshots: std::collections::BTreeMap::new(), section_order, retained_data: std::collections::BTreeMap::new(), + extent_priority_overrides: Vec::new(), + recovery_wire: None, + retained_v1: None, } } + pub fn retained_v1_bytes(&self) -> Option<&[u8]> { + self.retained_v1.as_deref() + } +} + +fn raw_priority_records(envelope: &LayoutEnvelope) -> PanelResult { + if envelope.quarantine.len() > MAX_INSTANCES + || envelope.section_snapshots.len() > MAX_SECTIONS + || envelope.layout.instances.len() > MAX_INSTANCES + || envelope.layout.sections.len() > MAX_SECTIONS + { + return Err(error(Rule::CollectionLimit, "priority source collection cap")); + } + let mut records = std::collections::BTreeMap::new(); + let mut add = |target: ExtentPriorityTarget, + location: &SectionLocation, + column: &Option, + extent: Option, + priority: u16| + -> PanelResult<()> { + validate_extent_priority(extent, priority)?; + if extent.is_some() { + records.entry(target.clone()).or_insert(ExtentPriorityRecord { + target, + zone: location.zone(), + column: column.clone(), + stored_priority: priority, + priority, + }); + } + Ok(()) + }; + for (id, snapshot) in &envelope.section_snapshots { + let section: Section = serde_json::from_value(snapshot.data.clone()).map_err(|_| error(Rule::Schema, "invalid priority snapshot"))?; + add(ExtentPriorityTarget::Section(id.clone()), §ion.location, §ion.column, section.preferred_extent, section.extent_priority)?; + if let SectionLocation::Window { return_to, .. } = §ion.location { + add( + ExtentPriorityTarget::SectionReturn(id.clone()), + &SectionLocation::Dock { zone: return_to.zone }, + &return_to.column, + return_to.preferred_extent, + return_to.extent_priority, + )?; + } + } + for section in &envelope.layout.sections { + add( + ExtentPriorityTarget::Section(section.id.clone()), + §ion.location, + §ion.column, + section.preferred_extent, + section.extent_priority, + )?; + if let SectionLocation::Window { return_to, .. } = §ion.location { + add( + ExtentPriorityTarget::SectionReturn(section.id.clone()), + &SectionLocation::Dock { zone: return_to.zone }, + &return_to.column, + return_to.preferred_extent, + return_to.extent_priority, + )?; + } + } + for panel in &envelope.layout.instances { + add( + ExtentPriorityTarget::Memory(panel.id.clone()), + &panel.memory.location, + &panel.memory.column, + panel.memory.preferred_extent, + panel.memory.extent_priority, + )?; + if let SectionLocation::Window { return_to, .. } = &panel.memory.location { + add( + ExtentPriorityTarget::MemoryReturn(panel.id.clone()), + &SectionLocation::Dock { zone: return_to.zone }, + &return_to.column, + return_to.preferred_extent, + return_to.extent_priority, + )?; + } + } + for item in &envelope.quarantine { + let panel: PanelInstance = + serde_json::from_value(item.instance_data.clone()).map_err(|_| error(Rule::Schema, "invalid priority quarantine"))?; + add( + ExtentPriorityTarget::Memory(panel.id.clone()), + &panel.memory.location, + &panel.memory.column, + panel.memory.preferred_extent, + panel.memory.extent_priority, + )?; + if let SectionLocation::Window { return_to, .. } = &panel.memory.location { + add( + ExtentPriorityTarget::MemoryReturn(panel.id.clone()), + &SectionLocation::Dock { zone: return_to.zone }, + &return_to.column, + return_to.preferred_extent, + return_to.extent_priority, + )?; + } + } + let context = ExtentPriorityContext { records: records.into_values().collect(), complete: true }; + context.validate()?; + Ok(context) +} + +pub(super) fn typed_priority(layout: &Layout, target: &ExtentPriorityTarget) -> Option { + match target { + ExtentPriorityTarget::Section(id) => layout.section(id).ok().map(|s| s.extent_priority), + ExtentPriorityTarget::Memory(id) => layout.instance(id).ok().map(|p| p.memory.extent_priority), + ExtentPriorityTarget::SectionReturn(id) => layout.section(id).ok().and_then(|s| match &s.location { + SectionLocation::Window { return_to, .. } => Some(return_to.extent_priority), + _ => None, + }), + ExtentPriorityTarget::MemoryReturn(id) => layout.instance(id).ok().and_then(|p| match &p.memory.location { + SectionLocation::Window { return_to, .. } => Some(return_to.extent_priority), + _ => None, + }), + } +} + +pub(super) fn synchronize_priority_context(layout: &mut Layout) -> PanelResult<()> { + layout.extent_priority_context.validate()?; + let priorities: Vec<_> = layout.extent_priority_context.records.iter().map(|record| typed_priority(layout, &record.target)).collect(); + for (record, priority) in layout.extent_priority_context.records.iter_mut().zip(priorities) { + if let Some(priority) = priority { + record.priority = priority; + } + } + Ok(()) +} + +fn apply_section_priorities(context: &ExtentPriorityContext, section: &mut Section) { + for record in &context.records { + if record.target == ExtentPriorityTarget::Section(section.id.clone()) && section.preferred_extent.is_some() { + section.extent_priority = record.priority; + } + if record.target == ExtentPriorityTarget::SectionReturn(section.id.clone()) + && let SectionLocation::Window { return_to, .. } = &mut section.location + && return_to.preferred_extent.is_some() + { + return_to.extent_priority = record.priority; + } + } +} + +fn apply_memory_priorities(context: &ExtentPriorityContext, panel: &mut PanelInstance) { + for record in &context.records { + if record.target == ExtentPriorityTarget::Memory(panel.id.clone()) && panel.memory.preferred_extent.is_some() { + panel.memory.extent_priority = record.priority; + } + if record.target == ExtentPriorityTarget::MemoryReturn(panel.id.clone()) + && let SectionLocation::Window { return_to, .. } = &mut panel.memory.location + && return_to.preferred_extent.is_some() + { + return_to.extent_priority = record.priority; + } + } +} + +fn effective_priority_context(envelope: &LayoutEnvelope) -> PanelResult { + let mut context = raw_priority_records(envelope)?; + for record in &mut context.records { + if let Some(priority) = typed_priority(&envelope.layout, &record.target) { + record.priority = priority; + } + } + if envelope.extent_priority_overrides.len() > MAX_EXTENT_PRIORITY_RECORDS { + return Err(error(Rule::CollectionLimit, "priority override cap")); + } + let mut seen = std::collections::BTreeSet::new(); + for saved in &envelope.extent_priority_overrides { + if !seen.insert(&saved.target) { + return Err(error(Rule::DuplicateId, "duplicate priority override")); + } + let record = context + .records + .iter_mut() + .find(|r| r.target == saved.target) + .ok_or_else(|| error(Rule::MissingTarget, "priority override has no raw preference"))?; + if record.zone != saved.zone || record.column != saved.column || record.stored_priority != saved.stored_priority { + return Err(error(Rule::Schema, "priority override disagrees with raw source")); + } + record.priority = saved.priority; + } + context.validate()?; + Ok(context) +} + +fn seed_priority_context(envelope: &mut LayoutEnvelope) -> PanelResult<()> { + let context = effective_priority_context(envelope)?; + for section in &mut envelope.layout.sections { + apply_section_priorities(&context, section); + } + for panel in &mut envelope.layout.instances { + apply_memory_priorities(&context, panel); + } + envelope.layout.extent_priority_context = context; + Ok(()) +} + +fn reconcile_priority_context(envelope: &mut LayoutEnvelope) -> PanelResult<()> { + let mut context = raw_priority_records(envelope)?; + for record in &mut context.records { + if let Some(priority) = typed_priority(&envelope.layout, &record.target) { + record.priority = priority; + } else if let Some(old) = envelope + .layout + .extent_priority_context + .records + .iter() + .find(|old| old.target == record.target && old.zone == record.zone && old.column == record.column) + { + record.priority = old.priority; + } + } + envelope.extent_priority_overrides = context.overrides().cloned().collect(); + envelope.layout.extent_priority_context = context; + Ok(()) +} + +/// Raw sidecars have already been merged, but their effective tiers must travel +/// with them. Live preset fields remain authoritative; shared latent sources +/// cannot silently choose between conflicting effective recovery intents. +pub(super) fn merge_retained_priority_context( + envelope: &mut LayoutEnvelope, + current: &ExtentPriorityContext, + incoming: &ExtentPriorityContext, +) -> PanelResult<()> { + current.validate()?; + incoming.validate()?; + let mut merged = raw_priority_records(envelope)?; + for record in &mut merged.records { + let matches = |source: &&ExtentPriorityRecord| { + source.target == record.target + && source.zone == record.zone + && source.column == record.column + && source.stored_priority == record.stored_priority + }; + let retained = current.records.iter().find(matches); + let preset = incoming.records.iter().find(matches); + if let Some(priority) = typed_priority(&envelope.layout, &record.target) { + record.priority = priority; + } else { + if let (Some(retained), Some(preset)) = (retained, preset) + && retained.priority != preset.priority + { + return Err(error(Rule::DuplicateId, "retained effective priority collision")); + } + if let Some(source) = preset.or(retained) { + record.priority = source.priority; + } + } + } + merged.validate()?; + envelope.extent_priority_overrides = merged.overrides().cloned().collect(); + envelope.layout.extent_priority_context = merged; + Ok(()) +} + +fn authors_priority(envelope: &LayoutEnvelope, layout: &Layout, context: &ExtentPriorityContext) -> PanelResult { + // Compare owner intent, not just surviving section identities. Open and + // native redock may copy a saved tier into a new section; close may leave + // the only newly authored intent in a retained placement memory. A Window + // primary tuple cannot certify dock inheritance; its return descriptor can. + type Intent<'a> = (Zone, Option<&'a ColumnId>, f32, u16); + fn section_intents(section: &Section) -> [Option>; 2] { + [ + section.preferred_extent.map(|extent| (section.location.zone(), section.column.as_ref(), extent, section.extent_priority)), + match §ion.location { + SectionLocation::Window { return_to, .. } => { + return_to.preferred_extent.map(|extent| (return_to.zone, return_to.column.as_ref(), extent, return_to.extent_priority)) + } + _ => None, + }, + ] + } + fn memory_intents(panel: &PanelInstance) -> [Option>; 2] { + [ + panel + .memory + .preferred_extent + .map(|extent| (panel.memory.location.zone(), panel.memory.column.as_ref(), extent, panel.memory.extent_priority)), + match &panel.memory.location { + SectionLocation::Window { return_to, .. } => { + return_to.preferred_extent.map(|extent| (return_to.zone, return_to.column.as_ref(), extent, return_to.extent_priority)) + } + _ => None, + }, + ] + } + let mut sections = envelope.layout.sections.clone(); + for snapshot in envelope.section_snapshots.values() { + sections.push(serde_json::from_value(snapshot.data.clone()).map_err(|_| error(Rule::Schema, "invalid inherited priority snapshot"))?); + } + let mut panels = envelope.layout.instances.clone(); + for item in &envelope.quarantine { + panels.push(serde_json::from_value(item.instance_data.clone()).map_err(|_| error(Rule::Schema, "invalid inherited priority memory"))?); + } + for section in &mut sections { + apply_section_priorities(context, section); + } + for panel in &mut panels { + apply_memory_priorities(context, panel); + } + for section in &layout.sections { + for intent in section_intents(section).into_iter().flatten().filter(|(_, _, _, rank)| *rank > 0) { + let inherited = sections.iter().any(|old| { + (old.id == section.id || old.tabs.iter().any(|id| section.tabs.contains(id))) && section_intents(old).contains(&Some(intent)) + }) || panels.iter().any(|old| section.tabs.contains(&old.id) && memory_intents(old).contains(&Some(intent))); + if !inherited { + return Ok(true); + } + } + } + for panel in &layout.instances { + for intent in memory_intents(panel).into_iter().flatten().filter(|(_, _, _, rank)| *rank > 0) { + let inherited = panels.iter().any(|old| old.id == panel.id && memory_intents(old).contains(&Some(intent))) + || sections + .iter() + .any(|old| (old.id == panel.memory.section || old.tabs.contains(&panel.id)) && section_intents(old).contains(&Some(intent))); + if !inherited { + return Ok(true); + } + } + } + Ok(false) +} + +fn reserve_context_location(context: &mut LayoutPreparationContext, location: &SectionLocation) { + if let SectionLocation::Window { return_to, .. } = location { + if let Some(id) = &return_to.section { + context.sections.insert(id.clone()); + } + if let Some(join) = &return_to.join { + context.sections.insert(join.section.clone()); + } + if let Some(id) = &return_to.column { + context.columns.insert(id.clone()); + } + } +} + +/// Immutable full-envelope preparation metadata, without placed surrogates or encoding. +pub fn preparation_context(envelope: &LayoutEnvelope) -> PanelResult { + validate_wire_structure(&envelope.layout)?; + validate_envelope_metadata_for_read(envelope, envelope.retained_v1.is_some())?; + let mut seeded = envelope.clone(); + seeded.layout.extent_priority_context = effective_priority_context(envelope)?; + // Live edits already carry effective ranks; do not replace them with an old snapshot. + reconcile_priority_context(&mut seeded)?; + let mut context = LayoutPreparationContext { + extent_priorities: seeded.layout.extent_priority_context, + replacement_ownership: Some(ReplacementIdentityOwnership::from_layout(&envelope.layout)?), + ..LayoutPreparationContext::default() + }; + for section in &envelope.layout.sections { + context.sections.insert(section.id.clone()); + if let Some(id) = §ion.column { + context.columns.insert(id.clone()); + } + reserve_context_location(&mut context, §ion.location); + } + for column in &envelope.layout.columns { + context.columns.insert(column.id.clone()); + } + for panel in &envelope.layout.instances { + context.sections.insert(panel.memory.section.clone()); + if let Some(id) = &panel.memory.column { + context.columns.insert(id.clone()); + } + reserve_context_location(&mut context, &panel.memory.location); + } + for item in &envelope.quarantine { + let panel: PanelInstance = serde_json::from_value(item.instance_data.clone()).map_err(|_| error(Rule::Schema, "invalid context instance"))?; + context.sections.insert(panel.memory.section.clone()); + if let Some(id) = &panel.memory.column { + context.columns.insert(id.clone()); + } + reserve_context_location(&mut context, &panel.memory.location); + } + for (id, snapshot) in &envelope.section_snapshots { + let section: Section = serde_json::from_value(snapshot.data.clone()).map_err(|_| error(Rule::Schema, "invalid context section"))?; + context.sections.insert(id.clone()); + if let Some(id) = §ion.column { + context.columns.insert(id.clone()); + } + reserve_context_location(&mut context, §ion.location); + } + if context.sections.len() > MAX_RESERVED_IDENTITIES || context.columns.len() > MAX_RESERVED_IDENTITIES { + return Err(error(Rule::CollectionLimit, "preparation context identity cap")); + } + Ok(context) } #[derive(Clone, Debug)] @@ -86,15 +506,158 @@ pub fn encode(envelope: &LayoutEnvelope, registry: &PanelRegistry) -> PanelResul } fn encode_record(envelope: &LayoutEnvelope) -> PanelResult> { - let mut writer = BoundedEnvelopeWriter { bytes: Vec::new() }; - serde_json::to_writer(&mut writer, envelope).map_err(|_| error(Rule::CollectionLimit, "cannot encode panel envelope within byte cap"))?; - // Aggregated opaque entries must also fit the decoder's global node/depth - // budget. Never persist bytes that this same version would reject on reopen. - let value: serde_json::Value = serde_json::from_slice(&writer.bytes).map_err(|_| error(Rule::Schema, "invalid encoded panel envelope"))?; + if let Some(raw) = &envelope.recovery_wire { + bounded_json(raw)?; + } + let current = serde_json::to_value(envelope).map_err(|_| error(Rule::Schema, "cannot encode panel envelope"))?; + let value = match &envelope.recovery_wire { + Some(raw) => { + let mut raw = raw.clone(); + if let Some(layout) = raw.get_mut("layout") { + if let Some(sections) = layout.get_mut("sections").and_then(|v| v.as_array_mut()) { + sections.retain(|section| { + !envelope.section_snapshots.keys().any(|id| section.get("id").and_then(|v| v.as_str()) == Some(id.0.as_str())) + }); + } + if let Some(instances) = layout.get_mut("instances").and_then(|v| v.as_array_mut()) { + instances.retain(|instance| { + let id = instance.get("id").and_then(|v| v.as_str()); + !envelope.retained_data.values().any(|data| { + data.get("instance").and_then(|p| p.get("id")).and_then(|v| v.as_str()).is_some_and(|saved| Some(saved) == id) + }) + }); + } + } + overlay_wire(&raw, current) + } + None => current, + }; + // Aggregated opaque entries must fit the decoder's global node/depth + // budget before serialization; the writer separately enforces the byte cap. bounded_json(&value)?; + let mut writer = BoundedEnvelopeWriter { bytes: Vec::new() }; + serde_json::to_writer(&mut writer, &value).map_err(|_| error(Rule::CollectionLimit, "cannot encode panel envelope within byte cap"))?; Ok(writer.bytes) } +/// Unknown object keys survive; known arrays use current membership/order. +/// Identity matching prevents an old tab/section's fields following a new peer. +fn overlay_wire(saved: &serde_json::Value, current: serde_json::Value) -> serde_json::Value { + match (saved, current) { + (serde_json::Value::Object(old), serde_json::Value::Object(mut new)) => { + for (key, value) in old { + let merged = match new.remove(key) { + Some(current) => overlay_wire(value, current), + None => value.clone(), + }; + new.insert(key.clone(), merged); + } + serde_json::Value::Object(new) + } + (serde_json::Value::Array(old), serde_json::Value::Array(new)) => serde_json::Value::Array( + new.into_iter() + .map(|current| { + let identity = current.get("id").or_else(|| current.get("instance")); + match identity.and_then(|id| old.iter().find(|entry| entry.get("id").or_else(|| entry.get("instance")) == Some(id))) { + Some(saved) => overlay_wire(saved, current), + None => current, + } + }) + .collect(), + ), + (_, current) => current, + } +} + +/// These callers supply a typed Section, PlacementMemory or DockReturn. An +/// omitted optional preference clears old known intent, rather than retaining +/// it as an opaque extension. Other nested opaque fields still merge losslessly. +fn overlay_preference_record(saved: &serde_json::Value, current: serde_json::Value) -> serde_json::Value { + let clear = current.get("preferred_extent").is_none_or(|v| v.is_null()); + let clear_priority = current.get("extent_priority").is_none_or(|v| v.as_u64() == Some(0)); + let clear_native = current + .get("location") + .filter(|v| v.get("type").and_then(|v| v.as_str()) == Some("window")) + .and_then(|v| v.get("return_to")) + .is_some_and(|v| v.get("preferred_extent").is_none_or(|v| v.is_null())); + let clear_native_priority = current + .get("location") + .filter(|v| v.get("type").and_then(|v| v.as_str()) == Some("window")) + .and_then(|v| v.get("return_to")) + .is_some_and(|v| v.get("extent_priority").is_none_or(|v| v.as_u64() == Some(0))); + let mut merged = overlay_wire(saved, current); + if clear && let Some(object) = merged.as_object_mut() { + object.remove("preferred_extent"); + } + if clear_priority && let Some(object) = merged.as_object_mut() { + object.remove("extent_priority"); + } + if clear_native && let Some(object) = merged.get_mut("location").and_then(|v| v.get_mut("return_to")).and_then(|v| v.as_object_mut()) { + object.remove("preferred_extent"); + } + if clear_native_priority && let Some(object) = merged.get_mut("location").and_then(|v| v.get_mut("return_to")).and_then(|v| v.as_object_mut()) { + object.remove("extent_priority"); + } + merged +} + +fn retain_unknown_wire(envelope: &mut LayoutEnvelope, raw: serde_json::Value) -> PanelResult<()> { + let typed = serde_json::to_value(&*envelope).map_err(|_| error(Rule::Schema, "cannot compare panel wire semantics"))?; + envelope.recovery_wire = unknown_wire(&raw, &typed); + Ok(()) +} + +fn unknown_wire(saved: &serde_json::Value, current: &serde_json::Value) -> Option { + match (saved, current) { + (serde_json::Value::Object(old), serde_json::Value::Object(new)) => { + let mut unknown = serde_json::Map::new(); + let placement_record = new.contains_key("weight") + && new.contains_key("size") + && ((new.contains_key("location") && (new.contains_key("tabs") || new.contains_key("tab_index"))) + || (new.contains_key("zone") && new.contains_key("index"))); + for (key, value) in old { + // A recognized optional field encoded as null means None, not + // an unknown extension that can resurrect an omitted override. + if placement_record && key == "preferred_extent" && value.is_null() && !new.contains_key(key) { + continue; + } + if placement_record && key == "extent_priority" && value.as_u64() == Some(0) && !new.contains_key(key) { + continue; + } + let retained = match new.get(key) { + Some(current) => unknown_wire(value, current), + None => Some(value.clone()), + }; + if let Some(value) = retained { + unknown.insert(key.clone(), value); + } + } + (!unknown.is_empty()).then_some(serde_json::Value::Object(unknown)) + } + (serde_json::Value::Array(old), serde_json::Value::Array(new)) => { + let mut unknown = Vec::new(); + for saved in old { + let key = if saved.get("id").is_some() { "id" } else { "instance" }; + if let Some(id) = saved.get(key) + && let Some(current) = new.iter().find(|entry| entry.get(key) == Some(id)) + && let Some(mut retained) = unknown_wire(saved, current) + && let Some(object) = retained.as_object_mut() + { + object.insert(key.into(), id.clone()); + unknown.push(retained); + } + } + (!unknown.is_empty()).then_some(serde_json::Value::Array(unknown)) + } + _ => None, + } +} + +fn refresh_recovery_wire(envelope: &mut LayoutEnvelope, encoded: &[u8]) -> PanelResult<()> { + let raw = serde_json::from_slice(encoded).map_err(|_| error(Rule::Schema, "invalid canonical panel wire"))?; + retain_unknown_wire(envelope, raw) +} + struct BoundedEnvelopeWriter { bytes: Vec, } @@ -123,6 +686,13 @@ fn validate_envelope(envelope: &LayoutEnvelope, registry: &PanelRegistry) -> Pan } fn validate_envelope_metadata(envelope: &LayoutEnvelope) -> PanelResult<()> { + validate_envelope_metadata_for_read(envelope, false) +} + +/// Only private decoding of an already globally bounded original v1 tree may +/// defer budgets for ADDED typed fields. Semantic limits still apply in full. +/// Public writes always use the strict wrapper and the unchanged encoded cap. +fn validate_envelope_metadata_for_read(envelope: &LayoutEnvelope, migrated_v1: bool) -> PanelResult<()> { if envelope.quarantine.len() + envelope.layout.instances.len() > MAX_INSTANCES { return Err(error(Rule::CollectionLimit, "quarantine instance cap")); } @@ -131,18 +701,22 @@ fn validate_envelope_metadata(envelope: &LayoutEnvelope) -> PanelResult<()> { } for (id, data) in &envelope.retained_data { valid_id(&id.0)?; - bounded_json(data)?; + if !migrated_v1 { + bounded_json(data)?; + } } if envelope.section_snapshots.len() > MAX_SECTIONS { return Err(error(Rule::CollectionLimit, "section snapshot cap")); } validate_section_order(&envelope.section_order)?; for (id, snapshot) in &envelope.section_snapshots { - validate_snapshot(id, snapshot)?; + validate_snapshot_for_read(id, snapshot, migrated_v1)?; } let mut ids = std::collections::BTreeSet::new(); for item in &envelope.quarantine { - bounded_json(&item.instance_data)?; + if !migrated_v1 { + bounded_json(&item.instance_data)?; + } valid_id(&item.instance.0)?; valid_id(&item.kind.0)?; if !ids.insert(&item.instance) || envelope.layout.instances.iter().any(|p| p.id == item.instance) { @@ -159,6 +733,14 @@ fn validate_envelope_metadata(envelope: &LayoutEnvelope) -> PanelResult<()> { valid_id(&instance.memory.section.0)?; instance.memory.location.validate()?; instance.memory.size.validate()?; + validate_column_memory( + instance.memory.location.zone(), + &instance.memory.column, + instance.memory.column_index, + instance.memory.column_width, + instance.memory.weight, + )?; + validate_extent_priority(instance.memory.preferred_extent, instance.memory.extent_priority)?; if instance.memory.section_index > MAX_SECTIONS || instance.memory.tab_index >= MAX_TABS { return Err(error(Rule::CollectionLimit, "quarantine placement cap")); } @@ -170,6 +752,7 @@ fn validate_envelope_metadata(envelope: &LayoutEnvelope) -> PanelResult<()> { } } } + effective_priority_context(envelope)?; Ok(()) } @@ -191,6 +774,14 @@ fn validate_section_record(section: &Section) -> PanelResult<()> { valid_id(§ion.id.0)?; section.location.validate()?; section.size.validate()?; + validate_weight(section.weight)?; + validate_extent_priority(section.preferred_extent, section.extent_priority)?; + if section.location.zone().side() != section.column.is_some() { + return Err(error(Rule::Placement, "snapshot column/zone mismatch")); + } + if let Some(column) = §ion.column { + valid_id(&column.0)?; + } if section.tabs.is_empty() || section.tabs.len() > MAX_TABS || !section.tabs.contains(§ion.active) { return Err(error(Rule::CollectionLimit, "section snapshot tabs/active bound")); } @@ -204,9 +795,11 @@ fn validate_section_record(section: &Section) -> PanelResult<()> { Ok(()) } -fn validate_snapshot(id: &SectionId, snapshot: &SectionSnapshot) -> PanelResult<()> { +fn validate_snapshot_for_read(id: &SectionId, snapshot: &SectionSnapshot, migrated_v1: bool) -> PanelResult<()> { valid_id(&id.0)?; - bounded_json(&snapshot.data)?; + if !migrated_v1 { + bounded_json(&snapshot.data)?; + } let section: Section = serde_json::from_value(snapshot.data.clone()).map_err(|_| error(Rule::Schema, "invalid shared section snapshot"))?; if section.id != *id || snapshot.index > MAX_SECTIONS { return Err(error(Rule::Id, "section snapshot identity/index mismatch")); @@ -255,13 +848,14 @@ fn refresh_section_memory( envelope: &mut LayoutEnvelope, raw: Option<&serde_json::Value>, capture: &std::collections::BTreeSet, + migrated_v1: bool, ) -> PanelResult<()> { if envelope.section_snapshots.len() > MAX_SECTIONS || envelope.quarantine.len() > MAX_INSTANCES { return Err(error(Rule::CollectionLimit, "section memory collection cap")); } validate_section_order(&envelope.section_order)?; for (id, snapshot) in &envelope.section_snapshots { - validate_snapshot(id, snapshot)?; + validate_snapshot_for_read(id, snapshot, migrated_v1)?; } let dormant_sections: std::collections::BTreeSet<_> = envelope.quarantine.iter().filter_map(|item| item.section.clone()).collect(); let live_order: Vec<_> = envelope.layout.sections.iter().map(|section| section.id.clone()).collect(); @@ -328,11 +922,35 @@ fn refresh_section_memory( }; // Overlay current fields, preserving opaque keys absent from the typed // layout. A current raw value for the same key is the latest saved intent. - let object = data.as_object_mut().ok_or_else(|| error(Rule::Schema, "section memory must be an object"))?; - let current = current.as_object().ok_or_else(|| error(Rule::Schema, "saved section must be an object"))?; - for (key, value) in current { - object.insert(key.clone(), value.clone()); + let raw_priority = data.get("extent_priority").cloned(); + let raw_return_priority = data.get("location").and_then(|v| v.get("return_to")).and_then(|v| v.get("extent_priority")).cloned(); + data = overlay_preference_record(&data, current); + if section.preferred_extent.is_some() + && let Some(object) = data.as_object_mut() + { + match raw_priority { + Some(priority) => { + object.insert("extent_priority".into(), priority); + } + None => { + object.remove("extent_priority"); + } + } } + if let SectionLocation::Window { return_to, .. } = §ion.location + && return_to.preferred_extent.is_some() + && let Some(object) = data.get_mut("location").and_then(|v| v.get_mut("return_to")).and_then(|v| v.as_object_mut()) + { + match raw_return_priority { + Some(priority) => { + object.insert("extent_priority".into(), priority); + } + None => { + object.remove("extent_priority"); + } + } + } + let object = data.as_object_mut().ok_or_else(|| error(Rule::Schema, "section memory must be an object"))?; object.insert("tabs".into(), serde_json::to_value(tabs).map_err(|_| error(Rule::Schema, "cannot encode complete tab order"))?); object.insert("active".into(), serde_json::to_value(active).map_err(|_| error(Rule::Schema, "cannot encode complete activation"))?); let rank = envelope @@ -359,17 +977,368 @@ fn record_section_projections(envelope: &mut LayoutEnvelope) { /// Stage live edits without losing dormant order, projected activation or opaque /// fields. The caller publishes only after its guarded layout dispatch succeeds. -pub fn with_live_layout(envelope: &LayoutEnvelope, layout: Layout, registry: &PanelRegistry) -> PanelResult { +pub fn with_live_layout(envelope: &LayoutEnvelope, mut layout: Layout, registry: &PanelRegistry) -> PanelResult { encode(envelope, registry)?; validate(&layout, registry)?; + let full = preparation_context(envelope)?; + let authors_priority = authors_priority(envelope, &layout, &full.extent_priorities)?; + let unresolved = |old: &ExtentPriorityRecord| { + typed_priority(&envelope.layout, &old.target).is_none() + || !(match &old.target { + ExtentPriorityTarget::Section(id) | ExtentPriorityTarget::SectionReturn(id) => envelope + .layout + .section(id) + .is_ok_and(|s| s.tabs.iter().any(|id| envelope.layout.instance(id).is_ok_and(|p| registry.get(&p.kind).is_ok()))), + ExtentPriorityTarget::Memory(id) | ExtentPriorityTarget::MemoryReturn(id) => { + envelope.layout.instance(id).is_ok_and(|p| registry.get(&p.kind).is_ok()) + } + }) + }; + if authors_priority + && full.extent_priorities.records.iter().any(&unresolved) + && (!layout.extent_priority_context.complete + || full.extent_priorities.records.iter().filter(|old| unresolved(old)).any(|old| { + !layout.extent_priority_context.records.iter().any(|record| { + record.target == old.target + && record.zone == old.zone + && record.column == old.column + && record.stored_priority == old.stored_priority + }) + })) + { + return Err(error(Rule::Capability, "authored priority requires full recovery context")); + } + if authors_priority + && full.extent_priorities.records.iter().filter(|old| unresolved(old)).any(|old| { + layout.extent_priority_context.records.iter().any(|record| { + record.target == old.target + && record.zone == old.zone + && record.column == old.column + && record.stored_priority == old.stored_priority + && record.priority > old.priority + }) + }) + { + return Err(error(Rule::Revision, "stale recovery context would promote an older opaque preference")); + } + let mut priorities = full.extent_priorities; + for record in &mut priorities.records { + if let Some(current) = layout.extent_priority_context.records.iter().find(|current| { + current.target == record.target + && current.zone == record.zone + && current.column == record.column + && current.stored_priority == record.stored_priority + }) { + record.priority = current.priority; + } + } + layout.extent_priority_context = priorities; + synchronize_priority_context(&mut layout)?; + let reserved = reserve_envelope_identities(envelope)?; + validate_incoming_reservations(&envelope.layout, &reserved, &layout)?; + let mut dormant = std::collections::BTreeSet::new(); + for item in &envelope.quarantine { + let p: PanelInstance = serde_json::from_value(item.instance_data.clone()).map_err(|_| error(Rule::Schema, "invalid dormant placement"))?; + if let Some(column) = p.memory.column { + dormant.insert(column); + } + if let SectionLocation::Window { return_to, .. } = p.memory.location + && let Some(column) = return_to.column + { + dormant.insert(column); + } + } + if let Some(columns) = envelope.recovery_wire.as_ref().and_then(|raw| raw.get("layout")).and_then(|l| l.get("columns")).and_then(|v| v.as_array()) + { + for column in columns { + if let Some(id) = column.get("id").and_then(|v| v.as_str()) { + dormant.insert(ColumnId::new(id)?); + } + } + } + for section in &layout.sections { + let restoring = envelope.layout.instances.iter().any(|p| !p.requested_open && p.memory.section == section.id && section.tabs.contains(&p.id)); + let remembered = reserved.instances.iter().any(|p| { + p.memory.section == section.id + || matches!(&p.memory.location, SectionLocation::Window { return_to, .. } + if return_to.section.as_ref() == Some(§ion.id) || return_to.join.as_ref().is_some_and(|join| join.section == section.id)) + }); + let native_return = reserved.sections.iter().any(|s| { + matches!(&s.location, SectionLocation::Window { return_to, .. } + if return_to.section.as_ref() == Some(§ion.id) || return_to.join.as_ref().is_some_and(|join| join.section == section.id)) + }); + let native_restoring = envelope.layout.sections.iter().any(|s| { + matches!(&s.location, SectionLocation::Window { return_to, .. } + if return_to.section.as_ref() == Some(§ion.id) && s.tabs.iter().all(|id| section.tabs.contains(id))) + }) || envelope.layout.instances.iter().any(|p| { + !p.requested_open + && section.tabs.contains(&p.id) + && matches!(&p.memory.location, SectionLocation::Window { return_to, .. } if return_to.section.as_ref() == Some(§ion.id)) + }); + if !restoring + && !native_restoring + && envelope.layout.section(§ion.id).is_err() + && (remembered || native_return || reserved.sections.iter().any(|saved| saved.id == section.id)) + { + return Err(error(Rule::DuplicateId, "new section collides with quarantined section identity")); + } + } + for column in &layout.columns { + let restoring = envelope.layout.instances.iter().any(|p| { + !p.requested_open + && p.memory.column.as_ref() == Some(&column.id) + && layout.containing(&p.id).is_ok_and(|s| s.column.as_ref() == Some(&column.id) && s.id == p.memory.section) + }); + let native_reserved = reserved + .instances + .iter() + .any(|p| matches!(&p.memory.location, SectionLocation::Window { return_to, .. } if return_to.column.as_ref() == Some(&column.id))) + || reserved + .sections + .iter() + .any(|s| matches!(&s.location, SectionLocation::Window { return_to, .. } if return_to.column.as_ref() == Some(&column.id))); + let native_restoring = envelope.layout.sections.iter().any(|s| { + matches!(&s.location, SectionLocation::Window { return_to, .. } + if return_to.column.as_ref() == Some(&column.id) && layout.sections.iter().any(|target| target.column.as_ref() == Some(&column.id) + && s.tabs.iter().all(|id| target.tabs.contains(id)))) + }) || envelope.layout.instances.iter().any(|p| { + !p.requested_open + && matches!(&p.memory.location, SectionLocation::Window { return_to, .. } + if return_to.column.as_ref() == Some(&column.id) && layout.containing(&p.id).is_ok_and(|s| s.column.as_ref() == Some(&column.id) + && return_to.section.as_ref().is_none_or(|id| s.id == *id))) + }); + if !restoring + && !native_restoring + && envelope.layout.column(&column.id).is_err() + && (native_reserved || reserved.columns.iter().any(|saved| saved.id == column.id)) + { + return Err(error(Rule::DuplicateId, "new column collides with quarantined column identity")); + } + if !restoring + && !native_restoring + && dormant.contains(&column.id) + && !envelope.layout.sections.iter().any(|s| s.column.as_ref() == Some(&column.id)) + && layout.sections.iter().any(|s| s.column.as_ref() == Some(&column.id)) + { + return Err(error(Rule::DuplicateId, "new live column reuses dormant extension identity")); + } + } + // Keep opaque dormant column records and their width/order slots even when + // the live reducer no longer needs them. They do not reserve paint geometry. + let saved: Vec<_> = envelope.layout.columns.iter().map(|c| c.id.clone()).collect(); + let live: Vec<_> = layout.columns.iter().map(|c| c.id.clone()).collect(); + let order = merge_visible_order(&saved, &live, &dormant); + let mut columns = Vec::new(); + for id in order { + if let Some(column) = layout.columns.iter().chain(&envelope.layout.columns).find(|c| c.id == id) { + columns.push(column.clone()); + } + } + layout.columns = columns; + validate(&layout, registry)?; let mut next = envelope.clone(); + retain_displaced_wire(&mut next, &layout)?; next.layout = layout; - refresh_section_memory(&mut next, None, &std::collections::BTreeSet::new())?; + refresh_section_memory(&mut next, None, &std::collections::BTreeSet::new(), false)?; record_section_projections(&mut next); - encode(&next, registry)?; + reconcile_priority_context(&mut next)?; + let encoded = encode(&next, registry)?; + refresh_recovery_wire(&mut next, &encoded)?; Ok(next) } +fn reserve_owners( + reservations: &mut std::collections::BTreeMap>, + id: &T, + owners: &[InstanceId], +) { + reservations.entry(id.clone()).or_default().extend(owners.iter().cloned()); +} + +fn reserve_native_owners( + sections: &mut std::collections::BTreeMap>, + columns: &mut std::collections::BTreeMap>, + location: &SectionLocation, + owners: &[InstanceId], +) { + if let SectionLocation::Window { return_to, .. } = location { + if let Some(id) = &return_to.section { + reserve_owners(sections, id, owners); + } + if let Some(join) = &return_to.join { + reserve_owners(sections, &join.section, owners); + } + if let Some(id) = &return_to.column { + reserve_owners(columns, id, owners); + } + } +} + +/// Validate claims introduced as data, before they can become placed geometry. +/// Reserved includes closed quarantine memories and complete section snapshots. +/// Existing live groups may accept compatible tabs; dormant identities require +/// a same-kind original owner, including a peer sharing the actual new group. +fn validate_incoming_reservations(before: &Layout, reserved: &Layout, incoming: &Layout) -> PanelResult<()> { + let mut sections = std::collections::BTreeMap::new(); + let mut columns = std::collections::BTreeMap::new(); + for column in &reserved.columns { + reserve_owners(&mut columns, &column.id, &[]); + } + for section in &reserved.sections { + reserve_owners(&mut sections, §ion.id, §ion.tabs); + if let Some(id) = §ion.column { + reserve_owners(&mut columns, id, §ion.tabs); + } + reserve_native_owners(&mut sections, &mut columns, §ion.location, §ion.tabs); + } + for panel in &reserved.instances { + let owners = std::slice::from_ref(&panel.id); + reserve_owners(&mut sections, &panel.memory.section, owners); + if let Some(id) = &panel.memory.column { + reserve_owners(&mut columns, id, owners); + } + reserve_native_owners(&mut sections, &mut columns, &panel.memory.location, owners); + } + let owned = |owners: &[InstanceId], previous: &std::collections::BTreeSet| { + owners + .iter() + .any(|id| previous.contains(id) && reserved.instance(id).is_ok_and(|old| incoming.instance(id).is_ok_and(|new| old.kind == new.kind))) + }; + let section_claim = |id: &SectionId, owners: &[InstanceId]| -> PanelResult<()> { + if let Some(previous) = sections.get(id) + && before.section(id).is_err() + && !owned(owners, previous) + { + return Err(error(Rule::DuplicateId, "incoming latent section steals a dormant identity")); + } + Ok(()) + }; + let column_claim = |id: &ColumnId, owners: &[InstanceId]| -> PanelResult<()> { + if let Some(previous) = columns.get(id) + && !before.sections.iter().any(|s| s.column.as_ref() == Some(id)) + && !owned(owners, previous) + { + return Err(error(Rule::DuplicateId, "incoming latent column steals a dormant identity")); + } + Ok(()) + }; + let native_claim = |location: &SectionLocation, owners: &[InstanceId]| -> PanelResult<()> { + if let SectionLocation::Window { return_to, .. } = location { + if let Some(id) = &return_to.section { + section_claim(id, owners)?; + } + if let Some(join) = &return_to.join { + section_claim(&join.section, owners)?; + } + if let Some(id) = &return_to.column { + column_claim(id, owners)?; + } + } + Ok(()) + }; + for section in &incoming.sections { + native_claim(§ion.location, §ion.tabs)?; + } + for panel in &incoming.instances { + let owner = std::slice::from_ref(&panel.id); + let group = incoming.containing(&panel.id).ok().filter(|_| panel.requested_open); + let section_owners = group.filter(|s| s.id == panel.memory.section).map_or(owner, |s| s.tabs.as_slice()); + section_claim(&panel.memory.section, section_owners)?; + if let Some(id) = &panel.memory.column { + let column_owners = group.filter(|s| s.column.as_ref() == Some(id)).map_or(owner, |s| s.tabs.as_slice()); + column_claim(id, column_owners)?; + } + let native_owners = group.filter(|s| s.location == panel.memory.location).map_or(owner, |s| s.tabs.as_slice()); + native_claim(&panel.memory.location, native_owners)?; + } + Ok(()) +} + +fn retain_displaced_wire(envelope: &mut LayoutEnvelope, next: &Layout) -> PanelResult<()> { + let Some(raw) = envelope.recovery_wire.as_ref().and_then(|raw| raw.get("layout")) else { + return Ok(()); + }; + if let Some(records) = raw.get("sections").and_then(|v| v.as_array()) { + for record in records { + let Some(id) = record.get("id").and_then(|v| v.as_str()) else { + continue; + }; + let id = SectionId::new(id)?; + if next.section(&id).is_ok() || envelope.section_snapshots.contains_key(&id) { + continue; + } + let previous = envelope.layout.section(&id)?; + let data = overlay_wire(record, serde_json::to_value(previous).map_err(|_| error(Rule::Schema, "cannot retain displaced section"))?); + let index = envelope.layout.sections.iter().position(|s| s.id == id).unwrap_or(MAX_SECTIONS); + envelope.section_snapshots.insert(id, SectionSnapshot { data, index, projected: None }); + } + } + if let Some(records) = raw.get("instances").and_then(|v| v.as_array()) { + for record in records { + let Some(id) = record.get("id").and_then(|v| v.as_str()) else { + continue; + }; + let id = InstanceId::new(id)?; + if next.instance(&id).is_ok() || envelope.quarantine.iter().any(|item| item.instance == id) { + continue; + } + let previous = envelope.layout.instance(&id)?; + let instance = overlay_wire(record, serde_json::to_value(previous).map_err(|_| error(Rule::Schema, "cannot retain displaced instance"))?); + let data = serde_json::json!({"instance":instance,"section":previous.memory.section}); + if envelope.retained_data.get(&id).is_some_and(|old| *old != data) { + return Err(error(Rule::DuplicateId, "displaced instance opaque intent collision")); + } + envelope.retained_data.insert(id, data); + } + } + Ok(()) +} + +/// Allocation-only projection includes dormant identities without exposing +/// quarantined panels to the live reducer or presentation. +pub fn reserve_envelope_identities(envelope: &LayoutEnvelope) -> PanelResult { + validate_envelope_metadata(envelope)?; + let mut layout = envelope.layout.clone(); + for item in &envelope.quarantine { + let instance: PanelInstance = + serde_json::from_value(item.instance_data.clone()).map_err(|_| error(Rule::Schema, "invalid reserved instance"))?; + layout.instances.push(instance); + } + for snapshot in envelope.section_snapshots.values() { + let section: Section = serde_json::from_value(snapshot.data.clone()).map_err(|_| error(Rule::Schema, "invalid reserved section"))?; + if layout.section(§ion.id).is_err() { + layout.sections.push(section); + } + } + for instance in &layout.instances { + if let Some(id) = &instance.memory.column + && !layout.columns.iter().any(|c| c.id == *id) + { + layout.columns.push(Column { + id: id.clone(), + zone: instance.memory.location.zone(), + width: instance.memory.column_width.unwrap_or(instance.memory.size.width), + }); + } + } + for section in &layout.sections { + if let Some(id) = §ion.column + && !layout.columns.iter().any(|c| c.id == *id) + { + layout.columns.push(Column { id: id.clone(), zone: section.location.zone(), width: section.size.width }); + } + } + 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(id) = &return_to.column + && !layout.columns.iter().any(|column| column.id == *id) + { + layout.columns.push(Column { id: id.clone(), zone: return_to.zone, width: return_to.column_width.unwrap_or(return_to.size.width) }); + } + } + Ok(layout) +} + /// Iterative traversal also bounds caller-constructed JSON, which did not pass /// through serde_json's parser/recursion limit. pub fn bounded_json(value: &serde_json::Value) -> PanelResult<()> { @@ -408,8 +1377,281 @@ pub fn bounded_json(value: &serde_json::Value) -> PanelResult<()> { Ok(()) } -/// Decode bounded bytes, quarantine unknown kinds, and retry retained panels when -/// registered again. Corrupt/future input returns a validated safe preset plus notice. +#[derive(Default)] +struct MigrationColumns { + columns: Vec, + sections: std::collections::BTreeMap, + bounds: std::collections::BTreeMap, + section_bounds: std::collections::BTreeMap, +} +impl MigrationColumns { + fn assign(&mut self, zone: Zone, section: Option<&SectionId>, width: f32) -> PanelResult<(ColumnId, usize)> { + if let Some(column) = section.and_then(|id| self.sections.get(id)) + && self.columns.iter().any(|c| c.id == *column && c.zone == zone) + { + let rank = self.columns.iter().filter(|c| c.zone == zone).position(|c| c.id == *column).unwrap_or(0); + return Ok((column.clone(), rank)); + } + let (min, max) = section.and_then(|id| self.section_bounds.get(id)).copied().unwrap_or((width, width)); + // Preserve the v1 vertical stack and every preferred size. A shared + // column width is independently clamped to the composite interval. + // Only genuinely incompatible old sections require a further column. + let existing = self.columns.iter().rev().find(|c| c.zone == zone).and_then(|column| { + let (lower, upper) = self.bounds.get(&column.id).copied().unwrap_or((column.width, column.width)); + (lower.max(min) <= upper.min(max)).then_some((column.id.clone(), lower.max(min), upper.min(max))) + }); + let column = match existing { + Some((id, lower, upper)) => { + if let Some(column) = self.columns.iter_mut().find(|c| c.id == id) { + column.width = column.width.clamp(lower, upper); + } + self.bounds.insert(id.clone(), (lower, upper)); + id + } + None => { + let rank = self.columns.iter().filter(|c| c.zone == zone).count(); + let side = if zone == Zone::Left { "left" } else { "right" }; + let column = ColumnId::new(format!("column-v1-{side}-{}", rank + 1))?; + self.columns.push(Column { id: column.clone(), zone, width }); + self.bounds.insert(column.clone(), (min, max)); + column + } + }; + if let Some(section) = section { + self.sections.entry(section.clone()).or_insert_with(|| column.clone()); + } + let rank = self.columns.iter().filter(|c| c.zone == zone).position(|c| c.id == column).unwrap_or(0); + Ok((column, rank)) + } +} + +fn migrate_location(location: &mut serde_json::Value, columns: &mut MigrationColumns) -> PanelResult<()> { + if location.get("type").and_then(|v| v.as_str()) == Some("window") { + let destination = location.get_mut("return_to").ok_or_else(|| error(Rule::Schema, "native return absent"))?; + let mut destination_typed: DockReturn = + serde_json::from_value(destination.clone()).map_err(|_| error(Rule::Schema, "invalid v1 native return"))?; + if destination_typed.zone.side() && destination_typed.column.is_none() { + let section = destination_typed.section.as_ref().or_else(|| destination_typed.join.as_ref().map(|join| &join.section)); + let (column, rank) = columns.assign(destination_typed.zone, section, destination_typed.size.width)?; + destination_typed.column = Some(column); + destination_typed.column_index = rank; + destination_typed.column_width = Some(destination_typed.size.width); + } + if destination.get("weight").is_none() { + destination_typed.weight = + if destination_typed.zone == Zone::Bottom { destination_typed.size.width } else { destination_typed.size.height }; + } + let current = serde_json::to_value(destination_typed).map_err(|_| error(Rule::Schema, "cannot migrate native return"))?; + *destination = overlay_preference_record(destination, current); + } + Ok(()) +} + +fn migrate_section(value: &mut serde_json::Value, columns: &mut MigrationColumns) -> PanelResult<()> { + if let Some(location) = value.get_mut("location") { + migrate_location(location, columns)?; + } + let mut section: Section = serde_json::from_value(value.clone()).map_err(|_| error(Rule::Schema, "invalid v1 section"))?; + let zone = section.location.zone(); + if zone.side() && section.column.is_none() { + section.column = Some(columns.assign(zone, Some(§ion.id), section.size.width)?.0); + } + if value.get("weight").is_none() { + section.weight = if zone == Zone::Bottom { section.size.width } else { section.size.height }; + } + let current = serde_json::to_value(section).map_err(|_| error(Rule::Schema, "cannot migrate section"))?; + *value = overlay_preference_record(value, current); + Ok(()) +} + +fn migrate_instance(value: &mut serde_json::Value, columns: &mut MigrationColumns) -> PanelResult<()> { + let memory = value.get_mut("memory").ok_or_else(|| error(Rule::Schema, "v1 placement memory absent"))?; + if let Some(location) = memory.get_mut("location") { + migrate_location(location, columns)?; + } + let mut typed: PlacementMemory = serde_json::from_value(memory.clone()).map_err(|_| error(Rule::Schema, "invalid v1 placement memory"))?; + let zone = typed.location.zone(); + if zone.side() && typed.column.is_none() { + let (column, rank) = columns.assign(zone, Some(&typed.section), typed.size.width)?; + typed.column = Some(column); + typed.column_index = rank; + typed.column_width = Some(typed.size.width); + } + if memory.get("weight").is_none() { + typed.weight = if zone == Zone::Bottom { typed.size.width } else { typed.size.height }; + } + let current = serde_json::to_value(typed).map_err(|_| error(Rule::Schema, "cannot migrate placement memory"))?; + *memory = overlay_preference_record(memory, current); + Ok(()) +} + +/// Migrate the existing Rust envelope only. Opaque extension keys are overlaid, +/// not deserialized away; a failed migration leaves the exact bytes recoverable. +fn migrate_wire(raw: &mut serde_json::Value, registry: &PanelRegistry) -> PanelResult<()> { + let envelope_version = raw.get("version").and_then(|v| v.as_u64()).ok_or_else(|| error(Rule::Version, "envelope version absent"))?; + let layout_version = + raw.get("layout").and_then(|l| l.get("version")).and_then(|v| v.as_u64()).ok_or_else(|| error(Rule::Version, "layout version absent"))?; + if envelope_version == u64::from(ENVELOPE_VERSION) && layout_version == u64::from(LAYOUT_VERSION) { + return Ok(()); + } + if envelope_version != 1 || layout_version != 1 { + return Err(error(Rule::Version, "future or unsupported panel layout")); + } + let mut columns = MigrationColumns::default(); + let mut kinds = std::collections::BTreeMap::new(); + if let Some(instances) = raw.get("layout").and_then(|l| l.get("instances")).and_then(|v| v.as_array()) { + for instance in instances { + if let (Some(id), Some(kind)) = (instance.get("id").and_then(|v| v.as_str()), instance.get("kind").and_then(|v| v.as_str())) { + kinds.insert(id.to_owned(), PanelKind::new(kind)?); + } + } + } + if let Some(quarantine) = raw.get("quarantine").and_then(|v| v.as_array()) { + for instance in quarantine.iter().filter_map(|item| item.get("instance_data")) { + if let (Some(id), Some(kind)) = (instance.get("id").and_then(|v| v.as_str()), instance.get("kind").and_then(|v| v.as_str())) { + kinds.entry(id.to_owned()).or_insert(PanelKind::new(kind)?); + } + } + } + let mut records = Vec::new(); + if let Some(sections) = raw.get("layout").and_then(|l| l.get("sections")).and_then(|v| v.as_array()) { + records.extend(sections.iter()); + } + if let Some(snapshots) = raw.get("section_snapshots").and_then(|v| v.as_object()) { + records.extend(snapshots.values().filter_map(|v| v.get("data"))); + } + for record in records { + let section: Section = serde_json::from_value(record.clone()).map_err(|_| error(Rule::Schema, "invalid v1 section limits"))?; + let mut min: f32 = 0.0; + let mut max = MAX_LOGICAL; + for tab in §ion.tabs { + if let Some(spec) = kinds.get(&tab.0).and_then(|kind| registry.get(kind).ok()) { + min = min.max(spec.min_size.width); + max = max.min(spec.max_size.width); + } else { + // An absent peer's saved valid width is its only known safe + // interval. Preserve that slot instead of grouping across it. + min = min.max(section.size.width); + max = max.min(section.size.width); + } + } + if min > max { + return Err(error(Rule::IncompatibleTabs, "v1 tab width intervals do not intersect")); + } + columns.section_bounds.entry(section.id).or_insert((min, max)); + } + // Group in COMPLETE order before assigning any live column. Grouping A/C + // first cannot later insert an incompatible dormant B between them. + let mut records = std::collections::BTreeMap::new(); + let mut live_order = Vec::new(); + if let Some(sections) = raw.get("layout").and_then(|l| l.get("sections")).and_then(|v| v.as_array()) { + for value in sections { + let section: Section = serde_json::from_value(value.clone()).map_err(|_| error(Rule::Schema, "invalid migration section"))?; + live_order.push(section.id.clone()); + records.insert(section.id, value.clone()); + } + } + let dormant: std::collections::BTreeSet<_> = raw + .get("quarantine") + .and_then(|v| v.as_array()) + .into_iter() + .flatten() + .filter_map(|item| item.get("section").and_then(|v| v.as_str())) + .map(SectionId::new) + .collect::>()?; + let mut missing = Vec::new(); + if let Some(snapshots) = raw.get("section_snapshots").and_then(|v| v.as_object()) { + for (id, snapshot) in snapshots { + let id = SectionId::new(id)?; + if !dormant.contains(&id) { + continue; + } + let data = snapshot.get("data").ok_or_else(|| error(Rule::Schema, "dormant migration snapshot absent"))?; + records.entry(id.clone()).or_insert_with(|| data.clone()); + let rank = snapshot.get("index").and_then(|v| v.as_u64()).and_then(|v| usize::try_from(v).ok()).unwrap_or(MAX_SECTIONS); + missing.push((rank, id)); + } + } + let mut complete = Vec::new(); + if let Some(order) = raw.get("section_order").and_then(|v| v.as_array()) { + for id in order { + let id = SectionId::new(id.as_str().ok_or_else(|| error(Rule::Id, "invalid complete migration rank"))?)?; + if records.contains_key(&id) && !complete.contains(&id) { + complete.push(id); + } + } + } + for id in live_order { + if !complete.contains(&id) { + complete.push(id); + } + } + missing.sort(); + for (rank, id) in missing { + if !complete.contains(&id) { + complete.insert(rank.min(complete.len()), id); + } + } + if complete.len() > MAX_SECTIONS { + return Err(error(Rule::CollectionLimit, "complete migration section cap")); + } + for id in &complete { + let record = records.get_mut(id).ok_or_else(|| error(Rule::MissingTarget, "complete migration record absent"))?; + let section: Section = serde_json::from_value(record.clone()).map_err(|_| error(Rule::Schema, "invalid complete migration record"))?; + if section.location.zone().side() { + migrate_section(record, &mut columns)?; + } + } + if let Some(sections) = raw.get_mut("layout").and_then(|l| l.get_mut("sections")).and_then(|v| v.as_array_mut()) { + for section in sections { + migrate_section(section, &mut columns)?; + } + } + // Retain dormant column records as identity/order/width data, never paint. + let saved_columns: std::collections::BTreeSet<_> = columns.columns.iter().map(|c| c.id.clone()).collect(); + if let Some(snapshots) = raw.get_mut("section_snapshots").and_then(|v| v.as_object_mut()) { + for snapshot in snapshots.values_mut() { + if let Some(data) = snapshot.get_mut("data") { + migrate_section(data, &mut columns)?; + } + if let Some(projected) = snapshot.get_mut("projected").filter(|v| !v.is_null()) { + migrate_section(projected, &mut columns)?; + } + } + } + if let Some(instances) = raw.get_mut("layout").and_then(|l| l.get_mut("instances")).and_then(|v| v.as_array_mut()) { + for instance in instances { + migrate_instance(instance, &mut columns)?; + } + } + if let Some(quarantine) = raw.get_mut("quarantine").and_then(|v| v.as_array_mut()) { + for item in quarantine { + if let Some(data) = item.get_mut("instance_data") { + migrate_instance(data, &mut columns)?; + } + } + } + if let Some(retained) = raw.get_mut("retained_data").and_then(|v| v.as_object_mut()) { + for data in retained.values_mut() { + if let Some(instance) = data.get_mut("instance").filter(|v| v.get("memory").is_some()) { + migrate_instance(instance, &mut columns)?; + } + } + } + let layout = raw.get_mut("layout").and_then(|v| v.as_object_mut()).ok_or_else(|| error(Rule::Schema, "layout must be object"))?; + let saved_columns: Vec<_> = columns.columns.into_iter().filter(|c| saved_columns.contains(&c.id)).collect(); + layout.insert("columns".into(), serde_json::to_value(saved_columns).map_err(|_| error(Rule::Schema, "cannot migrate columns"))?); + layout.insert("version".into(), LAYOUT_VERSION.into()); + let envelope = raw.as_object_mut().ok_or_else(|| error(Rule::Schema, "envelope must be object"))?; + envelope.insert("version".into(), ENVELOPE_VERSION.into()); + // The caller bounded the ORIGINAL v1 tree. Added typed fields/columns are + // bounded by semantic collection limits; v2 encoding budgets apply at staging. + Ok(()) +} + +/// Decode bounded bytes, quarantine unknown kinds, and retry retained panels. +/// A valid v1 record retains its original bytes even if v2 expansion will refuse +/// explicit staging. Corrupt/future input returns a safe preset plus notice. pub fn decode(bytes: &[u8], registry: &PanelRegistry, fallback: &Layout) -> PanelResult { validate(fallback, registry)?; match decode_inner(bytes, registry, &fallback.workspace, true) { @@ -431,9 +1673,15 @@ pub fn decode_retained_record(bytes: &[u8], registry: &PanelRegistry) -> PanelRe if bytes.len() > MAX_ENVELOPE_BYTES { return Err(error(Rule::CollectionLimit, "panel envelope exceeds byte cap")); } - let raw: serde_json::Value = serde_json::from_slice(bytes).map_err(|_| error(Rule::Schema, "invalid panel envelope JSON"))?; + let mut raw: serde_json::Value = serde_json::from_slice(bytes).map_err(|_| error(Rule::Schema, "invalid panel envelope JSON"))?; bounded_json(&raw)?; - let envelope: LayoutEnvelope = serde_json::from_value(raw).map_err(|_| error(Rule::Schema, "invalid panel envelope shape"))?; + let migrated_v1 = raw.get("version").and_then(|v| v.as_u64()) == Some(1); + migrate_wire(&mut raw, registry)?; + let mut envelope: LayoutEnvelope = serde_json::from_value(raw.clone()).map_err(|_| error(Rule::Schema, "invalid panel envelope shape"))?; + retain_unknown_wire(&mut envelope, raw)?; + if migrated_v1 { + envelope.retained_v1 = Some(std::sync::Arc::from(bytes)); + } if envelope.format != ENVELOPE_FORMAT { return Err(error(Rule::Schema, "unknown panel envelope format")); } @@ -441,10 +1689,15 @@ pub fn decode_retained_record(bytes: &[u8], registry: &PanelRegistry) -> PanelRe return Err(error(Rule::Version, "unknown panel envelope version")); } validate_retained_layout(&envelope.layout, registry)?; - validate_envelope_metadata(&envelope)?; - // The same canonical encodability budget as admission, without filling any - // metadata or requiring absent peers. The caller retains the ORIGINAL bytes. - encode_record(&envelope)?; + validate_envelope_metadata_for_read(&envelope, migrated_v1)?; + seed_priority_context(&mut envelope)?; + // Current records retain the canonical encodability guarantee. Legacy reads + // preserve the original globally bounded bytes; only explicit staging may + // refuse the extra known-field overhead of the migrated v2 encoding. + if !migrated_v1 { + let encoded = encode_record(&envelope)?; + refresh_recovery_wire(&mut envelope, &encoded)?; + } Ok(envelope) } @@ -478,9 +1731,15 @@ fn decode_inner(bytes: &[u8], registry: &PanelRegistry, workspace: &WorkspaceId, } // serde_json's recursion limit remains enabled. Parsing starts only after the // byte bound, so oversized arrays/strings cannot allocate without a bound. - let raw: serde_json::Value = serde_json::from_slice(bytes).map_err(|_| error(Rule::Schema, "invalid panel envelope JSON"))?; + let mut raw: serde_json::Value = serde_json::from_slice(bytes).map_err(|_| error(Rule::Schema, "invalid panel envelope JSON"))?; bounded_json(&raw)?; + let migrated_v1 = raw.get("version").and_then(|v| v.as_u64()) == Some(1); + migrate_wire(&mut raw, registry)?; let mut envelope: LayoutEnvelope = serde_json::from_value(raw.clone()).map_err(|_| error(Rule::Schema, "invalid panel envelope shape"))?; + retain_unknown_wire(&mut envelope, raw.clone())?; + if migrated_v1 { + envelope.retained_v1 = Some(std::sync::Arc::from(bytes)); + } if envelope.version != ENVELOPE_VERSION || envelope.layout.version != LAYOUT_VERSION { return Err(error(Rule::Version, "future or unsupported panel layout")); } @@ -495,7 +1754,8 @@ fn decode_inner(bytes: &[u8], registry: &PanelRegistry, workspace: &WorkspaceId, return Err(error(Rule::CollectionLimit, "panel collection limit")); } validate_retained_layout(&envelope.layout, registry)?; - validate_envelope_metadata(&envelope)?; + validate_envelope_metadata_for_read(&envelope, migrated_v1)?; + seed_priority_context(&mut envelope)?; let unknown: Vec<_> = envelope.layout.instances.iter().filter(|p| registry.get(&p.kind).is_err()).cloned().collect(); let capture: std::collections::BTreeSet<_> = envelope .layout @@ -507,7 +1767,7 @@ fn decode_inner(bytes: &[u8], registry: &PanelRegistry, workspace: &WorkspaceId, // Refresh from the saved live layout BEFORE newly unknown members are // removed. A previous fully-restored snapshot is opaque metadata, not an // authority that can overwrite intervening saved edits. - refresh_section_memory(&mut envelope, Some(&raw), &capture)?; + refresh_section_memory(&mut envelope, Some(&raw), &capture, migrated_v1)?; for instance in unknown { let section_index = envelope.layout.sections.iter().position(|s| s.tabs.contains(&instance.id)); let instance_data = raw @@ -539,13 +1799,18 @@ fn decode_inner(bytes: &[u8], registry: &PanelRegistry, workspace: &WorkspaceId, // Newly quarantining an active tab creates a fallback selection. That // projection is produced by us, not an intervening user activation. record_section_projections(&mut envelope); - validate_envelope(&envelope, registry)?; + reconcile_priority_context(&mut envelope)?; + validate(&envelope.layout, registry)?; + validate_envelope_metadata_for_read(&envelope, migrated_v1)?; if restore { - restore_quarantine(&mut envelope, registry)?; + restore_quarantine_for_read(&mut envelope, registry, &AvailabilityMap::new(), migrated_v1)?; + } + // v2 reads remain persistable. Valid v1 projection retains original bytes + // and defers an expanded encoding refusal to an explicit staging operation. + if !migrated_v1 { + let encoded = encode(&envelope, registry)?; + refresh_recovery_wire(&mut envelope, &encoded)?; } - // Success means the lossless transformed envelope is itself persistable, - // including its aggregate byte/node/depth budget. Otherwise retain recovery. - encode(&envelope, registry)?; Ok(envelope) } @@ -558,7 +1823,21 @@ pub fn restore_quarantine_with_availability( registry: &PanelRegistry, availability: &AvailabilityMap, ) -> PanelResult<()> { - validate_envelope(envelope, registry)?; + restore_quarantine_for_read(envelope, registry, availability, false) +} + +fn restore_quarantine_for_read( + envelope: &mut LayoutEnvelope, + registry: &PanelRegistry, + availability: &AvailabilityMap, + migrated_v1: bool, +) -> PanelResult<()> { + if migrated_v1 { + validate(&envelope.layout, registry)?; + validate_envelope_metadata_for_read(envelope, true)?; + } else { + validate_envelope(envelope, registry)?; + } if availability.len() > MAX_INSTANCES { return Err(error(Rule::CollectionLimit, "reappearance availability cap")); } @@ -569,9 +1848,10 @@ pub fn restore_quarantine_with_availability( } } let mut working = envelope.clone(); + working.layout.extent_priority_context = preparation_context(envelope)?.extent_priorities; // Direct consumers may have edited the live layout since the last decode or // restore. Merge those edits before using saved ranks/activation again. - refresh_section_memory(&mut working, None, &std::collections::BTreeSet::new())?; + refresh_section_memory(&mut working, None, &std::collections::BTreeSet::new(), migrated_v1)?; // Build a candidate for each entry. An incompatible reappearance stays in // quarantine instead of invalidating the known layout or erasing its wire data. let mut remaining = Vec::new(); @@ -581,8 +1861,9 @@ pub fn restore_quarantine_with_availability( continue; } let mut candidate = working.layout.clone(); - let instance: PanelInstance = + let mut instance: PanelInstance = serde_json::from_value(item.instance_data.clone()).map_err(|_| error(Rule::Schema, "invalid quarantined instance"))?; + apply_memory_priorities(&working.layout.extent_priority_context, &mut instance); candidate.instances.push(instance.clone()); if instance.requested_open { let Some(section_id) = &item.section else { @@ -591,6 +1872,7 @@ pub fn restore_quarantine_with_availability( }; let snapshot = working.section_snapshots.get(section_id).ok_or_else(|| error(Rule::MissingTarget, "shared snapshot missing"))?; let mut saved: Section = serde_json::from_value(snapshot.data.clone()).map_err(|_| error(Rule::Schema, "invalid quarantined section"))?; + apply_section_priorities(&working.layout.extent_priority_context, &mut saved); if let Some(section) = candidate.sections.iter_mut().find(|s| s.id == saved.id) { let members: std::collections::BTreeSet<_> = section.tabs.iter().cloned().chain(std::iter::once(instance.id.clone())).collect(); section.tabs = saved @@ -604,6 +1886,23 @@ pub fn restore_quarantine_with_availability( section.active = saved.active.clone(); } } else { + if let Some(column) = &saved.column + && candidate.column(column).is_err() + { + let zone = saved.location.zone(); + let rank = instance.memory.column_index; + let index = candidate + .columns + .iter() + .enumerate() + .filter(|(_, c)| c.zone == zone) + .nth(rank) + .map(|(i, _)| i) + .unwrap_or(candidate.columns.len()); + candidate + .columns + .insert(index, Column { id: column.clone(), zone, width: instance.memory.column_width.unwrap_or(saved.size.width) }); + } saved.tabs = vec![instance.id.clone()]; saved.active = instance.id.clone(); candidate.sections.push(saved); @@ -628,7 +1927,14 @@ pub fn restore_quarantine_with_availability( } working.quarantine = remaining; record_section_projections(&mut working); - encode(&working, registry)?; + reconcile_priority_context(&mut working)?; + if !migrated_v1 { + let encoded = encode(&working, registry)?; + refresh_recovery_wire(&mut working, &encoded)?; + } else { + validate(&working.layout, registry)?; + validate_envelope_metadata_for_read(&working, true)?; + } *envelope = working; Ok(()) } @@ -679,19 +1985,38 @@ fn validate_wire_structure(layout: &Layout) -> PanelResult<()> { 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 instances = std::collections::BTreeSet::new(); let mut sections = std::collections::BTreeSet::new(); let mut seen = std::collections::BTreeSet::new(); let mut hosts = std::collections::BTreeSet::new(); + let mut columns = std::collections::BTreeSet::new(); + let mut last_column = std::collections::BTreeMap::::new(); + for column in &layout.columns { + valid_id(&column.id.0)?; + if !columns.insert(&column.id) { + return Err(error(Rule::DuplicateId, "duplicate saved column")); + } + if !column.zone.side() || !column.width.is_finite() || column.width <= 0.0 || column.width > MAX_LOGICAL { + return Err(error(Rule::Bounds, "invalid saved column")); + } + } for instance in &layout.instances { valid_id(&instance.id.0)?; valid_id(&instance.kind.0)?; valid_id(&instance.memory.section.0)?; instance.memory.location.validate()?; instance.memory.size.validate()?; + validate_column_memory( + instance.memory.location.zone(), + &instance.memory.column, + instance.memory.column_index, + instance.memory.column_width, + instance.memory.weight, + )?; + validate_extent_priority(instance.memory.preferred_extent, instance.memory.extent_priority)?; if instance.memory.tab_index >= MAX_TABS || instance.memory.section_index > MAX_SECTIONS { return Err(error(Rule::Bounds, "invalid placement memory")); } @@ -703,6 +2028,20 @@ fn validate_wire_structure(layout: &Layout) -> PanelResult<()> { valid_id(§ion.id.0)?; section.location.validate()?; section.size.validate()?; + validate_section_record(section)?; + let zone = section.location.zone(); + if let Some(column) = §ion.column { + let rank = layout + .columns + .iter() + .filter(|c| c.zone == zone) + .position(|c| c.id == *column) + .ok_or_else(|| error(Rule::Placement, "saved section column absent"))?; + if last_column.get(&zone).is_some_and(|last| *last > rank) { + return Err(error(Rule::Placement, "saved column sections are not contiguous")); + } + last_column.insert(zone, rank); + } if !sections.insert(§ion.id) { return Err(error(Rule::DuplicateId, "duplicate unknown/known section")); } diff --git a/crates/engine/src/panels/reducer.rs b/crates/engine/src/panels/reducer.rs index 5a8189162..a6772a5c9 100644 --- a/crates/engine/src/panels/reducer.rs +++ b/crates/engine/src/panels/reducer.rs @@ -1,14 +1,25 @@ use schemars::JsonSchema; use serde::{Deserialize, Serialize}; +use std::collections::BTreeSet; use super::*; /// Joining an existing tab group and creating a split are deliberately distinct. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum RelativePlacement { + BeforeColumn, + AfterColumn, + Above, + Below, +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] #[serde(tag = "type", rename_all = "snake_case")] pub enum Destination { NewSection { section: SectionId, index: usize, location: SectionLocation, size: Size }, JoinTab { section: SectionId, index: usize }, + Relative { section: SectionId, placement: RelativePlacement, new_section: SectionId, new_column: Option, size: Size }, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] @@ -48,6 +59,25 @@ pub enum Mutation { section: SectionId, size: Size, }, + SetColumnWidth { + column: ColumnId, + width: f32, + }, + SetBottomHeight { + section: SectionId, + height: f32, + }, + HeaderAction { + instance: InstanceId, + action: ControlId, + }, + /// Resize/reposition an existing floating section as one retained group. + /// This changes geometry and placement memories, never parent or focus. + SetFloatingRect { + section: SectionId, + origin: Point, + size: Size, + }, /// Both neighbours change together; their shared axis extent is conserved. ResizePair { first: SectionId, @@ -55,6 +85,20 @@ pub enum Mutation { first_size: Size, second_size: Size, }, + /// Host-admitted actual geometry and normalized shares. Unlike ResizePair, + /// actual extent conservation is checked against the captured allocator. + ResizeAllocatedPair { + first: SectionId, + second: SectionId, + first_size: Size, + second_size: Size, + first_weight: f32, + second_weight: f32, + #[serde(default = "unit_weight_scale")] + other_weight_scale: f32, + #[serde(default)] + prefer_allocated: bool, + }, ResetPair { first: SectionId, second: SectionId, @@ -65,6 +109,21 @@ pub enum Mutation { }, } +fn unit_weight_scale() -> f32 { + 1.0 +} + +/// Content actions have their own controller transaction, never placement admission. +pub fn validate_header_action_transaction(mutations: &[Mutation]) -> PanelResult<()> { + if mutations.len() > MAX_MUTATIONS { + return Err(error(Rule::CollectionLimit, "header action transaction cap")); + } + if mutations.len() != 1 && mutations.iter().any(|m| matches!(m, Mutation::HeaderAction { .. })) { + return Err(error(Rule::Capability, "header actions require a standalone transaction")); + } + Ok(()) +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] #[serde(tag = "type", rename_all = "snake_case")] pub enum LayoutAction { @@ -88,6 +147,7 @@ pub enum LayoutTarget { Workspace(WorkspaceId), Instance(InstanceId), Section(SectionId), + Column(ColumnId), NativeHost(HostId), } @@ -100,6 +160,7 @@ pub enum HostEffect { CreateNative { host: HostId, section: SectionId }, RebindNative { host: HostId, section: SectionId }, ReleaseNative { host: HostId }, + HeaderAction { instance: InstanceId, action: ControlId }, } #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] @@ -128,6 +189,12 @@ pub trait ActionSink { fn project(&self, _action: LayoutAction) -> PanelResult { Err(error(Rule::Capability, "layout sink cannot stage commands")) } + fn project_in_context(&self, action: LayoutAction, _context: &LayoutPreparationContext) -> PanelResult { + self.project(action) + } + fn dispatch_in_context(&mut self, action: LayoutAction, _context: &LayoutPreparationContext) -> PanelResult { + self.dispatch(action) + } } #[derive(Debug)] @@ -228,18 +295,139 @@ impl LayoutService { } } pub fn prepare(&self, action: LayoutAction) -> PanelResult { + self.prepare_with_reservations(action, &BTreeSet::new(), &BTreeSet::new()) + } + /// Borrowed dormant identities participate in generation and collision checks + /// without entering the proposed layout or consuming IDs during preparation. + pub fn prepare_with_reservations( + &self, + action: LayoutAction, + sections: &BTreeSet, + columns: &BTreeSet, + ) -> PanelResult { + self.prepare_internal(action, sections, columns, None, false, None) + } + /// Structural data for one proposed-owner capture, never an unchecked + /// committable candidate. Presentation metadata still uses the current map. + pub fn project_with_deferred_availability( + &self, + action: LayoutAction, + sections: &BTreeSet, + columns: &BTreeSet, + ) -> PanelResult { + Ok(self.prepare_internal(action, sections, columns, None, true, None)?.next) + } + /// Final pure admission against the captured proposed owner's availability. + /// Replace retains this map rather than clearing it as the legacy path does. + pub fn prepare_with_availability_and_reservations( + &self, + action: LayoutAction, + availability: &AvailabilityMap, + sections: &BTreeSet, + columns: &BTreeSet, + ) -> PanelResult { + self.prepare_internal(action, sections, columns, Some(availability), false, None) + } + pub fn project_with_context(&self, action: LayoutAction, context: &LayoutPreparationContext) -> PanelResult { + Ok(self.prepare_internal(action, &context.sections, &context.columns, None, true, Some(context))?.next) + } + pub fn prepare_with_context( + &self, + action: LayoutAction, + availability: &AvailabilityMap, + context: &LayoutPreparationContext, + ) -> PanelResult { + self.prepare_internal(action, &context.sections, &context.columns, Some(availability), false, Some(context)) + } + fn prepare_internal( + &self, + action: LayoutAction, + sections: &BTreeSet, + columns: &BTreeSet, + captured_availability: Option<&AvailabilityMap>, + defer_availability: bool, + full_context: Option<&LayoutPreparationContext>, + ) -> PanelResult { + let reservations = Reservations { sections, columns }; + reservations.validate()?; + if let Some(ownership) = full_context.and_then(|context| context.replacement_ownership.as_ref()) { + ownership.validate()?; + } + if let LayoutAction::Apply { mutations, .. } = &action + && (mutations.is_empty() || mutations.len() > MAX_MUTATIONS) + { + return Err(error(Rule::CollectionLimit, "transaction requires 1..64 mutations")); + } + if let Some(availability) = captured_availability { + validate_availability(availability)?; + } + let action_availability = captured_availability.unwrap_or(&self.availability); let mut next = self.layout.clone(); + let content_only = + matches!(&action, LayoutAction::Apply { mutations, .. } if matches!(mutations.as_slice(), [Mutation::HeaderAction { .. }])); + let authors_priority = matches!(&action, LayoutAction::Apply { mutations, .. } if mutations.iter().any(|m| + matches!(m, Mutation::SetSize { .. } | Mutation::ResizeAllocatedPair { prefer_allocated: true, .. }))); + if let Some(context) = full_context.filter(|_| !content_only) { + context.extent_priorities.validate()?; + if !context.extent_priorities.complete { + return Err(error(Rule::Capability, "full recovery priority context required")); + } + if authors_priority + && self.layout.extent_priority_context.records.iter().any(|old| { + super::persistence::typed_priority(&self.layout, &old.target).is_none() + && !context.extent_priorities.records.iter().any(|record| { + record.target == old.target + && record.zone == old.zone + && record.column == old.column + && record.stored_priority == old.stored_priority + }) + }) + { + return Err(error(Rule::Capability, "preparation context omits retained priority records")); + } + if authors_priority + && self.layout.extent_priority_context.records.iter().any(|old| { + super::persistence::typed_priority(&self.layout, &old.target).is_none() + && context.extent_priorities.records.iter().any(|record| { + record.target == old.target + && record.zone == old.zone + && record.column == old.column + && record.stored_priority == old.stored_priority + && record.priority != old.priority + }) + }) + { + return Err(error(Rule::Revision, "recovery priority context became stale")); + } + next.extent_priority_context = context.extent_priorities.clone(); + } else if authors_priority && (!sections.is_empty() || !columns.is_empty()) { + return Err(error(Rule::Capability, "external reservations require full priority context for authored sizing")); + } let mut interaction = self.interaction.clone(); let mut effects = Vec::new(); - let mut availability = self.availability.clone(); + let mut availability = action_availability.clone(); let mut destroyed = std::collections::BTreeSet::new(); + let synchronize_priorities = matches!(&action, LayoutAction::Apply { mutations, .. } + if !matches!(mutations.as_slice(), [Mutation::HeaderAction { .. }])) + || matches!(&action, LayoutAction::Replace { .. }); if let LayoutAction::Replace { expected_revision, layout } = &action { if expected_revision.is_some_and(|r| r != self.revision) { return Err(error(Rule::Revision, "stale layout revision")); } validate(layout, &self.registry)?; + reservations.validate_replacement(&self.layout, layout, full_context.and_then(|context| context.replacement_ownership.as_ref()))?; next = layout.clone(); - availability.clear(); + if !next.extent_priority_context.complete + && let Some(context) = full_context + { + if next.workspace != self.layout.workspace && !context.extent_priorities.records.is_empty() { + return Err(error(Rule::Capability, "workspace replacement requires incoming recovery context")); + } + next.extent_priority_context = context.extent_priorities.clone(); + } + if captured_availability.is_none() { + availability.clear(); + } interaction = InteractionState::default(); } if let LayoutAction::Apply { expected_revision, mutations } = action { @@ -250,16 +438,31 @@ impl LayoutService { return Err(error(Rule::CollectionLimit, "transaction requires 1..64 mutations")); } validate_lifecycle_intents(&mutations)?; + validate_header_action_transaction(&mutations)?; for mutation in &mutations { if let Mutation::Destroy { instance } = mutation { destroyed.insert(instance.clone()); } } + let context = MutationContext { + registry: &self.registry, + availability: action_availability, + caps: &self.capabilities, + reservations: &reservations, + defer_availability, + }; for mutation in mutations { - apply(&mut next, &self.registry, &self.availability, &self.capabilities, &mut interaction, &mut effects, mutation)?; + reservations.validate_mutation(&next, &mutation)?; + apply(&mut next, &context, &mut interaction, &mut effects, mutation)?; + if !content_only { + super::persistence::synchronize_priority_context(&mut next)?; + } // A bounded intermediate state cannot smuggle oversized collections into // a later mutation. Semantic invariants are checked at atomic commit. - if next.instances.len() > MAX_INSTANCES || next.sections.len() > MAX_SECTIONS || next.sections.iter().any(|s| s.tabs.len() > MAX_TABS) + if next.instances.len() > MAX_INSTANCES + || next.sections.len() > MAX_SECTIONS + || next.columns.len() > MAX_SECTIONS + || next.sections.iter().any(|s| s.tabs.len() > MAX_TABS) { return Err(error(Rule::CollectionLimit, "transaction collection limit")); } @@ -271,6 +474,9 @@ impl LayoutService { } } } + if synchronize_priorities { + super::persistence::synchronize_priority_context(&mut next)?; + } let mut identities = self.identities.clone(); for id in destroyed { identities.remove(&id); @@ -335,6 +541,13 @@ impl LayoutService { identities, }) } + /// Geometry and environment remain caller-owned. Failed admission cannot + /// publish a candidate or consume its proposed identities. + pub fn prepare_admitted(&self, action: LayoutAction, admission: impl FnOnce(&Layout, &Layout) -> PanelResult<()>) -> PanelResult { + let prepared = self.prepare(action)?; + admission(&self.layout, prepared.layout())?; + Ok(prepared) + } pub fn commit(&mut self, prepared: PreparedLayout) -> PanelResult { if !std::sync::Arc::ptr_eq(&prepared.service_identity, &self.identity) || prepared.base_revision != self.revision { return Err(error(Rule::Revision, "candidate became stale")); @@ -382,6 +595,7 @@ pub fn validate_lifecycle_intents(mutations: &[Mutation]) -> PanelResult<()> { | Mutation::Move { instance, .. } | Mutation::Activate { instance } | Mutation::Focus { instance } + | Mutation::HeaderAction { instance, .. } | Mutation::Peek { instance } => (instance, false), _ => continue, }; @@ -396,6 +610,13 @@ pub fn validate_lifecycle_intents(mutations: &[Mutation]) -> PanelResult<()> { } impl ActionSink for LayoutService { + fn project_in_context(&self, action: LayoutAction, context: &LayoutPreparationContext) -> PanelResult { + Ok(self.prepare_internal(action, &context.sections, &context.columns, None, false, Some(context))?.next) + } + fn dispatch_in_context(&mut self, action: LayoutAction, context: &LayoutPreparationContext) -> PanelResult { + let prepared = self.prepare_internal(action, &context.sections, &context.columns, None, false, Some(context))?; + self.commit(prepared) + } fn project(&self, action: LayoutAction) -> PanelResult { Ok(self.prepare(action)?.layout().clone()) } @@ -442,6 +663,10 @@ fn remember(layout: &mut Layout, id: &InstanceId) -> PanelResult<()> { let section = layout.containing(id)?.clone(); let section_index = layout.sections.iter().position(|s| s.id == section.id).ok_or_else(|| error(Rule::MissingTarget, "section not found"))?; let tab_index = section.tabs.iter().position(|p| p == id).ok_or_else(|| error(Rule::MissingTarget, "tab not found"))?; + let column = section.column.as_ref().map(|id| layout.column(id)).transpose()?; + let column_index = + column.map_or(0, |column| layout.columns.iter().filter(|c| c.zone == column.zone).position(|c| c.id == column.id).unwrap_or(0)); + let column_width = column.map(|column| column.width); let p = layout.instances.iter_mut().find(|p| p.id == *id).ok_or_else(|| error(Rule::MissingTarget, "instance not found"))?; p.memory = PlacementMemory { section: section.id, @@ -450,6 +675,12 @@ fn remember(layout: &mut Layout, id: &InstanceId) -> PanelResult<()> { tab_index, size: section.size, collapsed: section.collapsed, + column: section.column, + column_index, + column_width, + weight: section.weight, + preferred_extent: section.preferred_extent, + extent_priority: section.extent_priority, }; Ok(()) } @@ -466,19 +697,319 @@ fn detach(layout: &mut Layout, id: &InstanceId) { layout.sections.retain(|s| !s.tabs.is_empty()); } -fn place(layout: &mut Layout, id: &InstanceId, destination: Destination) -> PanelResult<()> { +fn restore_column(layout: &mut Layout, id: ColumnId, zone: Zone, rank: usize, width: f32) -> PanelResult { + valid_id(&id.0)?; + if let Ok(column) = layout.column(&id) { + if column.zone != zone { + return Err(error(Rule::Placement, "remembered column moved to a different side")); + } + return Ok(id); + } + if layout.columns.len() >= MAX_SECTIONS { + return Err(error(Rule::CollectionLimit, "column cap")); + } + let index = layout.columns.iter().enumerate().filter(|(_, c)| c.zone == zone).nth(rank).map(|(i, _)| i).unwrap_or(layout.columns.len()); + layout.columns.insert(index, Column { id: id.clone(), zone, width }); + Ok(id) +} + +fn fresh_section(layout: &Layout, id: &InstanceId, section: &SectionId) -> PanelResult<()> { + valid_id(§ion.0)?; + if layout.sections.iter().any(|s| s.id == *section) { + return Err(error(Rule::DuplicateId, "new-section identity already exists")); + } + let own = layout.instance(id).ok().map(|p| &p.memory.section); + let native_own = layout.instance(id).ok().is_some_and(|p| { + matches!(&p.memory.location, + SectionLocation::Window { return_to, .. } if return_to.section.as_ref() == Some(section)) + }); + if own != Some(section) && !native_own && layout.instances.iter().any(|p| p.memory.section == *section) { + return Err(error(Rule::DuplicateId, "new-section identity reserved by placement memory")); + } + 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 + && (return_to.section.as_ref() == Some(section) || return_to.join.as_ref().is_some_and(|join| join.section == *section)) + && own != Some(section) + && !native_own + { + return Err(error(Rule::DuplicateId, "new-section identity reserved by native return")); + } + } + Ok(()) +} + +fn column_insert_index(layout: &Layout, column: &ColumnId, requested: usize) -> PanelResult { + let target = layout.column(column)?; + let rank = layout.columns.iter().position(|c| c.id == *column).ok_or_else(|| error(Rule::MissingTarget, "column absent"))?; + let members: Vec<_> = layout.sections.iter().enumerate().filter(|(_, s)| s.column.as_ref() == Some(column)).map(|(i, _)| i).collect(); + if let (Some(first), Some(last)) = (members.first(), members.last()) { + return Ok(requested.clamp(*first, last.saturating_add(1))); + } + for (index, section) in layout.sections.iter().enumerate().filter(|(_, s)| s.location.zone() == target.zone) { + if section.column.as_ref().and_then(|id| layout.columns.iter().position(|c| c.id == *id)).is_some_and(|other| other > rank) { + return Ok(index); + } + } + Ok(layout.sections.iter().rposition(|s| s.location.zone() == target.zone).map_or(requested.min(layout.sections.len()), |index| index + 1)) +} + +struct Reservations<'a> { + sections: &'a BTreeSet, + columns: &'a BTreeSet, +} + +impl Reservations<'_> { + fn validate(&self) -> PanelResult<()> { + if self.sections.len() > MAX_RESERVED_IDENTITIES || self.columns.len() > MAX_RESERVED_IDENTITIES { + return Err(error(Rule::CollectionLimit, "external identity reservation cap")); + } + for id in self.sections { + valid_id(&id.0)?; + } + for id in self.columns { + valid_id(&id.0)?; + } + Ok(()) + } + fn owns_section(layout: &Layout, instance: &InstanceId, section: &SectionId) -> bool { + let Ok(panel) = layout.instance(instance) else { + return false; + }; + panel.memory.section == *section + || layout.containing(instance).is_ok_and(|s| s.id == *section) + || [Some(&panel.memory.location), layout.containing(instance).ok().map(|s| &s.location)].into_iter().flatten().any(|location| { + matches!(location, SectionLocation::Window { return_to, .. } + if return_to.section.as_ref() == Some(section) || return_to.join.as_ref().is_some_and(|join| join.section == *section)) + }) + } + fn owns_column(layout: &Layout, instance: &InstanceId, column: &ColumnId) -> bool { + let Ok(panel) = layout.instance(instance) else { + return false; + }; + panel.memory.column.as_ref() == Some(column) + || layout.containing(instance).is_ok_and(|s| s.column.as_ref() == Some(column)) + || [Some(&panel.memory.location), layout.containing(instance).ok().map(|s| &s.location)] + .into_iter() + .flatten() + .any(|location| matches!(location, SectionLocation::Window { return_to, .. } if return_to.column.as_ref() == Some(column))) + } + fn section(&self, layout: &Layout, instance: &InstanceId, id: &SectionId) -> PanelResult<()> { + if self.sections.contains(id) && !Self::owns_section(layout, instance, id) { + return Err(error(Rule::DuplicateId, "section identity externally reserved")); + } + Ok(()) + } + fn column(&self, layout: &Layout, instance: &InstanceId, id: &ColumnId) -> PanelResult<()> { + if self.columns.contains(id) && !Self::owns_column(layout, instance, id) { + return Err(error(Rule::DuplicateId, "column identity externally reserved")); + } + Ok(()) + } + fn destination(&self, layout: &Layout, instance: &InstanceId, destination: &Destination) -> PanelResult<()> { + match destination { + Destination::NewSection { section, location, .. } => { + self.section(layout, instance, section)?; + if let SectionLocation::Window { return_to, .. } = location { + if let Some(id) = &return_to.section { + self.section(layout, instance, id)?; + } + if let Some(join) = &return_to.join + && layout.section(&join.section).is_err() + { + self.section(layout, instance, &join.section)?; + } + if let Some(id) = &return_to.column { + self.column(layout, instance, id)?; + } + } + } + Destination::Relative { new_section, new_column, .. } => { + self.section(layout, instance, new_section)?; + if let Some(id) = new_column { + self.column(layout, instance, id)?; + } + } + Destination::JoinTab { .. } => {} + } + Ok(()) + } + fn validate_mutation(&self, layout: &Layout, mutation: &Mutation) -> PanelResult<()> { + match mutation { + Mutation::Open { instance, destination: Some(destination), .. } | Mutation::Move { instance, destination } => { + self.destination(layout, instance, destination) + } + _ => Ok(()), + } + } + fn validate_replacement(&self, before: &Layout, after: &Layout, captured: Option<&ReplacementIdentityOwnership>) -> PanelResult<()> { + let after_ownership = ReplacementIdentityOwnership::from_layout(after)?; + let captured_section = |id: &SectionId| { + captured.is_some_and(|captured| captured.sections.get(id).is_some_and(|owners| after_ownership.sections.get(id) == Some(owners))) + }; + let captured_column = |id: &ColumnId| { + captured.is_some_and(|captured| captured.columns.get(id).is_some_and(|owners| after_ownership.columns.get(id) == Some(owners))) + }; + for section in &after.sections { + if before.section(§ion.id).is_err() + && self.sections.contains(§ion.id) + && !section.tabs.iter().any(|id| Self::owns_section(before, id, §ion.id)) + && !captured_section(§ion.id) + { + return Err(error(Rule::DuplicateId, "replacement steals reserved section")); + } + if let Some(column) = §ion.column + && before.column(column).is_err() + && self.columns.contains(column) + && !section.tabs.iter().any(|id| Self::owns_column(before, id, column)) + && !captured_column(column) + { + return Err(error(Rule::DuplicateId, "replacement steals reserved column")); + } + for instance in §ion.tabs { + if let SectionLocation::Window { return_to, .. } = §ion.location { + if let Some(id) = &return_to.section + && !captured_section(id) + { + self.section(before, instance, id)?; + } + if let Some(join) = &return_to.join + && before.section(&join.section).is_err() + && !captured_section(&join.section) + { + self.section(before, instance, &join.section)?; + } + if let Some(id) = &return_to.column + && !captured_column(id) + { + self.column(before, instance, id)?; + } + } + } + } + for column in &after.columns { + if before.column(&column.id).is_err() + && self.columns.contains(&column.id) + && !after.instances.iter().any(|p| Self::owns_column(before, &p.id, &column.id)) + && !captured_column(&column.id) + { + return Err(error(Rule::DuplicateId, "replacement steals reserved dormant column")); + } + } + for panel in &after.instances { + let memory = &panel.memory; + if before.section(&memory.section).is_err() && !captured_section(&memory.section) { + self.section(before, &panel.id, &memory.section)?; + } + if let Some(column) = &memory.column + && before.column(column).is_err() + && !captured_column(column) + { + self.column(before, &panel.id, column)?; + } + if let SectionLocation::Window { return_to, .. } = &memory.location { + if let Some(id) = &return_to.section + && before.section(id).is_err() + && !captured_section(id) + { + self.section(before, &panel.id, id)?; + } + if let Some(join) = &return_to.join + && before.section(&join.section).is_err() + && !captured_section(&join.section) + { + self.section(before, &panel.id, &join.section)?; + } + if let Some(id) = &return_to.column + && before.column(id).is_err() + && !captured_column(id) + { + self.column(before, &panel.id, id)?; + } + } + } + Ok(()) + } +} + +fn place(layout: &mut Layout, id: &InstanceId, destination: Destination, reservations: &Reservations<'_>) -> PanelResult<()> { match destination { - Destination::NewSection { section, index, location, size } => { - valid_id(§ion.0)?; + Destination::NewSection { section, index, mut location, size } => { + fresh_section(layout, id, §ion)?; + if let SectionLocation::Window { return_to, .. } = &mut location { + if return_to.zone.side() && return_to.column.is_none() { + let existing = layout.sections.iter().filter(|s| s.location.zone() == return_to.zone).find_map(|s| s.column.clone()); + let column = match existing { + Some(column) => column, + None => { + let column = next_column_id_with_reservations(layout, reservations.columns)?; + restore_column( + layout, + column, + return_to.zone, + return_to.column_index, + return_to.column_width.unwrap_or(return_to.size.width), + )? + } + }; + return_to.column_width = Some(layout.column(&column)?.width); + return_to.column_index = layout.columns.iter().filter(|c| c.zone == return_to.zone).position(|c| c.id == column).unwrap_or(0); + return_to.column = Some(column); + } + if return_to.section.is_none() { + return_to.section = Some(section.clone()); + } + } location.validate()?; size.validate()?; - if layout.sections.iter().any(|s| s.id == section) { - return Err(error(Rule::DuplicateId, "new-section identity already exists")); - } if index > layout.sections.len() { return Err(error(Rule::Bounds, "section insertion index out of bounds")); } - layout.sections.insert(index, Section { id: section, location, tabs: vec![id.clone()], active: id.clone(), size, collapsed: false }); + let memory = layout + .instance(id) + .ok() + .filter(|p| p.memory.section == section && p.memory.location.zone() == location.zone()) + .map(|p| p.memory.clone()); + let zone = location.zone(); + let column = if zone.side() { + if let Some(memory) = &memory + && let Some(column) = &memory.column + { + Some(restore_column(layout, column.clone(), zone, memory.column_index, memory.column_width.unwrap_or(size.width))?) + } else { + let existing = layout + .sections + .iter() + .skip(index) + .find(|s| s.location.zone() == zone) + .and_then(|s| s.column.clone()) + .or_else(|| layout.sections.iter().rev().find(|s| s.location.zone() == zone).and_then(|s| s.column.clone())); + Some(match existing { + Some(column) => column, + None => { + let column = next_column_id_with_reservations(layout, reservations.columns)?; + restore_column(layout, column, zone, MAX_SECTIONS, size.width)? + } + }) + } + } else { + None + }; + let index = if let Some(column) = &column { column_insert_index(layout, column, index)? } else { index }; + layout.sections.insert( + index, + Section { + id: section, + location, + tabs: vec![id.clone()], + active: id.clone(), + size, + collapsed: memory.as_ref().is_some_and(|m| m.collapsed), + column, + preferred_extent: memory.as_ref().and_then(|m| m.preferred_extent), + extent_priority: memory.as_ref().map_or(0, |m| m.extent_priority), + weight: memory.map_or(if zone == Zone::Bottom { size.width } else { size.height }, |m| m.weight), + }, + ); } Destination::JoinTab { section, index } => { let s = section_mut(layout, §ion)?; @@ -488,6 +1019,68 @@ fn place(layout: &mut Layout, id: &InstanceId, destination: Destination) -> Pane s.tabs.insert(index, id.clone()); // Joining never steals active tab or resizes the group. } + Destination::Relative { section, placement, new_section, new_column, size } => { + fresh_section(layout, id, &new_section)?; + size.validate()?; + let target = layout.section(§ion)?.clone(); + let zone = target.location.zone(); + let target_column = target.column.as_ref().ok_or_else(|| error(Rule::Placement, "relative placement requires side column"))?; + let target_index = + layout.sections.iter().position(|s| s.id == section).ok_or_else(|| error(Rule::MissingTarget, "relative target absent"))?; + let (column, index, weight) = match placement { + RelativePlacement::Above | RelativePlacement::Below => { + if new_column.is_some() { + return Err(error(Rule::Placement, "stack placement reuses target column")); + } + validate_weight(target.weight)?; + // Stack weights are relative, not logical heights. A zero + // anchor stays at minimum; the new section can use surplus. + let weight = if target.weight > 0.0 { target.weight } else { default_weight() }; + (target_column.clone(), target_index + usize::from(placement == RelativePlacement::Below), weight) + } + RelativePlacement::BeforeColumn | RelativePlacement::AfterColumn => { + let column = new_column.ok_or_else(|| error(Rule::Placement, "column placement requires identity"))?; + valid_id(&column.0)?; + if layout.columns.iter().any(|c| c.id == column) + || layout.instances.iter().any(|p| p.memory.column.as_ref() == Some(&column)) + || layout.sections.iter().map(|s| &s.location).chain(layout.instances.iter().map(|p| &p.memory.location)).any( + |location| matches!(location, SectionLocation::Window { return_to, .. } if return_to.column.as_ref() == Some(&column)), + ) + { + return Err(error(Rule::DuplicateId, "column identity already reserved")); + } + let after = placement == RelativePlacement::AfterColumn; + let rank = layout + .columns + .iter() + .position(|c| c.id == *target_column) + .ok_or_else(|| error(Rule::MissingTarget, "target column absent"))?; + let index = if after { + layout.sections.iter().rposition(|s| s.column.as_ref() == Some(target_column)).map(|i| i + 1) + } else { + layout.sections.iter().position(|s| s.column.as_ref() == Some(target_column)) + } + .ok_or_else(|| error(Rule::MissingTarget, "target column empty"))?; + layout.columns.insert(rank + usize::from(after), Column { id: column.clone(), zone, width: size.width }); + (column, index, size.height) + } + }; + layout.sections.insert( + index, + Section { + id: new_section, + location: SectionLocation::Dock { zone }, + tabs: vec![id.clone()], + active: id.clone(), + size, + collapsed: false, + column: Some(column), + weight, + preferred_extent: None, + extent_priority: 0, + }, + ); + } } Ok(()) } @@ -505,20 +1098,49 @@ fn reopen_destination(layout: &Layout, p: &PanelInstance) -> Destination { } } +fn inherited_extent_preference(source: Zone, target: Zone, preferred_extent: Option, extent_priority: u16) -> (Option, u16) { + // Free placements retain latent intent; only concrete dock axes establish incompatibility. + if source.docked() && target.docked() && source.side() != target.side() { (None, 0) } else { (preferred_extent, extent_priority) } +} + +fn inherit_native_preference(destination: &mut Destination, source: Zone, preferred_extent: Option, extent_priority: u16) -> PanelResult<()> { + if let Destination::NewSection { location: SectionLocation::Window { return_to, .. }, .. } = destination { + validate_extent_priority(return_to.preferred_extent, return_to.extent_priority)?; + if return_to.preferred_extent.is_none() { + (return_to.preferred_extent, return_to.extent_priority) = + inherited_extent_preference(source, return_to.zone, preferred_extent, extent_priority); + } + } + Ok(()) +} + +struct MutationContext<'a, 'r> { + registry: &'a PanelRegistry, + availability: &'a AvailabilityMap, + caps: &'a HostCapabilities, + reservations: &'a Reservations<'r>, + defer_availability: bool, +} + +impl MutationContext<'_, '_> { + fn require_available(&self, instance: &InstanceId) -> PanelResult<()> { + if self.defer_availability { Ok(()) } else { available(self.availability, instance) } + } +} + fn apply( layout: &mut Layout, - registry: &PanelRegistry, - availability: &AvailabilityMap, - caps: &HostCapabilities, + context: &MutationContext<'_, '_>, interaction: &mut InteractionState, effects: &mut Vec, mutation: Mutation, ) -> PanelResult<()> { + let MutationContext { registry, availability, caps, reservations, defer_availability } = *context; match mutation { Mutation::Open { kind, instance, destination } => { valid_id(&instance.0)?; registry.get(&kind)?; - available(availability, &instance)?; + context.require_available(&instance)?; if let Ok(existing) = layout.instance(&instance) { if existing.kind != kind { return Err(error(Rule::DuplicateId, "instance belongs to another kind")); @@ -531,8 +1153,20 @@ fn apply( } let p = existing.clone(); let restore_collapsed = destination.is_none() && layout.section(&p.memory.section).is_err(); - let destination = destination.unwrap_or_else(|| reopen_destination(layout, &p)); - place(layout, &instance, destination)?; + let mut destination = destination.unwrap_or_else(|| reopen_destination(layout, &p)); + inherit_native_preference(&mut destination, p.memory.location.zone(), p.memory.preferred_extent, p.memory.extent_priority)?; + let created = !matches!(&destination, Destination::JoinTab { .. }); + place(layout, &instance, destination, reservations)?; + if created { + let section = layout.containing(&instance)?.id.clone(); + let section = section_mut(layout, §ion)?; + (section.preferred_extent, section.extent_priority) = inherited_extent_preference( + p.memory.location.zone(), + section.location.zone(), + p.memory.preferred_extent, + p.memory.extent_priority, + ); + } if let Some(entry) = layout.instances.iter_mut().find(|p| p.id == instance) { entry.requested_open = true; } @@ -541,7 +1175,7 @@ fn apply( } } else { let destination = destination.ok_or_else(|| error(Rule::Placement, "new instance requires explicit destination"))?; - place(layout, &instance, destination)?; + place(layout, &instance, destination, reservations)?; let s = layout.containing(&instance)?.clone(); layout.instances.push(PanelInstance { id: instance.clone(), @@ -554,6 +1188,12 @@ fn apply( tab_index: 0, size: s.size, collapsed: s.collapsed, + column: s.column, + column_index: 0, + column_width: None, + weight: s.weight, + preferred_extent: s.preferred_extent, + extent_priority: s.extent_priority, }, }); } @@ -577,33 +1217,66 @@ fn apply( } layout.instances.retain(|p| p.id != instance); } - Mutation::Move { instance, destination } => { + Mutation::Move { instance, mut destination } => { + context.require_available(&instance)?; if !layout.instance(&instance)?.requested_open { return Err(error(Rule::Placement, "cannot move a closed instance")); } let collapsed = layout.containing(&instance)?.collapsed; + let source = layout.containing(&instance)?.clone(); + if let Destination::NewSection { location: SectionLocation::Window { return_to, .. }, .. } = &mut destination + && source.location.zone() == return_to.zone + && source.location.zone().docked() + { + let column = source.column.as_ref().map(|id| layout.column(id)).transpose()?; + if return_to.column.is_none() { + return_to.column = source.column.clone(); + return_to.column_width = column.map(|c| c.width); + return_to.column_index = column + .map_or(0, |column| layout.columns.iter().filter(|c| c.zone == column.zone).position(|c| c.id == column.id).unwrap_or(0)); + return_to.weight = source.weight; + } + if return_to.section.is_none() { + return_to.section = Some(source.id.clone()); + } + if return_to.join.is_none() && source.tabs.len() > 1 { + return_to.join = + Some(ReturnTab { section: source.id.clone(), index: source.tabs.iter().position(|p| *p == instance).unwrap_or(0) }); + } + } + inherit_native_preference(&mut destination, source.location.zone(), source.preferred_extent, source.extent_priority)?; + if let Destination::Relative { section, .. } = &destination + && layout.section(section)?.tabs == [instance.clone()] + { + return Err(error(Rule::Placement, "relative destination cannot target its sole moving tab")); + } remember(layout, &instance)?; detach(layout, &instance); let new_section = match &destination { Destination::NewSection { section, .. } => Some(section.clone()), + Destination::Relative { new_section, .. } => Some(new_section.clone()), _ => None, }; - place(layout, &instance, destination)?; + place(layout, &instance, destination, reservations)?; if let Some(id) = new_section { - section_mut(layout, &id)?.collapsed = collapsed; + let section = section_mut(layout, &id)?; + section.collapsed = collapsed; + (section.preferred_extent, section.extent_priority) = + inherited_extent_preference(source.location.zone(), section.location.zone(), source.preferred_extent, source.extent_priority); } } Mutation::Activate { instance } => { - available(availability, &instance)?; + context.require_available(&instance)?; let section = layout.containing(&instance)?.id.clone(); section_mut(layout, §ion)?.active = instance; } Mutation::Focus { instance } => { - available(availability, &instance)?; + context.require_available(&instance)?; let p = layout.instance(&instance)?.clone(); if !p.requested_open { - let destination = reopen_destination(layout, &p); - place(layout, &instance, destination)?; + let mut destination = reopen_destination(layout, &p); + inherit_native_preference(&mut destination, p.memory.location.zone(), p.memory.preferred_extent, p.memory.extent_priority)?; + place(layout, &instance, destination, reservations)?; if let Some(entry) = layout.instances.iter_mut().find(|p| p.id == instance) { entry.requested_open = true; } @@ -617,7 +1290,7 @@ fn apply( effects.push(HostEffect::Focus { instance }); } Mutation::Peek { instance } => { - available(availability, &instance)?; + context.require_available(&instance)?; let s = layout.containing(&instance)?; if !s.collapsed { return Err(error(Rule::Placement, "peek requires a collapsed section")); @@ -634,7 +1307,83 @@ fn apply( } Mutation::SetSize { section, size } => { size.validate()?; - section_mut(layout, §ion)?.size = size; + let source = layout.section(§ion)?; + let zone = source.location.zone(); + let column = source.column.clone(); + let priority = if zone.docked() { Some(next_extent_priority(layout, zone, &column)?) } else { None }; + if let Some(column) = layout.section(§ion)?.column.clone() { + set_column_width(layout, registry, &column, size.width)?; + } + let target = section_mut(layout, §ion)?; + target.size = size; + if let Some(extent) = dock_stack_extent(target.location.zone(), size) { + target.preferred_extent = Some(extent); + target.extent_priority = priority.unwrap_or(0); + } + } + Mutation::SetColumnWidth { column, width } => { + set_column_width(layout, registry, &column, width)?; + } + Mutation::SetBottomHeight { section, height } => { + if layout.section(§ion)?.location.zone() != Zone::Bottom { + return Err(error(Rule::Placement, "row height requires a Bottom section")); + } + let (min, max) = bottom_height_bounds(layout, registry)?; + if !height.is_finite() || height <= 0.0 || height > MAX_LOGICAL || height < min || height > max { + return Err(error(Rule::Bounds, "Bottom height outside common row bounds")); + } + let members: BTreeSet<_> = + layout.sections.iter().filter(|s| s.location.zone() == Zone::Bottom).flat_map(|s| s.tabs.iter().cloned()).collect(); + for target in layout.sections.iter_mut().filter(|s| s.location.zone() == Zone::Bottom) { + target.size.height = height; + } + for panel in &mut layout.instances { + if members.contains(&panel.id) { + panel.memory.size.height = height; + } + } + // This orthogonal edit must not refresh divergent saved stack intent + // or prune unrelated retained columns through structural maintenance. + return Ok(()); + } + Mutation::HeaderAction { instance, action } => { + valid_id(&action.0)?; + context.require_available(&instance)?; + let panel = layout.instance(&instance)?; + let spec = registry.get(&panel.kind)?; + if !spec.header_actions.iter().any(|registered| registered.id == action) { + return Err(error(Rule::Capability, "header action is not registered for panel")); + } + if !panel.requested_open { + return Err(error(Rule::Availability, "header action requires an open presented tab")); + } + let section = layout.containing(&instance)?; + if !defer_availability && presented_tab(section, availability) != Some(&instance) { + return Err(error(Rule::Availability, "header action requires the presented available tab")); + } + effects.push(HostEffect::HeaderAction { instance, action }); + // Content-only dispatch deliberately bypasses catalogue staging. + // Preserve even divergent imported memories and retained columns. + return Ok(()); + } + Mutation::SetFloatingRect { section, origin, size } => { + valid_id(§ion.0)?; + LogicalRect { origin, size }.validate()?; + let source = layout.section(§ion)?; + if !matches!(&source.location, SectionLocation::Floating { .. }) { + return Err(error(Rule::Placement, "section rect requires an existing floating section")); + } + let (min, max) = tab_bounds(layout, registry, source)?; + if !size.within(min, max) { + return Err(error(Rule::Bounds, "floating rect outside intersected tab bounds")); + } + let members = source.tabs.clone(); + let target = section_mut(layout, §ion)?; + target.location = SectionLocation::Floating { origin }; + target.size = size; + for instance in members { + remember(layout, &instance)?; + } } Mutation::ResizePair { first, second, first_size, second_size } => { first_size.validate()?; @@ -649,8 +1398,84 @@ fn apply( { return Err(error(Rule::Bounds, "paired sash changes only split axis")); } + let total_weight = a.weight + b.weight; + let extent = sum(first_size, second_size); + let first_weight = total_weight * (if zone == Zone::Bottom { first_size.width } else { first_size.height }) / extent; section_mut(layout, &first)?.size = first_size; + section_mut(layout, &first)?.weight = first_weight; + section_mut(layout, &first)?.preferred_extent = None; + section_mut(layout, &first)?.extent_priority = 0; section_mut(layout, &second)?.size = second_size; + section_mut(layout, &second)?.weight = total_weight - first_weight; + section_mut(layout, &second)?.preferred_extent = None; + section_mut(layout, &second)?.extent_priority = 0; + } + Mutation::ResizeAllocatedPair { + first, + second, + first_size, + second_size, + first_weight, + second_weight, + other_weight_scale, + prefer_allocated, + } => { + first_size.validate()?; + second_size.validate()?; + for weight in [first_weight, second_weight] { + if !weight.is_finite() || !(0.0..=1.0).contains(&weight) { + return Err(error(Rule::Bounds, "allocated pair shares must be finite fractions")); + } + } + if !other_weight_scale.is_finite() || other_weight_scale <= 0.0 || other_weight_scale > MAX_LOGICAL { + return Err(error(Rule::Bounds, "unpaired weight scale must be finite positive bounded")); + } + let (a, b, zone) = presented_pair(layout, &first, &second, availability)?; + let (a_min, a_max) = tab_bounds(layout, registry, a)?; + let (b_min, b_max) = tab_bounds(layout, registry, b)?; + if !first_size.within(a_min, a_max) || !second_size.within(b_min, b_max) { + return Err(error(Rule::Bounds, "allocated pair outside composite tab bounds")); + } + let cross = |size: Size| if zone == Zone::Bottom { size.height } else { size.width }; + if (cross(first_size) - cross(second_size)).abs() > 0.01 { + return Err(error(Rule::Bounds, "allocated pair must retain a shared cross axis")); + } + if let Some(column) = &a.column { + let (min, max) = column_bounds(layout, registry, column)?; + if first_size.width < min || first_size.width > max { + return Err(error(Rule::Bounds, "allocated cross axis outside column bounds")); + } + } + let column = a.column.clone(); + let total = saved_group_total(layout, zone, &column)?; + let priority = if prefer_allocated { next_extent_priority(layout, zone, &column)? } else { 0 }; + let axis = |size: Size| if zone == Zone::Bottom { size.width } else { size.height }; + let authored_extents = prefer_allocated.then_some((axis(first_size), axis(second_size), priority)); + reweight_group( + layout, + zone, + &column, + total, + PairReweight { first: &first, second: &second, first_weight, second_weight, other_weight_scale, authored_extents }, + )?; + let target = section_mut(layout, &first)?; + if zone == Zone::Bottom { + target.size.width = first_size.width; + } else { + target.size.height = first_size.height; + } + target.weight = first_weight; + target.preferred_extent = prefer_allocated.then_some(axis(first_size)); + target.extent_priority = priority; + let target = section_mut(layout, &second)?; + if zone == Zone::Bottom { + target.size.width = second_size.width; + } else { + target.size.height = second_size.height; + } + target.weight = second_weight; + target.preferred_extent = prefer_allocated.then_some(axis(second_size)); + target.extent_priority = priority; } Mutation::ResetPair { first, second } => { let (a, b, zone) = pair(layout, &first, &second)?; @@ -669,6 +1494,7 @@ fn apply( let b_default = registry.get(&layout.instance(&b.active)?.kind)?.default_size; let preferred = extent * axis(a_default) / (axis(a_default) + axis(b_default)); let split = preferred.clamp(lo, hi); + let total_weight = a.weight + b.weight; if zone == Zone::Bottom { a_size.width = split; b_size.width = extent - split; @@ -677,7 +1503,13 @@ fn apply( b_size.height = extent - split; } section_mut(layout, &first)?.size = a_size; + section_mut(layout, &first)?.weight = total_weight * split / extent; + section_mut(layout, &first)?.preferred_extent = None; + section_mut(layout, &first)?.extent_priority = 0; section_mut(layout, &second)?.size = b_size; + section_mut(layout, &second)?.weight = total_weight * (extent - split) / extent; + section_mut(layout, &second)?.preferred_extent = None; + section_mut(layout, &second)?.extent_priority = 0; } Mutation::NativeClose { host } => { valid_id(&host.0)?; @@ -691,21 +1523,56 @@ fn apply( return Err(error(Rule::Placement, "not a native section")); }; if let Some(join) = &return_to.join - && let Some(target) = layout.sections.iter_mut().find(|s| s.id == join.section && s.location.zone() == return_to.zone) + && let Some(target) = layout.sections.iter_mut().find(|s| { + s.id == join.section + && s.location.zone() == return_to.zone + && return_to.column.as_ref().is_none_or(|column| s.column.as_ref() == Some(column)) + }) { if target.tabs.len().saturating_add(section.tabs.len()) > MAX_TABS { return Err(error(Rule::CollectionLimit, "native return tab capacity")); } let index = join.index.min(target.tabs.len()); drop(target.tabs.splice(index..index, section.tabs)); + let members = target.tabs.clone(); + for instance in members { + remember(layout, &instance)?; + } + prune_columns(layout); return Ok(()); } section.location = SectionLocation::Dock { zone: return_to.zone }; section.size = return_to.size; section.collapsed = return_to.collapsed; - layout.sections.insert(return_to.index.min(layout.sections.len()), section); + section.weight = return_to.weight; + section.preferred_extent = return_to.preferred_extent; + section.extent_priority = return_to.extent_priority; + section.column = if return_to.zone.side() { + let column = match return_to.column { + Some(column) => column, + None => next_column_id_with_reservations(layout, reservations.columns)?, + }; + Some(restore_column(layout, column, return_to.zone, return_to.column_index, return_to.column_width.unwrap_or(return_to.size.width))?) + } else { + None + }; + if let Some(id) = return_to.section { + section.id = if layout.section(&id).is_ok() { next_section_id_with_reservations(layout, reservations.sections)? } else { id }; + } + let index = match §ion.column { + Some(column) => column_insert_index(layout, column, return_to.index)?, + None => return_to.index.min(layout.sections.len()), + }; + layout.sections.insert(index, section); } } + // Every live member gets the same committed group geometry/proportions. + // Closed memories are intentionally independent until their panel reopens. + let members: Vec<_> = layout.sections.iter().flat_map(|s| s.tabs.iter().cloned()).collect(); + for instance in members { + remember(layout, &instance)?; + } + prune_columns(layout); let windows = native_hosts(layout); // Retained unsupported windows can be closed/redocked without native capability. if caps.native_windows && windows.len() > caps.max_native_hosts { @@ -714,6 +1581,251 @@ fn apply( Ok(()) } +fn prune_columns(layout: &mut Layout) { + let mut used = std::collections::BTreeSet::new(); + for column in layout.sections.iter().filter_map(|s| s.column.clone()).chain(layout.instances.iter().filter_map(|p| p.memory.column.clone())) { + used.insert(column); + } + 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.clone()); + } + } + layout.columns.retain(|column| used.contains(&column.id)); +} + +fn set_column_width(layout: &mut Layout, registry: &PanelRegistry, id: &ColumnId, width: f32) -> PanelResult<()> { + valid_id(&id.0)?; + let (min, max) = column_bounds(layout, registry, id)?; + if !width.is_finite() || width <= 0.0 || width < min || width > max { + return Err(error(Rule::Bounds, "column width outside composite stack bounds")); + } + let column = layout.columns.iter_mut().find(|c| c.id == *id).ok_or_else(|| error(Rule::MissingTarget, "column absent"))?; + column.width = width; + for section in layout.sections.iter_mut().filter(|s| s.column.as_ref() == Some(id)) { + section.size.width = width; + } + Ok(()) +} + +/// Comparison tolerance for callers inspecting normalized saved weights. +pub const WEIGHT_SHARE_TOLERANCE: f32 = 0.00001; + +fn same_group(zone: Zone, column: &Option, location: &SectionLocation, other: &Option) -> bool { + zone.docked() && location.zone() == zone && (zone == Zone::Bottom || (column.is_some() && column == other)) +} + +/// Assign an authored tier only within the bounded private proposed layout. +/// Validate every matching record before compaction can write any rank. +fn next_extent_priority(layout: &mut Layout, zone: Zone, column: &Option) -> PanelResult { + if !zone.docked() || (zone.side() && column.is_none()) { + return Err(error(Rule::Placement, "extent priority requires one dock group")); + } + if layout.sections.len() > MAX_SECTIONS || layout.instances.len() > MAX_INSTANCES { + return Err(error(Rule::CollectionLimit, "extent priority group cap")); + } + let mut ranks = BTreeSet::new(); + let mut collect = |extent: Option, priority: u16| -> PanelResult<()> { + validate_extent_priority(extent, priority)?; + if priority > 0 { + ranks.insert(priority); + } + Ok(()) + }; + for section in &layout.sections { + collect(section.preferred_extent, section.extent_priority)?; + } + for panel in &layout.instances { + let memory = &panel.memory; + collect(memory.preferred_extent, memory.extent_priority)?; + } + 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 { + collect(return_to.preferred_extent, return_to.extent_priority)?; + } + } + for record in &layout.extent_priority_context.records { + if record.priority > 0 { + ranks.insert(record.priority); + } + } + let highest = ranks.last().copied().unwrap_or(0); + if let Some(next) = highest.checked_add(1) { + return Ok(next); + } + let next = u16::try_from(ranks.len()) + .ok() + .and_then(|rank| rank.checked_add(1)) + .ok_or_else(|| error(Rule::CollectionLimit, "extent priority tiers exhausted"))?; + let mut compact = std::collections::BTreeMap::new(); + let mut ordinal = 0_u16; + for rank in ranks { + ordinal = ordinal.checked_add(1).ok_or_else(|| error(Rule::CollectionLimit, "extent priority compaction exhausted"))?; + compact.insert(rank, ordinal); + } + for section in &mut layout.sections { + section.extent_priority = compact.get(§ion.extent_priority).copied().unwrap_or(section.extent_priority); + } + for panel in &mut layout.instances { + let memory = &mut panel.memory; + memory.extent_priority = compact.get(&memory.extent_priority).copied().unwrap_or(memory.extent_priority); + } + for location in layout.sections.iter_mut().map(|s| &mut s.location).chain(layout.instances.iter_mut().map(|p| &mut p.memory.location)) { + if let SectionLocation::Window { return_to, .. } = location { + return_to.extent_priority = compact.get(&return_to.extent_priority).copied().unwrap_or(return_to.extent_priority); + } + } + for record in &mut layout.extent_priority_context.records { + record.priority = compact.get(&record.priority).copied().unwrap_or(record.priority); + } + Ok(next) +} + +fn saved_group_total(layout: &Layout, zone: Zone, column: &Option) -> PanelResult { + if layout.sections.len() > MAX_SECTIONS || layout.instances.len() > MAX_INSTANCES { + return Err(error(Rule::CollectionLimit, "saved resize group cap")); + } + let mut members = std::collections::BTreeMap::new(); + for section in &layout.sections { + if same_group(zone, column, §ion.location, §ion.column) { + validate_weight(section.weight)?; + members.insert(section.id.clone(), section.weight); + } + } + for instance in &layout.instances { + let memory = &instance.memory; + if same_group(zone, column, &memory.location, &memory.column) { + validate_weight(memory.weight)?; + members.entry(memory.section.clone()).and_modify(|weight| *weight = (*weight).max(memory.weight)).or_insert(memory.weight); + } + } + for (location, fallback) in + layout.sections.iter().map(|s| (&s.location, &s.id)).chain(layout.instances.iter().map(|p| (&p.memory.location, &p.memory.section))) + { + if let SectionLocation::Window { return_to, .. } = location + && return_to.zone == zone + && (zone == Zone::Bottom || &return_to.column == column) + { + validate_weight(return_to.weight)?; + let section = return_to.join.as_ref().map(|join| &join.section).or(return_to.section.as_ref()).unwrap_or(fallback); + members.entry(section.clone()).and_modify(|weight| *weight = (*weight).max(return_to.weight)).or_insert(return_to.weight); + } + } + let total: f64 = members.values().map(|weight| f64::from(*weight)).sum(); + if !total.is_finite() || total <= 0.0 { + return Err(error(Rule::Bounds, "resize group must have positive total saved weight")); + } + Ok(total) +} + +/// Pure shares for host inversion of actual minimum-first allocation. Closed, +/// collapsed and unavailable members retain the same normalization factor. +pub fn normalized_pair_weights(layout: &Layout, first: &SectionId, second: &SectionId) -> PanelResult<(f32, f32)> { + valid_id(&first.0)?; + valid_id(&second.0)?; + if layout.sections.len() > MAX_SECTIONS || layout.instances.len() > MAX_INSTANCES { + return Err(error(Rule::CollectionLimit, "saved resize group cap")); + } + let (a, b, zone) = expanded_group_pair(layout, first, second)?; + let total = saved_group_total(layout, zone, &a.column)?; + Ok(((f64::from(a.weight) / total) as f32, (f64::from(b.weight) / total) as f32)) +} + +struct PairReweight<'a> { + first: &'a SectionId, + second: &'a SectionId, + first_weight: f32, + second_weight: f32, + other_weight_scale: f32, + authored_extents: Option<(f32, f32, u16)>, +} + +fn reweight_group(layout: &mut Layout, zone: Zone, column: &Option, total: f64, plan: PairReweight<'_>) -> PanelResult<()> { + let PairReweight { first, second, first_weight, second_weight, other_weight_scale, authored_extents } = plan; + let fraction = |id: &SectionId, weight: f32| { + if id == first { + first_weight + } else if id == second { + second_weight + } else { + (f64::from(weight) / total * f64::from(other_weight_scale)) as f32 + } + }; + let preference = |id: &SectionId, extent: &mut Option, priority: &mut u16| { + if id == first || id == second { + *extent = authored_extents.map(|(a, b, _)| if id == first { a } else { b }); + *priority = authored_extents.map_or(0, |(_, _, priority)| priority); + } + }; + for section in &mut layout.sections { + if same_group(zone, column, §ion.location, §ion.column) { + section.weight = fraction(§ion.id, section.weight); + preference(§ion.id, &mut section.preferred_extent, &mut section.extent_priority); + } + } + for instance in &mut layout.instances { + let memory = &mut instance.memory; + if same_group(zone, column, &memory.location, &memory.column) { + memory.weight = fraction(&memory.section, memory.weight); + preference(&memory.section, &mut memory.preferred_extent, &mut memory.extent_priority); + } + } + for (location, fallback) in layout + .sections + .iter_mut() + .map(|s| (&mut s.location, &s.id)) + .chain(layout.instances.iter_mut().map(|p| (&mut p.memory.location, &p.memory.section))) + { + if let SectionLocation::Window { return_to, .. } = location + && return_to.zone == zone + && (zone == Zone::Bottom || &return_to.column == column) + { + let id = return_to.join.as_ref().map(|join| &join.section).or(return_to.section.as_ref()).unwrap_or(fallback); + return_to.weight = fraction(id, return_to.weight); + preference(id, &mut return_to.preferred_extent, &mut return_to.extent_priority); + } + } + let new_total = saved_group_total(layout, zone, column)?; + if new_total > f64::from(MAX_LOGICAL) { + return Err(error(Rule::Bounds, "reweighted group total exceeds bound")); + } + Ok(()) +} + +fn expanded_group_pair<'a>(layout: &'a Layout, first: &SectionId, second: &SectionId) -> PanelResult<(&'a Section, &'a Section, Zone)> { + if first == second { + return Err(error(Rule::Placement, "sash requires distinct sections")); + } + let a = layout.section(first)?; + let b = layout.section(second)?; + let zone = a.location.zone(); + if !same_group(zone, &a.column, &b.location, &b.column) || a.collapsed || b.collapsed { + return Err(error(Rule::Placement, "sash requires expanded sections in one dock group")); + } + Ok((a, b, zone)) +} + +fn presented_pair<'a>( + layout: &'a Layout, + first: &SectionId, + second: &SectionId, + availability: &AvailabilityMap, +) -> PanelResult<(&'a Section, &'a Section, Zone)> { + let (a, b, zone) = expanded_group_pair(layout, first, second)?; + let mut previous = None; + for section in &layout.sections { + if same_group(zone, &a.column, §ion.location, §ion.column) && presented_tab(section, availability).is_some() { + if previous == Some(first) && section.id == *second { + return Ok((a, b, zone)); + } + previous = Some(§ion.id); + } + } + Err(error(Rule::Placement, "allocated sash requires ordered presented neighbours")) +} + fn pair<'a>(layout: &'a Layout, first: &SectionId, second: &SectionId) -> PanelResult<(&'a Section, &'a Section, Zone)> { if first == second { return Err(error(Rule::Placement, "sash requires two distinct neighbours")); @@ -721,9 +1833,13 @@ fn pair<'a>(layout: &'a Layout, first: &SectionId, second: &SectionId) -> PanelR let a = layout.section(first)?; let b = layout.section(second)?; let zone = a.location.zone(); - let edge: Vec<_> = layout.sections.iter().filter(|s| s.location.zone() == zone).collect(); + let edge: Vec<_> = layout.sections.iter().filter(|s| s.location.zone() == zone && s.column == a.column).collect(); if !zone.docked() + || (zone.side() && a.column.is_none()) || b.location.zone() != zone + || a.column != b.column + || a.collapsed + || b.collapsed || !edge.windows(2).any(|p| p.first().is_some_and(|s| s.id == *first) && p.get(1).is_some_and(|s| s.id == *second)) { return Err(error(Rule::Placement, "sash requires ordered neighbours in one dock")); diff --git a/crates/engine/src/panels/tests.rs b/crates/engine/src/panels/tests.rs index 2db660b99..3f42199e8 100644 --- a/crates/engine/src/panels/tests.rs +++ b/crates/engine/src/panels/tests.rs @@ -265,6 +265,226 @@ fn unavailable_requests_fail_but_saved_open_layout_stays_dormant() { assert_eq!(resolve_geometry(&service, rect(1000.0, 800.0), Direction::Ltr, 48.0).unwrap().panels.len(), 1); } +fn floating_group_service() -> LayoutService { + let mut service = fixture_service(false).unwrap(); + service + .dispatch(transaction(vec![ + fixture_open("fixture.log", "one", "floating-group", Zone::Floating, 0).unwrap(), + Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("two"), + destination: Some(Destination::JoinTab { section: section("floating-group"), index: 1 }), + }, + Mutation::Activate { instance: id("two") }, + ])) + .unwrap(); + service +} + +#[test] +fn floating_rect_prepares_atomically_preserving_group_focus_peek_and_other_sections() { + let mut service = floating_group_service(); + open(&mut service, "three", "other-section"); + open(&mut service, "four", "peek-section"); + service + .dispatch(transaction(vec![ + Mutation::Focus { instance: id("two") }, + Mutation::Collapse { section: section("peek-section"), collapsed: true }, + Mutation::Peek { instance: id("four") }, + ])) + .unwrap(); + let before = service.inspect(); + let origin = Point { x: 520.0, y: 0.0 }; + let dimensions = size(250.0, 240.0); + let action = LayoutAction::Apply { + expected_revision: Some(before.revision), + mutations: vec![Mutation::SetFloatingRect { section: section("floating-group"), origin, size: dimensions }], + }; + assert_eq!(decode_action(&serde_json::to_vec(&action).unwrap()).unwrap(), action); + let prepared = service.prepare(action.clone()).unwrap(); + assert_eq!(service.inspect(), before, "preparing a rect has no saved or interaction effects"); + assert!(prepared.effects().is_empty()); + let reply = service.commit(prepared).unwrap(); + assert_eq!(reply.revision, before.revision + 1); + assert!(reply.effects.is_empty()); + assert_eq!(reply.interaction, before.interaction); + let group = reply.layout.section(§ion("floating-group")).unwrap(); + assert_eq!(group.id, section("floating-group")); + assert_eq!(group.tabs, vec![id("one"), id("two")]); + assert_eq!(group.active, id("two")); + assert_eq!(group.location, SectionLocation::Floating { origin }); + assert_eq!(group.size, dimensions); + assert!(!group.collapsed); + assert_eq!(reply.layout.sections.len(), before.layout.sections.len()); + assert_eq!(reply.layout.instances.len(), before.layout.instances.len()); + for (index, instance) in [id("one"), id("two")].iter().enumerate() { + let memory = &reply.layout.instance(instance).unwrap().memory; + assert_eq!(memory.section, group.id); + assert_eq!(memory.location, group.location); + assert_eq!(memory.size, dimensions); + assert_eq!(memory.section_index, 0); + assert_eq!(memory.tab_index, index); + assert!(!memory.collapsed); + } + for name in ["other-section", "peek-section"] { + assert_eq!(reply.layout.section(§ion(name)).unwrap(), before.layout.section(§ion(name)).unwrap()); + } + for name in ["three", "four"] { + assert_eq!(reply.layout.instance(&id(name)).unwrap(), before.layout.instance(&id(name)).unwrap()); + } + assert_eq!(service.dispatch(action).unwrap_err().rule, Rule::Revision); + assert_eq!(service.inspect().revision, reply.revision); + service + .dispatch(transaction(vec![ + Mutation::Collapse { section: section("floating-group"), collapsed: true }, + Mutation::Peek { instance: id("two") }, + ])) + .unwrap(); + let peek = service.interaction().clone(); + let reply = service + .dispatch(transaction(vec![Mutation::SetFloatingRect { + section: section("floating-group"), + origin: Point { x: 521.0, y: 0.0 }, + size: dimensions, + }])) + .unwrap(); + assert_eq!(reply.interaction, peek); + assert!(reply.effects.is_empty()); + assert!(reply.layout.section(§ion("floating-group")).unwrap().collapsed); + assert!(reply.layout.instance(&id("one")).unwrap().memory.collapsed); + assert!(reply.layout.instance(&id("two")).unwrap().memory.collapsed); + validate(service.layout(), service.registry()).unwrap(); +} + +#[test] +fn floating_rect_enforces_group_intersection_hostile_numbers_and_atomic_failure() { + let mut registry = synthetic_registry().unwrap(); + let mut narrow = registry.get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + narrow.kind = PanelKind::new("fixture.rect-bounds").unwrap(); + narrow.min_size = size(200.0, 180.0); + narrow.max_size = size(300.0, 260.0); + registry.register(narrow).unwrap(); + let mut service = + LayoutService::new(registry, Layout::empty(WorkspaceId::new("fixture.workspace").unwrap()), HostCapabilities::default()).unwrap(); + service + .dispatch(transaction(vec![ + fixture_open("fixture.log", "one", "floating-group", Zone::Floating, 0).unwrap(), + Mutation::Open { + kind: PanelKind::new("fixture.rect-bounds").unwrap(), + instance: id("two"), + destination: Some(Destination::JoinTab { section: section("floating-group"), index: 1 }), + }, + ])) + .unwrap(); + let origin = Point { x: 520.0, y: 0.0 }; + service.dispatch(transaction(vec![Mutation::SetFloatingRect { section: section("floating-group"), origin, size: size(250.0, 220.0) }])).unwrap(); + for dimensions in [size(199.0, 220.0), size(301.0, 220.0), size(250.0, 179.0), size(250.0, 261.0)] { + reject(&mut service, vec![Mutation::SetFloatingRect { section: section("floating-group"), origin, size: dimensions }], Rule::Bounds); + } + for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, MAX_LOGICAL + 1.0, -MAX_LOGICAL - 1.0] { + for hostile_origin in [Point { x: bad, y: 0.0 }, Point { x: 0.0, y: bad }] { + reject( + &mut service, + vec![Mutation::SetFloatingRect { section: section("floating-group"), origin: hostile_origin, size: size(250.0, 220.0) }], + Rule::Bounds, + ); + } + } + for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -1.0, 0.0, MAX_LOGICAL + 1.0] { + for dimensions in [size(bad, 220.0), size(250.0, bad)] { + reject(&mut service, vec![Mutation::SetFloatingRect { section: section("floating-group"), origin, size: dimensions }], Rule::Bounds); + } + } + reject( + &mut service, + vec![Mutation::SetFloatingRect { section: section("floating-group"), origin: Point { x: MAX_LOGICAL, y: 0.0 }, size: size(250.0, 220.0) }], + Rule::Bounds, + ); + reject(&mut service, vec![Mutation::SetFloatingRect { section: SectionId("UPPER".into()), origin, size: size(250.0, 220.0) }], Rule::Id); + reject(&mut service, vec![Mutation::SetFloatingRect { section: section("missing"), origin, size: size(250.0, 220.0) }], Rule::MissingTarget); + reject( + &mut service, + vec![ + Mutation::SetFloatingRect { section: section("floating-group"), origin: Point { x: 10.0, y: 20.0 }, size: size(260.0, 230.0) }, + Mutation::SetSize { section: section("floating-group"), size: size(301.0, 230.0) }, + ], + Rule::Bounds, + ); + for boundary in [Point { x: MAX_LOGICAL - 250.0, y: MAX_LOGICAL - 220.0 }, Point { x: -MAX_LOGICAL, y: -MAX_LOGICAL }] { + service + .dispatch(transaction(vec![Mutation::SetFloatingRect { section: section("floating-group"), origin: boundary, size: size(250.0, 220.0) }])) + .unwrap(); + assert_eq!(service.layout().section(§ion("floating-group")).unwrap().location, SectionLocation::Floating { origin: boundary }); + validate(service.layout(), service.registry()).unwrap(); + } +} + +#[test] +fn floating_rect_cannot_reparent_a_dock_or_bypass_native_close() { + let mut service = fixture_service(true).unwrap(); + open(&mut service, "one", "docked"); + open(&mut service, "two", "native"); + let host = HostId::new("rect-native-host").unwrap(); + service + .dispatch(transaction(vec![Mutation::Move { + instance: id("two"), + destination: Destination::NewSection { + section: section("native"), + index: 1, + location: SectionLocation::Window { + host: host.clone(), + origin: Point { x: 0.0, y: 0.0 }, + return_to: DockReturn { + zone: Zone::Left, + index: 1, + size: size(280.0, 240.0), + collapsed: false, + join: None, + section: None, + column: None, + column_index: 0, + column_width: None, + weight: 1.0, + preferred_extent: None, + extent_priority: 0, + }, + }, + size: size(280.0, 240.0), + }, + }])) + .unwrap(); + for target in ["docked", "native"] { + reject( + &mut service, + vec![Mutation::SetFloatingRect { section: section(target), origin: Point { x: 20.0, y: 30.0 }, size: size(250.0, 220.0) }], + Rule::Placement, + ); + } + assert!( + matches!(&service.layout().section(§ion("native")).unwrap().location, SectionLocation::Window { host: actual, .. } if *actual == host) + ); +} + +#[test] +fn floating_rect_updates_each_tab_reopen_memory_without_section_identity_churn() { + let mut service = floating_group_service(); + let origin = Point { x: 520.0, y: 0.0 }; + service.dispatch(transaction(vec![Mutation::SetFloatingRect { section: section("floating-group"), origin, size: size(250.0, 240.0) }])).unwrap(); + service.dispatch(transaction(vec![Mutation::Close { instance: id("one") }, Mutation::Close { instance: id("two") }])).unwrap(); + assert!(service.layout().sections.is_empty()); + for name in ["two", "one"] { + service + .dispatch(transaction(vec![Mutation::Open { kind: PanelKind::new("fixture.log").unwrap(), instance: id(name), destination: None }])) + .unwrap(); + } + let group = service.layout().section(§ion("floating-group")).unwrap(); + assert_eq!(group.tabs, vec![id("one"), id("two")]); + assert_eq!(group.active, id("two")); + assert_eq!(group.location, SectionLocation::Floating { origin }); + assert_eq!(group.size, size(250.0, 240.0)); + validate(service.layout(), service.registry()).unwrap(); +} + #[test] fn closed_state_reopens_with_placement_size_and_collapse_memory() { let mut service = fixture_service(false).unwrap(); @@ -295,10 +515,15 @@ fn peek_never_rewrites_saved_collapse_or_sizes_and_focus_restores_content() { let layout = service.layout().clone(); service.dispatch(transaction(vec![Mutation::Peek { instance: id("one") }])).unwrap(); assert_eq!(*service.layout(), layout); - assert_eq!(resolve_geometry(&service, rect(1000.0, 800.0), Direction::Ltr, 48.0).unwrap().panels.len(), 1); + let peek = resolve_geometry(&service, rect(1000.0, 800.0), Direction::Ltr, 48.0).unwrap(); + let header = peek.panels.first().unwrap(); + assert_eq!(header.outer.size, size(280.0, 24.0)); + assert!(header.body.is_none()); service.dispatch(transaction(vec![Mutation::DismissPeek])).unwrap(); - assert!(resolve_geometry(&service, rect(1000.0, 800.0), Direction::Ltr, 48.0).unwrap().panels.is_empty()); + assert_eq!(resolve_geometry(&service, rect(1000.0, 800.0), Direction::Ltr, 48.0).unwrap(), peek); + assert_eq!(*service.layout(), layout); service.dispatch(transaction(vec![Mutation::Focus { instance: id("one") }])).unwrap(); + assert!(resolve_geometry(&service, rect(1000.0, 800.0), Direction::Ltr, 48.0).unwrap().panels[0].body.is_some()); service.dispatch(transaction(vec![Mutation::Close { instance: id("one") }])).unwrap(); assert!(service.interaction().focused.is_none()); } @@ -309,21 +534,32 @@ fn overflow_is_transient_and_never_squeezes_or_rewrites_desired_dimensions() { open(&mut service, "one", "first"); let before = service.inspect(); let small = resolve_geometry(&service, rect(80.0, 80.0), Direction::Ltr, 48.0).unwrap(); - assert!(small.panels.is_empty()); - assert_eq!(small.unpresented.first().unwrap().reason, UnpresentedReason::MinimumOverflow); + let card = small.panels.first().unwrap(); + assert!(card.outer.size.width >= 160.0 && card.outer.size.height >= 120.0); + assert!(card.painted.iter().all(|painted| rect(80.0, 80.0).contains_rect(*painted))); + assert!(small.unpresented.is_empty()); + let mut env = allocated_pair_environment(&service, 80.0); + env.capacity = rect(80.0, 80.0); + env.scroll = Point { x: MAX_LOGICAL, y: MAX_LOGICAL }; + for request in allocation_measure_requests(service.layout(), service.registry(), &env).unwrap() { + env.content.push(SideContentMeasure { request, needed_height: 240.0, policy: SideHeightPolicy::Content }); + } + let scrolled = allocate_layout(service.layout(), service.registry(), &env).unwrap(); + assert_eq!(scrolled.scroll.x, (scrolled.extent.width - 80.0).max(0.0)); + assert_eq!(scrolled.scroll.y, (scrolled.extent.height - 80.0).max(0.0)); let large = resolve_geometry(&service, rect(1000.0, 800.0), Direction::Ltr, 48.0).unwrap(); assert_eq!(large.panels.first().unwrap().outer.size, size(280.0, 240.0)); assert_eq!(service.inspect(), before); } #[test] -fn logical_rtl_flow_hysteresis_and_size_classes_use_usable_units() { +fn logical_rtl_flow_aspect_and_size_classes_use_usable_units() { assert_eq!(Direction::Rtl.edge(Zone::Left).unwrap(), PhysicalEdge::Right); for (width, expected) in [(239.0, SizeClass::Compact), (240.0, SizeClass::Regular), (480.0, SizeClass::Regular), (481.0, SizeClass::Wide)] { assert_eq!(responsive(Zone::Floating, size(width, 600.0), None).unwrap().1, expected); } - assert_eq!(responsive(Zone::Floating, size(105.0, 100.0), Some(Flow::Tall)).unwrap().0, Flow::Tall); - assert_eq!(responsive(Zone::Window, size(95.0, 100.0), Some(Flow::Wide)).unwrap().0, Flow::Wide); + assert_eq!(responsive(Zone::Floating, size(105.0, 100.0), Some(Flow::Tall)).unwrap().0, Flow::Wide); + assert_eq!(responsive(Zone::Window, size(95.0, 100.0), Some(Flow::Wide)).unwrap().0, Flow::Tall); assert_eq!(responsive(Zone::Window, size(89.0, 100.0), Some(Flow::Wide)).unwrap().0, Flow::Tall); assert_eq!(responsive(Zone::Bottom, size(100.0, 400.0), None).unwrap().0, Flow::Wide); } @@ -349,7 +585,20 @@ fn native_capabilities_and_close_redock_are_atomic() { location: SectionLocation::Window { host: HostId::new("native-host").unwrap(), origin: Point { x: 0.0, y: 0.0 }, - return_to: DockReturn { zone: Zone::Left, index: 0, size: size(280.0, 240.0), collapsed: false, join: None }, + return_to: DockReturn { + zone: Zone::Left, + index: 0, + size: size(280.0, 240.0), + collapsed: false, + join: None, + section: None, + column: None, + column_index: 0, + column_width: None, + weight: 1.0, + preferred_extent: None, + extent_priority: 0, + }, }, size: size(300.0, 250.0), }; @@ -526,6 +775,10 @@ fn versioned_fixture_and_action_schema_are_consumable_without_a_ui() { let service = fixture_service(false).unwrap(); let loaded = decode(FIXTURE_LAYOUT_V1, service.registry(), service.layout()).unwrap(); assert!(loaded.notice.is_none()); + assert_eq!(loaded.envelope.version, 2); + assert_eq!(loaded.envelope.layout.version, 2); + assert_eq!(loaded.envelope.layout.columns.len(), 1); + assert_eq!(loaded.envelope.layout.sections[0].weight, 240.0); assert_eq!(loaded.envelope.layout.instances.len(), 1); let mut live = LayoutService::new(service.registry().clone(), loaded.envelope.layout, HostCapabilities::default()).unwrap(); let action = decode_action(br#"{"type":"apply","expected_revision":0,"mutations":[{"type":"focus","instance":"editor"}]}"#).unwrap(); @@ -632,6 +885,13 @@ fn native_close_returns_to_a_stable_tab_group_without_stealing_activation() { size: size(280.0, 240.0), collapsed: false, join: Some(ReturnTab { section: section("first"), index: 1 }), + section: None, + column: None, + column_index: 0, + column_width: None, + weight: 1.0, + preferred_extent: None, + extent_priority: 0, }, }, size: size(280.0, 240.0), @@ -864,8 +1124,22 @@ fn complete_layout_wire_contract_checks_native_capacity_and_destroyed_identity_r native.sections.first_mut().unwrap().location = SectionLocation::Window { host: HostId::new("native").unwrap(), origin: Point { x: 0.0, y: 0.0 }, - return_to: DockReturn { zone: Zone::Left, index: 0, size: size(280.0, 240.0), collapsed: false, join: None }, + return_to: DockReturn { + zone: Zone::Left, + index: 0, + size: size(280.0, 240.0), + collapsed: false, + join: None, + section: None, + column: None, + column_index: 0, + column_width: None, + weight: 1.0, + preferred_extent: None, + extent_priority: 0, + }, }; + native.sections.first_mut().unwrap().column = None; let before = service.inspect(); assert_eq!(service.dispatch(LayoutAction::Replace { expected_revision: None, layout: native }).unwrap_err().rule, Rule::Capability); assert_eq!(service.inspect(), before); @@ -969,6 +1243,7 @@ fn command_inputs() -> Vec<(&'static str, serde_json::Value)> { ("layout.reset", json!({})), ("layout.save", json!({"name":"Saved"})), ("layout.workspace.select", json!({"workspace":"fixture.other"})), + ("panel.action", json!({"target":command_target("one"),"action":"refresh"})), ("panel.activate", selected.clone()), ("panel.close", selected.clone()), ("panel.collapse", json!({"target":command_target("one"),"collapsed":true})), @@ -1021,7 +1296,7 @@ fn every_panel_command_has_strict_input_output_contracts_and_hostile_field_rejec assert_eq!(backend.service.inspect(), before, "{id}"); assert_eq!(backend.catalogue.state(), &catalogue, "{id}"); } - for field in ["id", "instance", "kind", "first", "second", "workspace"] { + for field in ["action", "id", "instance", "kind", "first", "second", "workspace"] { if input.get(field).is_some() { let mut hostile = input.clone(); hostile[field] = serde_json::json!("UPPER/invalid"); @@ -1042,6 +1317,10 @@ fn panel_command_success_replies_describe_committed_state_for_every_executable_o backend.execute("panel.collapse", &serde_json::json!({"target":command_target("one"),"collapsed":true})).unwrap(); } let result = backend.execute(id, &input); + if id == "panel.action" { + assert_eq!(result.unwrap_err().rule, Rule::Capability, "headless cannot invoke an unbound controller"); + continue; + } if matches!(id, "panel.popout" | "panel.native_close") { assert!(result.is_err(), "{id}"); continue; @@ -1093,6 +1372,296 @@ fn panel_commands_reject_nested_unknowns_sizes_indices_and_nonfinite_values_befo } } +#[test] +fn thickness_only_bottom_command_matches_pointer_mutation_and_preserves_saved_width_intent() { + use commands::LayoutCatalogue; + use serde_json::json; + for selector in [json!({"target":{"type":"section","id":"first"}}), json!({"target":command_target("one")}), json!({"id":"one"})] { + let mut registry = synthetic_registry().unwrap(); + let mut constrained = registry.get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + constrained.kind = PanelKind::new("fixture.short-height").unwrap(); + constrained.min_size.height = 140.0; + constrained.max_size.height = 300.0; + registry.register(constrained).unwrap(); + let mut service = + LayoutService::new(registry.clone(), Layout::empty(WorkspaceId::new("fixture.workspace").unwrap()), HostCapabilities::default()).unwrap(); + service + .dispatch(transaction(vec![ + fixture_open("fixture.log", "one", "first", Zone::Bottom, 0).unwrap(), + fixture_open("fixture.log", "two", "second", Zone::Bottom, 1).unwrap(), + Mutation::Open { + kind: PanelKind::new("fixture.short-height").unwrap(), + instance: id("inactive"), + destination: Some(Destination::JoinTab { section: section("first"), index: 1 }), + }, + Mutation::SetSize { section: section("first"), size: size(320.0, 240.0) }, + Mutation::SetSize { section: section("second"), size: size(450.0, 500.0) }, + ])) + .unwrap(); + let mut imported = service.layout().clone(); + let memory = &mut imported.instances.iter_mut().find(|p| p.id == id("one")).unwrap().memory; + memory.size.width = 800.0; + memory.preferred_extent = Some(600.0); + memory.extent_priority = 77; + memory.weight = 3.0; + let service = LayoutService::new(registry.clone(), imported.clone(), HostCapabilities::default()).unwrap(); + let expected = service.prepare(transaction(vec![Mutation::SetBottomHeight { section: section("first"), height: 180.0 }])).unwrap(); + let mut backend = commands::InMemoryPanelBackend::new(service, fixture_command_catalogue(®istry).unwrap()); + let mut params = selector; + // The valid ignored width is outside every panel's width bounds. + params["size"] = json!({"width":1,"height":180}); + params["thickness_only"] = json!(true); + backend.execute("panel.resize", ¶ms).unwrap(); + assert_eq!(backend.service.layout(), expected.layout()); + for (old, new) in imported.sections.iter().zip(&backend.service.layout().sections) { + let mut expected = old.clone(); + expected.size.height = 180.0; + assert_eq!(new, &expected, "row thickness preserves section width preference, tier and weight"); + } + for (old, new) in imported.instances.iter().zip(&backend.service.layout().instances) { + let mut expected = old.clone(); + expected.memory.size.height = 180.0; + assert_eq!(new, &expected, "inactive and divergent live memories retain width intent"); + } + let stored = backend.catalogue.state().remembered(&imported.workspace).unwrap().project_envelope(®istry, &imported.workspace).unwrap(); + assert_eq!(stored.layout.instances, backend.service.layout().instances); + assert_eq!(stored.layout.sections, backend.service.layout().sections); + let before = backend.service.inspect(); + let catalogue = backend.catalogue.state().clone(); + params["size"]["height"] = json!(301); + assert_eq!(backend.execute("panel.resize", ¶ms).unwrap_err().rule, Rule::Bounds, "inactive tab limits the common row"); + assert_eq!(backend.service.inspect(), before); + assert_eq!(backend.catalogue.state(), &catalogue); + } +} + +#[test] +fn thickness_only_side_command_resolves_columns_sections_instances_and_legacy_selectors() { + use serde_json::json; + for zone in [Zone::Left, Zone::Right] { + for selector in ["column", "section", "instance", "legacy"] { + let mut service = fixture_service(false).unwrap(); + service + .dispatch(transaction(vec![ + fixture_open("fixture.log", "one", "first", zone, 0).unwrap(), + fixture_open("fixture.log", "two", "second", zone, 1).unwrap(), + Mutation::SetSize { section: section("first"), size: size(280.0, 300.0) }, + Mutation::SetSize { section: section("second"), size: size(280.0, 500.0) }, + ])) + .unwrap(); + let before = service.layout().clone(); + let column = before.section(§ion("first")).unwrap().column.clone().unwrap(); + assert_eq!(before.section(§ion("second")).unwrap().column, Some(column.clone())); + let expected = service.prepare(transaction(vec![Mutation::SetColumnWidth { column: column.clone(), width: 360.0 }])).unwrap(); + let catalogue = fixture_command_catalogue(service.registry()).unwrap(); + let mut backend = commands::InMemoryPanelBackend::new(service, catalogue); + let mut params = match selector { + "column" => json!({"target":{"type":"column","id":column}}), + "section" => json!({"target":{"type":"section","id":"first"}}), + "instance" => json!({"target":command_target("one")}), + _ => json!({"id":"one"}), + }; + params["size"] = json!({"width":360,"height":1}); + params["thickness_only"] = json!(true); + backend.execute("panel.resize", ¶ms).unwrap(); + assert_eq!(backend.service.layout(), expected.layout()); + for (old, new) in before.sections.iter().zip(&backend.service.layout().sections) { + let mut expected = old.clone(); + expected.size.width = 360.0; + assert_eq!(new, &expected, "side thickness must not author a height preference or tier"); + } + for (old, new) in before.instances.iter().zip(&backend.service.layout().instances) { + let mut expected = old.clone(); + expected.memory.size.width = 360.0; + expected.memory.column_width = Some(360.0); + assert_eq!(new, &expected); + } + } + } +} + +#[test] +fn resize_omission_and_false_keep_full_size_behavior_in_dock_and_floating_hosts() { + use serde_json::json; + for zone in [Zone::Left, Zone::Bottom, Zone::Floating] { + for flag in [None, Some(false)] { + let mut service = fixture_service(false).unwrap(); + service.dispatch(transaction(vec![fixture_open("fixture.log", "one", "first", zone, 0).unwrap()])).unwrap(); + let expected = service.prepare(transaction(vec![Mutation::SetSize { section: section("first"), size: size(360.0, 320.0) }])).unwrap(); + let catalogue = fixture_command_catalogue(service.registry()).unwrap(); + let mut backend = commands::InMemoryPanelBackend::new(service, catalogue); + let mut params = json!({"target":command_target("one"),"size":{"width":360,"height":320}}); + if let Some(flag) = flag { + params["thickness_only"] = json!(flag); + } + backend.execute("panel.resize", ¶ms).unwrap(); + assert_eq!(backend.service.layout(), expected.layout()); + let group = backend.service.layout().section(§ion("first")).unwrap(); + assert_eq!(group.size, size(360.0, 320.0)); + if zone.docked() { + assert_eq!(group.preferred_extent, Some(if zone == Zone::Bottom { 360.0 } else { 320.0 })); + assert!(group.extent_priority > 0); + } + } + } +} + +#[test] +fn thickness_only_refuses_free_native_and_nondock_targets_without_layout_or_storage_effects() { + use commands::LayoutCatalogue; + use serde_json::json; + for native in [false, true] { + let mut service = fixture_service(native).unwrap(); + if native { + open(&mut service, "one", "first"); + service + .dispatch(transaction(vec![Mutation::Move { + instance: id("one"), + destination: Destination::NewSection { + section: section("free"), + index: 0, + size: size(280.0, 240.0), + location: SectionLocation::Window { + host: HostId::new("thickness-native").unwrap(), + origin: Point { x: 0.0, y: 0.0 }, + return_to: DockReturn { + zone: Zone::Left, + index: 0, + size: size(280.0, 240.0), + collapsed: false, + join: None, + section: None, + column: None, + column_index: 0, + column_width: None, + weight: 1.0, + preferred_extent: None, + extent_priority: 0, + }, + }, + }, + }])) + .unwrap(); + } else { + service.dispatch(transaction(vec![fixture_open("fixture.log", "one", "free", Zone::Floating, 0).unwrap()])).unwrap(); + } + let catalogue = fixture_command_catalogue(service.registry()).unwrap(); + let mut backend = commands::InMemoryPanelBackend::new(service, catalogue); + for target in [ + command_target("one"), + json!({"type":"section","id":"free"}), + json!({"type":"native_host","id":"thickness-native"}), + json!({"type":"workspace","id":"fixture.workspace"}), + ] { + let before = backend.service.inspect(); + let catalogue = backend.catalogue.state().clone(); + let result = backend.execute("panel.resize", &json!({"target":target,"size":{"width":300,"height":200},"thickness_only":true})); + assert_eq!( + result.unwrap_err().rule, + if target["type"] == "instance" || target["type"] == "section" { Rule::Placement } else { Rule::Schema } + ); + assert_eq!(backend.service.inspect(), before); + assert_eq!(backend.catalogue.state(), &catalogue); + } + } +} + +#[test] +fn thickness_only_schema_unused_dimensions_and_atomic_failures_use_existing_command_boundaries() { + use commands::LayoutCatalogue; + use serde_json::json; + let spec = crate::find_command("panel.resize").unwrap(); + let contract = spec.contract.unwrap(); + let schema = contract.input_schema(); + assert_eq!(schema.as_value()["properties"]["thickness_only"]["default"], false); + assert_eq!(schema.as_value()["properties"]["thickness_only"]["type"], "boolean"); + let mut backend = command_ready_backend(); + for (field, value) in [ + ("thickness_only", json!(null)), + ("thickness_only", json!(1)), + ("thickness_only", json!("true")), + ("thickness_only", json!([])), + ("thickness_only", json!({})), + ("unknown", json!(true)), + ] { + let mut params = json!({"target":command_target("one"),"size":{"width":300,"height":200},"thickness_only":true}); + params[field] = value; + assert!(!contract.check(¶ms).is_empty()); + assert_eq!(commands::parse_command("panel.resize", ¶ms).unwrap_err().rule, Rule::Schema); + let before = backend.service.inspect(); + let catalogue = backend.catalogue.state().clone(); + assert!(backend.execute("panel.resize", ¶ms).is_err()); + assert_eq!(backend.service.inspect(), before); + assert_eq!(backend.catalogue.state(), &catalogue); + } + backend.execute("panel.open", &json!({"kind":"fixture.log","instance":"bottom","destination":command_destination("bottom",2,"bottom")})).unwrap(); + let column = backend.service.layout().section(§ion("s-one")).unwrap().column.clone().unwrap(); + for (target, axis) in [(command_target("one"), "height"), (json!({"type":"column","id":column}), "height"), (command_target("bottom"), "width")] { + for value in [json!(0), json!(-1), json!(MAX_LOGICAL + 1.0), json!(1e100), json!(null), json!("NaN")] { + let mut params = json!({"target":target,"size":{"width":300,"height":200},"thickness_only":true}); + params["size"][axis] = value; + let before = backend.service.inspect(); + let catalogue = backend.catalogue.state().clone(); + assert!(!contract.check(¶ms).is_empty(), "unused {axis} remains hostile input"); + assert!(backend.execute("panel.resize", ¶ms).is_err()); + assert_eq!(backend.service.inspect(), before); + assert_eq!(backend.catalogue.state(), &catalogue); + } + } + for (panel, unused_width) in [("one", false), ("bottom", true)] { + for value in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { + let params = crate::schema::panels::Resize { + target: Some(crate::schema::panels::Target::Instance(id(panel))), + id: None, + size: crate::schema::panels::OuterSize { + width: if unused_width { value } else { 300.0 }, + height: if unused_width { 200.0 } else { value }, + }, + thickness_only: true, + expected_revision: None, + }; + let before = backend.service.inspect(); + let catalogue = backend.catalogue.state().clone(); + let registry = backend.service.registry().clone(); + let result = commands::execute_command( + commands::PanelCommand::Resize(params), + &mut commands::PanelCommandContext { sink: &mut backend.service, registry: ®istry, catalogue: &mut backend.catalogue, web: false }, + ); + assert_eq!(result.unwrap_err().rule, Rule::Bounds); + assert_eq!(backend.service.inspect(), before); + assert_eq!(backend.catalogue.state(), &catalogue); + } + } + for params in [ + json!({"target":command_target("one"),"thickness_only":true}), + json!({"target":command_target("one"),"size":{"width":300,"height":200,"unknown":true},"thickness_only":true}), + ] { + assert_eq!(commands::parse_command("panel.resize", ¶ms).unwrap_err().rule, Rule::Schema); + } + let before = backend.service.inspect(); + let catalogue = backend.catalogue.state().clone(); + assert!( + backend + .batch(&[ + json!({"command":"panel.resize","params":{"target":command_target("bottom"),"size":{"width":1,"height":180},"thickness_only":true}}), + json!({"command":"panel.resize","params":{"target":command_target("one"),"size":{"width":1,"height":1},"thickness_only":true}}), + ]) + .is_err() + ); + assert_eq!(backend.service.inspect(), before); + assert_eq!(backend.catalogue.state(), &catalogue); + backend.catalogue.fail_stage = true; + assert_eq!( + backend + .execute("panel.resize", &json!({"target":command_target("bottom"),"size":{"width":1,"height":180},"thickness_only":true})) + .unwrap_err() + .rule, + Rule::Capability + ); + assert_eq!(backend.service.inspect(), before); + assert_eq!(backend.catalogue.state(), &catalogue); +} + #[test] fn command_target_resolution_never_guesses_a_multi_instance_or_mismatched_target() { let mut backend = command_ready_backend(); @@ -2018,6 +2587,10 @@ mod catalogue_consumer { let mut wire = serde_json::to_value(LayoutEnvelope::new(pin_service.layout().clone())).unwrap(); wire["layout"]["sections"].as_array_mut().unwrap().reverse(); wire["layout"]["sections"][0]["location"] = serde_json::json!({"type":"dock","zone":"left"}); + let column = wire["layout"]["sections"][0]["column"].clone(); + let columns = wire["layout"]["columns"].as_array_mut().unwrap(); + columns.iter_mut().find(|saved| saved["id"] == column).unwrap()["zone"] = serde_json::json!("left"); + columns.reverse(); let bytes = serde_json::to_vec(&wire).unwrap(); assert_eq!(CatalogueState::hydrate(&snapshot(&[], &[("Pinned", &bytes, None)], &[], &[]), &absent).unwrap_err().rule, Rule::PinOrder); } @@ -2191,6 +2764,90 @@ mod catalogue_consumer { out } + #[test] + fn maximum_original_v1_record_hydrates_and_projects_without_claiming_expanded_encodability() { + use crate::panels::commands::StoredEnvelope; + let registry = synthetic_registry().unwrap(); + let absent = without_kind(®istry, "fixture.editor"); + let fallback = Layout::empty(WorkspaceId::new("fixture.workspace").unwrap()); + let mut raw: serde_json::Value = serde_json::from_slice(FIXTURE_LAYOUT_V1).unwrap(); + raw["future_envelope"] = serde_json::json!({"intent":"keep exact legacy bytes"}); + raw["retained_data"]["padding"] = serde_json::json!(""); + let overhead = serde_json::to_vec(&raw).unwrap().len(); + raw["retained_data"]["padding"] = serde_json::json!("x".repeat(MAX_ENVELOPE_BYTES - overhead)); + let legacy = serde_json::to_vec(&raw).unwrap(); + assert_eq!(legacy.len(), MAX_ENVELOPE_BYTES); + bounded_json(&raw).unwrap(); // Original v1 validity, not a padded v2 record. + let source = snapshot( + &[("Legacy", &legacy, None)], + &[], + &[("fixture.workspace", "ui.panel", "Legacy")], + &[("fixture.workspace", &legacy, Some(b"original recovery"))], + ); + for current in [®istry, &absent] { + let retained = decode_retained_record(&legacy, current).unwrap(); + assert_eq!(retained.retained_v1_bytes(), Some(legacy.as_slice())); + assert!(retained.layout.sections.iter().all(|s| s.preferred_extent.is_none())); + assert!(retained.layout.instances.iter().all(|p| p.memory.preferred_extent.is_none())); + assert!(retained.layout.sections.iter().all(|s| s.extent_priority == 0)); + assert!(retained.layout.instances.iter().all(|p| p.memory.extent_priority == 0)); + let typed = serde_json::to_value(&retained).unwrap(); + assert!(typed["layout"]["sections"][0].get("preferred_extent").is_none()); + assert!(typed["layout"]["instances"][0]["memory"].get("preferred_extent").is_none()); + assert!(typed["layout"]["sections"][0].get("extent_priority").is_none()); + assert!(typed["layout"]["instances"][0]["memory"].get("extent_priority").is_none()); + assert_eq!(decode_retained(&legacy, current, &fallback.workspace).unwrap().retained_v1_bytes(), Some(legacy.as_slice())); + let projected = project_retained_record(&legacy, current, &fallback.workspace).unwrap(); + let loaded = decode(&legacy, current, &fallback).unwrap(); + assert!(loaded.notice.is_none() && loaded.rejected.is_none()); + assert_eq!(loaded.envelope.retained_v1_bytes(), Some(legacy.as_slice())); + assert_eq!(projected.retained_v1_bytes(), Some(legacy.as_slice())); + assert_eq!(encode(&projected, current).unwrap_err().rule, Rule::CollectionLimit); + assert_eq!(StoredEnvelope::new(&projected, None, current).unwrap_err().rule, Rule::CollectionLimit); + assert_eq!(with_live_layout(&projected, projected.layout.clone(), current).unwrap_err().rule, Rule::CollectionLimit); + let catalogue = CatalogueState::hydrate(&source, current).unwrap(); + assert_eq!(catalogue.export().unwrap(), source); + let stored = catalogue.preset("Legacy").unwrap(); + assert_eq!(stored.bytes(), legacy.as_slice()); + assert_eq!(stored.project_envelope(current, &fallback.workspace).unwrap().retained_v1_bytes(), Some(legacy.as_slice())); + assert_eq!(catalogue.remembered(&fallback.workspace).unwrap().rejected(), Some(b"original recovery".as_slice())); + let catalogue = InMemoryCatalogue::from_snapshot(&source, current).unwrap(); + let service = LayoutService::new(current.clone(), projected.layout.clone(), HostCapabilities::default()).unwrap(); + let captured = commands::current_envelope_snapshot(&catalogue, &service.inspect(), current).unwrap(); + assert_eq!(captured.retained_v1_bytes(), Some(legacy.as_slice())); + assert_eq!(encode(&captured, current).unwrap_err().rule, Rule::CollectionLimit); + assert_eq!(catalogue.state().export().unwrap(), source); + } + } + + #[test] + fn maximum_priority_record_hydrates_without_overhead_and_expanded_shadow_staging_is_atomic() { + let (registry, envelope) = super::priority_recovery_envelope(u16::MAX, false); + let envelope = maximum_record(envelope, ®istry, MAX_ENVELOPE_BYTES); + let bytes = encode(&envelope, ®istry).unwrap(); + assert_eq!(bytes.len(), MAX_ENVELOPE_BYTES); + let retained = decode_retained_record(&bytes, ®istry).unwrap(); + assert!(retained.layout.extent_priority_context.complete); + assert!(retained.extent_priority_overrides.is_empty()); + assert_eq!(encode(&retained, ®istry).unwrap(), bytes); + let context = preparation_context(&retained).unwrap(); + let service = LayoutService::new(registry.clone(), retained.layout.clone(), HostCapabilities::default()).unwrap(); + let before = service.inspect(); + let prepared = service + .prepare_with_context( + transaction(vec![Mutation::SetSize { section: SectionId::new("a").unwrap(), size: Size { width: 280.0, height: 350.0 } }]), + &AvailabilityMap::new(), + &context, + ) + .unwrap(); + assert_eq!(with_live_layout(&retained, prepared.layout().clone(), ®istry).unwrap_err().rule, Rule::CollectionLimit); + assert_eq!(service.inspect(), before); + assert_eq!(encode(&retained, ®istry).unwrap(), bytes); + let source = snapshot(&[("Full", &bytes, None)], &[], &[], &[("fixture.workspace", &bytes, None)]); + let catalogue = InMemoryCatalogue::from_snapshot(&source, ®istry).unwrap(); + assert_eq!(catalogue.state().export().unwrap(), source); + } + #[test] fn catalogue_hydration_rejects_duplicate_names_workspaces_and_corrupt_framing_before_publication() { let registry = synthetic_registry().unwrap(); @@ -2356,12 +3013,22 @@ fn a_new_quarantine_episode_refreshes_saved_tab_order_activation_and_outer_seman for initial_active in ["a", "b"] { let mut envelope = decode(&serde_json::to_vec(&future_pair(initial_active)).unwrap(), &a, &fallback).unwrap().envelope; restore_quarantine(&mut envelope, &all).unwrap(); - let group = envelope.layout.sections.first_mut().unwrap(); - group.tabs = vec![id("b"), id("a")]; - group.active = id("b"); - group.size = size(400.0, 300.0); - group.collapsed = true; - group.location = SectionLocation::Dock { zone: Zone::Right }; + let mut service = LayoutService::new(all.clone(), envelope.layout.clone(), HostCapabilities::default()).unwrap(); + service.dispatch(transaction(vec![Mutation::Close { instance: id("a") }, Mutation::Close { instance: id("b") }])).unwrap(); + service + .dispatch(transaction(vec![ + fixture_open("extension.b", "b", "group", Zone::Right, 0).unwrap(), + Mutation::Open { + kind: PanelKind::new("extension.a").unwrap(), + instance: id("a"), + destination: Some(Destination::JoinTab { section: section("group"), index: 1 }), + }, + Mutation::Activate { instance: id("b") }, + Mutation::SetSize { section: section("group"), size: size(400.0, 300.0) }, + Mutation::Collapse { section: section("group"), collapsed: true }, + ])) + .unwrap(); + envelope = with_live_layout(&envelope, service.layout().clone(), &all).unwrap(); let mut saved: serde_json::Value = serde_json::from_slice(&encode(&envelope, &all).unwrap()).unwrap(); saved["layout"]["sections"][0]["new_future_field"] = serde_json::json!("latest opaque intent"); let loaded = decode(&serde_json::to_vec(&saved).unwrap(), &a, &fallback).unwrap(); @@ -2474,3 +3141,4069 @@ fn earlier_v1_rank_metadata_and_new_order_projection_bounds_are_supported() { snapshot.projected.as_mut().unwrap().tabs = vec![id("a"); MAX_TABS + 1]; assert_eq!(encode(&restored, &all).unwrap_err().rule, Rule::CollectionLimit); } + +#[test] +fn amended_registration_defaults_are_generic_and_header_metadata_is_bounded() { + let registry = synthetic_registry().unwrap(); + let base = registry.get(&PanelKind::new("fixture.log").unwrap()).unwrap(); + let mut raw = serde_json::to_value(base).unwrap(); + for field in ["allowed_zones", "side_height_policy", "header_actions", "text_heavy"] { + raw.as_object_mut().unwrap().remove(field); + } + raw["features"].as_object_mut().unwrap().remove("hot_closable"); + let spec: PanelSpec = serde_json::from_value(raw).unwrap(); + assert_eq!(spec.allowed_zones, all_zones()); + assert_eq!(spec.side_height_policy, SideHeightPolicy::Content); + assert!(!spec.text_heavy && !spec.features.hot_closable && spec.header_actions.is_empty()); + let mut duplicate = base.clone(); + let action = HeaderActionSpec { id: ControlId::new("refresh").unwrap(), label_key: "ui.refresh".into(), icon: "restore".into() }; + duplicate.header_actions = vec![action.clone(), action.clone()]; + assert_eq!(PanelRegistry::default().register(duplicate).unwrap_err().rule, Rule::DuplicateId); + let mut oversized = base.clone(); + oversized.header_actions = vec![action; MAX_HEADER_ACTIONS + 1]; + assert_eq!(PanelRegistry::default().register(oversized).unwrap_err().rule, Rule::CollectionLimit); + let mut visible_disabled = base.clone(); + visible_disabled.features.closable = false; + visible_disabled.features.hot_closable = true; + let mut registry = PanelRegistry::default(); + registry.register(visible_disabled.clone()).unwrap(); + assert!(registry.get(&visible_disabled.kind).unwrap().features.hot_closable); + let mut service = + LayoutService::new(registry, Layout::empty(WorkspaceId::new("fixture.workspace").unwrap()), HostCapabilities::default()).unwrap(); + service.dispatch(transaction(vec![fixture_open("fixture.log", "fixed", "fixed-group", Zone::Left, 0).unwrap()])).unwrap(); + reject(&mut service, vec![Mutation::Close { instance: id("fixed") }], Rule::FeatureDisabled); +} + +#[test] +fn all_relative_placements_keep_exact_prepared_columns_and_stack_order() { + for placement in [RelativePlacement::BeforeColumn, RelativePlacement::AfterColumn, RelativePlacement::Above, RelativePlacement::Below] { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "anchor", "anchor-group"); + open(&mut service, "mover", "source"); + let before = service.inspect(); + let column = next_column_id(service.layout()).unwrap(); + let split = matches!(placement, RelativePlacement::BeforeColumn | RelativePlacement::AfterColumn); + let action = transaction(vec![ + Mutation::Move { + instance: id("mover"), + destination: Destination::Relative { + section: section("anchor-group"), + placement, + new_section: section("landing"), + new_column: split.then_some(column.clone()), + size: size(280.0, 240.0), + }, + }, + Mutation::Activate { instance: id("mover") }, + ]); + let first = service.prepare(action.clone()).unwrap(); + let second = service.prepare(action).unwrap(); + assert_eq!(first.layout(), second.layout()); + assert_eq!(service.inspect(), before, "preview must not publish IDs or state"); + let shown = second.layout().clone(); + drop(first); + let committed = service.commit(second).unwrap(); + assert_eq!(committed.layout, shown); + let anchor = committed.layout.section(§ion("anchor-group")).unwrap(); + let landing = committed.layout.section(§ion("landing")).unwrap(); + assert_eq!(landing.active, id("mover")); + assert_eq!(anchor.column == landing.column, !split); + let ordered: Vec<_> = committed.layout.sections.iter().map(|s| s.id.clone()).collect(); + let before_anchor = matches!(placement, RelativePlacement::BeforeColumn | RelativePlacement::Above); + assert_eq!( + ordered, + if before_anchor { vec![section("landing"), section("anchor-group")] } else { vec![section("anchor-group"), section("landing")] } + ); + if split { + assert_eq!(landing.column, Some(column)); + } + } +} + +#[test] +fn relative_stacks_allocate_equal_heights_across_source_and_anchor_weight_scales() { + for placement in [RelativePlacement::Above, RelativePlacement::Below] { + for anchor_weight in [1.0, 240.0, 0.0001] { + for source_weight in [1.0, 240.0, 0.0001] { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "anchor", "anchor-group"); + service.dispatch(transaction(vec![fixture_open("fixture.log", "mover", "source", Zone::Floating, 1).unwrap()])).unwrap(); + let mut layout = service.layout().clone(); + layout.sections[0].weight = anchor_weight; + layout.sections[1].weight = source_weight; + layout.instances[0].memory.weight = anchor_weight; + layout.instances[1].memory.weight = source_weight; + let mut service = LayoutService::new(service.registry().clone(), layout, HostCapabilities::default()).unwrap(); + let mut env = allocated_pair_environment(&service, 800.0); + env.gap = 4.0; + let before = service.inspect(); + let prepared = service + .prepare(transaction(vec![Mutation::Move { + instance: id("mover"), + destination: Destination::Relative { + section: section("anchor-group"), + placement, + new_section: section("landing"), + new_column: None, + size: size(280.0, 240.0), + }, + }])) + .unwrap(); + assert_eq!(service.inspect(), before, "preparation cannot publish the stack"); + let anchor = prepared.layout().section(§ion("anchor-group")).unwrap(); + let landing = prepared.layout().section(§ion("landing")).unwrap(); + assert_eq!(anchor, before.layout.section(§ion("anchor-group")).unwrap()); + assert_eq!(landing.weight, anchor_weight); + assert_eq!(landing.size.height, 240.0, "desired height remains independent of surplus weight"); + let shown = allocate_layout(prepared.layout(), service.registry(), &env).unwrap(); + assert_eq!(shown.sections.len(), 2); + assert_eq!( + shown.sections.iter().map(|s| s.section.clone()).collect::>(), + if placement == RelativePlacement::Above { + vec![section("landing"), section("anchor-group")] + } else { + vec![section("anchor-group"), section("landing")] + } + ); + for (index, actual) in shown.sections.iter().enumerate() { + assert!( + (actual.outer.size.height - 398.0).abs() < 0.001, + "{placement:?}, anchor {anchor_weight}, source {source_weight}: {actual:?}" + ); + assert!((actual.outer.origin.y - (17.0 + index as f32 * 402.0)).abs() < 0.001); + } + service.commit(prepared).unwrap(); + assert_eq!(allocate_layout(service.layout(), service.registry(), &env).unwrap(), shown); + assert_eq!(service.layout().instance(&id("mover")).unwrap().memory.weight, anchor_weight); + } + } + } +} + +#[test] +fn relative_stacks_keep_zero_anchor_at_minimum_and_give_new_section_surplus() { + for placement in [RelativePlacement::Above, RelativePlacement::Below] { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "anchor", "anchor-group"); + let mut layout = service.layout().clone(); + layout.sections[0].weight = 0.0; + layout.instances[0].memory.weight = 0.0; + let mut service = LayoutService::new(service.registry().clone(), layout, HostCapabilities::default()).unwrap(); + service + .dispatch(transaction(vec![Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("new"), + destination: Some(Destination::Relative { + section: section("anchor-group"), + placement, + new_section: section("landing"), + new_column: None, + size: size(280.0, 240.0), + }), + }])) + .unwrap(); + let mut env = allocated_pair_environment(&service, 800.0); + env.gap = 4.0; + let geometry = allocate_layout(service.layout(), service.registry(), &env).unwrap(); + assert_eq!(geometry.sections.len(), 2); + assert_eq!(service.layout().section(§ion("anchor-group")).unwrap().weight, 0.0); + assert_eq!(service.layout().section(§ion("landing")).unwrap().weight, 1.0); + assert_eq!(service.layout().instance(&id("anchor")).unwrap().memory.weight, 0.0); + for actual in &geometry.sections { + let expected = if actual.section == section("anchor-group") { 120.0 } else { 676.0 }; + assert!((actual.outer.size.height - expected).abs() < 0.001); + } + } +} + +#[test] +fn relative_same_column_moves_preserve_authored_extents_ranks_and_other_saved_weights() { + for placement in [RelativePlacement::Above, RelativePlacement::Below] { + let mut service = fixture_service(false).unwrap(); + for (panel, group) in [("anchor", "anchor-group"), ("other", "other-group"), ("mover", "source"), ("closed", "closed-group")] { + open(&mut service, panel, group); + } + service + .dispatch(transaction(vec![ + Mutation::SetSize { section: section("anchor-group"), size: size(280.0, 300.0) }, + Mutation::SetSize { section: section("source"), size: size(280.0, 200.0) }, + Mutation::SetSize { section: section("closed-group"), size: size(280.0, 350.0) }, + Mutation::Close { instance: id("closed") }, + ])) + .unwrap(); + let mut layout = service.layout().clone(); + for (group, weight) in layout.sections.iter_mut().zip([0.0002, 0.0004, 0.0009]) { + group.weight = weight; + } + for panel in &mut layout.instances { + if let Some(group) = layout.sections.iter().find(|s| s.tabs.contains(&panel.id)) { + panel.memory.weight = group.weight; + } + } + let mut service = LayoutService::new(service.registry().clone(), layout, HostCapabilities::default()).unwrap(); + let before = service.layout().clone(); + let mut env = allocated_pair_environment(&service, 800.0); + env.gap = 4.0; + let prepared = service + .prepare(transaction(vec![Mutation::Move { + instance: id("mover"), + destination: Destination::Relative { + section: section("anchor-group"), + placement, + new_section: section("landing"), + new_column: None, + size: size(280.0, 200.0), + }, + }])) + .unwrap(); + let mut expected = before.section(§ion("source")).unwrap().clone(); + expected.id = section("landing"); + expected.weight = before.section(§ion("anchor-group")).unwrap().weight; + assert_eq!(prepared.layout().section(§ion("landing")).unwrap(), &expected); + for name in ["anchor-group", "other-group"] { + assert_eq!(prepared.layout().section(§ion(name)).unwrap(), before.section(§ion(name)).unwrap()); + } + assert_eq!(prepared.layout().instance(&id("closed")).unwrap(), before.instance(&id("closed")).unwrap()); + let shown = allocate_layout(prepared.layout(), service.registry(), &env).unwrap(); + assert_eq!(shown.sections.len(), 3); + for actual in &shown.sections { + let expected = match actual.section.0.as_str() { + "anchor-group" => 300.0, + "landing" => 200.0, + "other-group" => 292.0, + _ => panic!("unexpected section"), + }; + assert!((actual.outer.size.height - expected).abs() < 0.001); + } + service.commit(prepared).unwrap(); + assert_eq!(allocate_layout(service.layout(), service.registry(), &env).unwrap(), shown); + service.dispatch(transaction(vec![Mutation::Collapse { section: section("landing"), collapsed: true }])).unwrap(); + let folded = allocate_layout(service.layout(), service.registry(), &env).unwrap(); + assert_eq!(folded.sections.iter().find(|s| s.section == section("landing")).unwrap().outer.size.height, 20.0); + assert_eq!(service.layout().section(§ion("landing")).unwrap(), &Section { collapsed: true, ..expected.clone() }); + service.dispatch(transaction(vec![Mutation::Collapse { section: section("landing"), collapsed: false }])).unwrap(); + assert_eq!(service.layout().section(§ion("landing")).unwrap(), &expected); + assert_eq!(allocate_layout(service.layout(), service.registry(), &env).unwrap(), shown); + } +} + +#[test] +fn relative_requests_reject_self_targets_and_malformed_column_intents_atomically() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + open(&mut service, "two", "second"); + let before = service.inspect(); + for (target, placement, column) in [ + ("second", RelativePlacement::Above, None), + ("first", RelativePlacement::BeforeColumn, None), + ("first", RelativePlacement::Below, Some(ColumnId::new("unexpected").unwrap())), + ] { + reject( + &mut service, + vec![Mutation::Move { + instance: id("two"), + destination: Destination::Relative { + section: section(target), + placement, + new_section: section("new"), + new_column: column, + size: size(280.0, 240.0), + }, + }], + Rule::Placement, + ); + } + assert_eq!(service.inspect(), before); +} + +#[test] +fn shared_column_width_includes_inactive_tabs_and_all_stacked_sections() { + let mut registry = synthetic_registry().unwrap(); + let mut tight = registry.get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + tight.kind = PanelKind::new("fixture.tight").unwrap(); + tight.min_size.width = 200.0; + tight.max_size.width = 320.0; + registry.register(tight).unwrap(); + let mut service = + LayoutService::new(registry, Layout::empty(WorkspaceId::new("fixture.workspace").unwrap()), HostCapabilities::default()).unwrap(); + open(&mut service, "one", "first"); + open(&mut service, "two", "second"); + service + .dispatch(transaction(vec![Mutation::Open { + kind: PanelKind::new("fixture.tight").unwrap(), + instance: id("tight"), + destination: Some(Destination::JoinTab { section: section("second"), index: 1 }), + }])) + .unwrap(); + let column = service.layout().section(§ion("first")).unwrap().column.clone().unwrap(); + assert_eq!(column_bounds(service.layout(), service.registry(), &column).unwrap(), (200.0, 320.0)); + assert_eq!(service.layout().section(§ion("second")).unwrap().active, id("two")); + reject(&mut service, vec![Mutation::SetColumnWidth { column: column.clone(), width: 321.0 }], Rule::Bounds); + reject(&mut service, vec![Mutation::SetSize { section: section("first"), size: size(321.0, 240.0) }], Rule::Bounds); + service.dispatch(transaction(vec![Mutation::SetColumnWidth { column: column.clone(), width: 300.0 }])).unwrap(); + assert_eq!(service.layout().column(&column).unwrap().width, 300.0); + for name in ["one", "two", "tight"] { + let memory = &service.layout().instance(&id(name)).unwrap().memory; + assert_eq!(memory.column_width, Some(300.0)); + assert_eq!(memory.size.width, 300.0); + } +} + +#[test] +fn column_pairs_preserve_saved_proportions_and_reject_cross_column_or_collapsed_sashes() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + open(&mut service, "two", "second"); + service + .dispatch(transaction(vec![Mutation::ResizePair { + first: section("first"), + second: section("second"), + first_size: size(280.0, 180.0), + second_size: size(280.0, 300.0), + }])) + .unwrap(); + let a = service.layout().section(§ion("first")).unwrap().weight; + let b = service.layout().section(§ion("second")).unwrap().weight; + assert!((a / b - 0.6).abs() < 0.0001); + service.dispatch(transaction(vec![Mutation::Collapse { section: section("first"), collapsed: true }])).unwrap(); + reject(&mut service, vec![Mutation::ResetPair { first: section("first"), second: section("second") }], Rule::Placement); + service.dispatch(transaction(vec![Mutation::Collapse { section: section("first"), collapsed: false }])).unwrap(); + assert_eq!(service.layout().section(§ion("first")).unwrap().weight, a); + assert_eq!(service.layout().section(§ion("second")).unwrap().weight, b); + let column = next_column_id(service.layout()).unwrap(); + service + .dispatch(transaction(vec![Mutation::Move { + instance: id("two"), + destination: Destination::Relative { + section: section("first"), + placement: RelativePlacement::AfterColumn, + new_section: section("other"), + new_column: Some(column), + size: size(280.0, 300.0), + }, + }])) + .unwrap(); + reject(&mut service, vec![Mutation::ResetPair { first: section("first"), second: section("other") }], Rule::Placement); +} + +#[test] +fn closed_panel_reopens_with_column_identity_width_rank_and_saved_weight() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + open(&mut service, "two", "second"); + let column = next_column_id(service.layout()).unwrap(); + service + .dispatch(transaction(vec![Mutation::Move { + instance: id("two"), + destination: Destination::Relative { + section: section("first"), + placement: RelativePlacement::AfterColumn, + new_section: section("inner"), + new_column: Some(column.clone()), + size: size(310.0, 300.0), + }, + }])) + .unwrap(); + service + .dispatch(transaction(vec![Mutation::Collapse { section: section("inner"), collapsed: true }, Mutation::Close { instance: id("two") }])) + .unwrap(); + let memory = service.layout().instance(&id("two")).unwrap().memory.clone(); + assert_eq!(memory.column, Some(column.clone())); + assert_eq!(memory.column_index, 1); + assert_eq!(memory.column_width, Some(310.0)); + assert_eq!(memory.weight, 300.0); + assert_ne!(next_column_id(service.layout()).unwrap(), column); + service + .dispatch(transaction(vec![Mutation::Open { kind: PanelKind::new("fixture.log").unwrap(), instance: id("two"), destination: None }])) + .unwrap(); + let restored = service.layout().containing(&id("two")).unwrap(); + assert_eq!(restored.id, memory.section); + assert_eq!(restored.column, memory.column); + assert_eq!(restored.weight, memory.weight); + assert!(restored.collapsed); +} + +#[test] +fn native_redock_preserves_original_section_column_width_and_proportion() { + let mut service = fixture_service(true).unwrap(); + open(&mut service, "one", "first"); + let original = service.layout().section(§ion("first")).unwrap().clone(); + let column = original.column.clone().unwrap(); + service + .dispatch(transaction(vec![Mutation::Move { + instance: id("one"), + destination: Destination::NewSection { + section: section("native"), + index: 0, + size: size(320.0, 280.0), + location: SectionLocation::Window { + host: HostId::new("host").unwrap(), + origin: Point { x: 10.0, y: 10.0 }, + return_to: DockReturn { + zone: Zone::Left, + index: 0, + size: original.size, + collapsed: original.collapsed, + join: None, + section: None, + column: None, + column_index: 0, + column_width: None, + weight: 1.0, + preferred_extent: None, + extent_priority: 0, + }, + }, + }, + }])) + .unwrap(); + let SectionLocation::Window { return_to, .. } = &service.layout().containing(&id("one")).unwrap().location else { + panic!("native destination"); + }; + assert_eq!(return_to.section, Some(original.id.clone())); + assert_eq!(return_to.column, Some(column.clone())); + assert_eq!(return_to.weight, original.weight); + assert_ne!(next_section_id(service.layout()).unwrap(), original.id); + assert_ne!(next_column_id(service.layout()).unwrap(), column); + service.dispatch(transaction(vec![Mutation::NativeClose { host: HostId::new("host").unwrap() }])).unwrap(); + assert_eq!(service.layout().containing(&id("one")).unwrap(), &original); +} + +#[test] +fn command_drag_activation_is_atomic_and_background_join_keeps_destination_active() { + let mut backend = command_ready_backend(); + let before = backend.service.inspect(); + backend + .execute("panel.move", &serde_json::json!({"target":command_target("two"),"destination":{"type":"join_tab","section":"s-one","index":1}})) + .unwrap(); + assert_eq!(backend.service.layout().section(§ion("s-one")).unwrap().active, id("one")); + let revision = backend.service.inspect().revision; + backend + .execute( + "panel.move", + &serde_json::json!({"target":command_target("two"),"activate":true,"destination":{"type":"join_tab","section":"s-one","index":0}}), + ) + .unwrap(); + assert_eq!(backend.service.inspect().revision, revision + 1); + assert_eq!(backend.service.layout().section(§ion("s-one")).unwrap().active, id("two")); + assert_eq!(backend.service.inspect().revision, before.revision + 2); + let committed = backend.service.inspect(); + assert!( + backend + .execute( + "panel.move", + &serde_json::json!({"target":command_target("one"),"activate":true,"destination":{"type":"join_tab","section":"s-one","index":9}}) + ) + .is_err() + ); + assert_eq!(backend.service.inspect(), committed); +} + +#[test] +fn pin_follows_other_side_allows_ordinary_tabs_and_rejects_column_displacement() { + let mut service = fixture_service(false).unwrap(); + service.dispatch(transaction(vec![fixture_open("fixture.pin", "pin", "pinned", Zone::Left, 0).unwrap()])).unwrap(); + open(&mut service, "ordinary", "ordinary-section"); + service + .dispatch(transaction(vec![Mutation::Move { + instance: id("ordinary"), + destination: Destination::JoinTab { section: section("pinned"), index: 1 }, + }])) + .unwrap(); + service + .dispatch(transaction(vec![Mutation::Move { + instance: id("pin"), + destination: Destination::NewSection { + section: section("right-pin"), + index: 1, + location: SectionLocation::Dock { zone: Zone::Right }, + size: size(280.0, 240.0), + }, + }])) + .unwrap(); + let column = next_column_id(service.layout()).unwrap(); + reject( + &mut service, + vec![Mutation::Move { + instance: id("ordinary"), + destination: Destination::Relative { + section: section("right-pin"), + placement: RelativePlacement::BeforeColumn, + new_section: section("displacing"), + new_column: Some(column), + size: size(280.0, 240.0), + }, + }], + Rule::PinOrder, + ); + assert_eq!(service.layout().containing(&id("pin")).unwrap().location.zone(), Zone::Right); +} + +#[test] +fn header_action_intents_validate_registration_active_state_and_availability() { + let mut registry = synthetic_registry().unwrap(); + let mut spec = registry.get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + spec.kind = PanelKind::new("fixture.action").unwrap(); + spec.header_actions = vec![HeaderActionSpec { id: ControlId::new("refresh").unwrap(), label_key: "ui.refresh".into(), icon: "restore".into() }]; + registry.register(spec).unwrap(); + let mut service = + LayoutService::new(registry.clone(), Layout::empty(WorkspaceId::new("fixture.workspace").unwrap()), HostCapabilities::default()).unwrap(); + service.dispatch(transaction(vec![fixture_open("fixture.action", "action", "actions", Zone::Left, 0).unwrap()])).unwrap(); + let action = ControlId::new("refresh").unwrap(); + let reply = service.dispatch(transaction(vec![Mutation::HeaderAction { instance: id("action"), action: action.clone() }])).unwrap(); + assert_eq!(reply.effects, vec![HostEffect::HeaderAction { instance: id("action"), action: action.clone() }]); + reject(&mut service, vec![Mutation::HeaderAction { instance: id("action"), action: ControlId::new("unknown").unwrap() }], Rule::Capability); + service.dispatch(transaction(vec![Mutation::Collapse { section: section("actions"), collapsed: true }])).unwrap(); + assert!( + service.dispatch(transaction(vec![Mutation::HeaderAction { instance: id("action"), action: action.clone() }])).is_ok(), + "collapsed headers retain custom actions" + ); + service + .dispatch(transaction(vec![ + Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("other"), + destination: Some(Destination::JoinTab { section: section("actions"), index: 1 }), + }, + Mutation::Activate { instance: id("other") }, + ])) + .unwrap(); + reject(&mut service, vec![Mutation::HeaderAction { instance: id("action"), action: action.clone() }], Rule::Availability); + service.dispatch(transaction(vec![Mutation::Activate { instance: id("action") }])).unwrap(); + service.set_availability([(id("action"), Availability::Unavailable { reason: "owner unavailable".into() })].into()).unwrap(); + reject(&mut service, vec![Mutation::HeaderAction { instance: id("action"), action: action.clone() }], Rule::Availability); + service.set_availability(AvailabilityMap::new()).unwrap(); + let catalogue = fixture_command_catalogue(®istry).unwrap(); + let mut backend = commands::InMemoryPanelBackend::new(service, catalogue); + let before = backend.service.inspect(); + assert_eq!( + backend.execute("panel.action", &serde_json::json!({"target":command_target("action"),"action":"refresh"})).unwrap_err().rule, + Rule::Capability + ); + assert_eq!(backend.service.inspect(), before, "missing controller cannot publish an action effect"); +} + +#[test] +fn geometry_admission_failure_keeps_candidate_private_and_consumes_no_identity() { + let mut service = fixture_service(false).unwrap(); + let before = service.inspect(); + let section_id = next_section_id(service.layout()).unwrap(); + let mutation = fixture_open("fixture.log", "one", §ion_id.0, Zone::Left, 0).unwrap(); + let proposed = service.prepare_admitted(transaction(vec![mutation.clone()]), |committed, next| { + assert!(committed.sections.is_empty()); + assert_eq!(next.sections.len(), 1); + Err(error(Rule::NoSpace, "minimums cannot fit destination")) + }); + assert!(matches!(proposed, Err(PanelError { rule: Rule::NoSpace, .. }))); + assert_eq!(service.inspect(), before); + assert_eq!(next_section_id(service.layout()).unwrap(), section_id); + let admitted = service.prepare_admitted(transaction(vec![mutation]), |_, _| Ok(())).unwrap(); + service.commit(admitted).unwrap(); + assert_eq!(service.layout().sections[0].id, section_id); +} + +#[test] +fn v1_migration_preserves_unknown_wire_fields_and_explicit_saved_proportions() { + let registry = synthetic_registry().unwrap(); + let fallback = persistence_fallback(); + let mut raw: serde_json::Value = serde_json::from_slice(FIXTURE_LAYOUT_V1).unwrap(); + raw["future_envelope"] = serde_json::json!({"version":37,"keep":[1,2,3]}); + raw["layout"]["future_layout"] = serde_json::json!({"intent":"preserve"}); + raw["layout"]["sections"][0]["future_section"] = serde_json::json!({"keep":true}); + raw["layout"]["sections"][0]["weight"] = serde_json::json!(2.5); + raw["layout"]["instances"][0]["memory"]["future_memory"] = serde_json::json!({"draft":"saved"}); + raw["layout"]["instances"][0]["memory"]["weight"] = serde_json::json!(2.5); + let mut unknown = raw["layout"]["instances"][0].clone(); + unknown["id"] = serde_json::json!("unknown"); + unknown["kind"] = serde_json::json!("extension.panel"); + unknown["memory"]["section"] = serde_json::json!("unknown-section"); + unknown["memory"]["section_index"] = serde_json::json!(1); + unknown["future_payload"] = serde_json::json!({"draft":"retained"}); + raw["layout"]["instances"].as_array_mut().unwrap().push(unknown); + let mut unknown_section = raw["layout"]["sections"][0].clone(); + unknown_section["id"] = serde_json::json!("unknown-section"); + unknown_section["tabs"] = serde_json::json!(["unknown"]); + unknown_section["active"] = serde_json::json!("unknown"); + raw["layout"]["sections"].as_array_mut().unwrap().push(unknown_section); + raw["section_order"].as_array_mut().unwrap().push(serde_json::json!("unknown-section")); + let loaded = decode(&serde_json::to_vec(&raw).unwrap(), ®istry, &fallback).unwrap(); + assert!(loaded.notice.is_none()); + assert!(loaded.rejected.is_none()); + assert_eq!(loaded.envelope.layout.sections[0].weight, 2.5); + assert_eq!(loaded.envelope.quarantine.len(), 1); + assert!(loaded.envelope.layout.instance(&id("unknown")).is_err()); + let pending = loaded.envelope.quarantine[0].instance_data.clone(); + assert_eq!(pending["future_payload"]["draft"], "retained"); + let mut service = LayoutService::new(registry.clone(), loaded.envelope.layout.clone(), HostCapabilities::default()).unwrap(); + service.dispatch(transaction(vec![Mutation::Collapse { section: section("editor-section"), collapsed: true }])).unwrap(); + let edited = with_live_layout(&loaded.envelope, service.layout().clone(), ®istry).unwrap(); + assert_eq!(edited.quarantine[0].instance_data, pending); + let mut unexplained = loaded.envelope.clone(); + unexplained.recovery_wire.as_mut().unwrap()["layout"]["instances"] + .as_array_mut() + .unwrap() + .push(serde_json::json!({"id":"unexplained","future_payload":true})); + assert_eq!(with_live_layout(&unexplained, service.layout().clone(), ®istry).unwrap_err().rule, Rule::MissingTarget); + let encoded: serde_json::Value = serde_json::from_slice(&encode(&edited, ®istry).unwrap()).unwrap(); + assert_eq!(encoded["future_envelope"], raw["future_envelope"]); + assert_eq!(encoded["layout"]["future_layout"], raw["layout"]["future_layout"]); + assert_eq!(encoded["layout"]["sections"][0]["future_section"], raw["layout"]["sections"][0]["future_section"]); + assert_eq!(encoded["layout"]["instances"][0]["memory"]["future_memory"], raw["layout"]["instances"][0]["memory"]["future_memory"]); + assert_eq!(encoded["layout"]["sections"][0]["weight"], 2.5); + assert_eq!(encoded["layout"]["sections"][0]["collapsed"], true); + let roundtrip = decode(&serde_json::to_vec(&encoded).unwrap(), ®istry, &fallback).unwrap(); + assert!(roundtrip.notice.is_none()); + assert_eq!(roundtrip.envelope.quarantine[0].instance_data, pending); + let mut restored = roundtrip.envelope; + let mut grown = registry.clone(); + let mut spec = registry.get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + spec.kind = PanelKind::new("extension.panel").unwrap(); + grown.register(spec).unwrap(); + restore_quarantine(&mut restored, &grown).unwrap(); + assert!(restored.quarantine.is_empty()); + assert_eq!(restored.layout.section(§ion("unknown-section")).unwrap().tabs, vec![id("unknown")]); + assert!(restored.layout.section(§ion("editor-section")).unwrap().collapsed); + assert_eq!(restored.retained_data[&id("unknown")]["instance"], pending); + let restored = decode(&encode(&restored, &grown).unwrap(), &grown, &fallback).unwrap(); + assert!(restored.notice.is_none()); + assert_eq!(restored.envelope.retained_data[&id("unknown")]["instance"], pending); + let mut future = encoded; + future["layout"]["columns"][0]["future_column"] = serde_json::json!({"keep":"column intent"}); + let loaded = decode(&serde_json::to_vec(&future).unwrap(), ®istry, &fallback).unwrap(); + assert!(loaded.notice.is_none()); + let replaced = with_live_layout(&loaded.envelope, Layout::empty(fallback.workspace.clone()), ®istry).unwrap(); + assert!(replaced.layout.instances.is_empty() && replaced.layout.sections.is_empty()); + let preserved: serde_json::Value = serde_json::from_slice(&encode(&replaced, ®istry).unwrap()).unwrap(); + assert_eq!(preserved["retained_data"]["editor"]["instance"]["memory"]["future_memory"]["draft"], "saved"); + assert_eq!(preserved["section_snapshots"]["editor-section"]["data"]["future_section"]["keep"], true); + assert_eq!(preserved["layout"]["columns"][0]["future_column"]["keep"], "column intent"); +} + +#[test] +fn quarantined_and_closed_memories_reserve_section_and_column_allocation() { + let mut raw = future_group(); + raw["layout"]["sections"][0]["id"] = serde_json::json!("section-1"); + raw["layout"]["sections"][0]["column"] = serde_json::json!("column-1"); + raw["layout"]["columns"][0]["id"] = serde_json::json!("column-1"); + raw["section_order"] = serde_json::json!(["section-1"]); + for instance in raw["layout"]["instances"].as_array_mut().unwrap() { + instance["memory"]["section"] = serde_json::json!("section-1"); + instance["memory"]["column"] = serde_json::json!("column-1"); + } + let none = future_registry(&[]); + let fallback = persistence_fallback(); + let loaded = decode(&serde_json::to_vec(&raw).unwrap(), &none, &fallback).unwrap(); + assert!(loaded.notice.is_none()); + assert_eq!(loaded.envelope.quarantine.len(), 3); + let reserved = reserve_envelope_identities(&loaded.envelope).unwrap(); + assert_eq!(next_section_id(&reserved).unwrap(), section("section-2")); + assert_eq!(next_column_id(&reserved).unwrap(), ColumnId::new("column-2").unwrap()); + let mut restored = loaded.envelope; + restore_quarantine(&mut restored, &future_registry(&["a", "b", "c"])).unwrap(); + assert!(restored.quarantine.is_empty()); + assert_eq!(restored.layout.sections[0].id, section("section-1")); + assert_eq!(restored.layout.sections[0].column, Some(ColumnId::new("column-1").unwrap())); +} + +#[test] +fn v1_live_native_closed_and_quarantined_snapshots_migrate_without_losing_weights() { + use serde_json::json; + let registry = synthetic_registry().unwrap(); + let fallback = persistence_fallback(); + let mut raw: serde_json::Value = serde_json::from_slice(FIXTURE_LAYOUT_V1).unwrap(); + let closed = json!({"id":"closed","kind":"fixture.log","requested_open":false,"memory":{ + "section":"closed-section","location":{"type":"dock","zone":"left"},"section_index":1,"tab_index":0, + "size":{"width":280,"height":360},"collapsed":true + }}); + let native_location = json!({"type":"window","host":"native-host","origin":{"x":20,"y":30},"return_to":{ + "zone":"left","index":1,"size":{"width":280,"height":260},"collapsed":false, + "join":{"section":"editor-section","index":1},"weight":7.0,"future_monitor":"keep" + }}); + let native = json!({"id":"native","kind":"fixture.log","requested_open":true,"memory":{ + "section":"native-section","location":native_location,"section_index":1,"tab_index":0, + "size":{"width":300,"height":260},"collapsed":false,"weight":3.5 + }}); + let native_section = json!({"id":"native-section","location":native["memory"]["location"],"tabs":["native"],"active":"native", + "size":{"width":300,"height":260},"collapsed":false,"weight":3.5}); + raw["layout"]["instances"].as_array_mut().unwrap().extend([closed, native]); + raw["layout"]["sections"].as_array_mut().unwrap().push(native_section); + let unknown = json!({"id":"unknown","kind":"extension.panel","requested_open":true,"future_payload":{"draft":"retained"},"memory":{ + "section":"dormant-section","location":{"type":"dock","zone":"right"},"section_index":2,"tab_index":0, + "size":{"width":280,"height":180},"collapsed":false,"weight":9.0 + }}); + raw["quarantine"] = json!([{"instance":"unknown","kind":"extension.panel","instance_data":unknown,"section":"dormant-section"}]); + raw["section_snapshots"] = json!({"dormant-section":{"index":2,"data":{ + "id":"dormant-section","location":{"type":"dock","zone":"right"},"tabs":["unknown"],"active":"unknown", + "size":{"width":280,"height":180},"collapsed":false,"weight":9.0,"future_snapshot":"keep" + }}}); + raw["section_order"] = json!(["editor-section", "native-section", "dormant-section"]); + let loaded = decode(&serde_json::to_vec(&raw).unwrap(), ®istry, &fallback).unwrap(); + assert!(loaded.notice.is_none(), "{:?}", loaded.notice); + let mut envelope = loaded.envelope; + let closed = &envelope.layout.instance(&id("closed")).unwrap().memory; + assert_eq!(closed.weight, 360.0); + assert!(closed.column.is_some()); + assert_eq!(closed.column_width, Some(280.0)); + let native = envelope.layout.instance(&id("native")).unwrap(); + assert_eq!(native.memory.weight, 3.5); + let SectionLocation::Window { return_to, .. } = &native.memory.location else { + panic!("native memory"); + }; + assert_eq!(return_to.weight, 7.0); + assert_eq!(return_to.column, envelope.layout.sections[0].column); + let pending: PanelInstance = serde_json::from_value(envelope.quarantine[0].instance_data.clone()).unwrap(); + assert_eq!(pending.memory.weight, 9.0); + assert!(pending.memory.column.is_some()); + let mut with_extension = registry.clone(); + let mut spec = registry.get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + spec.kind = PanelKind::new("extension.panel").unwrap(); + with_extension.register(spec).unwrap(); + restore_quarantine(&mut envelope, &with_extension).unwrap(); + assert!(envelope.quarantine.is_empty()); + assert_eq!(envelope.layout.section(§ion("dormant-section")).unwrap().weight, 9.0); + let encoded: serde_json::Value = serde_json::from_slice(&encode(&envelope, &with_extension).unwrap()).unwrap(); + assert_eq!(encoded["section_snapshots"]["dormant-section"]["data"]["future_snapshot"], "keep"); + assert_eq!(encoded["layout"]["instances"][2]["memory"]["location"]["return_to"]["future_monitor"], "keep"); + assert_eq!(envelope.retained_data[&id("unknown")]["instance"]["future_payload"]["draft"], "retained"); +} + +#[test] +fn v1_distinct_preferred_widths_remain_saved_in_the_original_vertical_stack() { + use serde_json::json; + let mut raw: serde_json::Value = serde_json::from_slice(FIXTURE_LAYOUT_V1).unwrap(); + for (index, width) in [(1, 320), (2, 280)] { + let name = format!("log-{index}"); + let group = format!("group-{index}"); + raw["layout"]["instances"].as_array_mut().unwrap().push(json!({"id":name,"kind":"fixture.log","requested_open":true,"memory":{ + "section":group,"location":{"type":"dock","zone":"left"},"section_index":index,"tab_index":0, + "size":{"width":width,"height":200},"collapsed":false + }})); + raw["layout"]["sections"].as_array_mut().unwrap().push(json!({"id":group,"location":{"type":"dock","zone":"left"}, + "tabs":[name],"active":name,"size":{"width":width,"height":200},"collapsed":false})); + raw["section_order"].as_array_mut().unwrap().push(json!(group)); + } + let loaded = decode(&serde_json::to_vec(&raw).unwrap(), &synthetic_registry().unwrap(), &persistence_fallback()).unwrap(); + assert!(loaded.notice.is_none()); + let layout = loaded.envelope.layout; + assert_eq!(layout.columns.iter().map(|c| c.width).collect::>(), vec![280.0]); + assert_eq!(layout.sections.iter().map(|s| s.weight).collect::>(), vec![240.0, 200.0, 200.0]); + assert_eq!(layout.sections.iter().map(|s| s.size.width).collect::>(), vec![280.0, 320.0, 280.0]); + assert!(layout.sections.iter().all(|s| s.column.as_ref() == Some(&layout.columns[0].id))); +} + +fn allocated_pair_environment(service: &LayoutService, height: f32) -> AllocationEnvironment { + AllocationEnvironment { + capacity: LogicalRect { origin: Point { x: 11.0, y: 17.0 }, size: size(1200.0, height) }, + direction: Direction::Ltr, + header_height: 20.0, + footer_height: 0.0, + gap: 0.0, + inline_max_height: 88.0, + min_viewport: size(1.0, 1.0), + scroll: Point { x: 0.0, y: 0.0 }, + available: service.layout().instances.iter().map(|p| p.id.clone()).collect(), + content: Vec::new(), + content_revision: 0, + } +} + +#[test] +fn oversubscribed_highest_tier_fractional_residue_never_reaches_lower_preference_or_weight() { + for weighted_lower in [false, true] { + let mut registry = PanelRegistry::default(); + let mut spec = synthetic_registry().unwrap().get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + spec.min_size.height = 1.0; + registry.register(spec).unwrap(); + let mut service = + LayoutService::new(registry.clone(), Layout::empty(WorkspaceId::new("fixture.workspace").unwrap()), HostCapabilities::default()).unwrap(); + for (panel, group) in [("one", "first"), ("two", "second"), ("three", "third")] { + open(&mut service, panel, group); + } + let mut layout = service.layout().clone(); + for (group, extent) in layout.sections.iter_mut().zip([2.0, 3.0, 2.0]) { + let lower = group.id == section("third"); + group.preferred_extent = if lower && weighted_lower { None } else { Some(extent) }; + group.extent_priority = if lower { if weighted_lower { 0 } else { 1 } } else { 2 }; + group.weight = if lower { 1000.0 } else { 1.0 }; + } + for panel in &mut layout.instances { + let group = layout.sections.iter().find(|s| s.tabs.contains(&panel.id)).unwrap(); + panel.memory.preferred_extent = group.preferred_extent; + panel.memory.extent_priority = group.extent_priority; + panel.memory.weight = group.weight; + } + let service = LayoutService::new(registry.clone(), layout, HostCapabilities::default()).unwrap(); + let mut environment = allocated_pair_environment(&service, 4.0); + environment.header_height = 1.0; + let geometry = allocate_layout(service.layout(), ®istry, &environment).unwrap(); + assert_eq!(geometry.sections.len(), 3); + let height = |name| geometry.sections.iter().find(|s| s.section == section(name)).unwrap().outer.size.height; + // Minima consume three units. The highest tier requests three surplus + // units and receives the remaining one in the ratio 1:2. Inward f32 + // rounding must not turn its residue into a lower tier allocation. + assert!((height("first") - 4.0 / 3.0).abs() < 0.000001); + assert!((height("second") - 5.0 / 3.0).abs() < 0.000001); + assert_eq!(height("third"), 1.0, "an oversubscribed tier exhausts all surplus, including fractional residue"); + assert!(geometry.sections.iter().map(|s| f64::from(s.outer.size.height)).sum::() <= 4.0); + } +} + +#[test] +fn allocated_pair_reaches_actual_minimum_and_maximum_endpoints_and_returns_without_drift() { + for (height, low, high) in [(800.0, 120.0, 680.0), (1320.0, 120.0, 1200.0)] { + for swapped in [false, true] { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + open(&mut service, "two", "second"); + let env = allocated_pair_environment(&service, height); + let initial = allocate_layout(service.layout(), service.registry(), &env).unwrap(); + let (a, b) = normalized_pair_weights(service.layout(), §ion("first"), §ion("second")).unwrap(); + assert_eq!((a, b), (0.5, 0.5)); + let (first_height, second_height, first_weight, second_weight) = if swapped { (high, low, 1.0, 0.0) } else { (low, high, 0.0, 1.0) }; + let before = service.inspect(); + let prepared = service + .prepare(transaction(vec![Mutation::ResizeAllocatedPair { + first: section("first"), + second: section("second"), + first_size: size(280.0, first_height), + second_size: size(280.0, second_height), + first_weight, + second_weight, + other_weight_scale: 1.0, + prefer_allocated: false, + }])) + .unwrap(); + assert_eq!(service.inspect(), before); + let shown = allocate_layout(prepared.layout(), service.registry(), &env).unwrap(); + assert!((shown.sections[0].outer.size.height - first_height).abs() < 0.001); + assert!((shown.sections[1].outer.size.height - second_height).abs() < 0.001); + service.commit(prepared).unwrap(); + assert_eq!(allocate_layout(service.layout(), service.registry(), &env).unwrap(), shown); + service + .dispatch(transaction(vec![Mutation::ResizeAllocatedPair { + first: section("first"), + second: section("second"), + first_size: size(280.0, height / 2.0), + second_size: size(280.0, height / 2.0), + first_weight: 0.5, + second_weight: 0.5, + other_weight_scale: 1.0, + prefer_allocated: false, + }])) + .unwrap(); + assert_eq!(allocate_layout(service.layout(), service.registry(), &env).unwrap(), initial); + } + } +} + +#[test] +fn allocated_pair_preserves_saturated_third_rectangle_and_all_saved_group_shares() { + let mut registry = synthetic_registry().unwrap(); + let mut short = registry.get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + short.kind = PanelKind::new("fixture.short").unwrap(); + short.default_size.height = 180.0; + short.max_size.height = 180.0; + registry.register(short).unwrap(); + let mut service = + LayoutService::new(registry, Layout::empty(WorkspaceId::new("fixture.workspace").unwrap()), HostCapabilities::default()).unwrap(); + open(&mut service, "one", "first"); + open(&mut service, "two", "second"); + service + .dispatch(transaction(vec![Mutation::Open { + kind: PanelKind::new("fixture.short").unwrap(), + instance: id("short"), + destination: Some(Destination::NewSection { + section: section("third"), + index: 2, + location: SectionLocation::Dock { zone: Zone::Left }, + size: size(280.0, 180.0), + }), + }])) + .unwrap(); + open(&mut service, "closed", "remembered"); + service.dispatch(transaction(vec![Mutation::Close { instance: id("closed") }])).unwrap(); + let env = allocated_pair_environment(&service, 1000.0); + let initial = allocate_layout(service.layout(), service.registry(), &env).unwrap(); + let (a, b) = normalized_pair_weights(service.layout(), §ion("first"), §ion("second")).unwrap(); + let total = 240.0 + 240.0 + 180.0 + 240.0; + assert!((a - 240.0 / total).abs() < WEIGHT_SHARE_TOLERANCE); + service + .dispatch(transaction(vec![Mutation::ResizeAllocatedPair { + first: section("first"), + second: section("second"), + first_size: size(280.0, 120.0), + second_size: size(280.0, 700.0), + first_weight: 0.0, + second_weight: a + b, + other_weight_scale: 1.0, + prefer_allocated: false, + }])) + .unwrap(); + let after = allocate_layout(service.layout(), service.registry(), &env).unwrap(); + assert_eq!(after.sections[2].outer.size, initial.sections[2].outer.size); + assert_eq!(after.sections[2].outer.origin.x, initial.sections[2].outer.origin.x); + assert!( + (after.sections[2].outer.origin.y - initial.sections[2].outer.origin.y).abs() < 0.001, + "unrelated saturated neighbour keeps its rectangle within float precision" + ); + assert!((after.sections[0].outer.size.height - 120.0).abs() < 0.001); + assert!((after.sections[1].outer.size.height - 700.0).abs() < 0.001); + assert!((service.layout().sections[2].weight - 180.0 / total).abs() < WEIGHT_SHARE_TOLERANCE); + assert!((service.layout().instance(&id("closed")).unwrap().memory.weight - 240.0 / total).abs() < WEIGHT_SHARE_TOLERANCE); + let before_collapse = service.layout().sections[0].weight; + service + .dispatch(transaction(vec![ + Mutation::Collapse { section: section("first"), collapsed: true }, + Mutation::Collapse { section: section("first"), collapsed: false }, + ])) + .unwrap(); + assert_eq!(service.layout().sections[0].weight, before_collapse); +} + +#[test] +fn allocated_pair_rejects_hostile_shares_and_bounds_atomically_and_handles_large_legacy_weights() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + open(&mut service, "two", "second"); + for (first_weight, second_weight) in [(f32::NAN, 0.5), (0.5, f32::INFINITY), (-0.1, 1.1), (0.0, 0.0)] { + reject( + &mut service, + vec![Mutation::ResizeAllocatedPair { + first: section("first"), + second: section("second"), + first_size: size(280.0, 120.0), + second_size: size(280.0, 680.0), + first_weight, + second_weight, + other_weight_scale: 1.0, + prefer_allocated: false, + }], + Rule::Bounds, + ); + } + reject( + &mut service, + vec![Mutation::ResizeAllocatedPair { + first: section("first"), + second: section("second"), + first_size: size(280.0, 119.0), + second_size: size(280.0, 681.0), + first_weight: 0.0, + second_weight: 1.0, + other_weight_scale: 1.0, + prefer_allocated: false, + }], + Rule::Bounds, + ); + let mut large = service.layout().clone(); + for group in &mut large.sections { + group.weight = MAX_LOGICAL; + } + let mut large = LayoutService::new(service.registry().clone(), large, HostCapabilities::default()).unwrap(); + assert_eq!(normalized_pair_weights(large.layout(), §ion("first"), §ion("second")).unwrap(), (0.5, 0.5)); + large + .dispatch(transaction(vec![Mutation::ResizeAllocatedPair { + first: section("first"), + second: section("second"), + first_size: size(280.0, 120.0), + second_size: size(280.0, 680.0), + first_weight: 0.0, + second_weight: 1.0, + other_weight_scale: 1.0, + prefer_allocated: false, + }])) + .unwrap(); + assert_eq!(large.layout().sections.iter().map(|s| s.weight).collect::>(), vec![0.0, 1.0]); + let mut zero = service.layout().clone(); + for group in &mut zero.sections { + group.weight = 0.0; + } + for p in &mut zero.instances { + p.memory.weight = 0.0; + } + assert_eq!(normalized_pair_weights(&zero, §ion("first"), §ion("second")).unwrap_err().rule, Rule::Bounds); +} + +#[test] +fn allocated_bottom_pair_reaches_minimum_in_rtl_with_fractional_actual_sizes() { + let mut service = fixture_service(false).unwrap(); + service + .dispatch(transaction(vec![ + fixture_open("fixture.log", "one", "first", Zone::Bottom, 0).unwrap(), + fixture_open("fixture.log", "two", "second", Zone::Bottom, 1).unwrap(), + ])) + .unwrap(); + let mut env = allocated_pair_environment(&service, 600.0); + env.direction = Direction::Rtl; + env.capacity.size.width = 800.5; + service + .dispatch(transaction(vec![Mutation::ResizeAllocatedPair { + first: section("first"), + second: section("second"), + first_size: size(160.0, 240.0), + second_size: size(640.5, 240.0), + first_weight: 0.0, + second_weight: 1.0, + other_weight_scale: 1.0, + prefer_allocated: false, + }])) + .unwrap(); + let geometry = allocate_layout(service.layout(), service.registry(), &env).unwrap(); + assert!((geometry.sections[0].outer.size.width - 160.0).abs() < 0.001); + assert!((geometry.sections[1].outer.size.width - 640.5).abs() < 0.001); + assert!(geometry.sections[0].outer.origin.x > geometry.sections[1].outer.origin.x); + assert_eq!(geometry.sections[1].outer.origin.x, env.capacity.origin.x); +} + +#[test] +fn allocated_pair_normalizes_collapsed_and_unavailable_surrounding_sections_without_resizing_them() { + let mut service = fixture_service(false).unwrap(); + for (instance, group) in [("one", "first"), ("two", "second"), ("folded", "folded"), ("dormant", "dormant")] { + open(&mut service, instance, group); + } + service.dispatch(transaction(vec![Mutation::Collapse { section: section("folded"), collapsed: true }])).unwrap(); + service.set_availability([(id("dormant"), Availability::Unavailable { reason: "owner unavailable".into() })].into()).unwrap(); + let mut env = allocated_pair_environment(&service, 800.0); + env.available.retain(|instance| *instance != id("dormant")); + let before = allocate_layout(service.layout(), service.registry(), &env).unwrap(); + let shares = normalized_pair_weights(service.layout(), §ion("first"), §ion("second")).unwrap(); + service + .dispatch(transaction(vec![Mutation::ResizeAllocatedPair { + first: section("first"), + second: section("second"), + first_size: size(280.0, 120.0), + second_size: size(280.0, 660.0), + first_weight: 0.0, + second_weight: shares.0 + shares.1, + other_weight_scale: 1.0, + prefer_allocated: false, + }])) + .unwrap(); + let after = allocate_layout(service.layout(), service.registry(), &env).unwrap(); + assert_eq!(after.sections.len(), 3); + assert_eq!(after.sections[2].outer, before.sections[2].outer); + assert_eq!(service.layout().section(§ion("folded")).unwrap().weight, 0.25); + assert_eq!(service.layout().section(§ion("dormant")).unwrap().weight, 0.25); + assert_eq!(service.layout().section(§ion("dormant")).unwrap().size, size(280.0, 240.0)); +} + +fn legacy_instance_wire( + instance: &str, + kind: &str, + group: &str, + location: serde_json::Value, + preferred: Size, + index: usize, + requested_open: bool, +) -> serde_json::Value { + serde_json::json!({"id":instance,"kind":kind,"requested_open":requested_open,"memory":{ + "section":group,"location":location,"section_index":index,"tab_index":0,"size":preferred,"collapsed":false + }}) +} + +fn legacy_section_wire(group: &str, instance: &str, location: serde_json::Value, preferred: Size) -> serde_json::Value { + serde_json::json!({"id":group,"location":location,"tabs":[instance],"active":instance,"size":preferred,"collapsed":false}) +} + +#[test] +fn complete_v1_order_splits_compatible_live_peers_around_a_disjoint_dormant_section() { + use serde_json::json; + let mut registry = synthetic_registry().unwrap(); + for (kind, min, preferred, max) in [("fixture.narrow", 160.0, 200.0, 240.0), ("extension.wide", 360.0, 400.0, 440.0)] { + let mut spec = registry.get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + spec.kind = PanelKind::new(kind).unwrap(); + spec.min_size.width = min; + spec.default_size.width = preferred; + spec.max_size.width = max; + registry.register(spec).unwrap(); + } + let dock = json!({"type":"dock","zone":"left"}); + let mut raw: serde_json::Value = serde_json::from_slice(FIXTURE_LAYOUT_V1).unwrap(); + raw["layout"]["instances"] = json!([ + legacy_instance_wire("a", "fixture.narrow", "a-section", dock.clone(), size(200.0, 240.0), 0, true), + legacy_instance_wire("c", "fixture.narrow", "c-section", dock.clone(), size(200.0, 240.0), 2, true) + ]); + raw["layout"]["sections"] = json!([ + legacy_section_wire("a-section", "a", dock.clone(), size(200.0, 240.0)), + legacy_section_wire("c-section", "c", dock.clone(), size(200.0, 240.0)) + ]); + let mut pending = legacy_instance_wire("b", "extension.wide", "b-section", dock.clone(), size(400.0, 240.0), 1, true); + pending["future_payload"] = json!({"keep":"draft"}); + raw["quarantine"] = json!([{"instance":"b","kind":"extension.wide","section":"b-section","instance_data":pending}]); + let mut snapshot = legacy_section_wire("b-section", "b", dock, size(400.0, 240.0)); + snapshot["location"]["future_monitor"] = json!({"keep":"monitor"}); + raw["section_snapshots"] = json!({"b-section":{"index":1,"data":snapshot}}); + raw["section_order"] = json!(["a-section", "b-section", "c-section"]); + let bytes = serde_json::to_vec(&raw).unwrap(); + let mut absent = PanelRegistry::default(); + for spec in registry.specs().filter(|spec| spec.kind.0 != "extension.wide") { + absent.register(spec.clone()).unwrap(); + } + for current in [®istry, &absent] { + let loaded = decode(&bytes, current, &persistence_fallback()).unwrap(); + assert!(loaded.notice.is_none(), "{:?}", loaded.notice); + assert_eq!(loaded.envelope.retained_v1_bytes(), Some(bytes.as_slice())); + let mut envelope = loaded.envelope; + restore_quarantine(&mut envelope, ®istry).unwrap(); + assert!(envelope.quarantine.is_empty()); + assert_eq!( + envelope.layout.sections.iter().map(|s| s.id.clone()).collect::>(), + vec![section("a-section"), section("b-section"), section("c-section")] + ); + assert_eq!(envelope.layout.columns.iter().map(|c| c.width).collect::>(), vec![200.0, 400.0, 200.0]); + assert_eq!( + envelope.layout.sections.iter().map(|s| s.column.clone().unwrap()).collect::>(), + envelope.layout.columns.iter().map(|c| c.id.clone()).collect::>() + ); + assert_eq!(envelope.retained_data[&id("b")]["instance"]["future_payload"]["keep"], "draft"); + assert_eq!(envelope.section_snapshots[§ion("b-section")].data["location"]["future_monitor"]["keep"], "monitor"); + } +} + +#[test] +fn closed_quarantine_section_and_native_return_reservations_reject_unrelated_commands_then_restore() { + use serde_json::json; + for native_memory in [false, true] { + let registry = synthetic_registry().unwrap(); + let mut raw: serde_json::Value = serde_json::from_slice(FIXTURE_LAYOUT_V1).unwrap(); + raw["layout"]["instances"] = json!([]); + raw["layout"]["sections"] = json!([]); + raw["section_order"] = json!([]); + let location = if native_memory { + json!({"type":"window","host":"remembered-host","origin":{"x":20,"y":30}, + "return_to":{"zone":"left","index":0,"section":"section-1","size":{"width":280,"height":240},"collapsed":false}}) + } else { + json!({"type":"floating","origin":{"x":20,"y":30}}) + }; + let remembered = if native_memory { "native-memory" } else { "section-1" }; + let pending = legacy_instance_wire("extension", "extension.panel", remembered, location, size(280.0, 240.0), 0, false); + raw["quarantine"] = json!([{"instance":"extension","kind":"extension.panel","section":null,"instance_data":pending}]); + let loaded = decode(&serde_json::to_vec(&raw).unwrap(), ®istry, &persistence_fallback()).unwrap(); + assert!(loaded.notice.is_none()); + let envelope = loaded.envelope; + let service = LayoutService::new(registry.clone(), envelope.layout.clone(), HostCapabilities::default()).unwrap(); + let mut catalogue = commands::InMemoryCatalogue::default(); + catalogue.remember(&envelope, None, ®istry).unwrap(); + let mut backend = commands::InMemoryPanelBackend::new(service, catalogue); + let before = backend.service.inspect(); + let command = json!({"kind":"fixture.log","instance":"unrelated","destination":{"type":"new_section","section":"section-1","index":0, + "location":{"type":"floating","origin":{"x":40,"y":40}},"size":{"width":280,"height":240}}}); + assert_eq!(backend.execute("panel.open", &command).unwrap_err().rule, Rule::DuplicateId); + assert_eq!(backend.service.inspect(), before); + let mut grown = registry.clone(); + let mut spec = registry.get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + spec.kind = PanelKind::new("extension.panel").unwrap(); + grown.register(spec).unwrap(); + let mut restored = envelope; + restore_quarantine(&mut restored, &grown).unwrap(); + assert!(restored.quarantine.is_empty()); + assert!(!restored.layout.instance(&id("extension")).unwrap().requested_open); + if !native_memory { + let mut service = LayoutService::new(grown.clone(), restored.layout.clone(), HostCapabilities::default()).unwrap(); + service + .dispatch(transaction(vec![Mutation::Open { + kind: PanelKind::new("extension.panel").unwrap(), + instance: id("extension"), + destination: None, + }])) + .unwrap(); + assert_eq!(service.layout().containing(&id("extension")).unwrap().id, section("section-1")); + with_live_layout(&restored, service.layout().clone(), &grown).unwrap(); + } + } +} + +#[test] +fn missing_v1_native_return_weights_use_saved_extent_for_live_closed_and_redocked_groups() { + use serde_json::json; + let registry = synthetic_registry().unwrap(); + let dock = json!({"type":"dock","zone":"left"}); + let native_location = json!({"type":"window","host":"host","origin":{"x":20,"y":30},"return_to":{ + "zone":"left","section":"returned","index":1,"size":{"width":280,"height":360},"collapsed":false}}); + let closed_location = json!({"type":"window","host":"closed-host","origin":{"x":20,"y":30},"return_to":{ + "zone":"left","section":"closed-return","index":2,"size":{"width":280,"height":300},"collapsed":false}}); + let mut raw: serde_json::Value = serde_json::from_slice(FIXTURE_LAYOUT_V1).unwrap(); + raw["layout"]["instances"] = json!([ + legacy_instance_wire("sibling", "fixture.log", "sibling", dock.clone(), size(280.0, 240.0), 0, true), + legacy_instance_wire("native", "fixture.log", "native", native_location.clone(), size(280.0, 360.0), 1, true), + legacy_instance_wire("closed", "fixture.log", "closed", closed_location, size(280.0, 300.0), 2, false) + ]); + raw["layout"]["sections"] = json!([ + legacy_section_wire("sibling", "sibling", dock, size(280.0, 240.0)), + legacy_section_wire("native", "native", native_location, size(280.0, 360.0)) + ]); + raw["section_order"] = json!(["sibling", "native"]); + let loaded = decode(&serde_json::to_vec(&raw).unwrap(), ®istry, &persistence_fallback()).unwrap(); + assert!(loaded.notice.is_none()); + for (name, expected) in [("native", 360.0), ("closed", 300.0)] { + let SectionLocation::Window { return_to, .. } = &loaded.envelope.layout.instance(&id(name)).unwrap().memory.location else { + panic!("native memory"); + }; + assert_eq!(return_to.weight, expected); + } + let mut service = LayoutService::new(registry, loaded.envelope.layout, HostCapabilities::default()).unwrap(); + service.dispatch(transaction(vec![Mutation::NativeClose { host: HostId::new("host").unwrap() }])).unwrap(); + assert_eq!(service.layout().section(§ion("returned")).unwrap().weight, 360.0); + assert_eq!(service.layout().section(§ion("sibling")).unwrap().weight, 240.0); +} + +#[test] +fn unchanged_snapshot_refresh_preserves_nested_opaque_locations_and_current_known_fields() { + use serde_json::json; + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + let registry = service.registry().clone(); + let mut envelope = LayoutEnvelope::new(service.layout().clone()); + let mut data = serde_json::to_value(&envelope.layout.sections[0]).unwrap(); + data["location"]["future_monitor"] = json!({"id":"monitor-a","dpi":{"scale":2.0}}); + data["size"]["future_units"] = json!({"keep":"logical"}); + envelope.section_snapshots.insert(section("first"), SectionSnapshot { data, index: 0, projected: None }); + let bytes = encode(&envelope, ®istry).unwrap(); + let loaded = decode(&bytes, ®istry, &persistence_fallback()).unwrap(); + assert!(loaded.notice.is_none()); + let unchanged = with_live_layout(&loaded.envelope, loaded.envelope.layout.clone(), ®istry).unwrap(); + let reloaded = decode(&encode(&unchanged, ®istry).unwrap(), ®istry, &persistence_fallback()).unwrap(); + assert!(reloaded.notice.is_none()); + assert_eq!(reloaded.envelope.section_snapshots[§ion("first")].data["location"]["future_monitor"]["dpi"]["scale"], 2.0); + assert_eq!(reloaded.envelope.section_snapshots[§ion("first")].data["size"]["future_units"]["keep"], "logical"); + service.dispatch(transaction(vec![Mutation::SetSize { section: section("first"), size: size(300.0, 260.0) }])).unwrap(); + let edited = with_live_layout(&reloaded.envelope, service.layout().clone(), ®istry).unwrap(); + assert_eq!(edited.section_snapshots[§ion("first")].data["size"]["width"], 300.0); + assert_eq!(edited.section_snapshots[§ion("first")].data["size"]["future_units"]["keep"], "logical"); + assert_eq!(edited.section_snapshots[§ion("first")].data["location"]["future_monitor"]["id"], "monitor-a"); +} + +#[test] +fn header_action_accepts_the_available_fallback_without_rewriting_saved_activation() { + let mut registry = synthetic_registry().unwrap(); + let mut spec = registry.get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + spec.kind = PanelKind::new("fixture.fallback").unwrap(); + spec.header_actions = vec![HeaderActionSpec { id: ControlId::new("refresh").unwrap(), label_key: "ui.refresh".into(), icon: "restore".into() }]; + registry.register(spec).unwrap(); + let mut service = + LayoutService::new(registry, Layout::empty(WorkspaceId::new("fixture.workspace").unwrap()), HostCapabilities::default()).unwrap(); + open(&mut service, "unavailable-active", "group"); + service + .dispatch(transaction(vec![Mutation::Open { + kind: PanelKind::new("fixture.fallback").unwrap(), + instance: id("fallback"), + destination: Some(Destination::JoinTab { section: section("group"), index: 1 }), + }])) + .unwrap(); + service.set_availability([(id("unavailable-active"), Availability::Unavailable { reason: "owner unavailable".into() })].into()).unwrap(); + let availability = [(id("unavailable-active"), Availability::Unavailable { reason: "owner unavailable".into() })].into(); + assert_eq!(presented_tab(&service.layout().sections[0], &availability), Some(&id("fallback"))); + assert_eq!(presented_tab(&service.layout().sections[0], &AvailabilityMap::new()), Some(&id("unavailable-active"))); + let all_unavailable = [ + (id("unavailable-active"), Availability::Unavailable { reason: "owner unavailable".into() }), + (id("fallback"), Availability::Unavailable { reason: "owner unavailable".into() }), + ] + .into(); + assert_eq!(presented_tab(&service.layout().sections[0], &all_unavailable), None); + let reply = + service.dispatch(transaction(vec![Mutation::HeaderAction { instance: id("fallback"), action: ControlId::new("refresh").unwrap() }])).unwrap(); + assert_eq!(reply.effects, vec![HostEffect::HeaderAction { instance: id("fallback"), action: ControlId::new("refresh").unwrap() }]); + assert_eq!(service.layout().sections[0].active, id("unavailable-active")); +} + +#[test] +fn explicit_side_extent_means_requested_height_and_survives_sole_stack_and_collapse_transitions() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + open(&mut service, "two", "second"); + let mut env = allocated_pair_environment(&service, 800.0); + env.gap = 4.0; + let initial = allocate_layout(service.layout(), service.registry(), &env).unwrap(); + assert_eq!(initial.sections.iter().map(|s| s.outer.size.height).collect::>(), vec![398.0, 398.0]); + let weights: Vec<_> = service.layout().sections.iter().map(|s| s.weight).collect(); + let before = service.inspect(); + let prepared = service.prepare(transaction(vec![Mutation::SetSize { section: section("first"), size: size(280.0, 400.0) }])).unwrap(); + assert_eq!(service.inspect(), before); + assert_eq!(prepared.layout().sections[0].preferred_extent, Some(400.0)); + assert_eq!(prepared.layout().sections.iter().map(|s| s.weight).collect::>(), weights); + let shown = allocate_layout(prepared.layout(), service.registry(), &env).unwrap(); + assert_eq!( + shown.sections.iter().map(|s| s.outer.size.height).collect::>(), + vec![400.0, 396.0], + "requested feasible dimensions, not a derived weight ratio" + ); + service.commit(prepared).unwrap(); + assert_eq!(allocate_layout(service.layout(), service.registry(), &env).unwrap(), shown); + service.dispatch(transaction(vec![Mutation::Collapse { section: section("first"), collapsed: true }])).unwrap(); + let folded = allocate_layout(service.layout(), service.registry(), &env).unwrap(); + assert_eq!(folded.sections[0].outer.size.height, env.header_height); + assert_eq!(folded.sections[1].outer.size.height, 776.0); + service + .dispatch(transaction(vec![Mutation::Collapse { section: section("first"), collapsed: false }, Mutation::Close { instance: id("two") }])) + .unwrap(); + service + .dispatch(transaction(vec![Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("tab-peer"), + destination: Some(Destination::JoinTab { section: section("first"), index: 1 }), + }])) + .unwrap(); + env.available.push(id("tab-peer")); + for request in allocation_measure_requests(service.layout(), service.registry(), &env).unwrap() { + assert_eq!(request.chrome_height, env.header_height + env.footer_height, "tab groups share one header row"); + env.content.push(SideContentMeasure { request, needed_height: 180.0, policy: SideHeightPolicy::Content }); + } + let sole = allocate_layout(service.layout(), service.registry(), &env).unwrap(); + assert_eq!(sole.sections[0].outer.size.height, 180.0, "sole Content uses captured needed height despite the stored stack request"); + assert_eq!(service.layout().sections[0].preferred_extent, Some(400.0)); + service + .dispatch(transaction(vec![Mutation::Open { kind: PanelKind::new("fixture.log").unwrap(), instance: id("two"), destination: None }])) + .unwrap(); + let stacked = allocate_layout(service.layout(), service.registry(), &env).unwrap(); + assert_eq!(stacked.sections.iter().map(|s| s.outer.size.height).collect::>(), vec![400.0, 396.0]); + assert_eq!(service.layout().sections.iter().map(|s| s.weight).collect::>(), weights); + let mut tiny = env; + tiny.capacity.size.height = 150.0; + let overflow = allocate_layout(service.layout(), service.registry(), &tiny).unwrap(); + assert!(overflow.sections.iter().all(|s| s.outer.size.height >= 120.0)); + assert_eq!(service.layout().sections[0].preferred_extent, Some(400.0)); +} + +#[test] +fn explicit_bottom_extent_uses_width_without_replacing_surplus_proportions() { + let mut service = fixture_service(false).unwrap(); + service + .dispatch(transaction(vec![ + fixture_open("fixture.log", "one", "first", Zone::Bottom, 0).unwrap(), + fixture_open("fixture.log", "two", "second", Zone::Bottom, 1).unwrap(), + ])) + .unwrap(); + let mut env = allocated_pair_environment(&service, 600.0); + env.capacity.size.width = 800.0; + env.gap = 4.0; + env.direction = Direction::Rtl; + let weights: Vec<_> = service.layout().sections.iter().map(|s| s.weight).collect(); + service.dispatch(transaction(vec![Mutation::SetSize { section: section("first"), size: size(400.0, 240.0) }])).unwrap(); + let geometry = allocate_layout(service.layout(), service.registry(), &env).unwrap(); + assert_eq!(geometry.sections.iter().map(|s| s.outer.size.width).collect::>(), vec![400.0, 396.0]); + assert_eq!(service.layout().sections[0].preferred_extent, Some(400.0)); + assert_eq!(service.layout().sections.iter().map(|s| s.weight).collect::>(), weights); +} + +#[test] +fn dock_moves_and_explicit_reopens_clear_cross_axis_extent_intent_but_preserve_same_axis_intent() { + for (source, target) in [(Zone::Left, Zone::Bottom), (Zone::Bottom, Zone::Left), (Zone::Left, Zone::Right), (Zone::Bottom, Zone::Bottom)] { + for closed in [false, true] { + for reuse_section in [false, true] { + let mut service = fixture_service(false).unwrap(); + service + .dispatch(transaction(vec![ + fixture_open("fixture.log", "one", "source", source, 0).unwrap(), + fixture_open("fixture.log", "peer", "peer", target, 1).unwrap(), + Mutation::SetSize { section: section("source"), size: size(400.0, 400.0) }, + ])) + .unwrap(); + let saved = service.layout().containing(&id("one")).unwrap(); + let inherited = (saved.preferred_extent, saved.extent_priority); + assert_eq!(inherited, (Some(400.0), 1)); + if closed { + service.dispatch(transaction(vec![Mutation::Close { instance: id("one") }])).unwrap(); + } + let group = section(if reuse_section { "source" } else { "landing" }); + let destination = Destination::NewSection { + section: group.clone(), + index: 1, + location: SectionLocation::Dock { zone: target }, + size: size(280.0, 240.0), + }; + let mutation = if closed { + Mutation::Open { kind: PanelKind::new("fixture.log").unwrap(), instance: id("one"), destination: Some(destination) } + } else { + Mutation::Move { instance: id("one"), destination } + }; + service.dispatch(transaction(vec![mutation])).unwrap(); + let expected = if source.side() == target.side() { inherited } else { (None, 0) }; + let moved = service.layout().section(&group).unwrap(); + let memory = &service.layout().instance(&id("one")).unwrap().memory; + assert_eq!((moved.preferred_extent, moved.extent_priority), expected); + assert_eq!((memory.preferred_extent, memory.extent_priority), expected); + let mut env = allocated_pair_environment(&service, 800.0); + env.capacity.size.width = 800.0; + env.gap = 4.0; + let geometry = allocate_layout(service.layout(), service.registry(), &env).unwrap(); + assert_eq!(geometry.sections.len(), 2); + for actual in &geometry.sections { + let expected_extent = if expected.0.is_none() { + 398.0 + } else if actual.section == group { + 400.0 + } else { + 396.0 + }; + assert_eq!(dock_stack_extent(target, actual.outer.size), Some(expected_extent)); + } + } + } + } +} + +#[test] +fn relative_moves_and_explicit_reopens_clear_bottom_width_intent_in_side_sections() { + for placement in [RelativePlacement::Above, RelativePlacement::Below, RelativePlacement::BeforeColumn, RelativePlacement::AfterColumn] { + for closed in [false, true] { + let mut service = fixture_service(false).unwrap(); + service + .dispatch(transaction(vec![ + fixture_open("fixture.log", "anchor", "anchor", Zone::Left, 0).unwrap(), + fixture_open("fixture.log", "one", "source", Zone::Bottom, 1).unwrap(), + Mutation::SetSize { section: section("source"), size: size(400.0, 240.0) }, + ])) + .unwrap(); + if closed { + service.dispatch(transaction(vec![Mutation::Close { instance: id("one") }])).unwrap(); + } + let destination = Destination::Relative { + section: section("anchor"), + placement, + new_section: section("landing"), + new_column: matches!(placement, RelativePlacement::BeforeColumn | RelativePlacement::AfterColumn) + .then(|| ColumnId::new("landing-column").unwrap()), + size: size(280.0, 240.0), + }; + let mutation = if closed { + Mutation::Open { kind: PanelKind::new("fixture.log").unwrap(), instance: id("one"), destination: Some(destination) } + } else { + Mutation::Move { instance: id("one"), destination } + }; + service.dispatch(transaction(vec![mutation])).unwrap(); + let moved = service.layout().section(§ion("landing")).unwrap(); + let memory = &service.layout().instance(&id("one")).unwrap().memory; + assert_eq!((moved.preferred_extent, moved.extent_priority), (None, 0)); + assert_eq!((memory.preferred_extent, memory.extent_priority), (None, 0)); + } + } +} + +#[test] +fn native_return_extent_inheritance_checks_dock_axes_and_keeps_explicit_return_intent() { + for target in [Zone::Bottom, Zone::Right] { + for explicit in [false, true] { + for closed in [false, true] { + let mut service = fixture_service(true).unwrap(); + open(&mut service, "one", "source"); + service.dispatch(transaction(vec![Mutation::SetSize { section: section("source"), size: size(280.0, 400.0) }])).unwrap(); + if closed { + service.dispatch(transaction(vec![Mutation::Close { instance: id("one") }])).unwrap(); + } + let destination = Destination::NewSection { + section: section("native"), + index: 0, + size: size(320.0, 280.0), + location: SectionLocation::Window { + host: HostId::new("host").unwrap(), + origin: Point { x: 20.0, y: 30.0 }, + return_to: DockReturn { + zone: target, + index: 0, + size: size(280.0, 240.0), + collapsed: false, + section: None, + column: None, + column_index: 0, + column_width: None, + weight: 1.0, + join: None, + preferred_extent: explicit.then_some(500.0), + extent_priority: if explicit { 7 } else { 0 }, + }, + }, + }; + let mutation = if closed { + Mutation::Open { kind: PanelKind::new("fixture.log").unwrap(), instance: id("one"), destination: Some(destination) } + } else { + Mutation::Move { instance: id("one"), destination } + }; + service.dispatch(transaction(vec![mutation])).unwrap(); + let native = service.layout().containing(&id("one")).unwrap(); + assert_eq!((native.preferred_extent, native.extent_priority), (Some(400.0), 1)); + let SectionLocation::Window { return_to, .. } = &native.location else { + panic!("native section"); + }; + let expected = if explicit { + (Some(500.0), 7) + } else if target.side() { + (Some(400.0), 1) + } else { + (None, 0) + }; + assert_eq!((return_to.preferred_extent, return_to.extent_priority), expected); + assert_eq!(service.layout().instance(&id("one")).unwrap().memory.location, native.location); + service.dispatch(transaction(vec![Mutation::NativeClose { host: HostId::new("host").unwrap() }])).unwrap(); + let returned = service.layout().containing(&id("one")).unwrap(); + let memory = &service.layout().instance(&id("one")).unwrap().memory; + assert_eq!((returned.preferred_extent, returned.extent_priority), expected); + assert_eq!((memory.preferred_extent, memory.extent_priority), expected); + } + } + } +} + +#[test] +fn preferred_extent_defaults_omit_wire_fields_and_reject_hostile_values_in_live_and_retained_records() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + assert_eq!(dock_stack_extent(Zone::Left, size(280.0, 400.0)), Some(400.0)); + assert_eq!(dock_stack_extent(Zone::Bottom, size(280.0, 400.0)), Some(280.0)); + assert_eq!(dock_stack_extent(Zone::Window, size(280.0, 400.0)), None); + let wire = serde_json::to_value(service.layout()).unwrap(); + assert!(wire["sections"][0].get("preferred_extent").is_none()); + assert!(wire["instances"][0]["memory"].get("preferred_extent").is_none()); + let mut null_wire = serde_json::to_value(LayoutEnvelope::new(service.layout().clone())).unwrap(); + null_wire["layout"]["sections"][0]["preferred_extent"] = serde_json::Value::Null; + null_wire["layout"]["instances"][0]["memory"]["preferred_extent"] = serde_json::Value::Null; + let normalized = decode(&serde_json::to_vec(&null_wire).unwrap(), service.registry(), &persistence_fallback()).unwrap(); + assert!(normalized.notice.is_none()); + let normalized: serde_json::Value = serde_json::from_slice(&encode(&normalized.envelope, service.registry()).unwrap()).unwrap(); + assert!(normalized["layout"]["sections"][0].get("preferred_extent").is_none()); + assert!(normalized["layout"]["instances"][0]["memory"].get("preferred_extent").is_none()); + for bad in [0.0, -1.0, f32::NAN, f32::INFINITY, MAX_LOGICAL + 1.0] { + assert_eq!(validate_preferred_extent(Some(bad)).unwrap_err().rule, Rule::Bounds); + let mut broken = service.layout().clone(); + broken.sections[0].preferred_extent = Some(bad); + assert_eq!(validate(&broken, service.registry()).unwrap_err().rule, Rule::Bounds); + let mut broken = service.layout().clone(); + broken.instances[0].memory.preferred_extent = Some(bad); + assert_eq!(validate(&broken, service.registry()).unwrap_err().rule, Rule::Bounds); + let native = DockReturn { + zone: Zone::Left, + index: 0, + size: size(280.0, 240.0), + collapsed: false, + section: None, + column: None, + column_index: 0, + column_width: None, + weight: 1.0, + join: None, + preferred_extent: Some(bad), + extent_priority: 0, + }; + assert_eq!(native.validate().unwrap_err().rule, Rule::Bounds); + } + let fallback = persistence_fallback(); + let migrated = decode(FIXTURE_LAYOUT_V1, service.registry(), &fallback).unwrap(); + assert!(migrated.notice.is_none()); + assert_eq!(migrated.envelope.layout.sections[0].weight, 240.0); + assert_eq!(migrated.envelope.layout.sections[0].preferred_extent, None); + assert_eq!(migrated.envelope.layout.instances[0].memory.preferred_extent, None); + let mut snapshot = serde_json::to_value(&service.layout().sections[0]).unwrap(); + snapshot["preferred_extent"] = serde_json::json!(0); + let mut envelope = LayoutEnvelope::new(service.layout().clone()); + envelope.section_snapshots.insert(section("first"), SectionSnapshot { data: snapshot, index: 0, projected: None }); + assert_eq!(encode(&envelope, service.registry()).unwrap_err().rule, Rule::Bounds); +} + +#[test] +fn paired_resize_and_reset_clear_explicit_overrides_without_snapshot_resurrection() { + for operation in 0..3 { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + open(&mut service, "two", "second"); + service + .dispatch(transaction(vec![ + Mutation::SetSize { section: section("first"), size: size(280.0, 400.0) }, + Mutation::SetSize { section: section("second"), size: size(280.0, 396.0) }, + ])) + .unwrap(); + let mut envelope = LayoutEnvelope::new(service.layout().clone()); + for (index, group) in service.layout().sections.iter().enumerate() { + let mut data = serde_json::to_value(group).unwrap(); + data["location"]["future_monitor"] = serde_json::json!({"keep":"monitor intent"}); + envelope.section_snapshots.insert(group.id.clone(), SectionSnapshot { data, index, projected: Some(group.clone()) }); + } + let mutation = match operation { + 0 => Mutation::ResizeAllocatedPair { + first: section("first"), + second: section("second"), + first_size: size(280.0, 120.0), + second_size: size(280.0, 676.0), + first_weight: 0.0, + second_weight: 1.0, + other_weight_scale: 1.0, + prefer_allocated: false, + }, + 1 => Mutation::ResetPair { first: section("first"), second: section("second") }, + _ => Mutation::ResizePair { + first: section("first"), + second: section("second"), + first_size: size(280.0, 120.0), + second_size: size(280.0, 676.0), + }, + }; + service.dispatch(transaction(vec![mutation])).unwrap(); + assert!(service.layout().sections.iter().all(|s| s.preferred_extent.is_none())); + assert!(service.layout().instances.iter().all(|p| p.memory.preferred_extent.is_none())); + assert!(service.layout().sections.iter().all(|s| s.extent_priority == 0)); + assert!(service.layout().instances.iter().all(|p| p.memory.extent_priority == 0)); + let staged = with_live_layout(&envelope, service.layout().clone(), service.registry()).unwrap(); + let bytes = encode(&staged, service.registry()).unwrap(); + let raw: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + for group in ["first", "second"] { + assert!(raw["section_snapshots"][group]["data"].get("preferred_extent").is_none()); + assert!(raw["section_snapshots"][group]["data"].get("extent_priority").is_none()); + assert_eq!(raw["section_snapshots"][group]["data"]["location"]["future_monitor"]["keep"], "monitor intent"); + } + let restored = decode(&bytes, service.registry(), &persistence_fallback()).unwrap(); + assert!(restored.notice.is_none()); + assert!(restored.envelope.layout.sections.iter().all(|s| s.preferred_extent.is_none())); + } +} + +#[test] +fn explicit_extent_survives_native_sizing_closed_quarantine_reopen_and_redock() { + use serde_json::json; + let mut service = fixture_service(true).unwrap(); + open(&mut service, "one", "first"); + open(&mut service, "two", "second"); + service.dispatch(transaction(vec![Mutation::SetSize { section: section("first"), size: size(280.0, 400.0) }])).unwrap(); + let saved_weight = service.layout().sections[0].weight; + let saved_priority = service.layout().sections[0].extent_priority; + service + .dispatch(transaction(vec![Mutation::Move { + instance: id("one"), + destination: Destination::NewSection { + section: section("native"), + index: 1, + size: size(320.0, 280.0), + location: SectionLocation::Window { + host: HostId::new("host").unwrap(), + origin: Point { x: 20.0, y: 30.0 }, + return_to: DockReturn { + zone: Zone::Left, + section: None, + column: None, + column_index: 0, + column_width: None, + index: 0, + size: size(280.0, 400.0), + collapsed: false, + join: None, + weight: 1.0, + preferred_extent: None, + extent_priority: 0, + }, + }, + }, + }])) + .unwrap(); + service.dispatch(transaction(vec![Mutation::SetSize { section: section("native"), size: size(350.0, 300.0) }])).unwrap(); + assert_eq!(service.layout().section(§ion("native")).unwrap().preferred_extent, Some(400.0)); + service.dispatch(transaction(vec![Mutation::Close { instance: id("one") }])).unwrap(); + let mut raw = serde_json::to_value(LayoutEnvelope::new(service.layout().clone())).unwrap(); + raw["layout"]["instances"][0]["kind"] = json!("extension.panel"); + raw["layout"]["instances"][0]["future_preference"] = json!({"keep":"draft"}); + let registry = service.registry().clone(); + let mut loaded = decode(&serde_json::to_vec(&raw).unwrap(), ®istry, &persistence_fallback()).unwrap(); + assert!(loaded.notice.is_none()); + let pending: PanelInstance = serde_json::from_value(loaded.envelope.quarantine[0].instance_data.clone()).unwrap(); + assert_eq!(pending.memory.preferred_extent, Some(400.0)); + assert_eq!(pending.memory.extent_priority, saved_priority); + let SectionLocation::Window { return_to, .. } = &pending.memory.location else { + panic!("native closed memory"); + }; + assert_eq!(return_to.preferred_extent, Some(400.0)); + assert_eq!(return_to.extent_priority, saved_priority); + let mut grown = registry.clone(); + let mut spec = registry.get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + spec.kind = PanelKind::new("extension.panel").unwrap(); + grown.register(spec).unwrap(); + restore_quarantine(&mut loaded.envelope, &grown).unwrap(); + let mut service = LayoutService::new( + grown.clone(), + loaded.envelope.layout.clone(), + HostCapabilities { native_windows: true, max_native_hosts: 8, persistence: true }, + ) + .unwrap(); + service + .dispatch(transaction(vec![Mutation::Open { kind: PanelKind::new("extension.panel").unwrap(), instance: id("one"), destination: None }])) + .unwrap(); + let opened = with_live_layout(&loaded.envelope, service.layout().clone(), &grown).unwrap(); + service.dispatch(transaction(vec![Mutation::NativeClose { host: HostId::new("host").unwrap() }])).unwrap(); + let returned = service.layout().section(§ion("first")).unwrap(); + assert_eq!(returned.preferred_extent, Some(400.0)); + assert_eq!(returned.weight, saved_weight); + let persisted = with_live_layout(&opened, service.layout().clone(), &grown).unwrap(); + assert_eq!(persisted.retained_data[&id("one")]["instance"]["future_preference"]["keep"], "draft"); + assert_eq!(persisted.layout.instance(&id("one")).unwrap().memory.preferred_extent, Some(400.0)); + assert_eq!(persisted.layout.instance(&id("one")).unwrap().memory.extent_priority, saved_priority); +} + +#[test] +fn nested_quarantined_native_column_reservation_rejects_theft_and_allows_owner_redock() { + use commands::LayoutCatalogue; + use serde_json::json; + let mut service = fixture_service(false).unwrap(); + open(&mut service, "anchor", "anchor"); + let registry = service.registry().clone(); + let mut raw = serde_json::to_value(LayoutEnvelope::new(service.layout().clone())).unwrap(); + raw["quarantine"] = json!([{"instance":"extension","kind":"extension.panel","section":null,"instance_data":{ + "id":"extension","kind":"extension.panel","requested_open":false,"memory":{ + "section":"native-memory","section_index":1,"tab_index":0,"size":{"width":280,"height":240},"collapsed":false,"weight":240, + "preferred_extent":350,"location":{"type":"window","host":"return-host","origin":{"x":20,"y":30},"return_to":{ + "section":"return-section","zone":"left","index":1,"column":"column-2","column_index":1,"column_width":280, + "size":{"width":280,"height":240},"collapsed":false,"weight":240,"preferred_extent":350 + }} + } + }}]); + let loaded = decode(&serde_json::to_vec(&raw).unwrap(), ®istry, &persistence_fallback()).unwrap(); + assert!(loaded.notice.is_none()); + let envelope = loaded.envelope; + assert!(envelope.layout.column(&ColumnId::new("column-2").unwrap()).is_err()); + let reserved = reserve_envelope_identities(&envelope).unwrap(); + assert_eq!(next_column_id(&reserved).unwrap(), ColumnId::new("column-3").unwrap()); + let mut catalogue = commands::InMemoryCatalogue::default(); + catalogue.remember(&envelope, None, ®istry).unwrap(); + let mut backend = commands::InMemoryPanelBackend::new(service, catalogue); + let before = backend.service.inspect(); + let stored_before = backend.catalogue.state().export().unwrap(); + assert_eq!(backend.execute("panel.open", &json!({"kind":"fixture.log","instance":"unrelated","destination":{ + "type":"relative","section":"anchor","placement":"after_column","new_section":"intruder","new_column":"column-2","size":{"width":280,"height":240} + }})).unwrap_err().rule, Rule::DuplicateId); + assert_eq!(backend.service.inspect(), before); + assert_eq!(backend.catalogue.state().export().unwrap(), stored_before); + let mut grown = registry.clone(); + let mut spec = registry.get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + spec.kind = PanelKind::new("extension.panel").unwrap(); + grown.register(spec).unwrap(); + let mut envelope = envelope; + restore_quarantine(&mut envelope, &grown).unwrap(); + let mut owner = + LayoutService::new(grown.clone(), envelope.layout.clone(), HostCapabilities { native_windows: true, max_native_hosts: 8, persistence: true }) + .unwrap(); + owner + .dispatch(transaction(vec![Mutation::Open { + kind: PanelKind::new("extension.panel").unwrap(), + instance: id("extension"), + destination: None, + }])) + .unwrap(); + let opened = with_live_layout(&envelope, owner.layout().clone(), &grown).unwrap(); + owner.dispatch(transaction(vec![Mutation::NativeClose { host: HostId::new("return-host").unwrap() }])).unwrap(); + let redocked = with_live_layout(&opened, owner.layout().clone(), &grown).unwrap(); + assert_eq!(redocked.layout.section(§ion("return-section")).unwrap().column, Some(ColumnId::new("column-2").unwrap())); + assert_eq!(redocked.layout.section(§ion("return-section")).unwrap().preferred_extent, Some(350.0)); +} + +#[test] +fn allocated_pair_uncaps_a_member_without_moving_the_third_or_preserving_old_pair_share() { + let mut registry = synthetic_registry().unwrap(); + let mut capped = registry.get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + capped.kind = PanelKind::new("fixture.capped").unwrap(); + capped.default_size.height = 180.0; + capped.max_size.height = 200.0; + registry.register(capped).unwrap(); + let mut service = + LayoutService::new(registry.clone(), Layout::empty(WorkspaceId::new("fixture.workspace").unwrap()), HostCapabilities::default()).unwrap(); + service + .dispatch(transaction(vec![Mutation::Open { + kind: PanelKind::new("fixture.capped").unwrap(), + instance: id("one"), + destination: Some(Destination::NewSection { + section: section("first"), + index: 0, + location: SectionLocation::Dock { zone: Zone::Left }, + size: size(280.0, 180.0), + }), + }])) + .unwrap(); + open(&mut service, "two", "second"); + open(&mut service, "three", "third"); + let mut layout = service.layout().clone(); + for group in &mut layout.sections { + group.weight = 240.0; + } + for panel in &mut layout.instances { + panel.memory.weight = 240.0; + } + let mut service = LayoutService::new(registry, layout, HostCapabilities::default()).unwrap(); + let mut env = allocated_pair_environment(&service, 800.0); + env.gap = 4.0; + let before = allocate_layout(service.layout(), service.registry(), &env).unwrap(); + for (group, expected) in before.sections.iter().zip([200.0, 296.0, 296.0]) { + assert!((group.outer.size.height - expected).abs() < 0.001); + } + let old = normalized_pair_weights(service.layout(), §ion("first"), §ion("second")).unwrap(); + // The third's normalized saved weight doubles. Derive the pair from its + // actual 176 surplus units; this needs a different combined pair share. + let first_weight = (2.0 / 3.0) * 60.0 / 176.0; + let second_weight = (2.0 / 3.0) * 196.0 / 176.0; + assert!((first_weight + second_weight - old.0 - old.1).abs() > 0.01); + let prepared = service + .prepare(transaction(vec![Mutation::ResizeAllocatedPair { + first: section("first"), + second: section("second"), + first_size: size(280.0, 180.0), + second_size: size(280.0, 316.0), + first_weight, + second_weight, + other_weight_scale: 2.0, + prefer_allocated: false, + }])) + .unwrap(); + let shown = allocate_layout(prepared.layout(), service.registry(), &env).unwrap(); + assert!((shown.sections[0].outer.size.height - 180.0).abs() < 0.001); + assert!((shown.sections[1].outer.size.height - 316.0).abs() < 0.001); + assert!((shown.sections[2].outer.size.height - 296.0).abs() < 0.001); + assert!((shown.sections[2].outer.origin.y - before.sections[2].outer.origin.y).abs() < 0.001); + service.commit(prepared).unwrap(); + assert_eq!(allocate_layout(service.layout(), service.registry(), &env).unwrap(), shown); + assert!((service.layout().sections[2].weight - 2.0 / 3.0).abs() < 0.00001); +} + +#[test] +fn allocated_pair_scales_unpaired_closed_and_native_ratios_and_preserves_their_preferences() { + let mut service = fixture_service(true).unwrap(); + for (panel, group) in [("one", "first"), ("two", "second"), ("three", "third"), ("closed", "closed"), ("native", "return")] { + open(&mut service, panel, group); + } + service + .dispatch(transaction(vec![ + Mutation::SetSize { section: section("third"), size: size(280.0, 300.0) }, + Mutation::SetSize { section: section("closed"), size: size(280.0, 350.0) }, + Mutation::SetSize { section: section("return"), size: size(280.0, 400.0) }, + ])) + .unwrap(); + service.dispatch(transaction(vec![Mutation::Close { instance: id("closed") }])).unwrap(); + service + .dispatch(transaction(vec![Mutation::Move { + instance: id("native"), + destination: Destination::NewSection { + section: section("window"), + index: 3, + size: size(280.0, 400.0), + location: SectionLocation::Window { + host: HostId::new("host").unwrap(), + origin: Point { x: 0.0, y: 0.0 }, + return_to: DockReturn { + zone: Zone::Left, + index: 4, + size: size(280.0, 400.0), + collapsed: false, + join: None, + section: None, + column: None, + column_index: 0, + column_width: None, + weight: 240.0, + preferred_extent: None, + extent_priority: 0, + }, + }, + }, + }])) + .unwrap(); + let old = service.layout().clone(); + service + .dispatch(transaction(vec![Mutation::ResizeAllocatedPair { + first: section("first"), + second: section("second"), + first_size: size(280.0, 200.0), + second_size: size(280.0, 300.0), + first_weight: 0.1, + second_weight: 0.2, + other_weight_scale: 2.0, + prefer_allocated: false, + }])) + .unwrap(); + assert_eq!(service.layout().sections[0].weight, 0.1); + assert_eq!(service.layout().sections[1].weight, 0.2); + assert!((service.layout().section(§ion("third")).unwrap().weight - 0.4).abs() < 0.00001); + assert!((service.layout().instance(&id("closed")).unwrap().memory.weight - 0.4).abs() < 0.00001); + let SectionLocation::Window { return_to, .. } = &service.layout().section(§ion("window")).unwrap().location else { + panic!("native retained"); + }; + assert!((return_to.weight - 0.4).abs() < 0.00001); + assert_eq!(return_to.preferred_extent, Some(400.0)); + assert_eq!(service.layout().instance(&id("closed")).unwrap().memory.preferred_extent, Some(350.0)); + assert_eq!(service.layout().section(§ion("third")).unwrap().preferred_extent, Some(300.0)); + assert_eq!(service.layout().section(§ion("third")).unwrap().size, old.section(§ion("third")).unwrap().size); + assert_eq!(service.layout().instance(&id("native")).unwrap().memory.location, service.layout().section(§ion("window")).unwrap().location); +} + +#[test] +fn allocated_pair_skips_unavailable_sections_but_never_a_presented_collapsed_header() { + let mut service = fixture_service(false).unwrap(); + for (panel, group) in [("one", "first"), ("hidden", "middle"), ("two", "second")] { + open(&mut service, panel, group); + } + assert!(normalized_pair_weights(service.layout(), §ion("first"), §ion("second")).is_ok()); + let mutation = Mutation::ResizeAllocatedPair { + first: section("first"), + second: section("second"), + first_size: size(280.0, 180.0), + second_size: size(280.0, 300.0), + first_weight: 0.2, + second_weight: 0.3, + other_weight_scale: 1.0, + prefer_allocated: false, + }; + reject(&mut service, vec![mutation.clone()], Rule::Placement); + service.set_availability([(id("hidden"), Availability::Unavailable { reason: "absent".into() })].into()).unwrap(); + service.dispatch(transaction(vec![mutation.clone()])).unwrap(); + reject( + &mut service, + vec![Mutation::ResizePair { + first: section("first"), + second: section("second"), + first_size: size(280.0, 180.0), + second_size: size(280.0, 300.0), + }], + Rule::Placement, + ); + service.dispatch(transaction(vec![Mutation::Collapse { section: section("middle"), collapsed: true }])).unwrap(); + service.set_availability(AvailabilityMap::new()).unwrap(); + reject(&mut service, vec![mutation.clone()], Rule::Placement); + service.set_availability([(id("hidden"), Availability::Unavailable { reason: "absent".into() })].into()).unwrap(); + service.dispatch(transaction(vec![mutation])).unwrap(); + reject( + &mut service, + vec![Mutation::ResizeAllocatedPair { + first: section("second"), + second: section("first"), + first_size: size(280.0, 300.0), + second_size: size(280.0, 180.0), + first_weight: 0.3, + second_weight: 0.2, + other_weight_scale: 1.0, + prefer_allocated: false, + }], + Rule::Placement, + ); +} + +#[test] +fn allocated_pair_bounds_scale_and_total_without_old_share_equality_and_defaults_scale_on_wire() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + open(&mut service, "two", "second"); + for scale in [0.0, -1.0, f32::NAN, f32::INFINITY, MAX_LOGICAL + 1.0] { + reject( + &mut service, + vec![Mutation::ResizeAllocatedPair { + first: section("first"), + second: section("second"), + first_size: size(280.0, 120.0), + second_size: size(280.0, 680.0), + first_weight: 0.4, + second_weight: 0.4, + other_weight_scale: scale, + prefer_allocated: false, + }], + Rule::Bounds, + ); + } + let mutation: Mutation = serde_json::from_value(serde_json::json!({"type":"resize_allocated_pair","first":"first","second":"second", + "first_size":{"width":280,"height":120},"second_size":{"width":280,"height":680},"first_weight":0.4,"second_weight":0.4})) + .unwrap(); + assert!( + matches!(&mutation, Mutation::ResizeAllocatedPair { other_weight_scale, prefer_allocated, .. } if *other_weight_scale == 1.0 && !prefer_allocated) + ); + service.dispatch(transaction(vec![mutation])).unwrap(); + assert_eq!(service.layout().sections.iter().map(|s| s.weight).collect::>(), vec![0.4, 0.4]); + open(&mut service, "three", "third"); + let mut layout = service.layout().clone(); + for group in &mut layout.sections { + group.weight = if group.id == section("third") { MAX_LOGICAL } else { 0.000001 }; + } + for panel in &mut layout.instances { + panel.memory.weight = if panel.id == id("three") { MAX_LOGICAL } else { 0.000001 }; + } + let mut service = LayoutService::new(service.registry().clone(), layout, HostCapabilities::default()).unwrap(); + reject( + &mut service, + vec![Mutation::ResizeAllocatedPair { + first: section("first"), + second: section("second"), + first_size: size(280.0, 120.0), + second_size: size(280.0, 680.0), + first_weight: 1.0, + second_weight: 1.0, + other_weight_scale: MAX_LOGICAL, + prefer_allocated: false, + }], + Rule::Bounds, + ); +} + +#[test] +fn reservation_aware_prepare_skips_external_ids_and_rejects_explicit_theft_without_mutation() { + let mut service = fixture_service(false).unwrap(); + let sections = [section("section-1")].into(); + let columns = [ColumnId::new("column-1").unwrap()].into(); + let before = service.inspect(); + let action = transaction(vec![fixture_open("fixture.log", "one", "first", Zone::Left, 0).unwrap()]); + let prepared = service.prepare_with_reservations(action.clone(), §ions, &columns).unwrap(); + assert_eq!(prepared.layout().columns[0].id, ColumnId::new("column-2").unwrap()); + assert_eq!(service.prepare_with_reservations(action, §ions, &columns).unwrap().layout(), prepared.layout()); + assert_eq!(service.inspect(), before); + assert_eq!( + service + .prepare_with_reservations( + transaction(vec![fixture_open("fixture.log", "thief", "section-1", Zone::Left, 0).unwrap()]), + §ions, + &columns + ) + .err() + .unwrap() + .rule, + Rule::DuplicateId + ); + service.commit(prepared).unwrap(); + let before = service.inspect(); + let theft = transaction(vec![Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("thief"), + destination: Some(Destination::Relative { + section: section("first"), + placement: RelativePlacement::BeforeColumn, + new_section: section("new"), + new_column: Some(ColumnId::new("column-1").unwrap()), + size: size(280.0, 240.0), + }), + }]); + assert_eq!(service.prepare_with_reservations(theft, §ions, &columns).err().unwrap().rule, Rule::DuplicateId); + let prepared = service + .prepare_with_reservations(transaction(vec![fixture_open("fixture.log", "right", "right", Zone::Right, 1).unwrap()]), §ions, &columns) + .unwrap(); + assert_eq!(prepared.layout().section(§ion("right")).unwrap().column, Some(ColumnId::new("column-3").unwrap())); + assert_eq!(service.inspect(), before); +} + +#[test] +fn replacement_context_admits_typed_owners_and_refuses_changed_owner_sets() { + let mut source = fixture_service(true).unwrap(); + open(&mut source, "one", "first"); + source + .dispatch(transaction(vec![Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("two"), + destination: Some(Destination::JoinTab { section: section("first"), index: 1 }), + }])) + .unwrap(); + open(&mut source, "closed", "remembered"); + source.dispatch(transaction(vec![Mutation::Close { instance: id("closed") }])).unwrap(); + let mut incoming = source.layout().clone(); + let memory = &mut incoming.instances.iter_mut().find(|panel| panel.id == id("closed")).unwrap().memory; + memory.column = None; + memory.column_index = 0; + memory.column_width = None; + memory.location = SectionLocation::Window { + host: HostId::new("closed-host").unwrap(), + origin: Point { x: 0.0, y: 0.0 }, + return_to: DockReturn { + zone: Zone::Left, + index: 0, + size: size(280.0, 240.0), + collapsed: false, + section: Some(section("return-section")), + join: Some(ReturnTab { section: section("return-group"), index: 0 }), + column: Some(ColumnId::new("return-column").unwrap()), + column_index: 0, + column_width: Some(280.0), + weight: 240.0, + preferred_extent: None, + extent_priority: 0, + }, + }; + let dormant = ColumnId::new("dormant").unwrap(); + incoming.columns.push(Column { id: dormant.clone(), zone: Zone::Left, width: 280.0 }); + let service = fixture_service(true).unwrap(); + validate(&incoming, service.registry()).unwrap(); + let context = preparation_context(&LayoutEnvelope::new(incoming.clone())).unwrap(); + let ownership = context.replacement_ownership.as_ref().unwrap(); + assert_eq!(ownership.sections[§ion("first")], std::collections::BTreeSet::from([id("one"), id("two")])); + for name in ["remembered", "return-section", "return-group"] { + assert_eq!(ownership.sections[§ion(name)], std::collections::BTreeSet::from([id("closed")])); + } + assert_eq!(ownership.columns[&ColumnId::new("return-column").unwrap()], std::collections::BTreeSet::from([id("closed")])); + assert!(ownership.columns[&dormant].is_empty()); + let action = LayoutAction::Replace { expected_revision: Some(service.inspect().revision), layout: incoming.clone() }; + let before = service.inspect(); + let mut reservations_only = context.clone(); + reservations_only.replacement_ownership = None; + assert_eq!(service.prepare_with_context(action.clone(), &AvailabilityMap::new(), &reservations_only).err().unwrap().rule, Rule::DuplicateId); + let prepared = service.prepare_with_context(action, &AvailabilityMap::new(), &context).unwrap(); + assert_eq!(prepared.layout(), &incoming); + for attack in 0..3 { + let mut stolen = incoming.clone(); + match attack { + 0 => stolen.instances.retain(|panel| panel.id != id("two")), + 1 => { + let mut thief = stolen.instances[0].clone(); + thief.id = id("thief"); + stolen.instances.push(thief); + stolen.sections[0].tabs.push(id("thief")); + } + _ => stolen.sections[0].column = Some(dormant.clone()), + } + if attack == 0 { + stolen.sections[0].tabs.retain(|panel| *panel != id("two")); + } + validate(&stolen, service.registry()).unwrap(); + assert_eq!( + service + .prepare_with_context(LayoutAction::Replace { expected_revision: None, layout: stolen }, &AvailabilityMap::new(), &context) + .err() + .unwrap() + .rule, + Rule::DuplicateId + ); + } + assert_eq!(service.inspect(), before, "preparation and refused takeovers must not publish state"); +} + +#[test] +fn replacement_ownership_bounds_identities_and_owner_sets() { + let mut ownership = ReplacementIdentityOwnership::default(); + ownership.sections.insert(SectionId("INVALID".into()), Default::default()); + assert_eq!(ownership.validate().unwrap_err().rule, Rule::Id); + ownership.sections.clear(); + ownership.columns.insert(ColumnId("INVALID".into()), Default::default()); + assert_eq!(ownership.validate().unwrap_err().rule, Rule::Id); + ownership.columns.clear(); + ownership.sections.insert(section("first"), [InstanceId("INVALID".into())].into()); + assert_eq!(ownership.validate().unwrap_err().rule, Rule::Id); + ownership.sections.insert(section("first"), (0..=MAX_INSTANCES).map(|n| id(&format!("owner-{n}"))).collect()); + assert_eq!(ownership.validate().unwrap_err().rule, Rule::CollectionLimit); + ownership.sections = (0..=MAX_RESERVED_IDENTITIES).map(|n| (section(&format!("reserved-{n}")), Default::default())).collect(); + assert_eq!(ownership.validate().unwrap_err().rule, Rule::CollectionLimit); + let owners = (0..MAX_INSTANCES).map(|n| id(&format!("owner-{n}"))).collect::>(); + ownership.sections = (0..=MAX_RESERVED_IDENTITIES / MAX_INSTANCES).map(|n| (section(&format!("reserved-{n}")), owners.clone())).collect(); + assert_eq!(ownership.validate().unwrap_err().rule, Rule::CollectionLimit); +} + +#[test] +fn reservation_aware_prepare_preserves_owner_closed_reopen_and_native_redock() { + let mut service = fixture_service(true).unwrap(); + open(&mut service, "one", "first"); + let column = service.layout().sections[0].column.clone().unwrap(); + let sections = [section("first")].into(); + let columns = [column.clone()].into(); + service.dispatch(transaction(vec![Mutation::Close { instance: id("one") }])).unwrap(); + let prepared = service + .prepare_with_reservations( + transaction(vec![Mutation::Open { kind: PanelKind::new("fixture.log").unwrap(), instance: id("one"), destination: None }]), + §ions, + &columns, + ) + .unwrap(); + service.commit(prepared).unwrap(); + let prepared = service + .prepare_with_reservations( + transaction(vec![Mutation::Move { + instance: id("one"), + destination: Destination::NewSection { + section: section("window"), + index: 0, + size: size(280.0, 240.0), + location: SectionLocation::Window { + host: HostId::new("host").unwrap(), + origin: Point { x: 0.0, y: 0.0 }, + return_to: DockReturn { + zone: Zone::Left, + index: 0, + size: size(280.0, 240.0), + collapsed: false, + join: None, + section: Some(section("first")), + column: Some(column.clone()), + column_index: 0, + column_width: Some(280.0), + weight: 240.0, + preferred_extent: None, + extent_priority: 0, + }, + }, + }, + }]), + §ions, + &columns, + ) + .unwrap(); + service.commit(prepared).unwrap(); + let before = service.inspect(); + let context = preparation_context(&LayoutEnvelope::new(before.layout.clone())).unwrap(); + let ownership = context.replacement_ownership.as_ref().unwrap(); + assert_eq!(ownership.sections[§ion("window")], std::collections::BTreeSet::from([id("one")])); + assert_eq!(ownership.sections[§ion("first")], std::collections::BTreeSet::from([id("one")])); + assert_eq!(ownership.columns[&column], std::collections::BTreeSet::from([id("one")])); + let empty = fixture_service(true).unwrap(); + empty + .prepare_with_context(LayoutAction::Replace { expected_revision: None, layout: before.layout.clone() }, &AvailabilityMap::new(), &context) + .unwrap(); + let prepared = service + .prepare_with_reservations(transaction(vec![Mutation::NativeClose { host: HostId::new("host").unwrap() }]), §ions, &columns) + .unwrap(); + assert_eq!(service.inspect(), before); + assert_eq!(prepared.layout().sections[0].id, section("first")); + assert_eq!(prepared.layout().sections[0].column, Some(column)); + service.commit(prepared).unwrap(); +} + +#[test] +fn reservation_aware_prepare_bounds_and_validates_borrowed_sets_before_proposing() { + let service = fixture_service(false).unwrap(); + let before = service.inspect(); + let too_many = (0..=MAX_RESERVED_IDENTITIES).map(|n| section(&format!("reserved-{n}"))).collect(); + let empty = std::collections::BTreeSet::new(); + assert_eq!(service.prepare_with_reservations(LayoutAction::Inspect, &too_many, &empty).err().unwrap().rule, Rule::CollectionLimit); + let bad_sections = [SectionId("UPPER".into())].into(); + assert_eq!(service.prepare_with_reservations(LayoutAction::Inspect, &bad_sections, &empty).err().unwrap().rule, Rule::Id); + let bad_columns = [ColumnId("UPPER".into())].into(); + assert_eq!( + service.prepare_with_reservations(LayoutAction::Inspect, &std::collections::BTreeSet::new(), &bad_columns).err().unwrap().rule, + Rule::Id + ); + assert_eq!(service.inspect(), before); +} + +#[test] +fn reservation_aware_native_destinations_skip_implicit_columns_and_refuse_explicit_nested_theft() { + let service = fixture_service(true).unwrap(); + let sections = [section("section-1")].into(); + let column = ColumnId::new("column-1").unwrap(); + let columns = [column.clone()].into(); + let returning = |return_column, return_section| { + transaction(vec![Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("one"), + destination: Some(Destination::NewSection { + section: section("native"), + index: 0, + size: size(280.0, 240.0), + location: SectionLocation::Window { + host: HostId::new("host").unwrap(), + origin: Point { x: 0.0, y: 0.0 }, + return_to: DockReturn { + zone: Zone::Left, + index: 0, + size: size(280.0, 240.0), + collapsed: false, + join: None, + section: return_section, + column: return_column, + column_index: 0, + column_width: None, + weight: 240.0, + preferred_extent: None, + extent_priority: 0, + }, + }, + }), + }]) + }; + let before = service.inspect(); + assert_eq!(service.prepare_with_reservations(returning(Some(column), None), §ions, &columns).err().unwrap().rule, Rule::DuplicateId); + assert_eq!( + service.prepare_with_reservations(returning(None, Some(section("section-1"))), §ions, &columns).err().unwrap().rule, + Rule::DuplicateId + ); + let prepared = service.prepare_with_reservations(returning(None, None), §ions, &columns).unwrap(); + let SectionLocation::Window { return_to, .. } = &prepared.layout().sections[0].location else { + panic!("window"); + }; + assert_eq!(return_to.column, Some(ColumnId::new("column-2").unwrap())); + assert_eq!(service.inspect(), before); + assert_eq!(next_section_id_with_reservations(service.layout(), §ions).unwrap(), section("section-2")); + assert_eq!(next_column_id_with_reservations(service.layout(), &columns).unwrap(), ColumnId::new("column-2").unwrap()); +} + +#[test] +fn current_workspace_action_preflights_catalogue_then_consumes_the_exact_private_candidate_once() { + use commands::LayoutCatalogue; + use std::cell::{Cell, RefCell}; + struct CandidateSink { + service: LayoutService, + action: LayoutAction, + prepared: RefCell>, + projections: Cell, + dispatches: usize, + } + impl ActionSink for CandidateSink { + fn inspect(&self) -> LayoutReply { + self.service.inspect() + } + fn project(&self, action: LayoutAction) -> PanelResult { + assert_eq!(action, self.action); + self.projections.set(self.projections.get() + 1); + Ok(self.prepared.borrow().as_ref().unwrap().layout().clone()) + } + fn dispatch(&mut self, action: LayoutAction) -> PanelResult { + assert_eq!(action, self.action); + self.dispatches += 1; + self.service.commit(self.prepared.get_mut().take().unwrap()) + } + } + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + let registry = service.registry().clone(); + let action = LayoutAction::Apply { + expected_revision: Some(service.inspect().revision), + mutations: vec![Mutation::SetSize { section: section("first"), size: size(280.0, 400.0) }], + }; + let prepared = service.prepare(action.clone()).unwrap(); + let shown = prepared.layout().clone(); + let mut sink = + CandidateSink { service, action: action.clone(), prepared: RefCell::new(Some(prepared)), projections: Cell::new(0), dispatches: 0 }; + let mut catalogue = fixture_command_catalogue(®istry).unwrap(); + let original = catalogue.state().clone(); + let before = sink.inspect(); + catalogue.fail_stage = true; + let failed = commands::execute_layout_action( + action.clone(), + &mut commands::PanelCommandContext { sink: &mut sink, registry: ®istry, catalogue: &mut catalogue, web: false }, + ) + .unwrap_err(); + assert_eq!(failed.rule, Rule::Capability); + assert_eq!(sink.inspect(), before); + assert_eq!(sink.dispatches, 0); + assert!(sink.prepared.borrow().is_some()); + assert_eq!(catalogue.state(), &original); + catalogue.fail_stage = false; + let reply = commands::execute_layout_action( + action, + &mut commands::PanelCommandContext { sink: &mut sink, registry: ®istry, catalogue: &mut catalogue, web: false }, + ) + .unwrap(); + assert_eq!(reply.layout, shown); + assert_eq!(sink.dispatches, 1); + assert_eq!(sink.projections.get(), 2); + assert!(sink.prepared.borrow().is_none()); + assert_eq!( + catalogue.state().remembered(&reply.layout.workspace).unwrap().project_envelope(®istry, &reply.layout.workspace).unwrap().layout, + shown + ); + let mut other = shown; + other.workspace = WorkspaceId::new("fixture.other").unwrap(); + assert_eq!( + commands::execute_layout_action( + LayoutAction::Replace { expected_revision: None, layout: other }, + &mut commands::PanelCommandContext { sink: &mut sink, registry: ®istry, catalogue: &mut catalogue, web: false } + ) + .unwrap_err() + .rule, + Rule::Capability + ); + assert_eq!(sink.dispatches, 1); +} + +#[test] +fn standalone_header_commands_bypass_catalogue_and_no_space_projection_but_keep_authoritative_validation() { + use commands::{CatalogueState, LayoutCatalogue, PreparedCatalogue}; + use std::cell::Cell; + struct RefusingPlacementSink { + service: LayoutService, + projects: Cell, + dispatches: usize, + controller_enabled: bool, + } + impl ActionSink for RefusingPlacementSink { + fn inspect(&self) -> LayoutReply { + self.service.inspect() + } + fn project(&self, _action: LayoutAction) -> PanelResult { + self.projects.set(self.projects.get() + 1); + Err(error(Rule::NoSpace, "captured placement overflows")) + } + fn dispatch(&mut self, action: LayoutAction) -> PanelResult { + self.dispatches += 1; + if !self.controller_enabled { + return Err(error(Rule::Capability, "owning controller disabled")); + } + self.service.dispatch(action) + } + } + struct UnavailableCatalogue { + state: CatalogueState, + reads: Cell, + prepares: usize, + publishes: usize, + } + impl LayoutCatalogue for UnavailableCatalogue { + fn state(&self) -> &CatalogueState { + self.reads.set(self.reads.get() + 1); + &self.state + } + fn prepare(&mut self, _state: CatalogueState) -> PanelResult { + self.prepares += 1; + Err(error(Rule::Capability, "storage unavailable")) + } + fn publish(&mut self, _prepared: PreparedCatalogue) { + self.publishes += 1; + } + } + let mut registry = synthetic_registry().unwrap(); + let mut spec = registry.get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + spec.kind = PanelKind::new("fixture.action").unwrap(); + spec.header_actions = vec![HeaderActionSpec { id: ControlId::new("refresh").unwrap(), label_key: "ui.refresh".into(), icon: "restore".into() }]; + registry.register(spec).unwrap(); + let mut service = + LayoutService::new(registry.clone(), Layout::empty(WorkspaceId::new("fixture.workspace").unwrap()), HostCapabilities::default()).unwrap(); + service.dispatch(transaction(vec![fixture_open("fixture.action", "one", "first", Zone::Left, 0).unwrap()])).unwrap(); + let mut imported = service.layout().clone(); + let memory = &mut imported.instances[0].memory; + memory.section = section("divergent-memory"); + memory.location = SectionLocation::Floating { origin: Point { x: 31.0, y: 47.0 } }; + memory.size = size(320.0, 280.0); + memory.collapsed = true; + memory.weight = 7.0; + memory.preferred_extent = Some(220.0); + memory.column = None; + memory.column_width = None; + memory.column_index = 0; + imported.columns.push(Column { id: ColumnId::new("quarantine-column").unwrap(), zone: Zone::Right, width: 280.0 }); + let mut raw = serde_json::to_value(LayoutEnvelope::new(imported.clone())).unwrap(); + let mut extension = legacy_instance_wire( + "extension", + "extension.panel", + "extension-memory", + serde_json::json!({"type":"dock","zone":"right"}), + size(280.0, 240.0), + 1, + false, + ); + extension["memory"]["column"] = serde_json::json!("quarantine-column"); + raw["quarantine"] = serde_json::json!([{"instance":"extension","kind":"extension.panel","section":null,"instance_data":extension}]); + let loaded = decode(&serde_json::to_vec(&raw).unwrap(), ®istry, &persistence_fallback()).unwrap(); + assert!(loaded.notice.is_none()); + assert_eq!(loaded.envelope.layout, imported); + let service = LayoutService::new(registry.clone(), loaded.envelope.layout.clone(), HostCapabilities::default()).unwrap(); + let mut stored = commands::InMemoryCatalogue::default(); + stored.remember(&loaded.envelope, None, ®istry).unwrap(); + let mut sink = RefusingPlacementSink { service, projects: Cell::new(0), dispatches: 0, controller_enabled: true }; + let mut catalogue = UnavailableCatalogue { state: stored.state().clone(), reads: Cell::new(0), prepares: 0, publishes: 0 }; + let original_catalogue = catalogue.state.clone(); + let original_layout_bytes = serde_json::to_vec(&imported).unwrap(); + let header = Mutation::HeaderAction { instance: id("one"), action: ControlId::new("refresh").unwrap() }; + commands::execute_layout_action( + transaction(vec![header.clone()]), + &mut commands::PanelCommandContext { sink: &mut sink, registry: ®istry, catalogue: &mut catalogue, web: false }, + ) + .unwrap(); + let params = serde_json::json!({"target":{"type":"instance","id":"one"},"action":"refresh"}); + commands::execute( + "panel.action", + ¶ms, + &mut commands::PanelCommandContext { sink: &mut sink, registry: ®istry, catalogue: &mut catalogue, web: false }, + ) + .unwrap(); + let batch = [serde_json::json!({"command":"panel.action","params":params})]; + let result = commands::execute_batch( + &batch, + &mut commands::PanelCommandContext { sink: &mut sink, registry: ®istry, catalogue: &mut catalogue, web: false }, + ) + .unwrap(); + assert_eq!(result["completed"], 1); + assert_eq!(sink.dispatches, 3); + assert_eq!(sink.projects.get(), 0); + assert_eq!((catalogue.reads.get(), catalogue.prepares, catalogue.publishes), (0, 0, 0)); + assert_eq!(sink.inspect().layout, imported); + assert_eq!(serde_json::to_vec(&sink.inspect().layout).unwrap(), original_layout_bytes); + assert_eq!(catalogue.state, original_catalogue); + let before = sink.inspect(); + let mixed = transaction(vec![header.clone(), Mutation::SetSize { section: section("first"), size: size(280.0, 300.0) }]); + assert_eq!( + commands::execute_layout_action( + mixed.clone(), + &mut commands::PanelCommandContext { sink: &mut sink, registry: ®istry, catalogue: &mut catalogue, web: false } + ) + .unwrap_err() + .rule, + Rule::Capability + ); + assert_eq!(sink.service.dispatch(mixed).unwrap_err().rule, Rule::Capability); + assert_eq!( + commands::preflight_batch( + &[ + serde_json::json!({"command":"panel.action","params":{"target":{"type":"instance","id":"one"},"action":"refresh"}}), + serde_json::json!({"command":"layout.get"}), + ], + &before.layout.workspace + ) + .unwrap_err() + .rule, + Rule::Capability + ); + assert_eq!(sink.dispatches, 3); + assert_eq!(sink.inspect(), before); + let unknown = transaction(vec![Mutation::HeaderAction { instance: id("one"), action: ControlId::new("unknown").unwrap() }]); + assert_eq!( + commands::execute_layout_action( + unknown, + &mut commands::PanelCommandContext { sink: &mut sink, registry: ®istry, catalogue: &mut catalogue, web: false } + ) + .unwrap_err() + .rule, + Rule::Capability + ); + sink.controller_enabled = false; + assert_eq!( + commands::execute_layout_action( + transaction(vec![header.clone()]), + &mut commands::PanelCommandContext { sink: &mut sink, registry: ®istry, catalogue: &mut catalogue, web: false } + ) + .unwrap_err() + .rule, + Rule::Capability + ); + sink.controller_enabled = true; + sink.service.set_availability([(id("one"), Availability::Unavailable { reason: "not available".into() })].into()).unwrap(); + assert_eq!( + commands::execute_layout_action( + transaction(vec![header]), + &mut commands::PanelCommandContext { sink: &mut sink, registry: ®istry, catalogue: &mut catalogue, web: false } + ) + .unwrap_err() + .rule, + Rule::Availability + ); + assert_eq!(sink.projects.get(), 0); + assert_eq!((catalogue.reads.get(), catalogue.prepares, catalogue.publishes), (0, 0, 0)); +} + +#[test] +fn current_envelope_snapshot_without_remembered_state_returns_live_data_without_persisting() { + use commands::LayoutCatalogue; + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + let catalogue = commands::InMemoryCatalogue::default(); + let before = catalogue.state().clone(); + let envelope = commands::current_envelope_snapshot(&catalogue, &service.inspect(), service.registry()).unwrap(); + assert_eq!(envelope.layout, *service.layout()); + assert_eq!(catalogue.state(), &before); +} + +#[test] +fn persistence_rejects_new_latent_section_and_column_claims_before_native_close_and_preserves_owner_recovery() { + use serde_json::json; + for column_only in [false, true] { + let registry = synthetic_registry().unwrap(); + let mut raw = serde_json::to_value(LayoutEnvelope::new(Layout::empty(WorkspaceId::new("fixture.workspace").unwrap()))).unwrap(); + let location = if column_only { + json!({"type":"window","host":"extension-host","origin":{"x":20,"y":30},"return_to":{ + "zone":"left","index":0,"column":"reserved-column","column_width":280,"size":{"width":280,"height":240},"collapsed":false + }}) + } else { + json!({"type":"floating","origin":{"x":20,"y":30}}) + }; + let mut extension = legacy_instance_wire("extension", "extension.panel", "saved", location, size(280.0, 240.0), 0, false); + extension["future_draft"] = json!({"keep":"closed extension draft"}); + raw["quarantine"] = json!([{"instance":"extension","kind":"extension.panel","section":null,"instance_data":extension}]); + let loaded = decode(&serde_json::to_vec(&raw).unwrap(), ®istry, &persistence_fallback()).unwrap(); + assert!(loaded.notice.is_none()); + let envelope = loaded.envelope; + let original = encode(&envelope, ®istry).unwrap(); + let context = preparation_context(&envelope).unwrap(); + let ownership = context.replacement_ownership.as_ref().unwrap(); + assert!(!ownership.sections.contains_key(§ion("saved"))); + assert!(!ownership.columns.contains_key(&ColumnId::new("reserved-column").unwrap())); + let service = LayoutService::new( + registry.clone(), + envelope.layout.clone(), + HostCapabilities { native_windows: true, max_native_hosts: 8, persistence: true }, + ) + .unwrap(); + let before = service.inspect(); + let destination = Destination::NewSection { + section: section("window"), + index: 0, + size: size(280.0, 240.0), + location: SectionLocation::Window { + host: HostId::new("unrelated-host").unwrap(), + origin: Point { x: 40.0, y: 50.0 }, + return_to: DockReturn { + zone: Zone::Left, + index: 0, + size: size(280.0, 240.0), + collapsed: false, + join: None, + section: if column_only { None } else { Some(section("saved")) }, + column: if column_only { Some(ColumnId::new("reserved-column").unwrap()) } else { None }, + column_index: 0, + column_width: None, + weight: 240.0, + preferred_extent: None, + extent_priority: 0, + }, + }, + }; + // Deliberately omit preparation reservations: persistence is independently + // responsible for refusing these incoming, still-unmaterialized claims. + let prepared = service + .prepare(transaction(vec![Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("unrelated"), + destination: Some(destination), + }])) + .unwrap(); + let incoming = prepared.layout().clone(); + assert!(incoming.section(§ion("saved")).is_err()); + assert!(incoming.column(&ColumnId::new("reserved-column").unwrap()).is_err()); + assert_eq!( + service + .prepare_with_context(LayoutAction::Replace { expected_revision: None, layout: incoming.clone() }, &AvailabilityMap::new(), &context) + .err() + .unwrap() + .rule, + Rule::DuplicateId + ); + assert_eq!(with_live_layout(&envelope, incoming.clone(), ®istry).unwrap_err().rule, Rule::DuplicateId); + let mut closed = incoming.clone(); + closed.instances[0].requested_open = false; + closed.sections.clear(); + validate(&closed, ®istry).unwrap(); + assert_eq!( + with_live_layout(&envelope, closed, ®istry).unwrap_err().rule, + Rule::DuplicateId, + "closed native memory must not evade staging" + ); + if !column_only { + let mut remembered = incoming.clone(); + remembered.instances[0].requested_open = false; + remembered.instances[0].memory.section = section("saved"); + remembered.instances[0].memory.location = SectionLocation::Floating { origin: Point { x: 4.0, y: 8.0 } }; + remembered.sections.clear(); + validate(&remembered, ®istry).unwrap(); + assert_eq!(with_live_layout(&envelope, remembered, ®istry).unwrap_err().rule, Rule::DuplicateId); + let mut joining = incoming; + for location in [&mut joining.sections[0].location, &mut joining.instances[0].memory.location] { + let SectionLocation::Window { return_to, .. } = location else { + panic!("native descriptor"); + }; + return_to.section = None; + return_to.join = Some(ReturnTab { section: section("saved"), index: 0 }); + } + assert_eq!(with_live_layout(&envelope, joining, ®istry).unwrap_err().rule, Rule::DuplicateId); + } + assert_eq!(service.inspect(), before); + assert_eq!(encode(&envelope, ®istry).unwrap(), original); + let mut grown = registry.clone(); + let mut spec = registry.get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + spec.kind = PanelKind::new("extension.panel").unwrap(); + grown.register(spec).unwrap(); + let mut restored = envelope; + restore_quarantine(&mut restored, &grown).unwrap(); + let mut owner = LayoutService::new( + grown.clone(), + restored.layout.clone(), + HostCapabilities { native_windows: true, max_native_hosts: 8, persistence: true }, + ) + .unwrap(); + owner + .dispatch(transaction(vec![Mutation::Open { + kind: PanelKind::new("extension.panel").unwrap(), + instance: id("extension"), + destination: None, + }])) + .unwrap(); + let group = owner.layout().containing(&id("extension")).unwrap().id.clone(); + owner + .dispatch(transaction(vec![Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("companion"), + destination: Some(Destination::JoinTab { section: group, index: 1 }), + }])) + .unwrap(); + let opened = with_live_layout(&restored, owner.layout().clone(), &grown).unwrap(); + let recovered = if column_only { + owner.dispatch(transaction(vec![Mutation::NativeClose { host: HostId::new("extension-host").unwrap() }])).unwrap(); + let recovered = with_live_layout(&opened, owner.layout().clone(), &grown).unwrap(); + assert_eq!(recovered.layout.containing(&id("extension")).unwrap().column, Some(ColumnId::new("reserved-column").unwrap())); + recovered + } else { + assert_eq!(opened.layout.containing(&id("extension")).unwrap().id, section("saved")); + opened + }; + assert_eq!(recovered.retained_data[&id("extension")]["instance"]["future_draft"]["keep"], "closed extension draft"); + } +} + +#[test] +fn deferred_projection_and_captured_prepare_admit_a_new_owner_without_mutating_the_service() { + let mut service = fixture_service(false).unwrap(); + service.set_availability([(id("incoming"), Availability::Unavailable { reason: "outgoing owner".into() })].into()).unwrap(); + let sections = [section("section-1")].into(); + let columns = [ColumnId::new("column-1").unwrap()].into(); + let action = LayoutAction::Apply { + expected_revision: Some(service.inspect().revision), + mutations: vec![fixture_open("fixture.log", "incoming", "incoming-section", Zone::Left, 0).unwrap()], + }; + let before = service.inspect(); + assert_eq!(service.prepare(action.clone()).err().unwrap().rule, Rule::Availability); + assert_eq!(service.prepare_with_reservations(action.clone(), §ions, &columns).err().unwrap().rule, Rule::Availability); + let projection: Layout = service.project_with_deferred_availability(action.clone(), §ions, &columns).unwrap(); + assert_eq!(projection.columns[0].id, ColumnId::new("column-2").unwrap()); + let captured = [(id("incoming"), Availability::Available)].into(); + let prepared = service.prepare_with_availability_and_reservations(action.clone(), &captured, §ions, &columns).unwrap(); + assert_eq!(prepared.layout(), &projection); + assert_eq!(service.inspect(), before); + let blocked = [(id("incoming"), Availability::Unavailable { reason: "proposed owner refuses".into() })].into(); + assert_eq!(service.prepare_with_availability_and_reservations(action, &blocked, §ions, &columns).err().unwrap().rule, Rule::Availability); + assert_eq!(service.inspect(), before); + let reply = service.commit(prepared).unwrap(); + assert_eq!(reply.layout, projection); + assert_eq!(reply.availability, captured); +} + +#[test] +fn proposed_owner_capture_controls_open_move_focus_activate_peek_and_header_permission() { + for operation in 0..6 { + let mut registry = synthetic_registry().unwrap(); + let mut spec = registry.get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + spec.kind = PanelKind::new("fixture.action").unwrap(); + spec.header_actions = + vec![HeaderActionSpec { id: ControlId::new("refresh").unwrap(), label_key: "ui.refresh".into(), icon: "restore".into() }]; + registry.register(spec).unwrap(); + let mut service = + LayoutService::new(registry, Layout::empty(WorkspaceId::new("fixture.workspace").unwrap()), HostCapabilities::default()).unwrap(); + service + .dispatch(transaction(vec![ + fixture_open("fixture.action", "one", "first", Zone::Left, 0).unwrap(), + Mutation::Collapse { section: section("first"), collapsed: true }, + ])) + .unwrap(); + let blocked: AvailabilityMap = [(id("one"), Availability::Unavailable { reason: "old owner".into() })].into(); + service.set_availability(blocked.clone()).unwrap(); + let mutation = match operation { + 0 => Mutation::Open { kind: PanelKind::new("fixture.action").unwrap(), instance: id("one"), destination: None }, + 1 => Mutation::Focus { instance: id("one") }, + 2 => Mutation::Activate { instance: id("one") }, + 3 => Mutation::Peek { instance: id("one") }, + 4 => Mutation::Move { + instance: id("one"), + destination: Destination::NewSection { + section: section("moved"), + index: 0, + location: SectionLocation::Dock { zone: Zone::Right }, + size: size(280.0, 240.0), + }, + }, + _ => Mutation::HeaderAction { instance: id("one"), action: ControlId::new("refresh").unwrap() }, + }; + let action = transaction(vec![mutation]); + let sections = std::collections::BTreeSet::new(); + let columns = std::collections::BTreeSet::new(); + let before = service.inspect(); + assert_eq!(service.prepare(action.clone()).err().unwrap().rule, Rule::Availability); + let projection = service.project_with_deferred_availability(action.clone(), §ions, &columns).unwrap(); + assert_eq!( + service.prepare_with_availability_and_reservations(action.clone(), &blocked, §ions, &columns).err().unwrap().rule, + Rule::Availability + ); + let captured = [(id("one"), Availability::Available)].into(); + let prepared = service.prepare_with_availability_and_reservations(action, &captured, §ions, &columns).unwrap(); + assert_eq!(prepared.layout(), &projection); + assert_eq!(service.inspect(), before); + let reply = service.commit(prepared).unwrap(); + assert_eq!(reply.layout, projection); + assert_eq!(reply.availability, captured); + } +} + +#[test] +fn captured_header_fallback_is_validated_without_changing_requested_activation_or_layout() { + let mut registry = synthetic_registry().unwrap(); + let mut spec = registry.get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + spec.kind = PanelKind::new("fixture.action").unwrap(); + spec.header_actions = vec![HeaderActionSpec { id: ControlId::new("refresh").unwrap(), label_key: "ui.refresh".into(), icon: "restore".into() }]; + registry.register(spec).unwrap(); + let mut service = + LayoutService::new(registry, Layout::empty(WorkspaceId::new("fixture.workspace").unwrap()), HostCapabilities::default()).unwrap(); + service + .dispatch(transaction(vec![ + fixture_open("fixture.action", "one", "first", Zone::Left, 0).unwrap(), + Mutation::Open { + kind: PanelKind::new("fixture.action").unwrap(), + instance: id("two"), + destination: Some(Destination::JoinTab { section: section("first"), index: 1 }), + }, + ])) + .unwrap(); + let action = transaction(vec![Mutation::HeaderAction { instance: id("two"), action: ControlId::new("refresh").unwrap() }]); + let sections = std::collections::BTreeSet::new(); + let columns = std::collections::BTreeSet::new(); + let before = service.inspect(); + assert_eq!(service.prepare(action.clone()).err().unwrap().rule, Rule::Availability); + let projection = service.project_with_deferred_availability(action.clone(), §ions, &columns).unwrap(); + assert_eq!(projection, before.layout); + let captured = [(id("one"), Availability::Unavailable { reason: "incoming owner".into() }), (id("two"), Availability::Available)].into(); + let prepared = service.prepare_with_availability_and_reservations(action.clone(), &captured, §ions, &columns).unwrap(); + assert_eq!( + service.prepare_with_availability_and_reservations(action, &AvailabilityMap::new(), §ions, &columns).err().unwrap().rule, + Rule::Availability + ); + assert_eq!(service.inspect(), before); + let reply = service.commit(prepared).unwrap(); + assert_eq!(reply.layout, before.layout); + assert_eq!(reply.layout.sections[0].active, id("one")); + assert_eq!(reply.effects, vec![HostEffect::HeaderAction { instance: id("two"), action: ControlId::new("refresh").unwrap() }]); +} + +#[test] +fn captured_replace_retains_new_owner_availability_while_legacy_replace_still_clears_it() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + service.set_availability([(id("one"), Availability::Unavailable { reason: "old workspace".into() })].into()).unwrap(); + let action = LayoutAction::Replace { expected_revision: Some(service.inspect().revision), layout: service.layout().clone() }; + let empty = std::collections::BTreeSet::new(); + let columns = std::collections::BTreeSet::new(); + let before = service.inspect(); + let projection = service.project_with_deferred_availability(action.clone(), &empty, &columns).unwrap(); + let captured = [(id("one"), Availability::Unavailable { reason: "incoming workspace".into() })].into(); + let prepared = service.prepare_with_availability_and_reservations(action.clone(), &captured, &empty, &columns).unwrap(); + let legacy = service.prepare(action).unwrap(); + assert_eq!(prepared.layout(), &projection); + assert_eq!(service.inspect(), before); + assert_eq!(service.commit(prepared).unwrap().availability, captured); + assert_eq!(service.commit(legacy).unwrap_err().rule, Rule::Revision); + let legacy = service.prepare(LayoutAction::Replace { expected_revision: None, layout: projection }).unwrap(); + assert!(service.commit(legacy).unwrap().availability.is_empty()); +} + +#[test] +fn deferred_projection_preserves_presented_pair_metadata_and_final_prepare_rechecks_captured_adjacency() { + let mut service = fixture_service(false).unwrap(); + for (panel, group) in [("one", "first"), ("hidden", "middle"), ("two", "second")] { + open(&mut service, panel, group); + } + let current: AvailabilityMap = [(id("hidden"), Availability::Unavailable { reason: "old owner".into() })].into(); + service.set_availability(current.clone()).unwrap(); + let action = transaction(vec![Mutation::ResizeAllocatedPair { + first: section("first"), + second: section("second"), + first_size: size(280.0, 180.0), + second_size: size(280.0, 300.0), + first_weight: 0.2, + second_weight: 0.3, + other_weight_scale: 1.0, + prefer_allocated: false, + }]); + let sections = std::collections::BTreeSet::new(); + let columns = std::collections::BTreeSet::new(); + let before = service.inspect(); + let projection = service.project_with_deferred_availability(action.clone(), §ions, &columns).unwrap(); + assert_eq!( + service.prepare_with_availability_and_reservations(action.clone(), &AvailabilityMap::new(), §ions, &columns).err().unwrap().rule, + Rule::Placement + ); + let prepared = service.prepare_with_availability_and_reservations(action, ¤t, §ions, &columns).unwrap(); + assert_eq!(prepared.layout(), &projection); + assert_eq!(service.inspect(), before); +} + +#[test] +fn deferred_projection_keeps_identity_capability_lifecycle_and_input_limits_and_captured_maps_are_validated() { + let service = fixture_service(false).unwrap(); + let sections = [section("reserved")].into(); + let columns = std::collections::BTreeSet::new(); + let before = service.inspect(); + let theft = transaction(vec![fixture_open("fixture.log", "one", "reserved", Zone::Left, 0).unwrap()]); + assert_eq!(service.project_with_deferred_availability(theft.clone(), §ions, &columns).unwrap_err().rule, Rule::DuplicateId); + assert_eq!( + service.prepare_with_availability_and_reservations(theft, &AvailabilityMap::new(), §ions, &columns).err().unwrap().rule, + Rule::DuplicateId + ); + let lifecycle = transaction(vec![fixture_open("fixture.log", "one", "new", Zone::Left, 0).unwrap(), Mutation::Close { instance: id("one") }]); + assert_eq!(service.project_with_deferred_availability(lifecycle, §ions, &columns).unwrap_err().rule, Rule::Lifecycle); + let missing = transaction(vec![Mutation::Open { kind: PanelKind::new("missing.kind").unwrap(), instance: id("one"), destination: None }]); + assert_eq!(service.project_with_deferred_availability(missing, §ions, &columns).unwrap_err().rule, Rule::MissingTarget); + let bad_map = [(InstanceId("UPPER".into()), Availability::Available)].into(); + assert_eq!( + service.prepare_with_availability_and_reservations(LayoutAction::Inspect, &bad_map, §ions, &columns).err().unwrap().rule, + Rule::Id + ); + let oversized = (0..=MAX_INSTANCES).map(|n| (id(&format!("instance-{n}")), Availability::Available)).collect(); + assert_eq!( + service.prepare_with_availability_and_reservations(LayoutAction::Inspect, &oversized, §ions, &columns).err().unwrap().rule, + Rule::CollectionLimit + ); + let native = transaction(vec![Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("one"), + destination: Some(Destination::NewSection { + section: section("window"), + index: 0, + size: size(280.0, 240.0), + location: SectionLocation::Window { + host: HostId::new("host").unwrap(), + origin: Point { x: 0.0, y: 0.0 }, + return_to: DockReturn { + zone: Zone::Left, + index: 0, + size: size(280.0, 240.0), + collapsed: false, + section: None, + column: None, + column_index: 0, + column_width: None, + weight: 240.0, + preferred_extent: None, + extent_priority: 0, + join: None, + }, + }, + }), + }]); + assert_eq!(service.project_with_deferred_availability(native, §ions, &columns).unwrap_err().rule, Rule::Capability); + assert_eq!(service.inspect(), before); +} + +#[test] +fn extent_priority_defaults_omit_zero_and_reject_untyped_or_orphaned_ranks() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + let wire = serde_json::to_value(service.layout()).unwrap(); + assert!(wire["sections"][0].get("extent_priority").is_none()); + assert!(wire["instances"][0]["memory"].get("extent_priority").is_none()); + let native = DockReturn { + zone: Zone::Left, + index: 0, + size: size(280.0, 240.0), + collapsed: false, + section: None, + column: None, + column_index: 0, + column_width: None, + weight: 1.0, + preferred_extent: None, + extent_priority: 0, + join: None, + }; + assert!(serde_json::to_value(&native).unwrap().get("extent_priority").is_none()); + for rank in [serde_json::json!(-1), serde_json::json!(65536), serde_json::json!(1.5), serde_json::json!("future"), serde_json::Value::Null] { + let mut group = wire["sections"][0].clone(); + group["extent_priority"] = rank.clone(); + assert!(serde_json::from_value::
(group).is_err()); + let mut memory = wire["instances"][0]["memory"].clone(); + memory["extent_priority"] = rank.clone(); + assert!(serde_json::from_value::(memory).is_err()); + let mut returning = serde_json::to_value(&native).unwrap(); + returning["extent_priority"] = rank; + assert!(serde_json::from_value::(returning).is_err()); + } + assert!(validate_extent_priority(Some(240.0), u16::MAX).is_ok()); + assert_eq!(validate_extent_priority(None, 1).unwrap_err().rule, Rule::Bounds); + let mut invalid = service.layout().clone(); + invalid.sections[0].extent_priority = 1; + assert_eq!(validate(&invalid, service.registry()).unwrap_err().rule, Rule::Bounds); + let mut invalid = service.layout().clone(); + invalid.instances[0].memory.extent_priority = 1; + assert_eq!(validate(&invalid, service.registry()).unwrap_err().rule, Rule::Bounds); + let mut invalid = native; + invalid.extent_priority = 1; + assert_eq!(invalid.validate().unwrap_err().rule, Rule::Bounds); + let mut native_service = fixture_service(true).unwrap(); + open(&mut native_service, "one", "first"); + native_service.dispatch(transaction(vec![Mutation::SetSize { section: section("first"), size: size(280.0, 400.0) }])).unwrap(); + reject( + &mut native_service, + vec![Mutation::Move { + instance: id("one"), + destination: Destination::NewSection { + section: section("window"), + index: 0, + size: size(280.0, 240.0), + location: SectionLocation::Window { host: HostId::new("host").unwrap(), origin: Point { x: 0.0, y: 0.0 }, return_to: invalid }, + }, + }], + Rule::Bounds, + ); + let mut raw = serde_json::to_value(LayoutEnvelope::new(service.layout().clone())).unwrap(); + raw["layout"]["sections"][0]["extent_priority"] = serde_json::json!(0); + raw["layout"]["instances"][0]["memory"]["extent_priority"] = serde_json::json!(0); + let loaded = decode(&serde_json::to_vec(&raw).unwrap(), service.registry(), &persistence_fallback()).unwrap(); + assert!(loaded.notice.is_none()); + let encoded: serde_json::Value = serde_json::from_slice(&encode(&loaded.envelope, service.registry()).unwrap()).unwrap(); + assert!(encoded["layout"]["sections"][0].get("extent_priority").is_none()); + assert!(encoded["layout"]["instances"][0]["memory"].get("extent_priority").is_none()); + let mut data = serde_json::to_value(&service.layout().sections[0]).unwrap(); + data["extent_priority"] = serde_json::json!(1); + let mut invalid = LayoutEnvelope::new(service.layout().clone()); + invalid.section_snapshots.insert(section("first"), SectionSnapshot { data, index: 0, projected: None }); + assert_eq!(encode(&invalid, service.registry()).unwrap_err().rule, Rule::Bounds); +} + +#[test] +fn dock_set_size_authors_a_new_tier_and_free_window_sizing_retains_its_latent_rank() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + open(&mut service, "two", "second"); + let weights: Vec<_> = service.layout().sections.iter().map(|s| s.weight).collect(); + for (group, extent, rank) in [("first", 400.0, 1), ("second", 300.0, 2), ("first", 350.0, 3)] { + service.dispatch(transaction(vec![Mutation::SetSize { section: section(group), size: size(280.0, extent) }])).unwrap(); + let saved = service.layout().section(§ion(group)).unwrap(); + assert_eq!((saved.preferred_extent, saved.extent_priority), (Some(extent), rank)); + for panel in service.layout().instances.iter().filter(|p| saved.tabs.contains(&p.id)) { + assert_eq!((panel.memory.preferred_extent, panel.memory.extent_priority), (Some(extent), rank)); + } + } + assert_eq!(service.layout().sections.iter().map(|s| s.weight).collect::>(), weights); + service + .dispatch(transaction(vec![Mutation::Move { + instance: id("one"), + destination: Destination::NewSection { + section: section("float"), + index: 1, + location: SectionLocation::Floating { origin: Point { x: 20.0, y: 30.0 } }, + size: size(300.0, 280.0), + }, + }])) + .unwrap(); + service.dispatch(transaction(vec![Mutation::SetSize { section: section("float"), size: size(500.0, 600.0) }])).unwrap(); + let floating = service.layout().section(§ion("float")).unwrap(); + assert_eq!(floating.size, size(500.0, 600.0)); + assert_eq!((floating.preferred_extent, floating.extent_priority), (Some(350.0), 3)); + service.dispatch(transaction(vec![Mutation::Close { instance: id("one") }])).unwrap(); + service.dispatch(transaction(vec![Mutation::Focus { instance: id("one") }])).unwrap(); + assert_eq!(service.layout().containing(&id("one")).unwrap().extent_priority, 3); +} + +#[test] +fn exhausted_extent_tiers_compact_live_closed_native_ties_and_preserve_other_group_intent_atomically() { + let mut service = fixture_service(true).unwrap(); + for (panel, group) in [("one", "first"), ("two", "second"), ("zero", "zero"), ("closed", "closed"), ("native", "native-source")] { + open(&mut service, panel, group); + } + service.dispatch(transaction(vec![Mutation::Close { instance: id("closed") }])).unwrap(); + service + .dispatch(transaction(vec![Mutation::Move { + instance: id("native"), + destination: Destination::NewSection { + section: section("window"), + index: 3, + size: size(280.0, 240.0), + location: SectionLocation::Window { + host: HostId::new("host").unwrap(), + origin: Point { x: 0.0, y: 0.0 }, + return_to: DockReturn { + zone: Zone::Left, + index: 3, + size: size(280.0, 240.0), + collapsed: false, + section: None, + column: None, + column_index: 0, + column_width: None, + weight: 240.0, + preferred_extent: None, + extent_priority: 0, + join: None, + }, + }, + }, + }])) + .unwrap(); + service.dispatch(transaction(vec![fixture_open("fixture.log", "right", "right", Zone::Right, 4).unwrap()])).unwrap(); + let mut layout = service.layout().clone(); + for group in &mut layout.sections { + match group.id.0.as_str() { + "first" => { + group.preferred_extent = Some(200.0); + group.extent_priority = 40000; + } + "second" => { + group.preferred_extent = Some(200.0); + group.extent_priority = 17; + } + "zero" => { + group.preferred_extent = Some(200.0); + } + "right" => { + group.preferred_extent = Some(500.0); + group.extent_priority = u16::MAX; + } + _ => {} + } + if let SectionLocation::Window { return_to, .. } = &mut group.location { + return_to.preferred_extent = Some(260.0); + return_to.extent_priority = u16::MAX; + } + } + for panel in &mut layout.instances { + if let Some(group) = layout.sections.iter().find(|s| s.tabs.contains(&panel.id)) { + panel.memory.preferred_extent = group.preferred_extent; + panel.memory.extent_priority = group.extent_priority; + panel.memory.location = group.location.clone(); + } else { + panel.memory.preferred_extent = Some(250.0); + panel.memory.extent_priority = 17; + } + } + let mut service = LayoutService::new(service.registry().clone(), layout, service.capabilities().clone()).unwrap(); + let before = service.inspect(); + reject( + &mut service, + vec![ + Mutation::SetSize { section: section("first"), size: size(280.0, 350.0) }, + Mutation::SetBottomHeight { section: section("first"), height: 200.0 }, + ], + Rule::Placement, + ); + let prepared = service.prepare(transaction(vec![Mutation::SetSize { section: section("first"), size: size(280.0, 350.0) }])).unwrap(); + assert_eq!(service.inspect(), before); + let next = prepared.layout(); + assert_eq!(next.section(§ion("first")).unwrap().extent_priority, 4); + assert_eq!(next.section(§ion("second")).unwrap().extent_priority, 1); + assert_eq!(next.instance(&id("closed")).unwrap().memory.extent_priority, 1); + assert_eq!(next.section(§ion("zero")).unwrap().extent_priority, 0); + let mut right = before.layout.section(§ion("right")).unwrap().clone(); + right.extent_priority = 3; // Global compaction preserves its tier tie with the native return. + assert_eq!(next.section(§ion("right")).unwrap(), &right); + let SectionLocation::Window { return_to, .. } = &next.section(§ion("window")).unwrap().location else { + panic!("window"); + }; + assert_eq!((return_to.preferred_extent, return_to.extent_priority), (Some(260.0), 3)); + let SectionLocation::Window { return_to, .. } = &next.instance(&id("native")).unwrap().memory.location else { + panic!("memory"); + }; + assert_eq!(return_to.extent_priority, 3); + assert_eq!(next.sections.iter().map(|s| s.weight).collect::>(), before.layout.sections.iter().map(|s| s.weight).collect::>()); + service.commit(prepared).unwrap(); + service.dispatch(transaction(vec![Mutation::SetSize { section: section("second"), size: size(280.0, 300.0) }])).unwrap(); + assert_eq!(service.layout().section(§ion("second")).unwrap().extent_priority, 5); +} + +#[test] +fn ranked_allocated_pairs_represent_explicit_underfill_compression_and_repeated_overlap() { + for height in [1000.0, 400.0] { + let mut service = fixture_service(false).unwrap(); + for (panel, group) in [("one", "first"), ("two", "second"), ("three", "third")] { + open(&mut service, panel, group); + } + let mut layout = service.layout().clone(); + for group in &mut layout.sections { + group.preferred_extent = Some(200.0); + } + for panel in &mut layout.instances { + panel.memory.preferred_extent = Some(200.0); + } + let mut service = LayoutService::new(service.registry().clone(), layout, HostCapabilities::default()).unwrap(); + let mut env = allocated_pair_environment(&service, height); + env.gap = 4.0; + let initial = allocate_layout(service.layout(), service.registry(), &env).unwrap(); + let expected = if height == 1000.0 { 200.0 } else { 392.0 / 3.0 }; + for group in &initial.sections { + assert!((group.outer.size.height - expected).abs() < 0.002); + } + let first = if height == 1000.0 { 180.0 } else { 120.0 }; + let second = initial.sections[0].outer.size.height + initial.sections[1].outer.size.height - first; + let action = transaction(vec![Mutation::ResizeAllocatedPair { + first: section("first"), + second: section("second"), + first_size: size(280.0, first), + second_size: size(280.0, second), + first_weight: 0.1, + second_weight: 0.2, + other_weight_scale: 1.0, + prefer_allocated: true, + }]); + let before = service.inspect(); + let prepared = service.prepare(action).unwrap(); + assert_eq!(service.inspect(), before); + let shown = allocate_layout(prepared.layout(), service.registry(), &env).unwrap(); + assert!((shown.sections[0].outer.size.height - first).abs() < 0.002); + assert!((shown.sections[1].outer.size.height - second).abs() < 0.002); + assert!((shown.sections[2].outer.size.height - initial.sections[2].outer.size.height).abs() < 0.002); + assert!((shown.sections[2].outer.origin.y - initial.sections[2].outer.origin.y).abs() < 0.002); + assert_eq!(prepared.layout().sections.iter().map(|s| s.extent_priority).collect::>(), vec![1, 1, 0]); + service.commit(prepared).unwrap(); + assert_eq!(allocate_layout(service.layout(), service.registry(), &env).unwrap(), shown); + let saved = service.layout().clone(); + service + .dispatch(transaction(vec![ + Mutation::Collapse { section: section("first"), collapsed: true }, + Mutation::Collapse { section: section("first"), collapsed: false }, + ])) + .unwrap(); + assert_eq!(service.layout(), &saved); + let overlap_first = if height == 1000.0 { 210.0 } else { 130.0 }; + let overlap_second = shown.sections[1].outer.size.height + shown.sections[2].outer.size.height - overlap_first; + service + .dispatch(transaction(vec![Mutation::ResizeAllocatedPair { + first: section("second"), + second: section("third"), + first_size: size(280.0, overlap_first), + second_size: size(280.0, overlap_second), + first_weight: 0.2, + second_weight: 0.3, + other_weight_scale: 1.0, + prefer_allocated: true, + }])) + .unwrap(); + let overlap = allocate_layout(service.layout(), service.registry(), &env).unwrap(); + assert!((overlap.sections[0].outer.size.height - first).abs() < 0.002); + assert!((overlap.sections[1].outer.size.height - overlap_first).abs() < 0.002); + assert!((overlap.sections[2].outer.size.height - overlap_second).abs() < 0.002); + assert_eq!(service.layout().sections.iter().map(|s| s.extent_priority).collect::>(), vec![1, 2, 2]); + let mut expanded = env.clone(); + expanded.capacity.size.height = 1400.0; + let roomy = allocate_layout(service.layout(), service.registry(), &expanded).unwrap(); + for (actual, saved) in roomy.sections.iter().zip(&service.layout().sections) { + assert!((actual.outer.size.height - saved.preferred_extent.unwrap()).abs() < 0.002); + } + } + let mut service = fixture_service(false).unwrap(); + for (panel, group) in [("one", "first"), ("two", "second"), ("three", "third")] { + open(&mut service, panel, group); + } + let mut layout = service.layout().clone(); + for (group, extent) in layout.sections.iter_mut().zip([1200.0, 120.0, 200.0]) { + group.preferred_extent = Some(extent); + } + for panel in &mut layout.instances { + panel.memory.preferred_extent = layout.sections.iter().find(|s| s.tabs.contains(&panel.id)).unwrap().preferred_extent; + } + let mut service = LayoutService::new(service.registry().clone(), layout, HostCapabilities::default()).unwrap(); + let mut env = allocated_pair_environment(&service, 1528.0); + env.gap = 4.0; + let initial = allocate_layout(service.layout(), service.registry(), &env).unwrap(); + for (first, second) in [(120.0, 1200.0), (1200.0, 120.0)] { + service + .dispatch(transaction(vec![Mutation::ResizeAllocatedPair { + first: section("first"), + second: section("second"), + first_size: size(280.0, first), + second_size: size(280.0, second), + first_weight: 0.0, + second_weight: 1.0, + other_weight_scale: 1.0, + prefer_allocated: true, + }])) + .unwrap(); + let actual = allocate_layout(service.layout(), service.registry(), &env).unwrap(); + assert!((actual.sections[0].outer.size.height - first).abs() < 0.002); + assert!((actual.sections[1].outer.size.height - second).abs() < 0.002); + assert!((actual.sections[2].outer.origin.y - initial.sections[2].outer.origin.y).abs() < 0.002); + assert_eq!(actual.sections[2].outer.size, initial.sections[2].outer.size); + } +} + +#[test] +fn ranked_pair_intent_roundtrips_and_false_clears_rank_without_snapshot_resurrection() { + let mut service = fixture_service(false).unwrap(); + open(&mut service, "one", "first"); + open(&mut service, "two", "second"); + service + .dispatch(transaction(vec![Mutation::ResizeAllocatedPair { + first: section("first"), + second: section("second"), + first_size: size(280.0, 180.0), + second_size: size(280.0, 220.0), + first_weight: 0.4, + second_weight: 0.6, + other_weight_scale: 1.0, + prefer_allocated: true, + }])) + .unwrap(); + let mut envelope = LayoutEnvelope::new(service.layout().clone()); + for (index, group) in service.layout().sections.iter().enumerate() { + let mut data = serde_json::to_value(group).unwrap(); + data["future"] = serde_json::json!({"extent_priority":"opaque payload"}); + envelope.section_snapshots.insert(group.id.clone(), SectionSnapshot { data, index, projected: Some(group.clone()) }); + } + let loaded = decode(&encode(&envelope, service.registry()).unwrap(), service.registry(), &persistence_fallback()).unwrap(); + assert!(loaded.notice.is_none()); + assert_eq!(loaded.envelope.layout, *service.layout()); + for group in &loaded.envelope.layout.sections { + assert_eq!(group.extent_priority, 1); + } + service + .dispatch(transaction(vec![Mutation::ResizeAllocatedPair { + first: section("first"), + second: section("second"), + first_size: size(280.0, 120.0), + second_size: size(280.0, 280.0), + first_weight: 0.0, + second_weight: 1.0, + other_weight_scale: 1.0, + prefer_allocated: false, + }])) + .unwrap(); + let staged = with_live_layout(&loaded.envelope, service.layout().clone(), service.registry()).unwrap(); + let raw: serde_json::Value = serde_json::from_slice(&encode(&staged, service.registry()).unwrap()).unwrap(); + for name in ["first", "second"] { + assert!(raw["section_snapshots"][name]["data"].get("extent_priority").is_none()); + assert!(raw["section_snapshots"][name]["data"].get("preferred_extent").is_none()); + assert_eq!(raw["section_snapshots"][name]["data"]["future"]["extent_priority"], "opaque payload"); + } +} + +#[test] +fn bottom_height_updates_the_common_row_and_preserves_width_intent_rank_and_weight() { + let mut registry = synthetic_registry().unwrap(); + let mut constrained = registry.get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + constrained.kind = PanelKind::new("fixture.short-height").unwrap(); + constrained.min_size.height = 140.0; + constrained.max_size.height = 300.0; + registry.register(constrained).unwrap(); + let mut service = + LayoutService::new(registry.clone(), Layout::empty(WorkspaceId::new("fixture.workspace").unwrap()), HostCapabilities::default()).unwrap(); + service + .dispatch(transaction(vec![ + fixture_open("fixture.log", "one", "first", Zone::Bottom, 0).unwrap(), + fixture_open("fixture.log", "two", "second", Zone::Bottom, 1).unwrap(), + Mutation::Open { + kind: PanelKind::new("fixture.short-height").unwrap(), + instance: id("inactive"), + destination: Some(Destination::JoinTab { section: section("first"), index: 1 }), + }, + ])) + .unwrap(); + service + .dispatch(transaction(vec![ + Mutation::SetSize { section: section("first"), size: size(320.0, 240.0) }, + Mutation::SetSize { section: section("second"), size: size(450.0, 500.0) }, + ])) + .unwrap(); + let mut imported = service.layout().clone(); + let memory = &mut imported.instances.iter_mut().find(|p| p.id == id("one")).unwrap().memory; + memory.size.width = 800.0; + memory.preferred_extent = Some(600.0); + memory.extent_priority = 77; + memory.weight = 3.0; + let mut service = LayoutService::new(registry.clone(), imported, HostCapabilities::default()).unwrap(); + assert_eq!(bottom_height_bounds(service.layout(), ®istry).unwrap(), (140.0, 300.0)); + let before = service.layout().clone(); + let prepared = service.prepare(transaction(vec![Mutation::SetBottomHeight { section: section("first"), height: 180.0 }])).unwrap(); + assert_eq!(service.layout(), &before); + for (old, new) in before.sections.iter().zip(&prepared.layout().sections) { + assert_eq!(new.size.height, 180.0); + assert_eq!( + (new.size.width, new.preferred_extent, new.extent_priority, new.weight), + (old.size.width, old.preferred_extent, old.extent_priority, old.weight) + ); + assert_eq!(new.active, old.active); + } + for (old, new) in before.instances.iter().zip(&prepared.layout().instances) { + let mut expected = old.memory.clone(); + expected.size.height = 180.0; + assert_eq!(new.memory, expected, "height-only edit preserves divergent remembered width intent"); + } + service.commit(prepared).unwrap(); + assert!(service.layout().instances.iter().all(|p| p.memory.size.height == 180.0)); + for height in [0.0, -1.0, f32::NAN, f32::INFINITY, 139.0, 301.0, MAX_LOGICAL + 1.0] { + reject(&mut service, vec![Mutation::SetBottomHeight { section: section("second"), height }], Rule::Bounds); + } + service.dispatch(transaction(vec![fixture_open("fixture.log", "side", "side", Zone::Left, 2).unwrap()])).unwrap(); + reject(&mut service, vec![Mutation::SetBottomHeight { section: section("side"), height: 180.0 }], Rule::Placement); + reject(&mut service, vec![Mutation::SetBottomHeight { section: section("missing"), height: 180.0 }], Rule::MissingTarget); + assert_eq!( + commands::parse_command("panel.set_bottom_height", &serde_json::json!({"section":"first","height":180})).unwrap_err().rule, + Rule::MissingTarget + ); +} + +#[test] +fn bottom_height_refuses_disjoint_registered_card_intervals_atomically() { + let mut registry = synthetic_registry().unwrap(); + for (kind, min, max, default) in [("fixture.low", 120.0, 200.0, 180.0), ("fixture.high", 400.0, 600.0, 450.0)] { + let mut spec = registry.get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + spec.kind = PanelKind::new(kind).unwrap(); + spec.min_size.height = min; + spec.max_size.height = max; + spec.default_size.height = default; + registry.register(spec).unwrap(); + } + let mut service = + LayoutService::new(registry, Layout::empty(WorkspaceId::new("fixture.workspace").unwrap()), HostCapabilities::default()).unwrap(); + for (kind, group, height) in [("fixture.low", "low", 180.0), ("fixture.high", "high", 450.0)] { + let index = service.layout().sections.len(); + service + .dispatch(transaction(vec![Mutation::Open { + kind: PanelKind::new(kind).unwrap(), + instance: id(group), + destination: Some(Destination::NewSection { + section: section(group), + index, + size: size(280.0, height), + location: SectionLocation::Dock { zone: Zone::Bottom }, + }), + }])) + .unwrap(); + } + assert_eq!(bottom_height_bounds(service.layout(), service.registry()).unwrap_err().rule, Rule::IncompatibleTabs); + reject(&mut service, vec![Mutation::SetBottomHeight { section: section("low"), height: 180.0 }], Rule::IncompatibleTabs); +} + +#[test] +fn raw_quarantine_priority_and_nested_opaque_fields_survive_known_compaction_then_native_reappearance() { + use commands::LayoutCatalogue; + use serde_json::json; + let mut service = fixture_service(true).unwrap(); + open(&mut service, "one", "first"); + open(&mut service, "two", "second"); + let mut layout = service.layout().clone(); + for (group, rank) in layout.sections.iter_mut().zip([u16::MAX, 17]) { + group.preferred_extent = Some(300.0); + group.extent_priority = rank; + } + for panel in &mut layout.instances { + let group = layout.sections.iter().find(|s| s.tabs.contains(&panel.id)).unwrap(); + panel.memory.preferred_extent = group.preferred_extent; + panel.memory.extent_priority = group.extent_priority; + } + let registry = service.registry().clone(); + let column = layout.sections[0].column.clone().unwrap(); + let mut raw = serde_json::to_value(LayoutEnvelope::new(layout)).unwrap(); + raw["quarantine"] = json!([{"instance":"extension","kind":"extension.panel","section":null,"instance_data":{ + "id":"extension","kind":"extension.panel","requested_open":false,"future":{"extent_priority":"opaque rank payload"},"memory":{ + "section":"native-memory","section_index":2,"tab_index":0,"size":{"width":280,"height":400},"collapsed":false,"weight":240, + "preferred_extent":400,"extent_priority":41,"location":{"type":"window","host":"extension-host","origin":{"x":20,"y":30}, + "future_monitor":{"extent_priority":"monitor metadata"},"return_to":{ + "section":"extension-return","zone":"left","index":2,"column":column,"column_index":0,"column_width":280, + "size":{"width":280,"height":350},"collapsed":false,"weight":240,"preferred_extent":350,"extent_priority":42 + } + } + } + }}]); + let pending: PanelInstance = serde_json::from_value(raw["quarantine"][0]["instance_data"].clone()).unwrap(); + let snapshot = Section { + id: pending.memory.section.clone(), + location: pending.memory.location.clone(), + tabs: vec![pending.id.clone()], + active: pending.id, + size: pending.memory.size, + collapsed: false, + column: None, + weight: pending.memory.weight, + preferred_extent: pending.memory.preferred_extent, + extent_priority: pending.memory.extent_priority, + }; + let snapshot_data = serde_json::to_value(snapshot).unwrap(); + raw["section_snapshots"]["native-memory"] = json!({"index":2,"data":snapshot_data}); + let loaded = decode(&serde_json::to_vec(&raw).unwrap(), ®istry, &persistence_fallback()).unwrap(); + assert!(loaded.notice.is_none()); + let opaque = loaded.envelope.quarantine[0].instance_data.clone(); + let mut service = LayoutService::new( + registry.clone(), + loaded.envelope.layout.clone(), + HostCapabilities { native_windows: true, max_native_hosts: 8, persistence: true }, + ) + .unwrap(); + service.dispatch(transaction(vec![Mutation::SetSize { section: section("first"), size: size(280.0, 350.0) }])).unwrap(); + assert_eq!(service.layout().section(§ion("first")).unwrap().extent_priority, 5); + let mut staged = with_live_layout(&loaded.envelope, service.layout().clone(), ®istry).unwrap(); + assert_eq!(staged.quarantine[0].instance_data, opaque); + let shadow = staged.extent_priority_overrides.iter().find(|record| record.target == ExtentPriorityTarget::MemoryReturn(id("extension"))).unwrap(); + assert_eq!((shadow.stored_priority, shadow.priority), (42, 3)); + let shared = staged + .extent_priority_overrides + .iter() + .find(|record| record.target == ExtentPriorityTarget::SectionReturn(section("native-memory"))) + .unwrap(); + assert_eq!((shared.stored_priority, shared.priority), (42, 3)); + assert_eq!(staged.section_snapshots[§ion("native-memory")].data, snapshot_data); + let roundtrip = decode(&encode(&staged, ®istry).unwrap(), ®istry, &persistence_fallback()).unwrap(); + assert!(roundtrip.notice.is_none()); + assert_eq!(roundtrip.envelope.quarantine[0].instance_data, opaque); + let mut preset = LayoutEnvelope::new(staged.layout.clone()); + preset.layout.extent_priority_context = ExtentPriorityContext::default(); + let mut catalogue = commands::InMemoryCatalogue::default(); + catalogue.register_builtin("Without native peer", &preset, ®istry).unwrap(); + catalogue.remember(&staged, None, ®istry).unwrap(); + let mut backend = commands::InMemoryPanelBackend::new( + LayoutService::new(registry.clone(), staged.layout.clone(), HostCapabilities::default()).unwrap(), + catalogue, + ); + backend.execute("layout.apply", &json!({"name":"Without native peer"})).unwrap(); + staged = backend.catalogue.state().remembered(&staged.layout.workspace).unwrap().project_envelope(®istry, &staged.layout.workspace).unwrap(); + assert_eq!(staged.quarantine[0].instance_data, opaque); + assert_eq!(staged.section_snapshots[§ion("native-memory")].data, snapshot_data); + for target in [ExtentPriorityTarget::MemoryReturn(id("extension")), ExtentPriorityTarget::SectionReturn(section("native-memory"))] { + let shadow = staged.extent_priority_overrides.iter().find(|record| record.target == target).unwrap(); + assert_eq!((shadow.stored_priority, shadow.priority), (42, 3), "preset merge retains native recovery precedence"); + } + let mut grown = registry.clone(); + let mut spec = registry.get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + spec.kind = PanelKind::new("extension.panel").unwrap(); + grown.register(spec).unwrap(); + restore_quarantine(&mut staged, &grown).unwrap(); + let mut owner = + LayoutService::new(grown.clone(), staged.layout.clone(), HostCapabilities { native_windows: true, max_native_hosts: 8, persistence: true }) + .unwrap(); + owner + .dispatch(transaction(vec![Mutation::Open { + kind: PanelKind::new("extension.panel").unwrap(), + instance: id("extension"), + destination: None, + }])) + .unwrap(); + let window = owner.layout().containing(&id("extension")).unwrap(); + assert_eq!((window.preferred_extent, window.extent_priority), (Some(400.0), 2)); + let opened = with_live_layout(&staged, owner.layout().clone(), &grown).unwrap(); + assert_eq!(opened.section_snapshots[§ion("native-memory")].data, snapshot_data); + owner.dispatch(transaction(vec![Mutation::NativeClose { host: HostId::new("extension-host").unwrap() }])).unwrap(); + let dock = owner.layout().containing(&id("extension")).unwrap(); + assert_eq!((dock.preferred_extent, dock.extent_priority), (Some(350.0), 3)); + let mut environment = allocated_pair_environment(&owner, 400.0); + environment.gap = 4.0; + let geometry = allocate_layout(owner.layout(), owner.registry(), &environment).unwrap(); + for (name, expected) in [("first", 152.0), ("second", 120.0), ("extension-return", 120.0)] { + let actual = geometry.sections.iter().find(|s| s.section == section(name)).unwrap(); + assert!((actual.outer.size.height - expected).abs() < 0.002, "new authored precedence survives opaque native recovery"); + } + let saved = with_live_layout(&opened, owner.layout().clone(), &grown).unwrap(); + assert_eq!(saved.retained_data[&id("extension")]["instance"]["future"]["extent_priority"], "opaque rank payload"); + assert_eq!(saved.retained_data[&id("extension")]["instance"]["memory"]["location"]["future_monitor"]["extent_priority"], "monitor metadata"); +} + +fn priority_recovery_envelope(first_rank: u16, snapshot: bool) -> (PanelRegistry, LayoutEnvelope) { + use serde_json::json; + let mut service = fixture_service(false).unwrap(); + open(&mut service, "a", "a"); + open(&mut service, "b", "b"); + let mut layout = service.layout().clone(); + for (group, rank) in layout.sections.iter_mut().zip([first_rank, 17]) { + group.preferred_extent = Some(300.0); + group.extent_priority = rank; + } + for panel in &mut layout.instances { + let group = layout.sections.iter().find(|s| s.id == panel.memory.section).unwrap(); + panel.memory.preferred_extent = group.preferred_extent; + panel.memory.extent_priority = group.extent_priority; + } + let column = layout.columns[0].id.clone(); + let mut raw = serde_json::to_value(LayoutEnvelope::new(layout)).unwrap(); + raw["quarantine"] = json!([{"instance":"q","kind":"extension.priority","section":if snapshot { json!("q") } else { serde_json::Value::Null }, + "instance_data":{"id":"q","kind":"extension.priority","requested_open":snapshot,"memory":{ + "section":"q","location":{"type":"dock","zone":"left"},"column":column,"column_width":280, + "section_index":2,"tab_index":0,"size":{"width":280,"height":350},"collapsed":false,"weight":240, + "preferred_extent":350,"extent_priority":42},"future":{"draft":"keep Q raw","extent_priority":"opaque"}}}]); + if snapshot { + raw["section_snapshots"]["q"] = json!({"index":2,"data":{"id":"q","location":{"type":"dock","zone":"left"}, + "column":column,"tabs":["q"],"active":"q","size":{"width":280,"height":350},"collapsed":false, + "weight":240,"preferred_extent":350,"extent_priority":42,"future_surface":{"keep":true}}}); + raw["section_order"].as_array_mut().unwrap().push(json!("q")); + } + let registry = service.registry().clone(); + let loaded = decode(&serde_json::to_vec(&raw).unwrap(), ®istry, &persistence_fallback()).unwrap(); + assert!(loaded.notice.is_none()); + (registry, loaded.envelope) +} + +fn restored_priority_owner(mut envelope: LayoutEnvelope, registry: &PanelRegistry) -> (PanelRegistry, LayoutEnvelope, LayoutService) { + let mut grown = registry.clone(); + let mut spec = registry.get(&PanelKind::new("fixture.log").unwrap()).unwrap().clone(); + spec.kind = PanelKind::new("extension.priority").unwrap(); + grown.register(spec).unwrap(); + restore_quarantine(&mut envelope, &grown).unwrap(); + let mut owner = LayoutService::new(grown.clone(), envelope.layout.clone(), HostCapabilities::default()).unwrap(); + owner + .dispatch(transaction(vec![Mutation::Open { kind: PanelKind::new("extension.priority").unwrap(), instance: id("q"), destination: None }])) + .unwrap(); + (grown, envelope, owner) +} + +#[test] +fn recovery_priority_context_preserves_latest_resize_with_and_without_exhaustion_and_shared_snapshots() { + for initial in [u16::MAX, 10] { + for snapshot in [false, true] { + let (registry, envelope) = priority_recovery_envelope(initial, snapshot); + let raw = envelope.quarantine[0].instance_data.clone(); + let original_snapshot = envelope.section_snapshots.get(§ion("q")).map(|s| s.data.clone()); + let context = preparation_context(&envelope).unwrap(); + assert!(context.extent_priorities.complete); + assert_eq!(envelope.layout.instances.len(), 2); + assert_eq!(envelope.layout.sections.len(), 2, "priority metadata creates no placed surrogates"); + let mut service = LayoutService::new(registry.clone(), envelope.layout.clone(), HostCapabilities::default()).unwrap(); + let action = transaction(vec![Mutation::SetSize { section: section("a"), size: size(280.0, 350.0) }]); + let before = service.inspect(); + let projected = service.project_with_context(action.clone(), &context).unwrap(); + let prepared = service.prepare_with_context(action.clone(), &AvailabilityMap::new(), &context).unwrap(); + assert_eq!(prepared.layout(), &projected); + assert_eq!(service.prepare(action.clone()).unwrap().layout(), &projected, "full-envelope hydration seeds bare preparation too"); + assert_eq!(service.inspect(), before); + let mut incomplete = context.clone(); + incomplete.extent_priorities.records.clear(); + assert_eq!(service.prepare_with_context(action.clone(), &AvailabilityMap::new(), &incomplete).err().unwrap().rule, Rule::Capability); + assert_eq!(service.prepare_with_reservations(action, &context.sections, &context.columns).err().unwrap().rule, Rule::Capability); + let staged = with_live_layout(&envelope, prepared.layout().clone(), ®istry).unwrap(); + assert_eq!(staged.quarantine[0].instance_data, raw); + assert_eq!(staged.section_snapshots.get(§ion("q")).map(|s| s.data.clone()), original_snapshot); + let authored = if initial == u16::MAX { 4 } else { 43 }; + assert_eq!(prepared.layout().section(§ion("a")).unwrap().extent_priority, authored); + if initial == u16::MAX { + assert!( + staged + .extent_priority_overrides + .iter() + .any(|r| r.target == ExtentPriorityTarget::Memory(id("q")) && r.stored_priority == 42 && r.priority == 2) + ); + } else { + assert!(staged.extent_priority_overrides.is_empty()); + } + let encoded = encode(&staged, ®istry).unwrap(); + let loaded = decode(&encoded, ®istry, &persistence_fallback()).unwrap(); + assert!(loaded.notice.is_none()); + let (grown, recovered, owner) = restored_priority_owner(loaded.envelope, ®istry); + let effective_q = if initial == u16::MAX { 2 } else { 42 }; + assert_eq!(owner.layout().containing(&id("q")).unwrap().extent_priority, effective_q); + let mut environment = allocated_pair_environment(&owner, 400.0); + environment.gap = 4.0; + let allocated = allocate_layout(owner.layout(), &grown, &environment).unwrap(); + for (name, expected) in [("a", 152.0), ("b", 120.0), ("q", 120.0)] { + assert!((allocated.sections.iter().find(|s| s.section == section(name)).unwrap().outer.size.height - expected).abs() < 0.002); + } + let saved = with_live_layout(&recovered, owner.layout().clone(), &grown).unwrap(); + assert_eq!(saved.retained_data[&id("q")]["instance"], raw); + if snapshot { + assert_eq!(saved.section_snapshots[§ion("q")].data["extent_priority"], 42); + } + service.commit(prepared).unwrap(); + if initial == u16::MAX { + assert_eq!( + service + .prepare_with_context( + transaction(vec![Mutation::SetSize { section: section("a"), size: size(280.0, 360.0) }]), + &AvailabilityMap::new(), + &context + ) + .err() + .unwrap() + .rule, + Rule::Revision + ); + } + } + } +} + +#[test] +fn catalogue_only_recovery_priorities_reach_headless_single_and_atomic_batch_preparation() { + use commands::LayoutCatalogue; + for batch in [false, true] { + let (registry, envelope) = priority_recovery_envelope(u16::MAX, false); + let raw = envelope.quarantine[0].instance_data.clone(); + let mut bare = envelope.layout.clone(); + bare.extent_priority_context = ExtentPriorityContext::default(); + let service = LayoutService::new(registry.clone(), bare, HostCapabilities::default()).unwrap(); + let mut catalogue = commands::InMemoryCatalogue::default(); + catalogue.remember(&envelope, None, ®istry).unwrap(); + let mut backend = commands::InMemoryPanelBackend::new(service, catalogue); + let params = serde_json::json!({"target":{"type":"section","id":"a"},"size":{"width":280,"height":350}}); + if batch { + backend + .batch(&[ + serde_json::json!({"command":"panel.resize","params":params}), + serde_json::json!({"command":"panel.resize","params":{"target":{"type":"section","id":"a"},"size":{"width":280,"height":360}}}), + ]) + .unwrap(); + } else { + backend.execute("panel.resize", ¶ms).unwrap(); + } + let stored = backend.catalogue.state().remembered(&backend.service.layout().workspace).unwrap(); + let remembered = stored.project_envelope(®istry, &backend.service.layout().workspace).unwrap(); + assert_eq!(remembered.quarantine[0].instance_data, raw); + let (grown, _, owner) = restored_priority_owner(remembered, ®istry); + let mut environment = allocated_pair_environment(&owner, 400.0); + environment.gap = 4.0; + let allocated = allocate_layout(owner.layout(), &grown, &environment).unwrap(); + assert!((allocated.sections.iter().find(|s| s.section == section("a")).unwrap().outer.size.height - 152.0).abs() < 0.002); + assert!((allocated.sections.iter().find(|s| s.section == section("q")).unwrap().outer.size.height - 120.0).abs() < 0.002); + } +} + +#[test] +fn incomplete_priority_proposals_and_hostile_shadow_metadata_cannot_publish_wrong_order() { + let (registry, envelope) = priority_recovery_envelope(u16::MAX, false); + let original = encode(&envelope, ®istry).unwrap(); + let mut bare = envelope.layout.clone(); + bare.extent_priority_context = ExtentPriorityContext::default(); + let service = LayoutService::new(registry.clone(), bare, HostCapabilities::default()).unwrap(); + let bad = service.prepare(transaction(vec![Mutation::SetSize { section: section("a"), size: size(280.0, 350.0) }])).unwrap(); + assert_eq!(with_live_layout(&envelope, bad.layout().clone(), ®istry).unwrap_err().rule, Rule::Capability); + assert_eq!(encode(&envelope, ®istry).unwrap(), original); + let full = preparation_context(&envelope).unwrap(); + let good = service + .prepare_with_context( + transaction(vec![Mutation::SetSize { section: section("a"), size: size(280.0, 350.0) }]), + &AvailabilityMap::new(), + &full, + ) + .unwrap(); + let staged = with_live_layout(&envelope, good.layout().clone(), ®istry).unwrap(); + let mut bare = staged.layout.clone(); + bare.extent_priority_context = ExtentPriorityContext::default(); + let bare = LayoutService::new(registry.clone(), bare, HostCapabilities::default()).unwrap(); + let stale = bare + .prepare_with_context( + transaction(vec![Mutation::SetSize { section: section("a"), size: size(280.0, 360.0) }]), + &AvailabilityMap::new(), + &full, + ) + .unwrap(); + assert_eq!(with_live_layout(&staged, stale.layout().clone(), ®istry).unwrap_err().rule, Rule::Revision); + let mut wrong = envelope.clone(); + wrong.extent_priority_overrides.push(ExtentPriorityRecord { + target: ExtentPriorityTarget::Memory(id("q")), + zone: Zone::Left, + column: wrong.layout.columns.first().map(|c| c.id.clone()), + stored_priority: 41, + priority: 2, + }); + assert_eq!(encode(&wrong, ®istry).unwrap_err().rule, Rule::Schema); + wrong.extent_priority_overrides[0].stored_priority = 42; + wrong.extent_priority_overrides.push(wrong.extent_priority_overrides[0].clone()); + assert_eq!(encode(&wrong, ®istry).unwrap_err().rule, Rule::DuplicateId); + let mut too_many = ExtentPriorityContext { complete: true, records: Vec::new() }; + for n in 0..=MAX_EXTENT_PRIORITY_RECORDS { + too_many.records.push(ExtentPriorityRecord { + target: ExtentPriorityTarget::Memory(id(&format!("q-{n}"))), + zone: Zone::Bottom, + column: None, + stored_priority: 42, + priority: 2, + }); + } + assert_eq!(too_many.validate().unwrap_err().rule, Rule::CollectionLimit); +} + +#[test] +fn preset_apply_and_reset_retain_opaque_effective_priorities_order_and_rejected_bytes() { + use commands::LayoutCatalogue; + use serde_json::json; + for initial in [u16::MAX, 10] { + for snapshot in [false, true] { + for operation in ["layout.apply", "layout.reset"] { + let (registry, original) = priority_recovery_envelope(initial, snapshot); + let service = LayoutService::new(registry.clone(), original.layout.clone(), HostCapabilities::default()).unwrap(); + let prepared = service.prepare(transaction(vec![Mutation::SetSize { section: section("a"), size: size(280.0, 350.0) }])).unwrap(); + let current = with_live_layout(&original, prepared.layout().clone(), ®istry).unwrap(); + let raw_q = current.quarantine[0].instance_data.clone(); + let raw_snapshot = current.section_snapshots.get(§ion("q")).map(|s| s.data.clone()); + let mut preset = LayoutEnvelope::new(current.layout.clone()); + preset.layout.extent_priority_context = ExtentPriorityContext::default(); + assert!(preset.quarantine.is_empty() && preset.section_snapshots.is_empty()); + let mut catalogue = commands::InMemoryCatalogue::default(); + catalogue.register_builtin("Without Q", &preset, ®istry).unwrap(); + catalogue + .register_workspace(commands::WorkspaceDescriptor { + id: current.layout.workspace.clone(), + title_key: "ui.panel".into(), + default_preset: "Without Q".into(), + }) + .unwrap(); + let rejected = [0, 255, 128, 17]; + catalogue.remember(¤t, Some(&rejected), ®istry).unwrap(); + let preset_bytes = catalogue.state().preset("Without Q").unwrap().bytes().to_vec(); + let service = LayoutService::new(registry.clone(), current.layout.clone(), HostCapabilities::default()).unwrap(); + let mut backend = commands::InMemoryPanelBackend::new(service, catalogue); + backend.execute(operation, &if operation == "layout.apply" { json!({"name":"Without Q"}) } else { json!({}) }).unwrap(); + assert_eq!(backend.catalogue.state().preset("Without Q").unwrap().bytes(), preset_bytes); + let stored = backend.catalogue.state().remembered(¤t.layout.workspace).unwrap(); + assert_eq!(stored.rejected(), Some(rejected.as_slice())); + let merged = stored.project_envelope(®istry, ¤t.layout.workspace).unwrap(); + assert_eq!(merged.quarantine[0].instance_data, raw_q); + assert_eq!(merged.section_snapshots.get(§ion("q")).map(|s| s.data.clone()), raw_snapshot); + assert_eq!(merged.section_order, current.section_order); + let effective_q = if initial == u16::MAX { 2 } else { 42 }; + let context = preparation_context(&merged).unwrap(); + let q = context.extent_priorities.records.iter().find(|r| r.target == ExtentPriorityTarget::Memory(id("q"))).unwrap(); + assert_eq!((q.stored_priority, q.priority), (42, effective_q)); + if initial == u16::MAX { + assert_eq!(merged.layout.section(§ion("a")).unwrap().extent_priority, 4); + assert_eq!(merged.layout.section(§ion("b")).unwrap().extent_priority, 1); + assert!(merged.extent_priority_overrides.windows(2).all(|pair| pair[0].target < pair[1].target)); + } + let (grown, recovered, owner) = restored_priority_owner(merged, ®istry); + assert_eq!(owner.layout().containing(&id("q")).unwrap().extent_priority, effective_q); + assert_eq!(owner.layout().sections.iter().map(|s| s.id.clone()).collect::>(), vec![section("a"), section("b"), section("q")]); + assert_eq!(recovered.retained_data[&id("q")]["instance"], raw_q); + let mut environment = allocated_pair_environment(&owner, 400.0); + environment.gap = 4.0; + let geometry = allocate_layout(owner.layout(), &grown, &environment).unwrap(); + for (name, expected) in [("a", 152.0), ("b", 120.0), ("q", 120.0)] { + assert!((geometry.sections.iter().find(|s| s.section == section(name)).unwrap().outer.size.height - expected).abs() < 0.002); + } + } + } + } +} + +#[test] +fn preset_merge_refuses_conflicting_effective_tiers_for_identical_raw_recovery_sources() { + use commands::LayoutCatalogue; + for snapshot in [false, true] { + for incoming_wins in [false, true] { + let (registry, original) = priority_recovery_envelope(u16::MAX, snapshot); + let service = LayoutService::new(registry.clone(), original.layout.clone(), HostCapabilities::default()).unwrap(); + let prepared = service.prepare(transaction(vec![Mutation::SetSize { section: section("a"), size: size(280.0, 350.0) }])).unwrap(); + let mut current = with_live_layout(&original, prepared.layout().clone(), ®istry).unwrap(); + let mut incoming = current.clone(); + let changed = if incoming_wins { &mut incoming } else { &mut current }; + for record in &mut changed.extent_priority_overrides { + if matches!(&record.target, ExtentPriorityTarget::Memory(owner) if *owner == id("q")) + || matches!(&record.target, ExtentPriorityTarget::Section(owner) if *owner == section("q")) + { + record.priority = 3; + } + } + changed.layout.extent_priority_context = preparation_context(changed).unwrap().extent_priorities; + assert_eq!(current.quarantine, incoming.quarantine); + assert_eq!(current.section_snapshots, incoming.section_snapshots); + let mut catalogue = commands::InMemoryCatalogue::default(); + catalogue.register_builtin("Same recovery", ¤t, ®istry).unwrap(); + catalogue.register_builtin("Conflicting recovery", &incoming, ®istry).unwrap(); + catalogue.remember(¤t, None, ®istry).unwrap(); + let service = LayoutService::new(registry.clone(), current.layout.clone(), HostCapabilities::default()).unwrap(); + let mut backend = commands::InMemoryPanelBackend::new(service, catalogue); + backend.execute("layout.apply", &serde_json::json!({"name":"Same recovery"})).unwrap(); + let before = backend.service.inspect(); + let catalogue = backend.catalogue.state().export().unwrap(); + let failure = backend.execute("layout.apply", &serde_json::json!({"name":"Conflicting recovery"})).unwrap_err(); + assert_eq!(failure.rule, Rule::DuplicateId); + assert_eq!(failure.detail, "retained effective priority collision"); + assert_eq!(backend.service.inspect(), before); + assert_eq!(backend.catalogue.state().export().unwrap(), catalogue); + } + } +} + +#[test] +fn staging_new_authored_sections_and_closed_memories_requires_complete_recovery_context() { + for was_closed in [false, true] { + for close_after in [false, true] { + for exhausted in [false, true] { + let (registry, mut envelope) = priority_recovery_envelope(10, false); + envelope.layout.sections.retain(|s| s.id != section("a")); + if was_closed { + envelope.layout.instances.iter_mut().find(|p| p.id == id("a")).unwrap().requested_open = false; + } else { + envelope.layout.instances.retain(|p| p.id != id("a")); + } + if exhausted { + envelope.layout.sections.iter_mut().find(|s| s.id == section("b")).unwrap().extent_priority = u16::MAX; + envelope.layout.instances.iter_mut().find(|p| p.id == id("b")).unwrap().memory.extent_priority = u16::MAX; + } + envelope.section_snapshots.remove(§ion("a")); + envelope.section_order.retain(|id| *id != section("a")); + envelope.layout.extent_priority_context = ExtentPriorityContext::default(); + let original = encode(&envelope, ®istry).unwrap(); + let loaded = decode(&original, ®istry, &persistence_fallback()).unwrap(); + assert!(loaded.notice.is_none()); + let envelope = loaded.envelope; + let raw_q = envelope.quarantine[0].instance_data.clone(); + let mut bare = envelope.layout.clone(); + bare.extent_priority_context = ExtentPriorityContext::default(); + let service = LayoutService::new(registry.clone(), bare, HostCapabilities::default()).unwrap(); + let action = transaction(vec![ + if was_closed { + Mutation::Open { kind: PanelKind::new("fixture.log").unwrap(), instance: id("a"), destination: None } + } else { + fixture_open("fixture.log", "a", "a", Zone::Left, 0).unwrap() + }, + Mutation::SetSize { section: section("a"), size: size(280.0, 350.0) }, + ]); + let close = |layout: &Layout| { + if close_after { + let mut closer = LayoutService::new(registry.clone(), layout.clone(), HostCapabilities::default()).unwrap(); + closer.dispatch(transaction(vec![Mutation::Close { instance: id("a") }])).unwrap(); + assert!(closer.layout().section(§ion("a")).is_err()); + closer.layout().clone() + } else { + layout.clone() + } + }; + let before = service.inspect(); + let bad = close(service.prepare(action.clone()).unwrap().layout()); + assert_eq!(with_live_layout(&envelope, bad, ®istry).unwrap_err().rule, Rule::Capability); + assert_eq!(service.inspect(), before); + assert_eq!(encode(&envelope, ®istry).unwrap(), original); + let context = preparation_context(&envelope).unwrap(); + let good = service.prepare_with_context(action, &AvailabilityMap::new(), &context).unwrap(); + let staged = with_live_layout(&envelope, close(good.layout()), ®istry).unwrap(); + assert_eq!(staged.quarantine[0].instance_data, raw_q); + let (grown, recovered, mut owner) = restored_priority_owner(staged, ®istry); + if close_after { + owner + .dispatch(transaction(vec![Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("a"), + destination: None, + }])) + .unwrap(); + } + assert!(owner.layout().containing(&id("a")).unwrap().extent_priority > owner.layout().containing(&id("q")).unwrap().extent_priority); + let mut environment = allocated_pair_environment(&owner, 400.0); + environment.gap = 4.0; + let geometry = allocate_layout(owner.layout(), &grown, &environment).unwrap(); + for (name, expected) in [("a", 152.0), ("b", 120.0), ("q", 120.0)] { + assert!((geometry.sections.iter().find(|s| s.section == section(name)).unwrap().outer.size.height - expected).abs() < 0.002); + } + let saved = with_live_layout(&recovered, owner.layout().clone(), &grown).unwrap(); + assert_eq!(saved.retained_data[&id("q")]["instance"], raw_q); + } + } + } +} + +#[test] +fn inherited_closed_reopen_and_native_return_tiers_remain_stageable_without_authored_intent() { + for native in [false, true] { + let (registry, envelope) = priority_recovery_envelope(60, false); + let caps = HostCapabilities { native_windows: true, max_native_hosts: 8, persistence: true }; + let mut service = LayoutService::new(registry.clone(), envelope.layout.clone(), caps.clone()).unwrap(); + if native { + service + .dispatch(transaction(vec![Mutation::Move { + instance: id("a"), + destination: Destination::NewSection { + section: section("native-a"), + index: 0, + size: size(280.0, 300.0), + location: SectionLocation::Window { + host: HostId::new("inherited-tier").unwrap(), + origin: Point { x: 0.0, y: 0.0 }, + return_to: DockReturn { + zone: Zone::Left, + index: 0, + section: None, + column: None, + column_index: 0, + column_width: None, + size: size(280.0, 300.0), + collapsed: false, + join: None, + weight: 1.0, + preferred_extent: None, + extent_priority: 0, + }, + }, + }, + }])) + .unwrap(); + } else { + service.dispatch(transaction(vec![Mutation::Close { instance: id("a") }])).unwrap(); + } + let saved = with_live_layout(&envelope, service.layout().clone(), ®istry).unwrap(); + let mut bare = saved.layout.clone(); + bare.extent_priority_context = ExtentPriorityContext::default(); + let service = LayoutService::new(registry.clone(), bare, caps).unwrap(); + let mutation = if native { + Mutation::NativeClose { host: HostId::new("inherited-tier").unwrap() } + } else { + Mutation::Open { kind: PanelKind::new("fixture.log").unwrap(), instance: id("a"), destination: None } + }; + let prepared = service.prepare(transaction(vec![mutation])).unwrap(); + let staged = with_live_layout(&saved, prepared.layout().clone(), ®istry).unwrap(); + assert_eq!(staged.layout.containing(&id("a")).unwrap().extent_priority, 60); + assert_eq!(staged.quarantine[0].instance_data, envelope.quarantine[0].instance_data); + let (grown, _, owner) = restored_priority_owner(staged, ®istry); + let mut environment = allocated_pair_environment(&owner, 400.0); + environment.gap = 4.0; + let geometry = allocate_layout(owner.layout(), &grown, &environment).unwrap(); + for (panel, expected) in [("a", 152.0), ("b", 120.0), ("q", 120.0)] { + let group = owner.layout().containing(&id(panel)).unwrap(); + assert!((geometry.sections.iter().find(|s| s.section == group.id).unwrap().outer.size.height - expected).abs() < 0.002); + } + } +} + +#[test] +fn native_close_then_resize_cannot_inherit_a_reused_window_primary_priority() { + for close_after in [false, true] { + let (registry, mut envelope) = priority_recovery_envelope(18, false); + let host = HostId::new("rank-reuse").unwrap(); + let original_a = envelope.layout.section(§ion("a")).unwrap().clone(); + let native = SectionLocation::Window { + host: host.clone(), + origin: Point { x: 20.0, y: 30.0 }, + return_to: DockReturn { + zone: Zone::Left, + section: Some(section("a")), + index: 0, + join: None, + column: original_a.column.clone(), + column_index: 0, + column_width: Some(280.0), + size: size(280.0, 300.0), + collapsed: false, + weight: original_a.weight, + preferred_extent: Some(300.0), + extent_priority: 18, + }, + }; + let group = envelope.layout.sections.iter_mut().find(|s| s.id == section("a")).unwrap(); + group.id = section("window-a"); + group.location = native.clone(); + group.column = None; + group.size.height = 350.0; + group.preferred_extent = Some(350.0); + group.extent_priority = 19; + let memory = &mut envelope.layout.instances.iter_mut().find(|p| p.id == id("a")).unwrap().memory; + memory.section = section("window-a"); + memory.location = native; + memory.column = None; + memory.column_width = None; + memory.column_index = 0; + memory.size.height = 350.0; + memory.preferred_extent = Some(350.0); + memory.extent_priority = 19; + for group in &mut envelope.section_order { + if *group == section("a") { + *group = section("window-a"); + } + } + envelope.layout.extent_priority_context = ExtentPriorityContext::default(); + let bytes = encode(&envelope, ®istry).unwrap(); + let loaded = decode(&bytes, ®istry, &persistence_fallback()).unwrap(); + assert!(loaded.notice.is_none()); + let envelope = loaded.envelope; + let raw_q = envelope.quarantine[0].instance_data.clone(); + let caps = HostCapabilities { native_windows: true, max_native_hosts: 8, persistence: true }; + let mut bare = envelope.layout.clone(); + bare.extent_priority_context = ExtentPriorityContext::default(); + let service = LayoutService::new(registry.clone(), bare, caps.clone()).unwrap(); + let before = service.inspect(); + // Matching the actual return descriptor remains an inherited operation + // even though its primary Window extent and tier differ. + let returned = service.prepare(transaction(vec![Mutation::NativeClose { host: host.clone() }])).unwrap(); + let inherited = with_live_layout(&envelope, returned.layout().clone(), ®istry).unwrap(); + let a = inherited.layout.section(§ion("a")).unwrap(); + assert_eq!((a.preferred_extent, a.extent_priority, &a.column), (Some(300.0), 18, &original_a.column)); + assert_eq!(inherited.quarantine[0].instance_data, raw_q); + + let action = transaction(vec![Mutation::NativeClose { host }, Mutation::SetSize { section: section("a"), size: size(280.0, 350.0) }]); + let close = |layout: &Layout| { + if close_after { + let mut closer = LayoutService::new(registry.clone(), layout.clone(), caps.clone()).unwrap(); + closer.dispatch(transaction(vec![Mutation::Close { instance: id("a") }])).unwrap(); + assert!(closer.layout().section(§ion("a")).is_err()); + closer.layout().clone() + } else { + layout.clone() + } + }; + let bad = service.prepare(action.clone()).unwrap(); + let a = bad.layout().section(§ion("a")).unwrap(); + assert_eq!((a.preferred_extent, a.extent_priority), (Some(350.0), 19), "bare redock removes the former primary tier before reusing 19"); + assert_eq!(with_live_layout(&envelope, close(bad.layout()), ®istry).unwrap_err().rule, Rule::Capability); + assert_eq!(service.inspect(), before); + assert_eq!(encode(&envelope, ®istry).unwrap(), bytes); + + let context = preparation_context(&envelope).unwrap(); + let good = service.prepare_with_context(action, &AvailabilityMap::new(), &context).unwrap(); + assert_eq!(good.layout().section(§ion("a")).unwrap().extent_priority, 43); + let staged = with_live_layout(&envelope, close(good.layout()), ®istry).unwrap(); + assert_eq!(staged.quarantine[0].instance_data, raw_q); + let (grown, recovered, mut owner) = restored_priority_owner(staged, ®istry); + if close_after { + owner + .dispatch(transaction(vec![Mutation::Open { kind: PanelKind::new("fixture.log").unwrap(), instance: id("a"), destination: None }])) + .unwrap(); + } + let mut environment = allocated_pair_environment(&owner, 400.0); + environment.gap = 4.0; + let geometry = allocate_layout(owner.layout(), &grown, &environment).unwrap(); + for (name, expected) in [("a", 152.0), ("b", 120.0), ("q", 120.0)] { + assert!((geometry.sections.iter().find(|s| s.section == section(name)).unwrap().outer.size.height - expected).abs() < 0.002); + } + let saved = with_live_layout(&recovered, owner.layout().clone(), &grown).unwrap(); + assert_eq!(saved.retained_data[&id("q")]["instance"], raw_q); + } +} diff --git a/crates/engine/src/schema/features.rs b/crates/engine/src/schema/features.rs index ee83f04a0..2e1e77c67 100644 --- a/crates/engine/src/schema/features.rs +++ b/crates/engine/src/schema/features.rs @@ -113,9 +113,9 @@ pub struct ExtrudeParams { /// Which way to extrude. Default: positive. #[serde(default)] pub direction: Option, - /// 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, /// Start this far from the sketch plane, along its normal. diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs index 70327e14a..6f1251c8f 100644 --- a/crates/engine/src/schema/mod.rs +++ b/crates/engine/src/schema/mod.rs @@ -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; diff --git a/crates/engine/src/schema/panels.rs b/crates/engine/src/schema/panels.rs index 9adf2f5d4..c3441b25c 100644 --- a/crates/engine/src/schema/panels.rs +++ b/crates/engine/src/schema/panels.rs @@ -46,6 +46,7 @@ pub enum Target { Workspace(WorkspaceId), Instance(InstanceId), Section(SectionId), + Column(ColumnId), NativeHost(HostId), } impl From for LayoutTarget { @@ -54,6 +55,7 @@ impl From 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, + #[serde(default)] + pub column: Option, + #[serde(default)] + pub column_index: usize, + #[serde(default)] + pub column_width: Option, + #[serde(default = "default_weight")] + pub weight: f32, + #[serde(default)] + pub preferred_extent: Option, + #[serde(default)] + pub extent_priority: u16, + #[serde(default)] pub join: Option, } impl From for DockReturn { @@ -104,6 +120,13 @@ impl From 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 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, size: OuterSize }, } impl From for Destination { fn from(value: Placement) -> Self { @@ -137,6 +161,9 @@ impl From 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, pub destination: Placement, pub expected_revision: Option, + #[serde(default)] + pub activate: bool, +} +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct HeaderAction { + pub target: Option, + pub id: Option, + pub action: ControlId, + pub expected_revision: Option, } #[derive(Debug, Deserialize, JsonSchema)] #[serde(deny_unknown_fields)] @@ -174,6 +211,10 @@ pub struct Resize { pub target: Option, pub id: Option, 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, } #[derive(Debug, Deserialize, JsonSchema)] diff --git a/crates/engine/src/schema/sketch_clipboard.rs b/crates/engine/src/schema/sketch_clipboard.rs new file mode 100644 index 000000000..8f481c188 --- /dev/null +++ b/crates/engine/src/schema/sketch_clipboard.rs @@ -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: D) -> Result { + 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::() + } +} + +/// 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, + /// The sketch they are in (default: the one being edited). + #[serde(default)] + pub sketch: Option, +} + +/// 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, + /// The sketch they are in (default: the one being edited). + #[serde(default)] + pub sketch: Option, +} + +/// 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, + /// How far to move the copy from where it was (mm). + #[serde(default, deserialize_with = "present")] + #[schemars(with = "PastePoint")] + pub translate: Option, + /// The sketch to paste into (default: the one being edited). + #[serde(default)] + pub sketch: Option, +} + +/// 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, +} + +/// What `sketch.paste` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct Pasted { + /// The new curves' ids. + pub curves: Vec, + /// The new lone points' ids. + pub points: Vec, + /// The new constraints' and dimensions' ids. + pub constraints: Vec, + /// 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, +} + +#[cfg(test)] +#[path = "sketch_clipboard_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/sketch_clipboard_tests.rs b/crates/engine/src/schema/sketch_clipboard_tests.rs new file mode 100644 index 000000000..76bb1aa84 --- /dev/null +++ b/crates/engine/src/schema/sketch_clipboard_tests.rs @@ -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::(), &["entities", "sketch"]); + assert_keys(input_schema_for::(), &["entities", "sketch"]); + assert_keys(input_schema_for::(), &["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::(), output_schema_for::()); + 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); +} diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt index a2b9722db..379149013 100644 --- a/crates/engine/src/schema/unconverted.txt +++ b/crates/engine/src/schema/unconverted.txt @@ -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 diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 4280dc95f..e068b923f 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -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 = 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(); diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 2f1dde8bd..74ede324e 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -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 { + 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 { 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 { 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 { 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 = 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 { + 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 = 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| { + 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 = 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] diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index ec8e90ebb..518cc18ef 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -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 { + 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)> { + 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::(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 diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 87690cd59..fec5fad8a 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -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::::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::::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(); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index a76febed8..33bb76cf7 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -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, 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) -> Result { + 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. diff --git a/crates/ui-egui/src/dialogs_assembly.rs b/crates/ui-egui/src/dialogs_assembly.rs index 672cacc2d..f8f6ee05d 100644 --- a/crates/ui-egui/src/dialogs_assembly.rs +++ b/crates/ui-egui/src/dialogs_assembly.rs @@ -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, @@ -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 { 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 { let kind = TYPES.get(f.kind).copied().unwrap_or("rigid"); let jk = f.joint_kind(); + let custom_name = f.name.trim(); let limits: Vec = 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 Result { diff --git a/crates/ui-egui/src/dialogs_assembly_tests.rs b/crates/ui-egui/src/dialogs_assembly_tests.rs index a3522409e..66dab8453 100644 --- a/crates/ui-egui/src/dialogs_assembly_tests.rs +++ b/crates/ui-egui/src/dialogs_assembly_tests.rs @@ -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"); + } +} diff --git a/crates/ui-egui/src/dialogs_surface.rs b/crates/ui-egui/src/dialogs_surface.rs index cdc393941..af49ad834 100644 --- a/crates/ui-egui/src/dialogs_surface.rs +++ b/crates/ui-egui/src/dialogs_surface.rs @@ -528,9 +528,12 @@ pub fn commands(app: &SolveApp, k: &Surf, inputs: &[SelInput], extra: &Map { 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")?, }; diff --git a/crates/ui-egui/src/extrude_edit_tests.rs b/crates/ui-egui/src/extrude_edit_tests.rs index 85ee2ba16..a32acd9a9 100644 --- a/crates/ui-egui/src/extrude_edit_tests.rs +++ b/crates/ui-egui/src/extrude_edit_tests.rs @@ -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 { + 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); +} diff --git a/crates/ui-egui/src/extrude_face_snap.rs b/crates/ui-egui/src/extrude_face_snap.rs new file mode 100644 index 000000000..c02736618 --- /dev/null +++ b/crates/ui-egui/src/extrude_face_snap.rs @@ -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, +} + +type Faces = (Option>, Arc>); + +thread_local! { + /// The face the arrow stopped at this frame (for the outline, scenarios and tests). + static CURRENT: RefCell> = const { RefCell::new(None) }; + /// The flat faces of the last model state looked at. + static FACES: RefCell = 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 { + CURRENT.with(|c| c.borrow().clone()) +} + +pub(crate) fn set(stop: Option) { + 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 { + let mut by_face: Vec<(Vec3, Vec)> = 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) -> Arc> { + 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> = 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) -> 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 { + 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 { + 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 = 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 = 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))); + } +} diff --git a/crates/ui-egui/src/file_load.rs b/crates/ui-egui/src/file_load.rs index 216ee4dfd..45b087649 100644 --- a/crates/ui-egui/src/file_load.rs +++ b/crates/ui-egui/src/file_load.rs @@ -61,6 +61,9 @@ pub struct Request { pub design: Option, /// The chat turn that requested the load. It must still be current when the file lands. pub(crate) chat_turn: Option>, + /// 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()); diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index d9f930077..bc5fe867e 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -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, diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 3f60f5094..1a454bc70 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -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, /// The bodies of a just-opened Y-up file, offered to be stood up (`stand_up`). pub stand_up: Option>, /// 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) { 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, 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 = 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 { 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 { + 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) { diff --git a/crates/ui-egui/src/mesh_units.rs b/crates/ui-egui/src/mesh_units.rs new file mode 100644 index 000000000..5a8c3a533 --- /dev/null +++ b/crates/ui-egui/src/mesh_units.rs @@ -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"); + } +} diff --git a/crates/ui-egui/src/navigation.rs b/crates/ui-egui/src/navigation.rs index 9aaf7323a..d2a16fc9f 100644 --- a/crates/ui-egui/src/navigation.rs +++ b/crates/ui-egui/src/navigation.rs @@ -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 } } diff --git a/crates/ui-egui/src/navigation_bar_view.rs b/crates/ui-egui/src/navigation_bar_view.rs index 094caf0e0..ac1e7e9eb 100644 --- a/crates/ui-egui/src/navigation_bar_view.rs +++ b/crates/ui-egui/src/navigation_bar_view.rs @@ -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 { diff --git a/crates/ui-egui/src/panel_runtime/app.rs b/crates/ui-egui/src/panel_runtime/app.rs index af9a0ca33..358093d02 100644 --- a/crates/ui-egui/src/panel_runtime/app.rs +++ b/crates/ui-egui/src/panel_runtime/app.rs @@ -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, + native: Box, + host: Option, + last_tick_frame: Option, last_error: Option, catalogue: Box, - native: Box, adapters_set: bool, } impl AppPanelRuntime { - pub fn new(runtime: PanelRuntime, services: Box) -> Self { - Self { + pub fn new(runtime: PanelRuntime, services: Box) -> PanelResult { + 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::::default(), + host: None, + last_tick_frame: None, last_error: None, catalogue: Box::::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, native: Box) -> 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 { - 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 { + 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(&mut self, execute: impl FnOnce(&mut commands::PanelCommandContext<'_>) -> PanelResult) -> PanelResult { + 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(&mut self, use_services: impl FnOnce(&mut PanelRuntime, &mut ContentServices<'_>) -> PanelResult) -> PanelResult { - 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(&mut self, use_services: impl FnOnce(&PanelRuntime, &mut ContentServices<'_>) -> PanelResult) -> PanelResult { + self.with_adapters(|runtime, _native, services| use_services(runtime, services)) + } + fn with_adapters( + &mut self, + use_services: impl FnOnce(&mut PanelRuntime, &mut dyn NativeHostAdapter, &mut ContentServices<'_>) -> PanelResult, + ) -> PanelResult { + 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 { - 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 { + 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) -> 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, +} + +/// 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>, +} +impl AdmittedActionSink<'_, '_, '_> { + fn project_owned(&self, action: LayoutAction, context: Option<&LayoutPreparationContext>) -> PanelResult { + 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 { + 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 { + self.project_owned(action, None) + } + fn project_in_context(&self, action: LayoutAction, context: &LayoutPreparationContext) -> PanelResult { + self.project_owned(action, Some(context)) + } + fn inspect(&self) -> LayoutReply { + self.live.inspect() + } + fn dispatch(&mut self, action: LayoutAction) -> PanelResult { + self.dispatch_owned(action, None) + } + fn dispatch_in_context(&mut self, action: LayoutAction, context: &LayoutPreparationContext) -> PanelResult { + self.dispatch_owned(action, Some(context)) + } +} +impl ActionSink for CommandActionSink<'_> { + fn project_in_context(&self, action: LayoutAction, context: &LayoutPreparationContext) -> PanelResult { + self.live.project_in_context(action, context) + } + fn dispatch_in_context(&mut self, action: LayoutAction, context: &LayoutPreparationContext) -> PanelResult { + let reply = self.live.dispatch_in_context(action, context)?; + *self.committed = Some(reply.clone()); + Ok(reply) + } + fn project(&self, action: LayoutAction) -> PanelResult { + self.live.project(action) + } + fn inspect(&self) -> LayoutReply { + self.live.inspect() + } + fn dispatch(&mut self, action: LayoutAction) -> PanelResult { + 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) -> 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) -> 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 { 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); + } + }); + } +} diff --git a/crates/ui-egui/src/panel_runtime/fixtures.rs b/crates/ui-egui/src/panel_runtime/fixtures.rs index d7cdc9775..4d1d0ff52 100644 --- a/crates/ui-egui/src/panel_runtime/fixtures.rs +++ b/crates/ui-egui/src/panel_runtime/fixtures.rs @@ -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); } diff --git a/crates/ui-egui/src/panel_runtime/host.rs b/crates/ui-egui/src/panel_runtime/host.rs index 2208bba88..46a996d25 100644 --- a/crates/ui-egui/src/panel_runtime/host.rs +++ b/crates/ui-egui/src/panel_runtime/host.rs @@ -12,7 +12,7 @@ pub struct PanelContext { pub viewport: ViewportId, pub native_host: Option, pub outer: LogicalRect, - pub usable_body: LogicalRect, + pub usable_body: Option, 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); } }); diff --git a/crates/ui-egui/src/panel_runtime/interaction.rs b/crates/ui-egui/src/panel_runtime/interaction.rs new file mode 100644 index 000000000..311a7f726 --- /dev/null +++ b/crates/ui-egui/src/panel_runtime/interaction.rs @@ -0,0 +1,1854 @@ +//! Transient pointer capture. This module prepares candidates but never dispatches +//! or commits them: the retained runtime owns lifecycle/native side effects. + +use solidcraft_engine::panels::*; + +use super::LocalScope; +use super::layout::{ + HostContentMetrics, HostLayout, HostMetrics, bottom, next_host_column_id, next_host_section_id, rect, resolve_host_prepared_with_snapshot, + resolve_host_projected, resolve_host_projected_with_snapshot, right, +}; + +pub const HOST_DRAG_THRESHOLD: f32 = 6.0; + +const SIDE_DOCK_BAND: f32 = 16.0; +const EMPTY_SIDE_EXTRA: f32 = 40.0; +const BOTTOM_DOCK_BAND: f32 = 64.0; +const COLUMN_OUTWARD: f32 = 18.0; +const CENTRE_COLUMN_OUTWARD: f32 = 64.0; + +/// Resize target edges are logical for docks and physical for floating cards. +/// Pointer movement and rendered bounds use the corresponding physical edge. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum HostResizeEdge { + Left, + Right, + Top, + Bottom, + BottomRight, +} + +impl HostResizeEdge { + /// Dock targets retain their logical identity when the workspace mirrors. + /// Floating corners remain physical because floating rects do not mirror. + pub(super) fn physical(self, zone: Zone, direction: Direction) -> Self { + if zone.docked() && direction == Direction::Rtl { + match self { + Self::Left => Self::Right, + Self::Right => Self::Left, + other => other, + } + } else { + self + } + } +} + +/// Combine this typed identity with the owner/window-local scope for egui IDs. +/// Titles, coordinates, section ordering and short wire ControlIds are not IDs. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum HostPointerTarget { + Header { + instance: InstanceId, + }, + Tab { + instance: InstanceId, + }, + /// Legacy semantic identity; no rail is allocated or handled. + Rail { + instance: InstanceId, + }, + Collapse { + instance: InstanceId, + }, + Close { + instance: InstanceId, + }, + HeaderAction { + instance: InstanceId, + action: ControlId, + }, + Surface { + instance: InstanceId, + }, + Menu { + instance: InstanceId, + }, + TabOverflow { + section: SectionId, + }, + Sash { + first: SectionId, + second: SectionId, + }, + Resize { + section: SectionId, + edge: HostResizeEdge, + }, + Overflow { + zone: Zone, + }, + OverflowAll, +} + +impl HostPointerTarget { + pub fn validate(&self) -> PanelResult<()> { + match self { + Self::Header { instance } + | Self::Tab { instance } + | Self::Rail { instance } + | Self::Surface { instance } + | Self::Menu { instance } + | Self::Collapse { instance } + | Self::Close { instance } => valid_id(&instance.0), + Self::HeaderAction { instance, action } => { + valid_id(&instance.0)?; + valid_id(&action.0) + } + Self::TabOverflow { section } | Self::Resize { section, .. } => valid_id(§ion.0), + Self::Sash { first, second } => { + valid_id(&first.0)?; + valid_id(&second.0)?; + if first == second { + return Err(error(Rule::Placement, "sash targets must be distinct")); + } + Ok(()) + } + Self::Overflow { .. } | Self::OverflowAll => Ok(()), + } + } +} + +impl std::hash::Hash for HostPointerTarget { + fn hash(&self, state: &mut H) { + std::mem::discriminant(self).hash(state); + match self { + Self::Header { instance } + | Self::Tab { instance } + | Self::Rail { instance } + | Self::Surface { instance } + | Self::Menu { instance } + | Self::Collapse { instance } + | Self::Close { instance } => instance.hash(state), + Self::HeaderAction { instance, action } => { + instance.hash(state); + action.hash(state); + } + Self::TabOverflow { section } => section.hash(state), + Self::Sash { first, second } => { + first.hash(state); + second.hash(state); + } + Self::Resize { section, edge } => { + section.hash(state); + edge.hash(state); + } + Self::Overflow { zone } => (*zone as u8).hash(state), + Self::OverflowAll => {} + } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub enum HostPointerEvent { + Press { + at: Point, + target: Option, + }, + Move { + at: Point, + }, + Release { + at: Point, + }, + DoubleClick { + target: HostPointerTarget, + }, + Escape, + Cancel, + /// Transient pointer absence while the primary button remains held. Keep + /// capture, but require a fresh Move before any release can commit. + Leave, + /// Revalidate capture on a frame with no pointer movement. + Reconcile, + /// Panel-owned popovers count as inside. Dismissal never consumes outside + /// input, so the existing navigation path can use that same press. + OutsidePress { + at: Point, + inside_owned_overlay: bool, + }, +} + +#[derive(Clone, Debug, PartialEq)] +pub enum HostDropTargetId { + Dock { zone: Zone, before: Option }, + Tab { section: SectionId, before: Option }, + Relative { section: SectionId, placement: RelativePlacement }, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct HostDropTarget { + pub id: HostDropTargetId, + /// Explicit discoverable hover region in the committed layout. + pub bounds: LogicalRect, + pub destination: Destination, + pub rejection: Option, + pub priority: u8, + /// (horizontal axis, physical edge coordinate). + pub edge: Option<(bool, f32)>, + pub stable_key: String, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct HostPreview { + pub action: Option, + pub bounds: LogicalRect, + pub destination: Option, + pub rejection: Option, + pub projected: Option, + pub target: Option, + pub targets: Vec, + pub tab_marker: Option, +} + +impl HostPreview { + fn empty(bounds: LogicalRect) -> Self { + Self { action: None, bounds, destination: None, rejection: None, projected: None, target: None, targets: Vec::new(), tab_marker: None } + } +} + +#[derive(Debug, Default)] +pub struct HostInteractionUpdate { + pub candidate: Option, + pub preview: Option, + pub action: Option, + pub rejection: Option, + pub captured: bool, + pub consumed: bool, +} + +/// Captured exactly once for the proposed owner cohort, before final allocation. +#[derive(Clone, Debug)] +pub struct HostProposalSnapshot { + pub availability: AvailabilityMap, + pub metrics: std::sync::Arc, +} + +/// Adapter for synthetic callers with exact captured measurements but no provider. +/// It never guesses a new width and never measures a hidden/stretched body. +#[derive(Debug)] +struct CapturedHostMetrics { + revision: u64, + content: Vec, +} +impl HostContentMetrics for CapturedHostMetrics { + fn revision(&self) -> u64 { + self.revision + } + fn measure(&self, request: &ContentMeasureRequest) -> PanelResult { + self.content + .iter() + .find(|measure| measure.request == *request) + .cloned() + .ok_or_else(|| error(Rule::Revision, "captured owner metrics have no requested width")) + } +} +fn current_owner_snapshot(service: &LayoutService, reference: &HostLayout, proposed: &Layout) -> HostProposalSnapshot { + let metrics = reference.geometry_policy.measure.clone().unwrap_or_else(|| { + std::sync::Arc::new(CapturedHostMetrics { + revision: reference.allocation_environment.content_revision, + content: reference.allocation_environment.content.clone(), + }) + }); + HostProposalSnapshot { + availability: proposed.instances.iter().map(|instance| (instance.id.clone(), service.availability(&instance.id))).collect(), + metrics, + } +} + +/// One owned engine proposal plus its exact admitted host geometry. The engine +/// state cannot be forged, cloned or reconstructed from a preview action. +pub struct PreparedHostLayout { + prepared: PreparedLayout, + snapshot: HostProposalSnapshot, + action: LayoutAction, + layout: HostLayout, + reference: HostLayout, + scope: LocalScope, +} +impl std::fmt::Debug for PreparedHostLayout { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PreparedHostLayout").field("layout", &self.layout).field("scope", &self.scope).finish_non_exhaustive() + } +} +impl PreparedHostLayout { + pub fn layout(&self) -> &HostLayout { + &self.layout + } + pub fn prepared(&self) -> &PreparedLayout { + &self.prepared + } + pub fn proposal_snapshot(&self) -> &HostProposalSnapshot { + &self.snapshot + } + /// Original intent for lifecycle preflight only; commit uses into_prepared. + pub fn action(&self) -> &LayoutAction { + &self.action + } + pub fn validate_current(&self, service: &LayoutService, scope: &LocalScope, reference: &HostLayout) -> PanelResult<()> { + validate_context(service, scope, reference)?; + if self.scope != *scope || self.reference != *reference { + return Err(error(Rule::Revision, "prepared host environment or scope changed")); + } + self.layout.validate()?; + if self.snapshot.metrics.revision() != self.layout.allocation_environment.content_revision { + return Err(error(Rule::Revision, "proposed owner metric snapshot became stale")); + } + let available: Vec<_> = self + .prepared + .layout() + .instances + .iter() + .filter(|instance| self.snapshot.availability.get(&instance.id).is_none_or(|state| *state == Availability::Available)) + .map(|instance| instance.id.clone()) + .collect(); + if available != self.layout.allocation_environment.available { + return Err(error(Rule::Revision, "proposed availability differs from admitted geometry")); + } + Ok(()) + } + pub fn into_prepared(self, service: &LayoutService, scope: &LocalScope, reference: &HostLayout) -> PanelResult { + self.validate_current(service, scope, reference)?; + Ok(self.prepared) + } +} + +/// Every command and gesture calls this admission path before runtime lifecycle +/// preflight. It has no controller, preference, document or ID-allocation effects. +pub fn prepare_host_layout( + service: &LayoutService, + scope: &LocalScope, + reference: &HostLayout, + action: LayoutAction, +) -> PanelResult { + prepare_host_layout_with_snapshot(service, scope, reference, action, |proposed| Ok(current_owner_snapshot(service, reference, proposed))) +} + +/// One pure owner/topology projection, one capture, then numeric normalization +/// and final admission. C retains that cohort through every prefix and commit. +pub fn prepare_host_layout_with_snapshot( + service: &LayoutService, + scope: &LocalScope, + reference: &HostLayout, + action: LayoutAction, + capture: impl FnOnce(&Layout) -> PanelResult, +) -> PanelResult { + validate_context(service, scope, reference)?; + let exempt = matches!(&action, LayoutAction::Apply { mutations, .. } if !mutations.is_empty() && mutations.iter().all(|mutation| + matches!(mutation, Mutation::Close { .. } | Mutation::Collapse { .. } | Mutation::Focus { .. } | Mutation::Activate { .. } | Mutation::DismissPeek)) + && mutations.iter().any(|mutation| !matches!(mutation, Mutation::DismissPeek))); + let owners = project_host_action(service, reference, &action)?; + let snapshot = capture(&owners)?; + if snapshot.availability.len() > MAX_INSTANCES { + return Err(error(Rule::CollectionLimit, "proposed availability cap")); + } + for (id, state) in &snapshot.availability { + valid_id(&id.0)?; + owners.instance(id)?; + if let Availability::Unavailable { reason } = state + && (reason.is_empty() || reason.len() > 256) + { + return Err(error(Rule::Bounds, "proposed availability reason bound")); + } + } + // Refuse unavailable initiators before a numeric prefix can fail on their + // missing allocation. The private owner projection deliberately defers this + // check until the proposed owner's availability has been captured once. + if let LayoutAction::Apply { mutations, .. } = &action { + for mutation in mutations { + if let Mutation::Open { instance, .. } + | Mutation::Move { instance, .. } + | Mutation::Activate { instance } + | Mutation::Focus { instance } + | Mutation::Peek { instance } + | Mutation::HeaderAction { instance, .. } = mutation + && let Some(state) = snapshot.availability.get(instance) + { + state.require()?; + } + } + } + let normalized = normalize_host_action(service, reference, &action, &snapshot)?; + let proposed = project_captured(service, reference, normalized.action.clone(), &snapshot)?; + if !same_owner_topology(&owners, &proposed) { + return Err(error(Rule::Revision, "numeric normalization changed captured owner topology")); + } + let context = reference.geometry_policy.identity_reservations.preparation_context()?; + let prepared = service.prepare_with_context(normalized.action.clone(), &snapshot.availability, &context)?; + if prepared.layout() != &proposed || prepared.layout().extent_priority_context != proposed.extent_priority_context { + return Err(error(Rule::Revision, "captured availability changed the structural projection")); + } + let layout = resolve_host_prepared_with_snapshot(service, &prepared, reference, &snapshot)?; + // Final allocation remains authoritative even after cohort capture. + if let Some(expected) = &normalized.pair_geometry + && (expected.extent != layout.extent + || expected.sections.len() != layout.sections.len() + || expected.sections.iter().any(|old| !layout.sections.iter().any(|new| new.section == old.section && near_rect(old.outer, new.outer)))) + { + return Err(error(Rule::Bounds, "captured allocation changed the admitted pair geometry")); + } + for section in &prepared.layout().sections { + if section.location.zone() != Zone::Floating { + continue; + } + if presented_instance(section, &layout.allocation_environment.available).is_none() { + continue; + } + let old = service.layout().section(§ion.id).ok(); + let changed = old.is_none_or(|old| old.location != section.location || old.size != section.size || old.tabs != section.tabs); + if changed && !layout.sections.iter().any(|card| card.section == section.id && intersect_rect(card.header, layout.capacity).is_some()) { + return Err(error(Rule::NoSpace, "floating landing has no accessible clipped header")); + } + } + let extent = layout.extent; + let overflow = extent.width > layout.capacity.size.width || extent.height > layout.capacity.size.height; + let before = reference.extent; + let improves = extent.width <= before.width && extent.height <= before.height && (extent.width < before.width || extent.height < before.height); + if overflow && !exempt && !improves { + return Err(error(Rule::NoSpace, "candidate does not strictly improve existing overflow")); + } + Ok(PreparedHostLayout { prepared, snapshot, action, layout, reference: reference.clone(), scope: scope.clone() }) +} + +fn project_reserved(service: &LayoutService, reference: &HostLayout, action: LayoutAction) -> PanelResult { + service.project_with_context(action, &reference.geometry_policy.identity_reservations.preparation_context()?) +} + +fn project_captured(service: &LayoutService, reference: &HostLayout, action: LayoutAction, snapshot: &HostProposalSnapshot) -> PanelResult { + Ok(service + .prepare_with_context(action, &snapshot.availability, &reference.geometry_policy.identity_reservations.preparation_context()?)? + .layout() + .clone()) +} + +fn same_owner_topology(a: &Layout, b: &Layout) -> bool { + let location = |a: &SectionLocation, b: &SectionLocation| match (a, b) { + (SectionLocation::Dock { zone: a }, SectionLocation::Dock { zone: b }) => a == b, + (SectionLocation::Floating { origin: a }, SectionLocation::Floating { origin: b }) => a == b, + (SectionLocation::Window { host: a, origin: x, .. }, SectionLocation::Window { host: b, origin: y, .. }) => a == b && x == y, + _ => false, + }; + a.version == b.version + && a.workspace == b.workspace + && a.columns == b.columns + && a.instances.len() == b.instances.len() + && a.sections.len() == b.sections.len() + && a.instances.iter().zip(&b.instances).all(|(a, b)| a.id == b.id && a.kind == b.kind && a.requested_open == b.requested_open) + && a.sections.iter().zip(&b.sections).all(|(a, b)| { + a.id == b.id + && location(&a.location, &b.location) + && a.tabs == b.tabs + && a.active == b.active + && a.collapsed == b.collapsed + && a.column == b.column + }) +} + +fn geometry_tolerance(values: &[f32]) -> f32 { + values.iter().fold(1.0_f32, |largest, value| largest.max(value.abs())) * f32::EPSILON * 8.0 +} +fn axis(zone: Zone, size: Size) -> f32 { + if zone == Zone::Bottom { size.width } else { size.height } +} +fn with_axis(zone: Zone, mut size: Size, extent: f32) -> Size { + if zone == Zone::Bottom { + size.width = extent; + } else { + size.height = extent; + } + size +} +fn near_rect(a: LogicalRect, b: LogicalRect) -> bool { + let tolerance = geometry_tolerance(&[a.origin.x, a.origin.y, b.origin.x, b.origin.y, a.size.width, a.size.height, b.size.width, b.size.height]); + (a.origin.x - b.origin.x).abs() <= tolerance + && (a.origin.y - b.origin.y).abs() <= tolerance + && (a.size.width - b.size.width).abs() <= tolerance + && (a.size.height - b.size.height).abs() <= tolerance +} + +struct AllocatedPair<'a> { + first: &'a super::layout::HostSection, + second: &'a super::layout::HostSection, + zone: Zone, + total: f32, + lower: f32, + upper: f32, + first_min: f32, + second_min: f32, +} + +fn allocated_pair<'a>( + state: &Layout, + service: &LayoutService, + host: &'a HostLayout, + first: &SectionId, + second: &SectionId, +) -> PanelResult> { + let a = state.section(first)?; + let b = state.section(second)?; + let zone = a.location.zone(); + if !zone.docked() || b.location.zone() != zone || a.column != b.column || a.collapsed || b.collapsed { + return Err(error(Rule::Placement, "allocated sash requires one expanded dock group")); + } + let presented: Vec<_> = host + .sections + .iter() + .filter(|card| card.zone == zone && state.section(&card.section).is_ok_and(|section| section.column == a.column)) + .collect(); + let pair = presented + .windows(2) + .find(|pair| pair.first().is_some_and(|card| card.section == *first) && pair.get(1).is_some_and(|card| card.section == *second)) + .ok_or_else(|| error(Rule::Placement, "allocated sash requires presented adjacency"))?; + let first = pair.first().copied().ok_or_else(|| error(Rule::MissingTarget, "first allocated neighbour absent"))?; + let second = pair.get(1).copied().ok_or_else(|| error(Rule::MissingTarget, "second allocated neighbour absent"))?; + let (a_min, a_max) = effective_allocation_bounds(state, service.registry(), a, &host.allocation_environment)?; + let (b_min, b_max) = effective_allocation_bounds(state, service.registry(), b, &host.allocation_environment)?; + let total = axis(zone, first.outer.size) + axis(zone, second.outer.size); + let lower = f64::from(axis(zone, a_min)).max(f64::from(total) - f64::from(axis(zone, b_max))); + let upper = f64::from(axis(zone, a_max)).min(f64::from(total) - f64::from(axis(zone, b_min))); + let mut lo = lower as f32; + let mut hi = upper as f32; + if f64::from(lo) < lower { + lo = f32::from_bits(lo.to_bits().saturating_add(1)); + } + if f64::from(hi) > upper { + hi = f32::from_bits(hi.to_bits().saturating_sub(1)); + } + if !total.is_finite() || lo > hi { + return Err(error(Rule::Bounds, "allocated pair has no feasible interval")); + } + Ok(AllocatedPair { first, second, zone, total, lower: lo, upper: hi, first_min: axis(zone, a_min), second_min: axis(zone, b_min) }) +} + +fn requested_pair_axis(pair: &AllocatedPair<'_>, a: Size, b: Size) -> PanelResult { + a.validate()?; + b.validate()?; + let tolerance = geometry_tolerance(&[pair.total]); + let cross = |size: Size| if pair.zone == Zone::Bottom { size.height } else { size.width }; + if (axis(pair.zone, a) + axis(pair.zone, b) - pair.total).abs() > tolerance + || (cross(a) - cross(pair.first.outer.size)).abs() > tolerance + || (cross(b) - cross(pair.second.outer.size)).abs() > tolerance + { + return Err(error(Rule::Bounds, "pair request must conserve actual extent and cross axes")); + } + Ok(axis(pair.zone, a)) +} + +fn normalized_allocated_pair( + service: &LayoutService, + state: &Layout, + host: &HostLayout, + first: &SectionId, + second: &SectionId, + requested: Option<(Size, Size)>, +) -> PanelResult { + let pair = allocated_pair(state, service, host, first, second)?; + let wanted = if let Some((a, b)) = requested { + requested_pair_axis(&pair, a, b)? + } else { + let a = service.registry().get(&state.instance(&pair.first.instance)?.kind)?.default_size; + let b = service.registry().get(&state.instance(&pair.second.instance)?.kind)?.default_size; + (f64::from(pair.total) * f64::from(axis(pair.zone, a)) / (f64::from(axis(pair.zone, a)) + f64::from(axis(pair.zone, b)))) as f32 + }; + let split = wanted.clamp(pair.lower, pair.upper); + let first_size = with_axis(pair.zone, pair.first.outer.size, split); + let second_size = with_axis(pair.zone, pair.second.outer.size, pair.total - split); + let (first_weight, second_weight, other_weight_scale) = effective_pair_weights( + service, + state, + host, + first, + second, + (f64::from(split) - f64::from(pair.first_min)).max(0.0), + (f64::from(pair.total - split) - f64::from(pair.second_min)).max(0.0), + )?; + Ok(Mutation::ResizeAllocatedPair { + first: first.clone(), + second: second.clone(), + first_size, + second_size, + first_weight, + second_weight, + other_weight_scale, + prefer_allocated: false, + }) +} + +/// Infer the constrained allocator's surplus unit, not the latent total of +/// capped weights. Scaling all unpaired saved records preserves their ratios. +fn effective_pair_weights( + service: &LayoutService, + state: &Layout, + host: &HostLayout, + first: &SectionId, + second: &SectionId, + first_surplus: f64, + second_surplus: f64, +) -> PanelResult<(f32, f32, f32)> { + let anchor = state.section(first)?; + let zone = anchor.location.zone(); + let (old_first, old_second) = normalized_pair_weights(state, first, second)?; + if first_surplus + second_surplus <= 0.0 { + // At an all-minimum allocation, retaining positive saved weights is + // harmless and avoids inventing a degenerate all-zero saved group. + return Ok((old_first, old_second, 1.0)); + } + let mut outside_surplus = 0.0_f64; + let mut outside_coefficients = 0.0_f64; + let mut pair_surplus = 0.0_f64; + let mut pair_coefficients = 0.0_f64; + let mut capped_lower_unit = 0.0_f64; + for card in &host.sections { + let member = state.section(&card.section)?; + if card.zone != zone || member.column != anchor.column || member.collapsed || member.preferred_extent.is_some() { + continue; + } + let paired = member.id == *first || member.id == *second; + let coefficient = if member.id == *first { + old_first + } else if member.id == *second { + old_second + } else { + normalized_pair_weights(state, first, &member.id)?.1 + }; + if coefficient <= 0.0 { + continue; + } + let (min, max) = effective_allocation_bounds(state, service.registry(), member, &host.allocation_environment)?; + let actual = axis(zone, card.outer.size); + let surplus = (f64::from(actual) - f64::from(axis(zone, min))).max(0.0); + if actual < axis(zone, max) && surplus > 0.0 { + if paired { + pair_surplus += surplus; + pair_coefficients += f64::from(coefficient); + } else { + outside_surplus += surplus; + outside_coefficients += f64::from(coefficient); + } + } else if !paired { + capped_lower_unit = capped_lower_unit.max(surplus / f64::from(coefficient)); + } + } + let unit = if outside_coefficients > 0.0 { + outside_surplus / outside_coefficients + } else if pair_coefficients > 0.0 { + pair_surplus / pair_coefficients + } else { + capped_lower_unit.max(1.0) + }; + let unit = unit.max(capped_lower_unit); + let denominator = unit.max(first_surplus).max(second_surplus); + let a = (first_surplus / denominator) as f32; + let b = (second_surplus / denominator) as f32; + let scale = (unit / denominator) as f32; + if !denominator.is_finite() + || denominator <= 0.0 + || !a.is_finite() + || !b.is_finite() + || !(0.0..=1.0).contains(&a) + || !(0.0..=1.0).contains(&b) + || !scale.is_finite() + || scale <= 0.0 + || scale > MAX_LOGICAL + { + return Err(error(Rule::Bounds, "actual pair cannot be represented by bounded saved weights")); + } + Ok((a, b, scale)) +} + +fn validate_allocated_pair(before: &HostLayout, after: &HostLayout, mutation: &Mutation) -> PanelResult<()> { + let Mutation::ResizeAllocatedPair { first, second, first_size, second_size, .. } = mutation else { + return Ok(()); + }; + for (id, size) in [(first, *first_size), (second, *second_size)] { + let old = before.sections.iter().find(|card| card.section == *id).ok_or_else(|| error(Rule::MissingTarget, "old pair member absent"))?; + let new = after.sections.iter().find(|card| card.section == *id).ok_or_else(|| error(Rule::MissingTarget, "new pair member absent"))?; + if !near_rect(LogicalRect { origin: new.outer.origin, size }, new.outer) { + return Err(error(Rule::Bounds, "saved shares cannot represent requested actual pair sizes")); + } + let cross = |size: Size| if old.zone == Zone::Bottom { size.height } else { size.width }; + if (cross(old.outer.size) - cross(new.outer.size)).abs() > geometry_tolerance(&[cross(old.outer.size)]) { + return Err(error(Rule::Bounds, "allocated pair changes actual cross axis")); + } + } + for old in &before.sections { + if old.section != *first + && old.section != *second + && !after.sections.iter().any(|new| new.section == old.section && near_rect(old.outer, new.outer)) + { + return Err(error(Rule::Bounds, "allocated pair would move an unrelated neighbour")); + } + } + let envelope = |host: &HostLayout| -> PanelResult { + let a = + host.sections.iter().find(|card| card.section == *first).ok_or_else(|| error(Rule::MissingTarget, "first pair envelope absent"))?.outer; + let b = + host.sections.iter().find(|card| card.section == *second).ok_or_else(|| error(Rule::MissingTarget, "second pair envelope absent"))?.outer; + let x = a.origin.x.min(b.origin.x); + let y = a.origin.y.min(b.origin.y); + Ok(rect(x, y, right(a).max(right(b)) - x, bottom(a).max(bottom(b)) - y)) + }; + if !near_rect(envelope(before)?, envelope(after)?) { + return Err(error(Rule::Bounds, "allocated pair changes its anchored actual envelope")); + } + if before.extent != after.extent { + return Err(error(Rule::Bounds, "allocated pair changes scroll extent")); + } + Ok(()) +} + +struct NormalizedHostAction { + action: LayoutAction, + pair_geometry: Option, +} + +/// Normalize public/gesture/reset intent against current allocated rectangles. +/// Each prefix becomes the current geometry for a subsequent overlapping edit. +/// The original action stays separately owned for lifecycle preflight. +fn normalize_host_action( + service: &LayoutService, + reference: &HostLayout, + action: &LayoutAction, + snapshot: &HostProposalSnapshot, +) -> PanelResult { + let LayoutAction::Apply { expected_revision, mutations } = action else { + return Ok(NormalizedHostAction { action: action.clone(), pair_geometry: None }); + }; + if mutations.len() > MAX_MUTATIONS { + return Err(error(Rule::CollectionLimit, "host mutation cap")); + } + if !mutations + .iter() + .any(|mutation| matches!(mutation, Mutation::ResizePair { .. } | Mutation::ResetPair { .. } | Mutation::ResizeAllocatedPair { .. })) + { + return Ok(NormalizedHostAction { action: action.clone(), pair_geometry: None }); + } + let mut normalized = Vec::new(); + let mut state = service.layout().clone(); + let mut host = resolve_host_projected_with_snapshot(service, &state, reference, snapshot)?; + for mutation in mutations { + let next = match mutation { + Mutation::ResizePair { first, second, first_size, second_size } => { + normalized_allocated_pair(service, &state, &host, first, second, Some((*first_size, *second_size)))? + } + Mutation::ResetPair { first, second } => normalized_allocated_pair(service, &state, &host, first, second, None)?, + Mutation::ResizeAllocatedPair { first, second, first_size, second_size, first_weight, second_weight, other_weight_scale, .. } => { + let pair = allocated_pair(&state, service, &host, first, second)?; + let requested = requested_pair_axis(&pair, *first_size, *second_size)?; + if requested < pair.lower + || requested > pair.upper + || !first_weight.is_finite() + || !second_weight.is_finite() + || !(0.0..=1.0).contains(first_weight) + || !(0.0..=1.0).contains(second_weight) + || !other_weight_scale.is_finite() + || *other_weight_scale <= 0.0 + || *other_weight_scale > MAX_LOGICAL + { + return Err(error(Rule::Bounds, "invalid explicit allocated pair plan")); + } + // Common-factor-equivalent plans are valid: actual forward + // allocation proves the requested split and untouched neighbours. + mutation.clone() + } + other => other.clone(), + }; + normalized.push(next.clone()); + let mut proposed = project_captured( + service, + reference, + LayoutAction::Apply { expected_revision: *expected_revision, mutations: normalized.clone() }, + snapshot, + )?; + let mut projected = resolve_host_projected_with_snapshot(service, &proposed, reference, snapshot)?; + if let Mutation::ResizeAllocatedPair { first, prefer_allocated: false, .. } = &next { + let anchor = state.section(first)?; + let explicit_group = state.sections.iter().any(|member| { + member.location.zone() == anchor.location.zone() && member.column == anchor.column && member.preferred_extent.is_some() + }); + if explicit_group { + // Preserve explicit pair intent even when weights happen to + // reproduce today's allocation. Reuse the captured cohort. + if let Some(Mutation::ResizeAllocatedPair { prefer_allocated, .. }) = normalized.last_mut() { + *prefer_allocated = true; + } + proposed = project_captured( + service, + reference, + LayoutAction::Apply { expected_revision: *expected_revision, mutations: normalized.clone() }, + snapshot, + )?; + projected = resolve_host_projected_with_snapshot(service, &proposed, reference, snapshot)?; + } + } + validate_allocated_pair(&host, &projected, &next)?; + host = projected; + // Capture already occurred; final admission retains this same snapshot. + state = proposed; + } + Ok(NormalizedHostAction { + action: LayoutAction::Apply { expected_revision: *expected_revision, mutations: normalized }, + pair_geometry: Some(host), + }) +} + +/// Owner/topology staging only, before numeric pair normalization and capture. +/// Omitted pair dimensions never create owners. This is not geometry admission. +pub fn project_host_action(service: &LayoutService, reference: &HostLayout, action: &LayoutAction) -> PanelResult { + reference.validate()?; + if reference.source_state != service.inspect() + || reference.source_state.layout.extent_priority_context != service.layout().extent_priority_context + || reference.registry_specs.iter().ne(service.registry().specs()) + { + return Err(error(Rule::Revision, "host projection source changed")); + } + let topology = if let LayoutAction::Apply { expected_revision, mutations } = action { + if mutations.is_empty() || mutations.len() > MAX_MUTATIONS { + return Err(error(Rule::CollectionLimit, "host mutation cap")); + } + if expected_revision.is_some_and(|revision| revision != service.inspect().revision) { + return Err(error(Rule::Revision, "stale host owner projection")); + } + validate_header_action_transaction(mutations)?; + let owners: Vec<_> = mutations + .iter() + .filter(|mutation| !matches!(mutation, Mutation::ResizePair { .. } | Mutation::ResetPair { .. } | Mutation::ResizeAllocatedPair { .. })) + .cloned() + .collect(); + if owners.is_empty() { LayoutAction::Inspect } else { LayoutAction::Apply { expected_revision: *expected_revision, mutations: owners } } + } else { + action.clone() + }; + project_reserved(service, reference, topology) +} + +#[derive(Clone, Debug)] +enum GestureKind { + Move { instance: InstanceId, section: SectionId, click_activates: bool, targets: Vec }, + Resize { section: SectionId, edge: HostResizeEdge, size: Size, outer: LogicalRect }, + Pair { first: SectionId, second: SectionId, first_size: Size, second_size: Size, zone: Zone, outer: LogicalRect }, +} + +#[derive(Clone, Debug)] +struct Gesture { + kind: GestureKind, + scope: LocalScope, + revision: u64, + direction: Direction, + capacity: LogicalRect, + metrics: HostMetrics, + render_domain: LogicalRect, + chrome_obstacles: Vec, + policy: super::layout::HostGeometryPolicy, + reference: HostLayout, + pressed_target: HostPointerTarget, + start: Point, + dragging: bool, +} + +#[derive(Debug, Default)] +pub struct HostInteraction { + candidate: Option, + last_position: Option, + capture: Option, + preview: Option, +} + +impl HostInteraction { + pub fn is_captured(&self) -> bool { + self.capture.is_some() + } + + pub fn preview(&self) -> Option<&HostPreview> { + self.preview.as_ref() + } + + /// Identity feedback follows the held Move, independently of drop admission. + /// A suspended drag retains its source but has no current cursor position. + pub(crate) fn move_source(&self) -> Option<&InstanceId> { + match &self.capture { + Some(Gesture { kind: GestureKind::Move { instance, .. }, dragging: true, .. }) => Some(instance), + _ => None, + } + } + + pub(crate) fn move_position(&self) -> Option { + self.move_source().and(self.last_position) + } + + pub fn cancel(&mut self) { + self.capture = None; + self.suspend(); + } + + fn suspend(&mut self) { + if let Some(Gesture { kind: GestureKind::Move { click_activates, .. }, .. }) = &mut self.capture { + *click_activates = false; + } + self.preview = None; + self.candidate = None; + self.last_position = None; + } + + /// Independent commands invalidate even a preview whose command refuses. + /// Hosts without a live capture call prepare_host_layout directly. + pub fn prepare_command( + &mut self, + service: &LayoutService, + scope: &LocalScope, + reference: &HostLayout, + action: LayoutAction, + ) -> PanelResult { + self.cancel(); + prepare_host_layout(service, scope, reference, action) + } + + /// Call with live service/scope on each input event, including idle captured + /// frames. Runtime preflights and consumes the owned release candidate. + pub fn update(&mut self, service: &LayoutService, scope: &LocalScope, layout: &HostLayout, event: HostPointerEvent) -> HostInteractionUpdate { + if matches!(event, HostPointerEvent::Cancel) { + self.cancel(); + return HostInteractionUpdate::default(); + } + if let Err(reason) = validate_context(service, scope, layout) { + self.cancel(); + return rejected(reason, false); + } + if let Some(capture) = &self.capture + && let Err(reason) = validate_capture(capture, service, scope, layout) + { + self.cancel(); + return rejected(reason, false); + } + match event { + HostPointerEvent::Cancel => HostInteractionUpdate::default(), + HostPointerEvent::Leave => { + self.suspend(); + self.current(false) + } + HostPointerEvent::Reconcile => self.current(false), + HostPointerEvent::Escape => { + let consumed = self.is_captured(); + self.cancel(); + HostInteractionUpdate { consumed, ..Default::default() } + } + HostPointerEvent::OutsidePress { at, inside_owned_overlay } => { + if let Err(reason) = at.validate() { + self.cancel(); + return rejected(reason, false); + } + if !inside_owned_overlay { + self.cancel(); + } + self.current(false) + } + HostPointerEvent::Press { at, target } => { + self.cancel(); + if let Err(reason) = at.validate() { + return rejected(reason, false); + } + let target = target.or_else(|| layout.hit_test(at)); + if let Some(target) = &target + && !layout.control(target).is_some_and(|control| control.bounds.contains(at)) + { + return rejected(error(Rule::MissingTarget, "pointer target is not under the press"), false); + } + let Some(target) = target else { + return HostInteractionUpdate::default(); + }; + let kind = match begin_gesture(service, layout, &target) { + Ok(kind) => kind, + Err(reason) => return rejected(reason, true), + }; + if let Some(kind) = kind { + self.capture = Some(Gesture { + kind, + scope: scope.clone(), + revision: layout.revision, + direction: layout.direction, + capacity: layout.capacity, + metrics: layout.metrics, + render_domain: layout.render_domain, + chrome_obstacles: layout.chrome_obstacles.clone(), + policy: layout.geometry_policy.clone(), + reference: layout.clone(), + pressed_target: target, + start: at, + dragging: false, + }); + self.last_position = Some(at); + } + self.current(true) + } + HostPointerEvent::Move { at } => { + if let Err(reason) = at.validate() { + let captured = self.is_captured(); + self.cancel(); + return rejected(reason, captured); + } + // Native capture can report bounded negative/outside positions + // before PointerGone. Neither may destroy a valid gesture. + if !layout.render_domain.contains(at) { + if let Some(capture) = &mut self.capture { + capture.dragging |= distance_squared(capture.start, at) >= HOST_DRAG_THRESHOLD * HOST_DRAG_THRESHOLD; + } + self.suspend(); + return self.current(self.is_captured()); + } + let Some(capture) = &mut self.capture else { + return HostInteractionUpdate::default(); + }; + self.last_position = Some(at); + capture.dragging |= distance_squared(capture.start, at) >= HOST_DRAG_THRESHOLD * HOST_DRAG_THRESHOLD; + if capture.dragging { + let (preview, candidate) = preview_gesture(capture, service, layout, at); + self.preview = Some(preview); + self.candidate = candidate; + } + self.current(true) + } + HostPointerEvent::Release { at } => { + let capture = self.capture.take(); + let shown = self.preview.take(); + let candidate = self.candidate.take(); + let last_position = self.last_position.take(); + let Some(capture) = capture else { + return HostInteractionUpdate::default(); + }; + if let Err(reason) = at.validate() { + return rejected(reason, true); + } + let release_domain = if matches!(&capture.kind, GestureKind::Move { .. }) { layout.render_domain } else { layout.capacity }; + if !release_domain.contains(at) { + return rejected(error(Rule::Placement, "release outside placement capacity"), true); + } + if last_position.is_none() { + return HostInteractionUpdate { consumed: true, ..Default::default() }; + } + if !capture.dragging { + // A release without a final Move is still positional input. + // It cannot turn an away-from-tab release into a click. + let click = distance_squared(capture.start, at) < HOST_DRAG_THRESHOLD * HOST_DRAG_THRESHOLD + && layout.control(&capture.pressed_target).is_some_and(|control| control.bounds.contains(at)) + && layout.hit_test(at).as_ref() == Some(&capture.pressed_target); + if !click { + return HostInteractionUpdate { consumed: true, ..Default::default() }; + } + if let GestureKind::Move { instance, click_activates: true, .. } = capture.kind + && service.layout().containing(&instance).is_ok_and(|section| section.active != instance) + { + return prepared_update(service, scope, layout, vec![Mutation::Activate { instance }], true); + } + return HostInteractionUpdate { consumed: true, ..Default::default() }; + } + let Some(candidate) = candidate else { + return HostInteractionUpdate { consumed: true, ..Default::default() }; + }; + // Resolve only the hit identity at release. Never allocate a new + // candidate at a position that was not shown to the user. + let still_inside = match &capture.kind { + GestureKind::Move { targets, .. } => { + selected_target(targets, layout, at).map(|target| &target.id) == shown.as_ref().and_then(|preview| preview.target.as_ref()) + } + _ => last_position == Some(at), + }; + if !still_inside { + return rejected(error(Rule::Placement, "release left the shown candidate"), true); + } + if let Err(reason) = candidate.validate_current(service, scope, layout) { + return rejected(reason, true); + } + HostInteractionUpdate { candidate: Some(candidate), preview: shown, consumed: true, ..Default::default() } + } + HostPointerEvent::DoubleClick { target } => { + self.cancel(); + if layout.control(&target).is_none() { + return rejected(error(Rule::MissingTarget, "double-click target is not presented"), false); + } + if let HostPointerTarget::Sash { first, second } = target { + prepared_update(service, scope, layout, vec![Mutation::ResetPair { first, second }], true) + } else { + HostInteractionUpdate::default() + } + } + } + } + + fn current(&self, consumed: bool) -> HostInteractionUpdate { + HostInteractionUpdate { + preview: self.preview.clone(), + rejection: self.preview.as_ref().and_then(|preview| preview.rejection.clone()), + action: None, + candidate: None, + captured: self.is_captured(), + consumed, + } + } +} + +fn validate_context(service: &LayoutService, scope: &LocalScope, layout: &HostLayout) -> PanelResult<()> { + scope.validate()?; + layout.validate()?; + if scope.workspace != service.layout().workspace { + return Err(error(Rule::Placement, "pointer scope differs from current workspace")); + } + let state = service.inspect(); + if layout.revision != state.revision + || layout.source_state != state + || layout.source_state.layout.extent_priority_context != state.layout.extent_priority_context + || layout.registry_specs.iter().ne(service.registry().specs()) + { + return Err(error(Rule::Revision, "pointer geometry became stale")); + } + Ok(()) +} + +fn validate_capture(capture: &Gesture, service: &LayoutService, scope: &LocalScope, layout: &HostLayout) -> PanelResult<()> { + if capture.reference != *layout { + return Err(error(Rule::Revision, "pointer environment signature changed")); + } + if capture.scope != *scope { + return Err(error(Rule::Placement, "pointer owner or local context changed")); + } + if capture.revision != layout.revision { + return Err(error(Rule::Revision, "pointer source revision changed")); + } + if capture.direction != layout.direction + || capture.capacity != layout.capacity + || capture.metrics != layout.metrics + || capture.render_domain != layout.render_domain + || capture.chrome_obstacles != layout.chrome_obstacles + || capture.policy != layout.geometry_policy + { + return Err(error(Rule::Bounds, "pointer geometry context changed")); + } + match &capture.kind { + GestureKind::Move { instance, section, .. } => { + service.availability(instance).require()?; + if service.layout().containing(instance)?.id != *section + || !layout.sections.iter().any(|presented| { + presented.section == *section && (presented.instance == *instance || presented.tabs.iter().any(|tab| tab.instance == *instance)) + }) + { + return Err(error(Rule::MissingTarget, "pointer source is no longer presented")); + } + } + GestureKind::Resize { section, .. } => { + let geometry = layout + .sections + .iter() + .find(|presented| presented.section == *section) + .ok_or_else(|| error(Rule::MissingTarget, "resize source is no longer presented"))?; + service.layout().section(section)?; + service.availability(&geometry.instance).require()?; + } + GestureKind::Pair { first, second, .. } => { + if !layout.sashes.iter().any(|sash| sash.first == *first && sash.second == *second) { + return Err(error(Rule::MissingTarget, "sash neighbours are no longer presented")); + } + } + } + Ok(()) +} + +fn begin_gesture(service: &LayoutService, layout: &HostLayout, target: &HostPointerTarget) -> PanelResult> { + match target { + HostPointerTarget::Header { instance } | HostPointerTarget::Tab { instance } => { + service.availability(instance).require()?; + let section = service.layout().containing(instance)?; + layout + .sections + .iter() + .find(|geometry| geometry.section == section.id) + .ok_or_else(|| error(Rule::MissingTarget, "drag source is not presented"))?; + Ok(Some(GestureKind::Move { + instance: instance.clone(), + section: section.id.clone(), + click_activates: matches!(target, HostPointerTarget::Tab { .. }), + targets: host_drop_targets(service, layout, instance)?, + })) + } + HostPointerTarget::Resize { section, edge } => { + let source = service.layout().section(section)?; + let geometry = layout + .sections + .iter() + .find(|geometry| geometry.section == *section) + .ok_or_else(|| error(Rule::MissingTarget, "resize section is not presented"))?; + Ok(Some(GestureKind::Resize { + section: section.clone(), + edge: edge.physical(source.location.zone(), layout.direction), + size: source.size, + outer: geometry.outer, + })) + } + HostPointerTarget::Sash { first, second } => { + let a = service.layout().section(first)?; + let b = service.layout().section(second)?; + let outer = layout + .sashes + .iter() + .find(|sash| sash.first == *first && sash.second == *second) + .ok_or_else(|| error(Rule::MissingTarget, "sash is not presented"))? + .bounds; + Ok(Some(GestureKind::Pair { + first: first.clone(), + second: second.clone(), + first_size: layout + .sections + .iter() + .find(|card| card.section == a.id) + .map(|card| card.outer.size) + .ok_or_else(|| error(Rule::MissingTarget, "first allocated section absent"))?, + second_size: layout + .sections + .iter() + .find(|card| card.section == b.id) + .map(|card| card.outer.size) + .ok_or_else(|| error(Rule::MissingTarget, "second allocated section absent"))?, + zone: a.location.zone(), + outer, + })) + } + _ => Ok(None), + } +} + +fn preview_gesture(capture: &Gesture, service: &LayoutService, layout: &HostLayout, at: Point) -> (HostPreview, Option) { + let mut preview = match &capture.kind { + GestureKind::Move { instance, section, targets, .. } => move_preview(service, layout, instance, section, at, targets), + GestureKind::Resize { section, edge, size, outer } => { + resize_preview(service, layout, section, *edge, *size, *outer, at.x - capture.start.x, at.y - capture.start.y) + } + GestureKind::Pair { first, second, first_size, second_size, zone, outer } => { + let delta = if *zone == Zone::Bottom { + (at.x - capture.start.x) * if layout.direction == Direction::Rtl { -1.0 } else { 1.0 } + } else { + at.y - capture.start.y + }; + pair_preview(service, layout, first, second, *first_size, *second_size, *zone, *outer, delta) + } + }; + let candidate = if let Some(action) = &preview.action { + match prepare_host_layout(service, &capture.scope, layout, action.clone()) { + Ok(candidate) => { + let shown_bounds = match &capture.kind { + GestureKind::Move { instance, .. } => { + candidate.layout().sections.iter().find(|card| card.instance == *instance).map(|card| card.outer) + } + GestureKind::Resize { section, .. } => { + candidate.layout().sections.iter().find(|card| card.section == *section).map(|card| card.outer) + } + GestureKind::Pair { first, second, .. } => { + candidate.layout().sashes.iter().find(|sash| sash.first == *first && sash.second == *second).map(|sash| sash.bounds) + } + }; + if shown_bounds != Some(preview.bounds) + || preview.projected.as_ref().is_some_and(|shown| { + shown.sections != candidate.layout().sections + || shown.sashes != candidate.layout().sashes + || shown.extent != candidate.layout().extent + || shown.painted != candidate.layout().painted + || shown.input != candidate.layout().input + }) + { + preview.action = None; + preview.projected = None; + preview.targets.clear(); + preview.tab_marker = None; + preview.rejection = Some(error(Rule::Revision, "candidate metrics changed during preparation")); + return (preview, None); + } + preview.projected = Some(candidate.layout().clone()); + Some(candidate) + } + Err(reason) => { + preview.action = None; + preview.projected = None; + preview.targets.clear(); + preview.tab_marker = None; + preview.rejection = Some(reason); + None + } + } + } else { + None + }; + (preview, candidate) +} + +fn move_preview( + service: &LayoutService, + layout: &HostLayout, + instance: &InstanceId, + source: &SectionId, + at: Point, + targets: &[HostDropTarget], +) -> HostPreview { + let fallback = layout.sections.iter().find(|section| section.section == *source).map_or(layout.capacity, |section| section.outer); + let result = (|| -> PanelResult { + let Some(target) = selected_target(targets, layout, at) else { + return Ok(HostPreview { + rejection: Some(error(Rule::Placement, "no explicit docking target")), + targets: Vec::new(), + ..HostPreview::empty(fallback) + }); + }; + if let Some(reason) = &target.rejection { + return Ok(HostPreview { + rejection: Some(reason.clone()), + target: Some(target.id.clone()), + targets: Vec::new(), + ..HostPreview::empty(fallback) + }); + } + let candidate = move_action(service, layout, instance, &target.destination)?; + let proposed = project_reserved(service, layout, candidate.clone())?; + let projected = resolve_host_projected(service, &proposed, layout)?; + let target_section = proposed.containing(instance)?; + let card = projected + .sections + .iter() + .find(|card| card.section == target_section.id) + .ok_or_else(|| error(Rule::Bounds, "docking candidate cannot be presented"))?; + let tab_marker = if matches!(target.destination, Destination::JoinTab { .. }) { + let bounds = card.tabs.iter().find(|tab| tab.instance == *instance).map_or(card.header, |tab| tab.bounds); + let width = layout.metrics.sash_width.min(bounds.size.width); + Some(rect( + if layout.direction == Direction::Rtl { right(bounds) - width } else { bounds.origin.x }, + bounds.origin.y, + width, + bounds.size.height, + )) + } else { + None + }; + Ok(HostPreview { + action: Some(candidate), + bounds: card.outer, + destination: Some(target.destination.clone()), + rejection: None, + projected: Some(projected), + target: Some(target.id.clone()), + targets: vec![target.clone()], + tab_marker, + }) + })(); + match result { + Ok(preview) => preview, + Err(reason) => HostPreview { rejection: Some(reason), ..HostPreview::empty(fallback) }, + } +} + +fn move_action(service: &LayoutService, layout: &HostLayout, instance: &InstanceId, destination: &Destination) -> PanelResult { + let mut mutations = vec![Mutation::Move { instance: instance.clone(), destination: destination.clone() }]; + // The selected instance is the landing tab, including when the source tab + // was inactive. Activation is part of the same guarded transaction. + if let Destination::JoinTab { .. } = destination { + mutations.push(Mutation::Activate { instance: instance.clone() }); + } + service.layout().instance(instance)?; + Ok(action(layout.revision, mutations)) +} + +/// Invisible physical regions. Geometry is logical already: do not multiply by +/// device scale. Rejection is evaluated only for the selected target. +pub fn host_drop_targets(service: &LayoutService, layout: &HostLayout, instance: &InstanceId) -> PanelResult> { + layout.validate()?; + let state = service.inspect(); + if layout.revision != state.revision + || layout.source_state != state + || layout.source_state.layout.extent_priority_context != state.layout.extent_priority_context + || layout.registry_specs.iter().ne(service.registry().specs()) + { + return Err(error(Rule::Revision, "drop geometry became stale")); + } + service.availability(instance).require()?; + let source = service.layout().containing(instance)?; + let new_section = if source.tabs.len() == 1 { + source.id.clone() + } else { + next_host_section_id(service.layout(), &layout.geometry_policy.identity_reservations)? + }; + let new_column = next_host_column_id(service.layout(), &layout.geometry_policy.identity_reservations)?; + let inner_left = innermost_receiving_column(layout, source, instance, Zone::Left); + let inner_right = innermost_receiving_column(layout, source, instance, Zone::Right); + let mut targets = Vec::new(); + let mut add = + |id: HostDropTargetId, bounds: LogicalRect, destination: Destination, priority: u8, edge: Option<(bool, f32)>, stable_key: String| { + if bounds.validate().is_ok() { + targets.push(HostDropTarget { id, bounds, destination, rejection: None, priority, edge, stable_key }); + } + }; + for card in &layout.sections { + let target = service.layout().section(&card.section)?; + if source.id == target.id && source.tabs.len() == 1 { + continue; + } + if intersect_rect(card.outer, layout.capacity).is_none() { + continue; + } + let tabs: Vec<_> = target.tabs.iter().filter(|tab| *tab != instance).collect(); + let side = matches!(card.zone, Zone::Left | Zone::Right); + let inward = 64.0_f32.min(card.outer.size.width * 0.28); + let vertical = 56.0_f32.min(card.outer.size.height * 0.25); + if side { + let physical = layout.direction.edge(card.zone)?; + for left in [true, false] { + let at = if left { card.outer.origin.x } else { right(card.outer) }; + let placement = + if left == (physical == PhysicalEdge::Left) { RelativePlacement::BeforeColumn } else { RelativePlacement::AfterColumn }; + let inner = if card.zone == Zone::Left { &inner_left } else { &inner_right }; + let outward = + if placement == RelativePlacement::AfterColumn && target.column.as_ref().is_some_and(|column| Some(column) == inner.as_ref()) { + clear_column_outward(layout, card.outer, left) + } else { + COLUMN_OUTWARD + }; + add( + HostDropTargetId::Relative { section: card.section.clone(), placement }, + rect(if left { at - outward } else { at - inward }, card.outer.origin.y, inward + outward, card.outer.size.height), + Destination::Relative { + section: card.section.clone(), + placement, + new_section: new_section.clone(), + new_column: Some(new_column.clone()), + size: source.size, + }, + 3, + Some((true, at)), + format!("column:{}:{}", card.section.0, if left { "left" } else { "right" }), + ); + } + for above in [true, false] { + let at = if above { card.outer.origin.y } else { bottom(card.outer) }; + let placement = if above { RelativePlacement::Above } else { RelativePlacement::Below }; + add( + HostDropTargetId::Relative { section: card.section.clone(), placement }, + rect( + card.outer.origin.x, + if above { at } else { at - vertical }, + card.outer.size.width, + vertical + if above { 0.0 } else { clear_below_end(layout, card.outer) - at }, + ), + Destination::Relative { + section: card.section.clone(), + placement, + new_section: new_section.clone(), + new_column: None, + size: source.size, + }, + 3, + Some((false, at)), + format!("stack:{}:{}", card.section.0, if above { "above" } else { "below" }), + ); + } + } + add( + HostDropTargetId::Tab { section: card.section.clone(), before: None }, + rect( + card.outer.origin.x + if side { inward } else { 0.0 }, + card.outer.origin.y + if side { vertical } else { 0.0 }, + card.outer.size.width - if side { 2.0 * inward } else { 0.0 }, + card.outer.size.height - if side { 2.0 * vertical } else { 0.0 }, + ), + Destination::JoinTab { section: card.section.clone(), index: tabs.len() }, + 4, + None, + format!("tab:{}:end", card.section.0), + ); + for tab in &card.tabs { + // Only the leading half selects insertion before this measured tab. + // Keep the dragged tab's own slot, indexing after its removal; a + // trailing half on every tab would steal the natural edge regions. + let index = target.tabs.iter().take_while(|id| **id != tab.instance).filter(|id| *id != instance).count(); + let before = tabs.get(index).map(|id| (*id).clone()); + let bounds = rect( + tab.bounds.origin.x + if layout.direction == Direction::Rtl { tab.bounds.size.width / 2.0 } else { 0.0 }, + tab.bounds.origin.y + 9.0, + tab.bounds.size.width / 2.0, + (tab.bounds.size.height - 18.0).max(1.0), + ); + add( + HostDropTargetId::Tab { section: card.section.clone(), before }, + bounds, + Destination::JoinTab { section: card.section.clone(), index }, + // A measured own-group slot stays reorderable even when a + // short Bottom header lies wholly inside the docking band. + if card.zone == Zone::Bottom && source.id == target.id { 0 } else { 2 }, + None, + format!("tab:{}:{index}", card.section.0), + ); + } + if let Some(last) = card.tabs.last() { + let bounds = rect( + last.bounds.origin.x + if layout.direction == Direction::Ltr { last.bounds.size.width / 2.0 } else { 0.0 }, + last.bounds.origin.y + 9.0, + last.bounds.size.width / 2.0, + (last.bounds.size.height - 18.0).max(1.0), + ); + add( + HostDropTargetId::Tab { section: card.section.clone(), before: None }, + bounds, + Destination::JoinTab { section: card.section.clone(), index: tabs.len() }, + if card.zone == Zone::Bottom && source.id == target.id { 0 } else { 2 }, + None, + format!("tab:{}:{}:end", card.section.0, tabs.len()), + ); + } + } + // Capacity excludes shell insets and reserved bottom chrome. Perimeter + // targets include the shell gutter, without moving underneath a status bar. + let workspace_bottom = (bottom(layout.capacity) + layout.metrics.gap).min(bottom(layout.render_domain)); + let workspace_height = (workspace_bottom - layout.capacity.origin.y).max(0.0); + let side_height = (workspace_height - 9.0).max(0.0); + for zone in [Zone::Left, Zone::Right, Zone::Bottom] { + let first = layout.sections.iter().find(|card| card.zone == zone && !(card.section == source.id && source.tabs.len() == 1)); + let edge = layout.direction.edge(zone)?; + let thickness = + if zone == Zone::Bottom { BOTTOM_DOCK_BAND.min(workspace_height) } else { SIDE_DOCK_BAND.min(layout.render_domain.size.width) }; + let bounds = match edge { + PhysicalEdge::Left => rect(layout.render_domain.origin.x, layout.capacity.origin.y, thickness, side_height), + PhysicalEdge::Right => rect(right(layout.render_domain) - thickness, layout.capacity.origin.y, thickness, side_height), + PhysicalEdge::Bottom => rect(layout.render_domain.origin.x, workspace_bottom - thickness, layout.render_domain.size.width, thickness), + }; + let destination = if zone != Zone::Bottom + && let Some(first) = first + { + Destination::Relative { + section: first.section.clone(), + placement: RelativePlacement::BeforeColumn, + new_section: new_section.clone(), + new_column: Some(new_column.clone()), + size: source.size, + } + } else { + let index = service.layout().sections.iter().filter(|section| !(section.id == source.id && source.tabs.len() == 1)).count(); + Destination::NewSection { section: new_section.clone(), index, location: SectionLocation::Dock { zone }, size: source.size } + }; + let zone_key = match zone { + Zone::Left => "Left", + Zone::Right => "Right", + _ => "Bottom", + }; + // Outside measured own-Bottom reorder slots, Bottom wins corners, then + // sides, measured tabs, relative edges and joins. + add( + HostDropTargetId::Dock { zone, before: None }, + bounds, + destination.clone(), + if zone == Zone::Bottom { 0 } else { 1 }, + None, + format!("edge:{zone_key}"), + ); + if first.is_none() && zone != Zone::Bottom { + let width = (layout.render_domain.size.width - thickness).clamp(0.0, EMPTY_SIDE_EXTRA); + let x = if edge == PhysicalEdge::Left { bounds.origin.x + thickness } else { bounds.origin.x - width }; + add( + HostDropTargetId::Dock { zone, before: None }, + rect(x, bounds.origin.y, width, bounds.size.height), + destination, + 1, + None, + format!("empty:{zone_key}"), + ); + } + } + if targets.len() > MAX_INSTANCES * 4 + MAX_SECTIONS * 8 { + return Err(error(Rule::CollectionLimit, "drop target limit")); + } + Ok(targets) +} + +/// Use captured presentation, ignoring a whole source card that will vacate. +/// Available retained tabs and other presented cards remain receivers. +fn innermost_receiving_column(layout: &HostLayout, source: &Section, instance: &InstanceId, zone: Zone) -> Option { + let physical_left = layout.direction.edge(zone).ok()? == PhysicalEdge::Left; + layout + .sections + .iter() + .filter(|card| card.zone == zone && intersect_rect(card.outer, layout.capacity).is_some()) + .filter_map(|card| { + let section = layout.source_state.layout.section(&card.section).ok()?; + if section.id == source.id && !section.tabs.iter().any(|tab| tab != instance && layout.allocation_environment.available.contains(tab)) { + return None; + } + Some((section.column.as_ref()?, if physical_left { right(card.outer) } else { -card.outer.origin.x })) + }) + .max_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(column, _)| column.clone()) +} + +/// Only the added strip enters clear canvas. Keep the original eighteen points +/// even when paint/chrome already overlaps them, and stop at the first obstacle. +fn clear_column_outward(layout: &HostLayout, card: LogicalRect, left: bool) -> f32 { + let Some(span) = intersect_rect(card, layout.capacity) else { + return COLUMN_OUTWARD; + }; + let at = if left { card.origin.x } else { right(card) }; + let limit = if left { at - layout.capacity.origin.x } else { right(layout.capacity) - at }; + layout + .painted + .iter() + .chain(&layout.chrome_obstacles) + .filter_map(|bounds| intersect_rect(*bounds, layout.capacity)) + .filter(|bounds| { + bounds.origin.y < bottom(span) && bottom(*bounds) > span.origin.y && if left { bounds.origin.x < at } else { right(*bounds) > at } + }) + .fold(CENTRE_COLUMN_OUTWARD.min(limit), |extent, bounds| extent.min(if left { at - right(bounds) } else { bounds.origin.x - at })) + .max(COLUMN_OUTWARD) +} + +/// Extend only through captured, actually presented clear space. Painted bounds +/// include collapsed/floating cards and sashes; hidden allocation is irrelevant. +fn clear_below_end(layout: &HostLayout, card: LogicalRect) -> f32 { + let start = bottom(card); + let Some(span) = intersect_rect(card, layout.capacity) else { + return start; + }; + layout + .painted + .iter() + .chain(&layout.chrome_obstacles) + .filter_map(|bounds| intersect_rect(*bounds, layout.capacity)) + .filter(|bounds| bounds.origin.x < right(span) && right(*bounds) > span.origin.x && bottom(*bounds) > start) + .fold(bottom(layout.capacity).max(start), |end, bounds| end.min(bounds.origin.y.max(start))) +} + +fn selected_target<'a>(targets: &'a [HostDropTarget], layout: &HostLayout, at: Point) -> Option<&'a HostDropTarget> { + if !layout.render_domain.contains(at) || layout.chrome_obstacles.iter().any(|bounds| bounds.contains(at)) { + return None; + } + let distance = |target: &HostDropTarget| target.edge.map_or(0.0, |(horizontal, edge)| ((if horizontal { at.x } else { at.y }) - edge).abs()); + let visible = |target: &HostDropTarget| match &target.id { + HostDropTargetId::Dock { .. } => true, + HostDropTargetId::Relative { section, placement: RelativePlacement::BeforeColumn | RelativePlacement::AfterColumn } => { + at.y >= layout.capacity.origin.y + && at.y <= bottom(layout.capacity) + && layout.sections.iter().find(|card| card.section == *section).is_some_and(|card| + // Preserve inclusive old bands; the added strip stops + // before its far boundary, including obstacle paint. + (at.x >= card.outer.origin.x - COLUMN_OUTWARD && at.x <= right(card.outer) + COLUMN_OUTWARD) + || (at.x > target.bounds.origin.x && at.x < right(target.bounds))) + } + HostDropTargetId::Relative { section, placement: RelativePlacement::Below } => { + layout.capacity.contains(at) + && layout + .sections + .iter() + .find(|card| card.section == *section) + .is_some_and(|card| card.outer.contains(at) || at.y < clear_below_end(layout, card.outer)) + } + _ => layout.capacity.contains(at), + }; + // Enlarging clear-space regions must not change original edge-band ties. + let area = |target: &HostDropTarget| match &target.id { + HostDropTargetId::Relative { section, placement: RelativePlacement::Below } => layout + .sections + .iter() + .find(|card| card.section == *section) + .map_or(0.0, |card| card.outer.size.width * 56.0_f32.min(card.outer.size.height * 0.25)), + HostDropTargetId::Relative { section, placement: RelativePlacement::BeforeColumn | RelativePlacement::AfterColumn } => layout + .sections + .iter() + .find(|card| card.section == *section) + .map_or(0.0, |card| (64.0_f32.min(card.outer.size.width * 0.28) + COLUMN_OUTWARD) * card.outer.size.height), + _ => target.bounds.size.width * target.bounds.size.height, + }; + targets.iter().filter(|target| target.bounds.contains(at) && visible(target)).min_by(|a, b| { + a.priority + .cmp(&b.priority) + .then_with(|| distance(a).total_cmp(&distance(b))) + .then_with(|| area(a).total_cmp(&area(b))) + .then_with(|| a.stable_key.cmp(&b.stable_key)) + }) +} + +fn resize_preview( + service: &LayoutService, + layout: &HostLayout, + section: &SectionId, + edge: HostResizeEdge, + initial: Size, + outer: LogicalRect, + dx: f32, + dy: f32, +) -> HostPreview { + let result = (|| -> PanelResult<(LayoutAction, LogicalRect)> { + let source = service.layout().section(section)?; + let (min, max) = effective_allocation_bounds(service.layout(), service.registry(), source, &layout.allocation_environment)?; + if min.width > max.width || min.height > max.height { + return Err(error(Rule::IncompatibleTabs, "resize has incompatible composite limits")); + } + if matches!(&source.location, SectionLocation::Floating { .. }) { + // A user's resize starts at the displayed rect, including both + // dimensions when the saved rect was larger than local capacity. + // Retaining an off-screen saved origin would move the opposite edge + // after drop; SetSize alone cannot express this group operation. + let width_cap = max.width.min(right(layout.capacity) - outer.origin.x); + let height_cap = max.height.min(bottom(layout.capacity) - outer.origin.y); + if width_cap < min.width || height_cap < min.height { + return Err(error(Rule::Bounds, "visible floating anchor cannot fit panel minimum")); + } + if edge != HostResizeEdge::BottomRight { + return Err(error(Rule::Placement, "floating resize requires its free corner")); + } + let size = + Size { width: (outer.size.width + dx).clamp(min.width, width_cap), height: (outer.size.height + dy).clamp(min.height, height_cap) }; + let candidate = action(layout.revision, vec![Mutation::SetFloatingRect { section: section.clone(), origin: outer.origin, size }]); + let projected = project_resize(service, layout, &candidate)?; + let bounds = projected + .sections + .iter() + .find(|card| card.section == *section) + .ok_or_else(|| error(Rule::Bounds, "floating resize cannot be presented"))? + .outer; + if bounds.origin != outer.origin || bounds.size != size { + return Err(error(Rule::Bounds, "floating resize cannot retain its visible anchor")); + } + return Ok((candidate, bounds)); + } + let mut size = initial; + match edge { + HostResizeEdge::Left => size.width = (outer.size.width - dx).clamp(min.width, max.width), + HostResizeEdge::Right => size.width = (outer.size.width + dx).clamp(min.width, max.width), + HostResizeEdge::Top if source.location.zone() == Zone::Bottom => { + size.height = bottom_resize_height(service.layout(), service.registry(), &layout.allocation_environment, outer.size.height - dy)?; + } + HostResizeEdge::Top => size.height = (outer.size.height - dy).clamp(min.height, max.height), + HostResizeEdge::Bottom => size.height = (outer.size.height + dy).clamp(min.height, max.height), + HostResizeEdge::BottomRight => { + return Err(error(Rule::Placement, "dock resize requires a dock edge")); + } + } + let mutation = if matches!(edge, HostResizeEdge::Left | HostResizeEdge::Right) && source.location.zone().side() { + Mutation::SetColumnWidth { + column: source.column.clone().ok_or_else(|| error(Rule::MissingTarget, "side resize has no column"))?, + width: size.width, + } + } else if source.location.zone() == Zone::Bottom && edge == HostResizeEdge::Top { + Mutation::SetBottomHeight { section: section.clone(), height: size.height } + } else { + Mutation::SetSize { section: section.clone(), size } + }; + let candidate = action(layout.revision, vec![mutation]); + let projected = project_resize(service, layout, &candidate)?; + let bounds = projected + .sections + .iter() + .find(|card| card.section == *section) + .ok_or_else(|| error(Rule::Bounds, "dock resize cannot be presented"))? + .outer; + if source.location.zone() == Zone::Bottom + && (outer.size.width - bounds.size.width).abs() > geometry_tolerance(&[outer.size.width, bounds.size.width]) + { + return Err(error(Rule::Bounds, "standalone resize changes an unrequested axis")); + } + if source.location.zone() == Zone::Bottom + && edge == HostResizeEdge::Top + && projected + .sections + .iter() + .filter(|card| card.zone == Zone::Bottom && !card.collapsed) + .any(|card| (card.outer.size.height - size.height).abs() > geometry_tolerance(&[size.height])) + { + return Err(error(Rule::Bounds, "Bottom allocation changed proposed shared thickness")); + } + Ok((candidate, bounds)) + })(); + match result { + Ok((candidate, bounds)) => resized_preview(candidate, bounds, outer), + Err(reason) => HostPreview { rejection: Some(reason), ..HostPreview::empty(outer) }, + } +} + +fn project_resize(service: &LayoutService, reference: &HostLayout, candidate: &LayoutAction) -> PanelResult { + let proposed = project_reserved(service, reference, candidate.clone())?; + resolve_host_projected(service, &proposed, reference) +} + +fn resized_preview(candidate: LayoutAction, bounds: LogicalRect, original: LogicalRect) -> HostPreview { + HostPreview { action: if bounds == original { None } else { Some(candidate) }, ..HostPreview::empty(bounds) } +} + +fn pair_preview( + service: &LayoutService, + layout: &HostLayout, + first: &SectionId, + second: &SectionId, + _initial_a: Size, + _initial_b: Size, + _zone: Zone, + outer: LogicalRect, + delta: f32, +) -> HostPreview { + let result = (|| -> PanelResult<(LayoutAction, LogicalRect)> { + let pair = allocated_pair(service.layout(), service, layout, first, second)?; + let split = (axis(pair.zone, pair.first.outer.size) + delta).clamp(pair.lower, pair.upper); + if split == axis(pair.zone, pair.first.outer.size) { + return Ok((action(layout.revision, Vec::new()), outer)); + } + let original = action( + layout.revision, + vec![Mutation::ResizePair { + first: first.clone(), + second: second.clone(), + first_size: with_axis(pair.zone, pair.first.outer.size, split), + second_size: with_axis(pair.zone, pair.second.outer.size, pair.total - split), + }], + ); + let owners = project_host_action(service, layout, &original)?; + let snapshot = current_owner_snapshot(service, layout, &owners); + let normalized = normalize_host_action(service, layout, &original, &snapshot)?; + let proposed = project_captured(service, layout, normalized.action, &snapshot)?; + let projected = resolve_host_projected_with_snapshot(service, &proposed, layout, &snapshot)?; + let bounds = projected + .sashes + .iter() + .find(|sash| sash.first == *first && sash.second == *second) + .map(|sash| sash.bounds) + .ok_or_else(|| error(Rule::MissingTarget, "allocated sash missing after resize"))?; + Ok((original, bounds)) + })(); + match result { + Ok((candidate, bounds)) => resized_preview(candidate, bounds, outer), + Err(reason) => HostPreview { rejection: Some(reason), ..HostPreview::empty(outer) }, + } +} + +fn prepared_update( + service: &LayoutService, + scope: &LocalScope, + reference: &HostLayout, + mutations: Vec, + consumed: bool, +) -> HostInteractionUpdate { + match prepare_host_layout(service, scope, reference, action(service.inspect().revision, mutations)) { + Ok(candidate) => HostInteractionUpdate { candidate: Some(candidate), consumed, ..Default::default() }, + Err(reason) => rejected(reason, consumed), + } +} + +fn action(revision: u64, mutations: Vec) -> LayoutAction { + LayoutAction::Apply { expected_revision: Some(revision), mutations } +} + +fn rejected(reason: PanelError, consumed: bool) -> HostInteractionUpdate { + HostInteractionUpdate { rejection: Some(reason), consumed, ..Default::default() } +} + +fn distance_squared(a: Point, b: Point) -> f32 { + let dx = b.x - a.x; + let dy = b.y - a.y; + dx * dx + dy * dy +} diff --git a/crates/ui-egui/src/panel_runtime/layout.rs b/crates/ui-egui/src/panel_runtime/layout.rs new file mode 100644 index 000000000..efea6756d --- /dev/null +++ b/crates/ui-egui/src/panel_runtime/layout.rs @@ -0,0 +1,1472 @@ +//! Pure, logical-unit geometry for the opt-in workspace host. +//! Desired sizes and collapse state are never changed by capacity fitting. + +use std::collections::{BTreeMap, BTreeSet}; + +use solidcraft_engine::panels::*; + +use super::interaction::{HostPointerTarget, HostProposalSnapshot, HostResizeEdge}; + +/// Compatibility constant only; the host never allocates rails. +pub const HOST_RAIL_THICKNESS: f32 = 32.0; + +pub const MAX_USABLE_OBSTACLES: usize = 256; +const MAX_USABLE_PIECES: usize = 16384; +// Per section: declared actions, surface/title/resize, three system actions, +// tab overflow and at most one sash; tabs are bounded globally by instances. +const MAX_HOST_CONTROLS: usize = MAX_SECTIONS * (MAX_HEADER_ACTIONS + 8) + MAX_INSTANCES; + +/// The full canvas minus actual occupied footprints. Free rectangles are a +/// disjoint decomposition of the region, not a replacement central viewport. +#[derive(Clone, Debug, PartialEq)] +pub struct HostUsableRegion { + pub domain: LogicalRect, + pub obstacles: Vec, + pub free: Vec, +} + +pub fn resolve_usable_region(domain: LogicalRect, obstacles: &[LogicalRect]) -> PanelResult { + validate_capacity(domain)?; + if obstacles.len() > MAX_USABLE_OBSTACLES { + return Err(error(Rule::CollectionLimit, "usable-space obstacle limit")); + } + let mut clipped = Vec::new(); + let mut rows = vec![domain.origin.y, bottom(domain)]; + for obstacle in obstacles { + obstacle.validate()?; + if overlaps(domain, *obstacle) { + rows.extend([domain.origin.y.max(obstacle.origin.y), bottom(domain).min(bottom(*obstacle))]); + // Preserve the supplied obstacle's edges: rounding an intersection + // inward would advertise a tiny occupied strip as usable space. + clipped.push(*obstacle); + } + } + rows.sort_by(f32::total_cmp); + rows.dedup(); + let mut free: Vec = Vec::new(); + let mut previous_row = BTreeMap::new(); + for row in rows.windows(2) { + let (Some(&top), Some(&end)) = (row.first(), row.get(1)) else { + continue; + }; + if top >= end { + continue; + } + let mut current_row = BTreeMap::new(); + for (left, right) in free_intervals(domain, &clipped, top, end) { + let Some(bounds) = inward_rect(left, top, right, end) else { + continue; + }; + if !domain.contains_rect(bounds) { + continue; + } + let key = (left.to_bits(), bounds.size.width.to_bits()); + if let Some(index) = previous_row.get(&key).copied() + && let Some(previous) = free.get_mut(index) + && bottom(*previous) == top + && let Some(merged) = inward_rect(left, previous.origin.y, right, end) + { + *previous = merged; + current_row.insert(key, index); + } else { + if free.len() >= MAX_USABLE_PIECES { + return Err(error(Rule::CollectionLimit, "usable-space contour limit")); + } + current_row.insert(key, free.len()); + free.push(bounds); + } + } + previous_row = current_row; + } + Ok(HostUsableRegion { domain, obstacles: clipped, free }) +} + +fn inward_rect(left: f32, top: f32, end_x: f32, end_y: f32) -> Option { + let mut width = end_x - left; + let mut height = end_y - top; + if left + width > end_x && width > 0.0 { + width = f32::from_bits(width.to_bits().saturating_sub(1)); + } + if top + height > end_y && height > 0.0 { + height = f32::from_bits(height.to_bits().saturating_sub(1)); + } + positive_rect(left, top, width, height) +} + +fn overlaps(a: LogicalRect, b: LogicalRect) -> bool { + a.origin.x < right(b) && b.origin.x < right(a) && a.origin.y < bottom(b) && b.origin.y < bottom(a) +} + +fn free_intervals(domain: LogicalRect, obstacles: &[LogicalRect], top: f32, end: f32) -> Vec<(f32, f32)> { + let mut blocked: Vec<_> = obstacles + .iter() + .filter(|bounds| bounds.origin.y < end && bottom(**bounds) > top) + .map(|bounds| (bounds.origin.x.max(domain.origin.x), right(*bounds).min(right(domain)))) + .collect(); + blocked.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.total_cmp(&b.1))); + let mut free = Vec::new(); + let mut cursor = domain.origin.x; + for (left, end) in blocked { + if cursor < left { + free.push((cursor, left)); + } + cursor = cursor.max(end); + } + if cursor < right(domain) { + free.push((cursor, right(domain))); + } + free +} + +impl HostUsableRegion { + fn bounded(&self) -> bool { + validate_capacity(self.domain).is_ok() + && self.obstacles.len() <= MAX_USABLE_OBSTACLES + && self.free.len() <= MAX_USABLE_PIECES + && self.obstacles.iter().all(|bounds| bounds.validate().is_ok()) + } + + fn contains_bounded_rect(&self, bounds: LogicalRect) -> bool { + bounds.validate().is_ok() && self.domain.contains_rect(bounds) && !self.obstacles.iter().any(|obstacle| overlaps(bounds, *obstacle)) + } + + pub fn contains_rect(&self, bounds: LogicalRect) -> bool { + self.bounded() && self.contains_bounded_rect(bounds) + } + + /// Place a measured footprint nearest its preferred centre. Candidate rows + /// include every obstacle boundary, so placement can cross free-strip seams. + pub fn place_footprint(&self, size: Size, preferred_center: Point, clearance: f32) -> Option { + if !self.bounded() || size.validate().is_err() || preferred_center.validate().is_err() || !clearance.is_finite() || clearance < 0.0 { + return None; + } + let padded = Size { width: size.width + 2.0 * clearance, height: size.height + 2.0 * clearance }; + if padded.validate().is_err() || padded.width > self.domain.size.width || padded.height > self.domain.size.height { + return None; + } + let min_y = self.domain.origin.y; + let max_y = bottom(self.domain) - padded.height; + if max_y < min_y { + return None; + } + let wanted = Point { x: preferred_center.x - padded.width / 2.0, y: preferred_center.y - padded.height / 2.0 }; + let mut rows = vec![min_y, max_y, wanted.y.clamp(min_y, max_y)]; + for obstacle in &self.obstacles { + rows.extend([(obstacle.origin.y - padded.height).clamp(min_y, max_y), bottom(*obstacle).clamp(min_y, max_y)]); + } + rows.sort_by(f32::total_cmp); + rows.dedup(); + let mut best: Option<(f64, LogicalRect)> = None; + for top in rows { + for (left, end) in free_intervals(self.domain, &self.obstacles, top, top + padded.height) { + let max_x = end - padded.width; + if max_x < left { + continue; + } + let outer = rect(wanted.x.clamp(left, max_x), top, padded.width, padded.height); + if !self.contains_bounded_rect(outer) { + continue; + } + let dx = f64::from(outer.origin.x) - f64::from(wanted.x); + let dy = f64::from(outer.origin.y) - f64::from(wanted.y); + let distance = dx * dx + dy * dy; + if best.as_ref().is_none_or(|(old, _)| distance < *old) { + best = Some((distance, outer)); + } + } + } + best.map(|(_, outer)| rect(outer.origin.x + clearance, outer.origin.y + clearance, size.width, size.height)) + .filter(|bounds| self.contains_bounded_rect(*bounds)) + } + + /// Largest safe rectangle at the requested aspect, for explicit Fit/Centre. + /// Model extents determine the aspect; layout gestures never call this. + pub fn fit_rect(&self, aspect: f32, preferred_center: Point) -> Option { + self.fit_rect_with_clearance(aspect, preferred_center, 0.0) + } + + /// Search the inner model rectangle with its clearance already reserved. + /// Shrinking an aspect-fitted result afterwards can erase thin selections. + pub fn fit_rect_with_clearance(&self, aspect: f32, preferred_center: Point, clearance: f32) -> Option { + if !self.bounded() + || !aspect.is_finite() + || aspect <= 0.0 + || preferred_center.validate().is_err() + || !clearance.is_finite() + || clearance < 0.0 + { + return None; + } + let padding = 2.0 * clearance; + if !padding.is_finite() { + return None; + } + let available = Size { width: self.domain.size.width - padding, height: self.domain.size.height - padding }; + if available.validate().is_err() { + return None; + } + let mut low = 0.0_f32; + let mut high = available.height.min(available.width / aspect); + if !high.is_finite() || high <= 0.0 { + return None; + } + let mut best = None; + for _ in 0..32 { + let height = low + (high - low) / 2.0; + if height <= low || height >= high { + break; + } + if let Some(bounds) = self.place_footprint(Size { width: height * aspect, height }, preferred_center, clearance) { + low = height; + best = Some(bounds); + } else { + high = height; + } + } + if let Some(bounds) = self.place_footprint(Size { width: high * aspect, height: high }, preferred_center, clearance) { + best = Some(bounds); + } + best + } + + pub fn largest_rect(&self) -> Option { + if !self.bounded() { + return None; + } + let mut rows = vec![self.domain.origin.y, bottom(self.domain)]; + for obstacle in &self.obstacles { + rows.extend([obstacle.origin.y.max(self.domain.origin.y), bottom(*obstacle).min(bottom(self.domain))]); + } + rows.sort_by(f32::total_cmp); + rows.dedup(); + let mut best: Option = None; + for (index, &top) in rows.iter().enumerate() { + for &end in rows.iter().skip(index + 1) { + for (left, right) in free_intervals(self.domain, &self.obstacles, top, end) { + let Some(bounds) = inward_rect(left, top, right, end) else { + continue; + }; + if self.contains_bounded_rect(bounds) + && best.is_none_or(|old| { + f64::from(bounds.size.width) * f64::from(bounds.size.height) > f64::from(old.size.width) * f64::from(old.size.height) + }) + { + best = Some(bounds); + } + } + } + } + best + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct HostMetrics { + pub header_height: f32, + pub content_header_height: f32, + pub footer_height: f32, + /// Separation supplied by the workspace's shared Container policy. Zero + /// joins compact cards; resize handles retain their own positive width. + pub gap: f32, + pub sash_width: f32, + pub control_extent: f32, + pub tab_min_width: f32, + /// Single-row Wide composition threshold, bounded by the shared contract. + pub inline_max_height: f32, + pub inline_title_width: f32, + pub min_viewport: Size, +} + +impl Default for HostMetrics { + fn default() -> Self { + let t = crate::theme::Tokens::get(); + Self { + header_height: t.form_header_height, + content_header_height: 0.0, + footer_height: t.form_footer_height, + gap: t.space_4, + sash_width: t.space_4, + control_extent: t.control_height, + tab_min_width: t.control_height * 2.0, + inline_max_height: (t.control_height * 2.0 + t.space_4).min(88.0), + inline_title_width: (t.control_height * 4.0).min(256.0), + min_viewport: Size { width: t.space_2, height: t.space_2 }, + } + } +} + +impl HostMetrics { + pub fn validate(self) -> PanelResult<()> { + for value in [self.header_height, self.sash_width, self.control_extent, self.tab_min_width] { + if !value.is_finite() || value <= 0.0 || value > 256.0 { + return Err(error(Rule::Bounds, "host chrome extent must be finite and in (0, 256]")); + } + } + if !self.footer_height.is_finite() + || self.footer_height < 0.0 + || self.footer_height > 256.0 + || !self.content_header_height.is_finite() + || self.content_header_height < 0.0 + || self.content_header_height > 256.0 + { + return Err(error(Rule::Bounds, "invalid host footer extent")); + } + if !self.gap.is_finite() || !(0.0..=256.0).contains(&self.gap) { + return Err(error(Rule::Bounds, "invalid host gap")); + } + if !self.inline_max_height.is_finite() || !(0.0..=88.0).contains(&self.inline_max_height) { + return Err(error(Rule::Bounds, "invalid inline row threshold")); + } + if !self.inline_title_width.is_finite() || self.inline_title_width <= 0.0 || self.inline_title_width > 512.0 { + return Err(error(Rule::Bounds, "invalid inline title width")); + } + self.min_viewport.validate() + } +} + +/// Immutable bounded content metric snapshot. Never render content or inspect +/// mutable controller/egui state here. Missing widths must return Revision. +pub trait HostContentMetrics: std::fmt::Debug + Send + Sync { + fn measure(&self, request: &ContentMeasureRequest) -> PanelResult; + fn revision(&self) -> u64; +} + +const MAX_HOST_RESERVED_IDS: usize = MAX_RESERVED_IDENTITIES; + +/// Immutable identity/recovery-priority environment. No registry entries, +/// controllers or bodies are created for quarantined placements. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct HostIdentityReservations { + pub sections: BTreeSet, + pub columns: BTreeSet, + pub extent_priorities: ExtentPriorityContext, + /// Typed incoming provenance, independent of additional live reservations. + pub replacement_ownership: Option, +} +impl HostIdentityReservations { + pub fn validate(&self) -> PanelResult<()> { + if self.sections.len() > MAX_HOST_RESERVED_IDS || self.columns.len() > MAX_HOST_RESERVED_IDS { + return Err(error(Rule::CollectionLimit, "host identity reservation cap")); + } + for id in &self.sections { + valid_id(&id.0)?; + } + for id in &self.columns { + valid_id(&id.0)?; + } + self.extent_priorities.validate()?; + if let Some(ownership) = &self.replacement_ownership { + ownership.validate()?; + } + Ok(()) + } + pub(super) fn preparation_context(&self) -> PanelResult { + self.validate()?; + Ok(LayoutPreparationContext { + sections: self.sections.clone(), + columns: self.columns.clone(), + extent_priorities: self.extent_priorities.clone(), + replacement_ownership: self.replacement_ownership.clone(), + }) + } + pub(super) fn include_layout(&mut self, layout: &Layout) -> PanelResult<()> { + if layout.sections.len() > MAX_HOST_RESERVED_IDS + || layout.instances.len() > MAX_HOST_RESERVED_IDS + || layout.columns.len() > MAX_HOST_RESERVED_IDS + { + return Err(error(Rule::CollectionLimit, "identity source cap")); + } + for section in &layout.sections { + valid_id(§ion.id.0)?; + if let Some(column) = §ion.column { + valid_id(&column.0)?; + } + self.sections.insert(section.id.clone()); + self.columns.extend(section.column.clone()); + } + for column in &layout.columns { + valid_id(&column.id.0)?; + self.columns.insert(column.id.clone()); + } + for instance in &layout.instances { + valid_id(&instance.memory.section.0)?; + if let Some(column) = &instance.memory.column { + valid_id(&column.0)?; + } + self.sections.insert(instance.memory.section.clone()); + self.columns.extend(instance.memory.column.clone()); + } + for location in + layout.sections.iter().map(|section| §ion.location).chain(layout.instances.iter().map(|instance| &instance.memory.location)) + { + if let SectionLocation::Window { return_to, .. } = location { + if let Some(section) = &return_to.section { + valid_id(§ion.0)?; + } + if let Some(join) = &return_to.join { + valid_id(&join.section.0)?; + } + if let Some(column) = &return_to.column { + valid_id(&column.0)?; + } + self.sections.extend(return_to.section.clone()); + self.sections.extend(return_to.join.as_ref().map(|join| join.section.clone())); + self.columns.extend(return_to.column.clone()); + } + } + self.validate() + } +} + +/// Capture recognized full preparation metadata and fixed identity paths: no +/// migrated-envelope encoding or materialized reservation placements/controllers. +pub fn host_identity_reservations(envelope: &LayoutEnvelope) -> PanelResult { + if envelope.quarantine.len().saturating_add(envelope.layout.instances.len()) > MAX_INSTANCES + || envelope.section_snapshots.len() > MAX_SECTIONS + || envelope.section_order.len() > MAX_SECTIONS + || envelope.retained_data.len() > MAX_INSTANCES + { + return Err(error(Rule::CollectionLimit, "envelope identity collection cap")); + } + let context = preparation_context(envelope)?; + let mut reservations = HostIdentityReservations { + sections: context.sections, + columns: context.columns, + extent_priorities: context.extent_priorities, + replacement_ownership: context.replacement_ownership, + }; + reservations.include_layout(&envelope.layout)?; + for id in &envelope.section_order { + valid_id(&id.0)?; + reservations.sections.insert(id.clone()); + } + for item in &envelope.quarantine { + valid_id(&item.instance.0)?; + valid_id(&item.kind.0)?; + if let Some(id) = &item.section { + valid_id(&id.0)?; + reservations.sections.insert(id.clone()); + } + reserve_wire_instance(&mut reservations, &item.instance_data)?; + } + for (id, snapshot) in &envelope.section_snapshots { + valid_id(&id.0)?; + reservations.sections.insert(id.clone()); + reserve_wire_section(&mut reservations, &snapshot.data)?; + if let Some(section) = &snapshot.projected { + valid_id(§ion.id.0)?; + if let Some(column) = §ion.column { + valid_id(&column.0)?; + } + reservations.sections.insert(section.id.clone()); + reservations.columns.extend(section.column.clone()); + reserve_location(&mut reservations, §ion.location)?; + } + } + for data in envelope.retained_data.values() { + // Retained extension payloads may have opaque unrelated fields. Inspect + // only the known host wrapper shape; never reinterpret arbitrary data. + if let Some(instance) = + data.get("instance").filter(|instance| instance.get("memory").and_then(|memory| memory.get("section")).is_some_and(|id| id.is_string())) + { + reserve_wire_instance(&mut reservations, instance)?; + if let Some(id) = data.get("section").and_then(|id| id.as_str()) { + valid_id(id)?; + reservations.sections.insert(SectionId(id.to_owned())); + } + } + } + reservations.validate()?; + Ok(reservations) +} + +fn wire_identity<'a>(value: &'a serde_json::Value, key: &str) -> PanelResult> { + let Some(raw) = value.get(key).filter(|raw| !raw.is_null()) else { + return Ok(None); + }; + let id = raw.as_str().ok_or_else(|| error(Rule::Schema, "reserved identity must be a string"))?; + valid_id(id)?; + Ok(Some(id)) +} +fn reserve_wire_instance(out: &mut HostIdentityReservations, value: &serde_json::Value) -> PanelResult<()> { + let memory = value.get("memory").filter(|memory| memory.is_object()).ok_or_else(|| error(Rule::Schema, "reserved instance memory missing"))?; + if let Some(id) = wire_identity(memory, "section")? { + out.sections.insert(SectionId(id.to_owned())); + } + if let Some(id) = wire_identity(memory, "column")? { + out.columns.insert(ColumnId(id.to_owned())); + } + if let Some(location) = memory.get("location") { + reserve_wire_location(out, location)?; + } + Ok(()) +} +fn reserve_wire_section(out: &mut HostIdentityReservations, value: &serde_json::Value) -> PanelResult<()> { + if let Some(id) = wire_identity(value, "id")? { + out.sections.insert(SectionId(id.to_owned())); + } + if let Some(id) = wire_identity(value, "column")? { + out.columns.insert(ColumnId(id.to_owned())); + } + if let Some(location) = value.get("location") { + reserve_wire_location(out, location)?; + } + Ok(()) +} +fn reserve_wire_location(out: &mut HostIdentityReservations, location: &serde_json::Value) -> PanelResult<()> { + if location.get("type").and_then(|value| value.as_str()) != Some("window") { + return Ok(()); + } + let target = location.get("return_to").filter(|value| value.is_object()).ok_or_else(|| error(Rule::Schema, "reserved native return missing"))?; + if let Some(id) = wire_identity(target, "section")? { + out.sections.insert(SectionId(id.to_owned())); + } + if let Some(id) = wire_identity(target, "column")? { + out.columns.insert(ColumnId(id.to_owned())); + } + if let Some(join) = target.get("join").filter(|value| !value.is_null()) + && let Some(id) = wire_identity(join, "section")? + { + out.sections.insert(SectionId(id.to_owned())); + } + Ok(()) +} +fn reserve_location(out: &mut HostIdentityReservations, location: &SectionLocation) -> PanelResult<()> { + if let SectionLocation::Window { return_to, .. } = location { + if let Some(section) = &return_to.section { + valid_id(§ion.0)?; + } + if let Some(join) = &return_to.join { + valid_id(&join.section.0)?; + } + if let Some(column) = &return_to.column { + valid_id(&column.0)?; + } + out.sections.extend(return_to.section.clone()); + out.sections.extend(return_to.join.as_ref().map(|join| join.section.clone())); + out.columns.extend(return_to.column.clone()); + } + Ok(()) +} + +pub fn next_host_section_id(layout: &Layout, external: &HostIdentityReservations) -> PanelResult { + external.validate()?; + next_section_id_with_reservations(layout, &external.sections) +} +pub fn next_host_column_id(layout: &Layout, external: &HostIdentityReservations) -> PanelResult { + external.validate()?; + next_column_id_with_reservations(layout, &external.columns) +} + +/// Captured renderer fill alpha, separate from declared surface policy. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct HostSurfaceAlpha { + pub docked: u8, + pub floating: u8, +} + +#[derive(Clone, Debug)] +pub struct HostGeometryPolicy { + pub surface_alpha: Option, + pub default_opaque: bool, + pub effective_surfaces: BTreeMap, + pub content: Vec, + pub content_revision: u64, + pub scroll: Point, + pub measure: Option>, + pub identity_reservations: HostIdentityReservations, +} + +impl PartialEq for HostGeometryPolicy { + fn eq(&self, other: &Self) -> bool { + self.surface_alpha == other.surface_alpha + && self.default_opaque == other.default_opaque + && self.effective_surfaces == other.effective_surfaces + && self.identity_reservations == other.identity_reservations + && self.content == other.content + && self.content_revision == other.content_revision + && self.scroll == other.scroll + && match (&self.measure, &other.measure) { + (None, None) => true, + (Some(a), Some(b)) => std::sync::Arc::ptr_eq(a, b) && a.revision() == b.revision(), + _ => false, + } + } +} + +impl Default for HostGeometryPolicy { + fn default() -> Self { + Self { + surface_alpha: None, + default_opaque: true, + effective_surfaces: BTreeMap::new(), + content: Vec::new(), + content_revision: 0, + scroll: Point { x: 0.0, y: 0.0 }, + measure: None, + identity_reservations: HostIdentityReservations::default(), + } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub struct HostControl { + pub target: HostPointerTarget, + pub bounds: LogicalRect, + pub role: InputRole, + pub accessible_name: String, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct HostTab { + pub instance: InstanceId, + pub bounds: LogicalRect, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct HostSection { + pub paint_alpha: Option, + pub section: SectionId, + pub instance: InstanceId, + pub zone: Zone, + pub outer: LogicalRect, + pub header: LogicalRect, + /// Shared title/grip drag region; grip only for tab groups. Disjoint from tabs, + /// actions and editable inline content. + pub title: Option, + pub menu: LogicalRect, + /// Tab headings within the shared header, after the section grip. + pub tab_strip: Option, + pub tabs: Vec, + pub hidden_tabs: Vec, + pub tab_overflow: Option, + pub body: Option, + pub collapsed: bool, + pub inline: bool, + /// Editable inline content is separate from the shared title drag region. + pub inline_content: Option, + pub collapse: LogicalRect, + pub close: Option, + pub actions: Vec<(ControlId, LogicalRect)>, + pub footer: Option, + pub peek: bool, + pub surface: PanelSurface, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct HostSash { + pub first: SectionId, + pub second: SectionId, + pub zone: Zone, + pub bounds: LogicalRect, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct HostRail { + pub section: SectionId, + pub instance: InstanceId, + pub zone: Zone, + pub bounds: LogicalRect, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct HostOverflow { + pub zone: Zone, + /// Complete hidden set, including entries that cannot have any physical chrome. + pub sections: Vec, + pub tabs: Vec, + pub bounds: Option, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct HostLayout { + pub resolved: ResolvedLayout, + /// Paint order: docks, then floating cards. + pub sections: Vec, + pub sashes: Vec, + pub rails: Vec, + pub overflow: Vec, + /// A single bounded menu for every hidden entry, including groups whose + /// own rail cannot fit. None means even one control cannot be presented. + pub overflow_launcher: Option, + /// Typed routes are authoritative; never parse a foundation ControlId. + pub controls: Vec, + pub render_domain: LogicalRect, + pub capacity: LogicalRect, + pub chrome_obstacles: Vec, + pub usable: HostUsableRegion, + pub viewport: Option, + pub painted: Vec, + pub input: Vec, + pub occlusion: Vec, + pub reservations: Vec, + pub revision: u64, + pub direction: Direction, + pub metrics: HostMetrics, + pub geometry_policy: HostGeometryPolicy, + pub extent: Size, + pub allocation_environment: AllocationEnvironment, + pub source_state: LayoutReply, + pub registry_specs: Vec, +} + +impl HostLayout { + /// Public geometry remains bounded even when a direct adapter constructs or + /// modifies it. In particular, pointer code must not clamp against NaN. + pub fn validate(&self) -> PanelResult<()> { + self.allocation_environment.validate()?; + self.geometry_policy.identity_reservations.validate()?; + if self.registry_specs.len() > MAX_INSTANCES { + return Err(error(Rule::CollectionLimit, "host registry signature bound")); + } + let env = &self.allocation_environment; + if env.capacity != self.capacity + || env.direction != self.direction + || env.header_height != self.metrics.header_height + || env.footer_height != self.metrics.footer_height + self.metrics.content_header_height + || env.gap != self.metrics.gap + || env.min_viewport != self.metrics.min_viewport + || env.inline_max_height != self.metrics.inline_max_height + || env.scroll != self.geometry_policy.scroll + || env.content_revision != self.geometry_policy.content_revision + { + return Err(error(Rule::Bounds, "host allocation environment differs from presentation")); + } + if !self.extent.width.is_finite() + || !self.extent.height.is_finite() + || self.extent.width < self.capacity.size.width + || self.extent.height < self.capacity.size.height + || self.extent.width > MAX_LOGICAL + || self.extent.height > MAX_LOGICAL + { + return Err(error(Rule::Bounds, "invalid host scroll extent")); + } + if self.geometry_policy.measure.as_ref().is_some_and(|provider| provider.revision() != self.allocation_environment.content_revision) { + return Err(error(Rule::Revision, "content metric snapshot changed")); + } + validate_capacity(self.capacity)?; + validate_capacity(self.render_domain)?; + if !self.render_domain.contains_rect(self.capacity) || self.usable.domain != self.render_domain { + return Err(error(Rule::Bounds, "placement/usable domain differs from render domain")); + } + if self.chrome_obstacles.len() > MAX_USABLE_OBSTACLES + || self.usable.obstacles.len() > MAX_USABLE_OBSTACLES + || self.usable.free.len() > MAX_USABLE_PIECES + { + return Err(error(Rule::CollectionLimit, "usable-space collection bound")); + } + for bounds in self.chrome_obstacles.iter().chain(&self.usable.obstacles) { + bounds.validate()?; + } + for bounds in &self.usable.free { + bounds.validate()?; + if !self.render_domain.contains_rect(*bounds) || self.usable.obstacles.iter().any(|obstacle| overlaps(*bounds, *obstacle)) { + return Err(error(Rule::Bounds, "usable-space geometry crosses occupied bounds")); + } + } + self.metrics.validate()?; + if self.geometry_policy.effective_surfaces.len() > MAX_SECTIONS { + return Err(error(Rule::CollectionLimit, "host geometry policy bound")); + } + for section in self.geometry_policy.effective_surfaces.keys() { + valid_id(§ion.0)?; + } + self.resolved.validate()?; + if self.sections.len() > MAX_SECTIONS + || self.sashes.len() > MAX_SECTIONS + || self.rails.len() > MAX_INSTANCES + || self.overflow.len() > 5 + || self.controls.len() > MAX_HOST_CONTROLS + || self.painted.len() > MAX_INSTANCES * 8 + || self.input.len() > MAX_INSTANCES * 8 + || self.occlusion.len() > MAX_INSTANCES * 8 + || self.reservations.len() > MAX_INSTANCES * 8 + { + return Err(error(Rule::CollectionLimit, "host geometry collection bound")); + } + for bounds in self.painted.iter().chain(&self.input).chain(&self.occlusion).chain(&self.reservations).chain(self.overflow_launcher.iter()) { + bounds.validate()?; + if !self.capacity.contains_rect(*bounds) { + return Err(error(Rule::Bounds, "host geometry outside capacity")); + } + } + if self.viewport + != positive_rect(self.render_domain.origin.x, self.render_domain.origin.y, self.render_domain.size.width, self.render_domain.size.height) + { + return Err(error(Rule::Bounds, "render viewport must fill its domain")); + } + for bounds in &self.input { + if !self.painted.iter().any(|paint| paint.contains_rect(*bounds)) { + return Err(error(Rule::Bounds, "host input outside paint")); + } + } + let mut targets = BTreeSet::new(); + for control in &self.controls { + control.target.validate()?; + control.bounds.validate()?; + if control.accessible_name.is_empty() || control.accessible_name.len() > 256 { + return Err(error(Rule::Bounds, "host control semantic name bound")); + } + if !targets.insert(&control.target) { + return Err(error(Rule::DuplicateId, "duplicate typed host target")); + } + if !self.painted.iter().any(|paint| paint.contains_rect(control.bounds)) { + return Err(error(Rule::Bounds, "host control outside paint")); + } + } + for section in &self.sections { + valid_id(§ion.section.0)?; + valid_id(§ion.instance.0)?; + if (section.collapsed || section.inline) && (section.body.is_some() || section.footer.is_some()) + || section.inline_content.is_some() && (!section.inline || section.collapsed) + || section.inline && section.header != section.outer + { + return Err(error(Rule::Bounds, "collapsed/inline host has inconsistent content roles")); + } + if section.actions.len() > MAX_HEADER_ACTIONS { + return Err(error(Rule::CollectionLimit, "host header action cap")); + } + let mut actions = BTreeSet::new(); + for (action, _) in §ion.actions { + valid_id(&action.0)?; + if !actions.insert(action) { + return Err(error(Rule::DuplicateId, "duplicate host header action")); + } + } + if section.tabs.len() > MAX_TABS || section.hidden_tabs.len() > MAX_TABS || section.tabs.len() + section.hidden_tabs.len() > MAX_TABS { + return Err(error(Rule::CollectionLimit, "host tab geometry bound")); + } + if !self.resolved.panels.iter().any(|panel| { + panel.section == section.section + && panel.instance == section.instance + && panel.zone == section.zone + && panel.outer == section.outer + && panel.body == section.body + }) { + return Err(error(Rule::Placement, "host section differs from mounted geometry")); + } + for bounds in [ + Some(section.header), + section.title, + Some(section.menu), + Some(section.collapse), + section.close, + section.tab_strip, + section.body, + section.footer, + section.tab_overflow, + section.inline_content, + ] + .into_iter() + .flatten() + .chain(section.actions.iter().map(|(_, bounds)| *bounds)) + { + bounds.validate()?; + if !section.outer.contains_rect(bounds) { + return Err(error(Rule::Bounds, "host slot outside card")); + } + } + for tab in §ion.tabs { + valid_id(&tab.instance.0)?; + tab.bounds.validate()?; + if !section.tab_strip.is_some_and(|strip| strip.contains_rect(tab.bounds)) { + return Err(error(Rule::Bounds, "tab outside strip")); + } + } + for instance in §ion.hidden_tabs { + valid_id(&instance.0)?; + } + } + for rail in &self.rails { + valid_id(&rail.section.0)?; + valid_id(&rail.instance.0)?; + rail.bounds.validate()?; + if !self.capacity.contains_rect(rail.bounds) { + return Err(error(Rule::Bounds, "rail outside capacity")); + } + } + for group in &self.overflow { + if group.sections.len() > MAX_SECTIONS || group.tabs.len() > MAX_INSTANCES { + return Err(error(Rule::CollectionLimit, "host overflow collection bound")); + } + for section in &group.sections { + valid_id(§ion.0)?; + } + for instance in &group.tabs { + valid_id(&instance.0)?; + } + if let Some(bounds) = group.bounds { + bounds.validate()?; + if !self.capacity.contains_rect(bounds) { + return Err(error(Rule::Bounds, "overflow outside capacity")); + } + } + } + Ok(()) + } + + pub fn control(&self, target: &HostPointerTarget) -> Option<&HostControl> { + self.controls.iter().find(|control| control.target == *target) + } + + /// Reverse traversal follows the actual topmost painted chrome. + pub fn hit_test(&self, at: Point) -> Option { + if at.validate().is_err() { + return None; + } + self.controls.iter().rev().find(|control| control.bounds.contains(at)).map(|control| control.target.clone()) + } + + pub fn consumes_pointer(&self, at: Point) -> bool { + at.validate().is_ok() && self.input.iter().any(|bounds| bounds.contains(at)) + } +} + +/// Construct allocation environment from captured service state. No content code +/// runs here; availability is a bounded snapshot, not a callback in the allocator. +fn allocation_environment( + service: &LayoutService, + proposed: &Layout, + capacity: LogicalRect, + direction: Direction, + metrics: HostMetrics, + policy: &HostGeometryPolicy, + availability: Option<&AvailabilityMap>, +) -> PanelResult { + metrics.validate()?; + policy.identity_reservations.validate()?; + let env = AllocationEnvironment { + capacity, + direction, + header_height: metrics.header_height, + footer_height: metrics.footer_height + metrics.content_header_height, + gap: metrics.gap, + inline_max_height: metrics.inline_max_height, + min_viewport: metrics.min_viewport, + scroll: policy.scroll, + available: proposed + .instances + .iter() + .filter(|instance| { + availability.map_or_else( + || service.availability(&instance.id) == Availability::Available, + |captured| captured.get(&instance.id).is_none_or(|state| *state == Availability::Available), + ) + }) + .map(|instance| instance.id.clone()) + .collect(), + content: policy.content.clone(), + content_revision: policy.content_revision, + }; + env.validate()?; + if policy.measure.as_ref().is_some_and(|provider| provider.revision() != env.content_revision) { + return Err(error(Rule::Revision, "content metric snapshot revision differs")); + } + Ok(env) +} + +pub fn host_measure_requests( + service: &LayoutService, + proposed: &Layout, + capacity: LogicalRect, + direction: Direction, + metrics: HostMetrics, + policy: &HostGeometryPolicy, +) -> PanelResult> { + allocation_measure_requests(proposed, service.registry(), &allocation_environment(service, proposed, capacity, direction, metrics, policy, None)?) +} + +pub fn resolve_host_layout( + service: &LayoutService, + capacity: LogicalRect, + direction: Direction, + metrics: HostMetrics, + policy: &HostGeometryPolicy, +) -> PanelResult { + resolve_host_layout_in_domain(service, capacity, capacity, &[], direction, metrics, policy) +} + +pub fn resolve_host_layout_in_domain( + service: &LayoutService, + render_domain: LogicalRect, + capacity: LogicalRect, + chrome_obstacles: &[LogicalRect], + direction: Direction, + metrics: HostMetrics, + policy: &HostGeometryPolicy, +) -> PanelResult { + resolve_layout_source(service, service.layout(), render_domain, capacity, chrome_obstacles, direction, metrics, policy, None) +} + +/// Noncommittable current-owner geometry probe over structural projection data. +pub(super) fn resolve_host_projected(service: &LayoutService, proposed: &Layout, reference: &HostLayout) -> PanelResult { + resolve_layout_source( + service, + proposed, + reference.render_domain, + reference.capacity, + &reference.chrome_obstacles, + reference.direction, + reference.metrics, + &reference.geometry_policy, + None, + ) +} + +/// Final proposal geometry uses proposed-owner availability and one immutable +/// metric snapshot. The outgoing reference still anchors placement and freshness. +pub(super) fn resolve_host_prepared_with_snapshot( + service: &LayoutService, + prepared: &PreparedLayout, + reference: &HostLayout, + snapshot: &HostProposalSnapshot, +) -> PanelResult { + resolve_host_projected_with_snapshot(service, prepared.layout(), reference, snapshot) +} + +/// All numeric prefix probes share the final owner's immutable environment. +pub(super) fn resolve_host_projected_with_snapshot( + service: &LayoutService, + proposed: &Layout, + reference: &HostLayout, + snapshot: &HostProposalSnapshot, +) -> PanelResult { + let mut policy = reference.geometry_policy.clone(); + policy.content.clear(); + policy.content_revision = snapshot.metrics.revision(); + policy.measure = Some(snapshot.metrics.clone()); + resolve_layout_source( + service, + proposed, + reference.render_domain, + reference.capacity, + &reference.chrome_obstacles, + reference.direction, + reference.metrics, + &policy, + Some(&snapshot.availability), + ) +} + +fn resolve_layout_source( + service: &LayoutService, + proposed: &Layout, + render_domain: LogicalRect, + capacity: LogicalRect, + chrome_obstacles: &[LogicalRect], + direction: Direction, + metrics: HostMetrics, + policy: &HostGeometryPolicy, + availability: Option<&AvailabilityMap>, +) -> PanelResult { + validate_capacity(capacity)?; + validate_capacity(render_domain)?; + if !render_domain.contains_rect(capacity) { + return Err(error(Rule::Bounds, "placement outside render domain")); + } + let usable = resolve_usable_region(render_domain, chrome_obstacles)?; + let mut env = allocation_environment(service, proposed, capacity, direction, metrics, policy, availability)?; + for request in allocation_measure_requests(proposed, service.registry(), &env)? { + if env.content.iter().any(|measure| measure.request == request) { + continue; + } + let provider = policy.measure.as_ref().ok_or_else(|| error(Rule::Revision, "assigned-width content metrics missing"))?; + let measure = provider.measure(&request)?; + if measure.request != request || provider.revision() != env.content_revision { + return Err(error(Rule::Revision, "assigned-width content metrics changed")); + } + env.content.push(measure); + } + let allocation = allocate_layout(proposed, service.registry(), &env)?; + let source_state = service.inspect(); + let mut result = HostLayout { + resolved: ResolvedLayout::default(), + sections: Vec::new(), + sashes: Vec::new(), + rails: Vec::new(), + overflow: Vec::new(), + overflow_launcher: None, + controls: Vec::new(), + render_domain, + capacity, + chrome_obstacles: usable.obstacles.clone(), + usable, + viewport: positive_rect(render_domain.origin.x, render_domain.origin.y, render_domain.size.width, render_domain.size.height), + painted: Vec::new(), + input: Vec::new(), + occlusion: Vec::new(), + reservations: Vec::new(), + revision: source_state.revision, + direction, + metrics, + geometry_policy: policy.clone(), + extent: allocation.extent, + allocation_environment: env, + source_state, + registry_specs: service.registry().specs().cloned().collect(), + }; + for card in allocation.sections { + let section = proposed.section(&card.section)?; + append_section(&mut result, service, proposed, section, &card.instance, card.outer, policy)?; + } + append_sashes(&mut result, proposed)?; + for section in &proposed.sections { + if !result.sections.iter().any(|shown| shown.section == section.id) { + result.resolved.unpresented.push(UnpresentedSection { + section: section.id.clone(), + reason: if section.location.zone() == Zone::Window && !service.capabilities().native_windows { + UnpresentedReason::NativeUnsupported + } else { + UnpresentedReason::Unavailable + }, + }); + } + } + result.reservations = result.painted.clone(); + let obstacles: Vec<_> = result.chrome_obstacles.iter().chain(&result.reservations).copied().collect(); + result.usable = resolve_usable_region(render_domain, &obstacles)?; + result.validate()?; + Ok(result) +} + +fn validate_capacity(capacity: LogicalRect) -> PanelResult<()> { + validate_allocation_capacity(capacity) +} + +fn effective_surface(service: &LayoutService, proposed: &Layout, section: &Section, policy: &HostGeometryPolicy) -> PanelResult { + let mut specs = Vec::new(); + for instance in §ion.tabs { + specs.push(service.registry().get(&proposed.instance(instance)?.kind)?); + } + let declared = group_surface(section.location.zone(), specs); + if declared == PanelSurface::Opaque { + return Ok(PanelSurface::Opaque); + } + if let Some(surface) = policy.effective_surfaces.get(§ion.id) + && *surface != PanelSurface::FollowZone + { + return Ok(*surface); + } + Ok(if policy.default_opaque { PanelSurface::Opaque } else { declared }) +} + +fn append_section( + out: &mut HostLayout, + service: &LayoutService, + proposed: &Layout, + section: &Section, + instance: &InstanceId, + outer: LogicalRect, + policy: &HostGeometryPolicy, +) -> PanelResult<()> { + outer.validate()?; + let metrics = out.metrics; + let spec = service.registry().get(&proposed.instance(instance)?.kind)?; + let (flow, _) = responsive(section.location.zone(), outer.size, None)?; + // A single row owns inline controls AND content; no hidden second body. + let inline = !section.collapsed && flow == Flow::Wide && outer.size.height <= metrics.inline_max_height; + let header = + rect(outer.origin.x, outer.origin.y, outer.size.width, if inline { outer.size.height } else { metrics.header_height.min(outer.size.height) }); + let control_count = spec.header_actions.len() + 2 + usize::from(spec.features.hot_closable); + let extent = metrics.control_extent.min(header.size.width / control_count.max(1) as f32); + let mut cursor = if out.direction == Direction::Ltr { right(header) } else { header.origin.x }; + let take = |cursor: &mut f32| { + let x = if out.direction == Direction::Ltr { *cursor - extent } else { *cursor }; + *cursor += if out.direction == Direction::Ltr { -extent } else { extent }; + rect(x, header.origin.y, extent, header.size.height) + }; + let close = if spec.features.hot_closable { Some(take(&mut cursor)) } else { None }; + let collapse = take(&mut cursor); + let menu = take(&mut cursor); + let mut actions = Vec::new(); + let (heading, inline_content) = if inline { + // Shared title/grip, declared custom actions, editable inline content, + // then shared system actions. The whole sequence mirrors in RTL. + let available = (header.size.width - extent * control_count as f32).max(0.0); + let title_width = metrics.inline_title_width.min(available * 0.4); + let mut leading = if out.direction == Direction::Ltr { header.origin.x } else { right(header) }; + let title_x = if out.direction == Direction::Ltr { leading } else { leading - title_width }; + let title = positive_rect(title_x, header.origin.y, title_width, header.size.height); + leading += if out.direction == Direction::Ltr { title_width } else { -title_width }; + for action in &spec.header_actions { + let x = if out.direction == Direction::Ltr { leading } else { leading - extent }; + actions.push((action.id.clone(), rect(x, header.origin.y, extent, header.size.height))); + leading += if out.direction == Direction::Ltr { extent } else { -extent }; + } + let content = if out.direction == Direction::Ltr { + positive_rect(leading, header.origin.y, cursor - leading, header.size.height) + } else { + positive_rect(cursor, header.origin.y, leading - cursor, header.size.height) + }; + (title, content) + } else { + for action in spec.header_actions.iter().rev() { + actions.push((action.id.clone(), take(&mut cursor))); + } + actions.reverse(); + ( + positive_rect( + if out.direction == Direction::Ltr { header.origin.x } else { cursor }, + header.origin.y, + if out.direction == Direction::Ltr { cursor - header.origin.x } else { right(header) - cursor }, + header.size.height, + ), + None, + ) + }; + // A group replaces the single title with one grip and text-only tabs in + // that same slot. Collapsing never removes access to individual tabs. + let (title, tab_strip) = if section.tabs.len() > 1 { + if let Some(heading) = heading { + let t = crate::theme::Tokens::get(); + let grip_width = metrics.control_extent.min(t.space_10 + t.space_8).min(heading.size.width); + let grip_x = if out.direction == Direction::Ltr { heading.origin.x } else { right(heading) - grip_width }; + let tabs_x = if out.direction == Direction::Ltr { grip_x + grip_width } else { heading.origin.x }; + ( + positive_rect(grip_x, heading.origin.y, grip_width, heading.size.height), + positive_rect(tabs_x, heading.origin.y, heading.size.width - grip_width, heading.size.height), + ) + } else { + (None, None) + } + } else { + (heading, None) + }; + let body_y = bottom(header) + metrics.content_header_height; + let body = if section.collapsed || inline { + None + } else { + positive_rect(outer.origin.x, body_y, outer.size.width, bottom(outer) - metrics.footer_height - body_y) + }; + let footer = if section.collapsed || inline { + None + } else { + positive_rect(outer.origin.x, bottom(outer) - metrics.footer_height, outer.size.width, metrics.footer_height) + }; + let mut tabs = Vec::new(); + let mut hidden_tabs = Vec::new(); + let mut tab_overflow = None; + if let Some(strip) = tab_strip { + let count = (strip.size.width / metrics.tab_min_width).floor().min(MAX_TABS as f32) as usize; + let overflowed = count < section.tabs.len(); + // Overflow is a compact control, not another full-width tab. Keep the + // active heading whenever its minimum width fits beside that control. + let overflow_width = if overflowed { metrics.control_extent.min(strip.size.width) } else { 0.0 }; + let visible_count = if overflowed { + ((strip.size.width - overflow_width) / metrics.tab_min_width).floor().min(MAX_TABS as f32) as usize + } else { + section.tabs.len() + }; + let mut visible: BTreeSet<_> = section.tabs.iter().take(visible_count).cloned().collect(); + if visible_count > 0 && !visible.contains(instance) { + if let Some(last) = section.tabs.get(visible_count.saturating_sub(1)) { + visible.remove(last); + } + visible.insert(instance.clone()); + } + let width = (strip.size.width - overflow_width) / visible.len().max(1) as f32; + let mut cursor = if out.direction == Direction::Ltr { strip.origin.x } else { right(strip) }; + for id in §ion.tabs { + if visible.contains(id) { + let remaining = + if out.direction == Direction::Ltr { right(strip) - overflow_width - cursor } else { cursor - strip.origin.x - overflow_width }; + let cell_width = width.min(remaining); + let x = if out.direction == Direction::Ltr { cursor } else { cursor - cell_width }; + tabs.push(HostTab { instance: id.clone(), bounds: rect(x, strip.origin.y, cell_width, strip.size.height) }); + cursor = if out.direction == Direction::Ltr { x + cell_width } else { x }; + } else { + hidden_tabs.push(id.clone()); + } + } + if overflowed { + tab_overflow = positive_rect( + if out.direction == Direction::Ltr { right(strip) - overflow_width } else { strip.origin.x }, + strip.origin.y, + overflow_width, + strip.size.height, + ); + } + } else if section.tabs.len() > 1 { + hidden_tabs = section.tabs.clone(); + } + let surface = effective_surface(service, proposed, section, policy)?; + let painted: Vec<_> = intersect_rect(outer, out.capacity).into_iter().collect(); + let input = painted + .iter() + .map(|bounds| InputRegion { + control: ControlId(instance.0.clone()), + role: InputRole::Surface, + bounds: *bounds, + keyboard_focusable: true, + accessible_name: spec.title_key.clone(), + }) + .collect(); + out.resolved.panels.push(ResolvedPanel { + instance: instance.clone(), + section: section.id.clone(), + zone: section.location.zone(), + outer, + body, + painted: painted.clone(), + input, + }); + out.painted.extend(&painted); + out.occlusion.extend(&painted); + out.input.extend(&painted); + add_control(out, HostPointerTarget::Surface { instance: instance.clone() }, outer, InputRole::Surface, "ui.panel_host.surface"); + if let Some(title) = title { + add_control(out, HostPointerTarget::Header { instance: instance.clone() }, title, InputRole::Header, "ui.panel_host.header"); + } + add_control(out, HostPointerTarget::Menu { instance: instance.clone() }, menu, InputRole::Action, "ui.panel_host.menu"); + add_control(out, HostPointerTarget::Collapse { instance: instance.clone() }, collapse, InputRole::Action, "ui.panel_host.collapse"); + if let Some(close) = close { + add_control(out, HostPointerTarget::Close { instance: instance.clone() }, close, InputRole::Action, "ui.panel_host.close"); + } + for (id, bounds) in &actions { + let name = spec.header_actions.iter().find(|action| action.id == *id).map_or("ui.panel_host.menu", |action| action.label_key.as_str()); + add_control(out, HostPointerTarget::HeaderAction { instance: instance.clone(), action: id.clone() }, *bounds, InputRole::Action, name); + } + for tab in &tabs { + add_control(out, HostPointerTarget::Tab { instance: tab.instance.clone() }, tab.bounds, InputRole::Tab, "ui.panel_host.tab"); + } + if let Some(bounds) = tab_overflow { + add_control(out, HostPointerTarget::TabOverflow { section: section.id.clone() }, bounds, InputRole::Action, "ui.panel_host.overflow"); + } + // Workspace paints the card's resize response last, above header/content. + // Reverse geometric hit-testing must choose the same owner at their edges. + let edge = match section.location.zone() { + Zone::Floating => HostResizeEdge::BottomRight, + Zone::Bottom => HostResizeEdge::Top, + Zone::Left => HostResizeEdge::Right, + _ => HostResizeEdge::Left, + }; + if !section.collapsed { + add_control( + out, + HostPointerTarget::Resize { section: section.id.clone(), edge }, + resize_rect(outer, edge.physical(section.location.zone(), out.direction), metrics.sash_width), + InputRole::Sash, + "ui.panel_host.resize", + ); + } + let paint_alpha = policy.surface_alpha.map(|alpha| if section.location.zone() == Zone::Floating { alpha.floating } else { alpha.docked }); + out.sections.push(HostSection { + paint_alpha, + section: section.id.clone(), + instance: instance.clone(), + zone: section.location.zone(), + outer, + header, + title, + menu, + tab_strip, + tabs, + hidden_tabs, + tab_overflow, + body, + footer, + peek: false, + surface, + collapsed: section.collapsed, + inline, + inline_content, + collapse, + close, + actions, + }); + Ok(()) +} + +fn append_sashes(out: &mut HostLayout, proposed: &Layout) -> PanelResult<()> { + let mut groups: BTreeMap<(Zone, Option), Vec> = BTreeMap::new(); + // Allocation order is already per presented column/Bottom row. Unavailable + // members occupy no space; collapsed headers remain intervening members. + for shown in &out.sections { + if shown.zone.docked() { + let section = proposed.section(&shown.section)?; + groups.entry((shown.zone, section.column.clone())).or_default().push(section.id.clone()); + } + } + for members in groups.values() { + for pair in members.windows(2) { + let (Some(first), Some(second)) = (pair.first(), pair.get(1)) else { + continue; + }; + let a = out.sections.iter().find(|shown| shown.section == *first); + let b = out.sections.iter().find(|shown| shown.section == *second); + if let (Some(a), Some(b)) = (a, b) { + if a.collapsed || b.collapsed { + continue; + } + let zone = a.zone; + let bounds = if zone == Zone::Bottom { + let left = if out.direction == Direction::Ltr { a.outer } else { b.outer }; + let right_card = if out.direction == Direction::Ltr { b.outer } else { a.outer }; + let gap = right_card.origin.x - right(left); + let width = if out.metrics.gap == 0.0 { out.metrics.sash_width.min(left.size.width).min(right_card.size.width) } else { gap }; + positive_rect( + right(left) - if out.metrics.gap == 0.0 { width / 2.0 } else { 0.0 }, + left.origin.y.max(right_card.origin.y), + width, + left.size.height.min(right_card.size.height), + ) + } else { + let gap = b.outer.origin.y - bottom(a.outer); + let height = if out.metrics.gap == 0.0 { out.metrics.sash_width.min(a.outer.size.height).min(b.outer.size.height) } else { gap }; + positive_rect( + a.outer.origin.x, + bottom(a.outer) - if out.metrics.gap == 0.0 { height / 2.0 } else { 0.0 }, + a.outer.size.width, + height, + ) + }; + if let Some(bounds) = bounds.and_then(|bounds| intersect_rect(bounds, out.capacity)) { + out.sashes.push(HostSash { first: first.clone(), second: second.clone(), zone, bounds }); + out.painted.push(bounds); + out.occlusion.push(bounds); + out.input.push(bounds); + add_control( + out, + HostPointerTarget::Sash { first: first.clone(), second: second.clone() }, + bounds, + InputRole::Sash, + "ui.panel_host.sash", + ); + } + } + } + } + Ok(()) +} + +fn add_control(out: &mut HostLayout, target: HostPointerTarget, bounds: LogicalRect, role: InputRole, name: &str) { + if let Some(bounds) = intersect_rect(bounds, out.capacity) { + out.controls.push(HostControl { target, bounds, role, accessible_name: name.into() }); + } +} + +fn resize_rect(outer: LogicalRect, edge: HostResizeEdge, thickness: f32) -> LogicalRect { + let width = thickness.min(outer.size.width); + let height = thickness.min(outer.size.height); + match edge { + HostResizeEdge::Left => rect(outer.origin.x, outer.origin.y, width, outer.size.height), + HostResizeEdge::Right => rect(right(outer) - width, outer.origin.y, width, outer.size.height), + HostResizeEdge::Top => rect(outer.origin.x, outer.origin.y, outer.size.width, height), + HostResizeEdge::Bottom => rect(outer.origin.x, bottom(outer) - height, outer.size.width, height), + HostResizeEdge::BottomRight => rect(right(outer) - width, bottom(outer) - height, width, height), + } +} + +pub(super) fn rect(x: f32, y: f32, width: f32, height: f32) -> LogicalRect { + LogicalRect { origin: Point { x, y }, size: Size { width, height } } +} +pub(super) fn positive_rect(x: f32, y: f32, width: f32, height: f32) -> Option { + let bounds = rect(x, y, width, height); + if bounds.validate().is_ok() { Some(bounds) } else { None } +} +pub(super) fn right(bounds: LogicalRect) -> f32 { + bounds.origin.x + bounds.size.width +} +pub(super) fn bottom(bounds: LogicalRect) -> f32 { + bounds.origin.y + bounds.size.height +} diff --git a/crates/ui-egui/src/panel_runtime/mod.rs b/crates/ui-egui/src/panel_runtime/mod.rs index 7293ab066..0ea1ea652 100644 --- a/crates/ui-egui/src/panel_runtime/mod.rs +++ b/crates/ui-egui/src/panel_runtime/mod.rs @@ -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; diff --git a/crates/ui-egui/src/panel_runtime/runtime.rs b/crates/ui-egui/src/panel_runtime/runtime.rs index 403caf10f..d58adeb18 100644 --- a/crates/ui-egui/src/panel_runtime/runtime.rs +++ b/crates/ui-egui/src/panel_runtime/runtime.rs @@ -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> { + 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 { + 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 { + 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>, + revision: u64, +} +impl HostContentMetrics for CapturedPanelMetrics { + fn measure(&self, request: &ContentMeasureRequest) -> PanelResult { + 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 PanelResult>>, } -#[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, + availability: AvailabilityMap, + metrics: std::sync::Arc, + metric_revision: u64, + providers: BTreeMap>, +} + +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 { + self.runtime.layout.project_with_context(action, context) + } + fn dispatch_in_context(&mut self, action: LayoutAction, context: &LayoutPreparationContext) -> PanelResult { + 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 { self.runtime.layout.project(action) } fn dispatch(&mut self, action: LayoutAction) -> PanelResult { - 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> { + // 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 { + 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, + mut providers: BTreeMap>, + models: &dyn PanelModels, + ) -> PanelResult { + 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, + models: &dyn PanelModels, + ) -> PanelResult { + 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 { + 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 { + 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 { + 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, + context: Option<&LayoutPreparationContext>, + ) -> PanelResult { + // 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 { + 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 { + 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 { + self.require_live()?; + let key = self.key(self.layout.layout().instance(instance)?)?; + self.presentation(&key) + } + pub fn instance_owner(&self, instance: &InstanceId) -> PanelResult { + self.key(self.layout.layout().instance(instance)?).map(|key| key.owner) + } fn key(&self, instance: &PanelInstance) -> PanelResult { 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> { - 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, + ) -> PanelResult> { let mut owner_counts = BTreeMap::::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 { + 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, + mut prepared: PreparedLayout, + native: &mut dyn NativeHostAdapter, + services: &mut ContentServices<'_>, + cohort: Option, + ) -> PanelResult { + 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(()) + } } diff --git a/crates/ui-egui/src/panel_runtime/specimen.rs b/crates/ui-egui/src/panel_runtime/specimen.rs new file mode 100644 index 000000000..f035f3256 --- /dev/null +++ b/crates/ui-egui/src/panel_runtime/specimen.rs @@ -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>>>; + +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::>(); + 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, + 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> { + 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 { + 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, + calls: Rc>, +} +impl PanelModels for SpecimenModels { + fn read(&self, _owner: &ContentOwner, key: &str) -> PanelResult { + 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>, +} +impl ContentCommandSink for SpecimenCommands { + fn execute(&mut self, _owner: &ContentOwner, command: &str, input: Value) -> PanelResult { + 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 { + 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 { + 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::>(), + "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::>(),"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}) + } + } +} diff --git a/crates/ui-egui/src/panel_runtime/tests.rs b/crates/ui-egui/src/panel_runtime/tests.rs index ccee0ee4a..eaa79871b 100644 --- a/crates/ui-egui/src/panel_runtime/tests.rs +++ b/crates/ui-egui/src/panel_runtime/tests.rs @@ -2,6 +2,4249 @@ use solidcraft_engine::panels::*; use super::*; +/// Immutable analytic metrics fixture. These cases do not render bodies and do +/// not establish visual fidelity. +#[derive(Debug)] +struct AllocationMetricsFixture { + revision: u64, + policies: std::collections::BTreeMap, + width: Option, + narrow_height: f32, + wide_height: f32, +} +impl HostContentMetrics for AllocationMetricsFixture { + fn revision(&self) -> u64 { + self.revision + } + fn measure(&self, request: &ContentMeasureRequest) -> PanelResult { + if self.width.is_some_and(|width| width != request.width) { + return Err(error(Rule::Revision, "fixture has no metrics at requested width")); + } + Ok(SideContentMeasure { + request: request.clone(), + needed_height: (if request.width < 300.0 { self.narrow_height } else { self.wide_height }).max(request.chrome_height), + policy: self.policies.get(&request.instance).copied().unwrap_or(SideHeightPolicy::Content), + }) + } +} +fn fixture_complete_reservations(service: &LayoutService) -> HostIdentityReservations { + // This fixture owns the complete synthetic envelope, including all memories. + // Production bare defaults remain incomplete and cannot author priorities. + host_identity_reservations(&LayoutEnvelope::new(service.layout().clone())).unwrap() +} +fn fixture_metric_policy(service: &LayoutService) -> HostGeometryPolicy { + let policies = service + .layout() + .instances + .iter() + .map(|instance| (instance.id.clone(), service.registry().get(&instance.kind).unwrap().side_height_policy)) + .collect(); + HostGeometryPolicy { + measure: Some(std::sync::Arc::new(AllocationMetricsFixture { revision: 7, policies, width: None, narrow_height: 240.0, wide_height: 240.0 })), + content_revision: 7, + identity_reservations: fixture_complete_reservations(service), + ..HostGeometryPolicy::default() + } +} +fn host_layout(h: &PanelMountHarness, width: f32, height: f32, direction: Direction) -> HostLayout { + resolve_host_layout( + h.runtime.layout(), + LogicalRect { origin: Point { x: 0.0, y: 0.0 }, size: Size { width, height } }, + direction, + HostMetrics::default(), + &fixture_metric_policy(h.runtime.layout()), + ) + .unwrap() +} +fn allocate_fixture(service: &LayoutService, size: Size, direction: Direction, policy: &HostGeometryPolicy) -> HostLayout { + let mut policy = policy.clone(); + if policy.identity_reservations == HostIdentityReservations::default() { + policy.identity_reservations = fixture_complete_reservations(service); + } + resolve_host_layout( + service, + LogicalRect { origin: Point { x: 0.0, y: 30.0 }, size }, + direction, + HostMetrics { + header_height: 24.0, + footer_height: 16.0, + inline_max_height: 88.0, + content_header_height: 0.0, + min_viewport: Size { width: 8.0, height: 8.0 }, + ..HostMetrics::default() + }, + &policy, + ) + .unwrap() +} +fn apply_fixture(service: &mut LayoutService, mutations: Vec) { + let prepared = service.prepare(transaction(mutations)).unwrap(); + service.commit(prepared).unwrap(); +} +fn fixture_scope(service: &LayoutService) -> LocalScope { + LocalScope { workspace: service.layout().workspace.clone(), document: None, viewport: ViewportId::new("fixture.viewport").unwrap() } +} +fn fixture_press(service: &LayoutService, layout: &HostLayout, interaction: &mut HostInteraction, target: HostPointerTarget) -> Point { + let at = middle(layout.control(&target).unwrap().bounds); + let update = interaction.update(service, &fixture_scope(service), layout, HostPointerEvent::Press { at, target: Some(target) }); + assert!(update.rejection.is_none(), "{update:?}"); + assert!(update.candidate.is_none()); + at +} +fn fixture_move(service: &LayoutService, layout: &HostLayout, interaction: &mut HostInteraction, at: Point) -> HostPreview { + let update = interaction.update(service, &fixture_scope(service), layout, HostPointerEvent::Move { at }); + assert!(update.action.is_none()); + assert!(update.candidate.is_none(), "candidate stays privately owned until release"); + update.preview.unwrap() +} +fn fixture_commit(service: &mut LayoutService, layout: &HostLayout, candidate: PreparedHostLayout) -> HostLayout { + let expected = candidate.layout().clone(); + let prepared = candidate.into_prepared(service, &fixture_scope(service), layout).unwrap(); + service.commit(prepared).unwrap(); + let actual = resolve_host_layout(service, layout.capacity, layout.direction, layout.metrics, &layout.geometry_policy).unwrap(); + assert_eq!(actual.sections, expected.sections); + assert_eq!(actual.allocation_environment, expected.allocation_environment); + assert_eq!(actual.usable, expected.usable); + actual +} + +fn allocation_service(edit: impl Fn(&mut PanelSpec)) -> LayoutService { + let mut registry = PanelRegistry::default(); + for original in synthetic_registry().unwrap().specs() { + let mut spec = original.clone(); + edit(&mut spec); + registry.register(spec).unwrap(); + } + LayoutService::new(registry, Layout::empty(WorkspaceId::new("fixture.workspace").unwrap()), HostCapabilities::default()).unwrap() +} + +#[test] +fn allocation_columns_have_independent_widths_and_mirror_outer_order_in_logical_units() { + for zone in [Zone::Left, Zone::Right] { + let mut service = fixture_service(false).unwrap(); + apply_fixture( + &mut service, + (0..3).map(|index| fixture_open("fixture.log", &format!("p{index}"), &format!("s{index}"), zone, index).unwrap()).collect(), + ); + for (instance, target, column) in [("p1", "s0", "column.one"), ("p2", "s1", "column.two")] { + apply_fixture( + &mut service, + vec![Mutation::Move { + instance: id(instance), + destination: Destination::Relative { + section: section(target), + placement: RelativePlacement::AfterColumn, + new_section: section(&instance.replace('p', "s")), + new_column: Some(ColumnId::new(column).unwrap()), + size: Size { width: 280.0, height: 240.0 }, + }, + }], + ); + } + let widths = [200.0, 260.0, 320.0]; + let mutations = service + .layout() + .columns + .iter() + .zip(widths) + .map(|(column, width)| Mutation::SetColumnWidth { column: column.id.clone(), width }) + .collect(); + apply_fixture(&mut service, mutations); + let before = service.inspect(); + for scale in [1.0, 2.0] { + for direction in [Direction::Ltr, Direction::Rtl] { + let host = allocate_fixture(&service, Size { width: 1600.0, height: 900.0 }, direction, &fixture_metric_policy(&service)); + assert_eq!(host.sections.len(), 3); + let physical_left = direction.edge(zone).unwrap() == PhysicalEdge::Left; + for (index, card) in host.sections.iter().enumerate() { + assert_eq!(card.outer.size.width, widths[index]); + assert_eq!(card.outer.origin.y, host.capacity.origin.y); + if index > 0 { + let previous = host.sections[index - 1].outer; + assert!(if physical_left { + previous.origin.x + previous.size.width < card.outer.origin.x + } else { + card.outer.origin.x + card.outer.size.width < previous.origin.x + }); + } + assert_eq!((card.outer.size.width * scale) / scale, widths[index]); + } + assert_eq!(host.viewport, Some(host.render_domain)); + } + } + assert_eq!(service.inspect(), before); + } +} + +#[test] +fn allocation_intersects_inactive_tab_and_every_stacked_section_width() { + let mut service = allocation_service(|spec| { + if spec.kind.0 == "fixture.application" { + spec.min_size.width = 250.0; + spec.max_size.width = 300.0; + } + }); + apply_fixture( + &mut service, + vec![ + fixture_open("fixture.log", "one", "one", Zone::Left, 0).unwrap(), + fixture_open("fixture.log", "two", "two", Zone::Left, 1).unwrap(), + Mutation::Open { + kind: PanelKind::new("fixture.application").unwrap(), + instance: id("inactive"), + destination: Some(Destination::JoinTab { section: section("one"), index: 1 }), + }, + ], + ); + let column = service.layout().sections[0].column.clone().unwrap(); + assert_eq!(column_bounds(service.layout(), service.registry(), &column).unwrap(), (250.0, 300.0)); + let before = service.inspect(); + assert!(service.prepare(transaction(vec![Mutation::SetColumnWidth { column: column.clone(), width: 310.0 }])).is_err()); + assert_eq!(service.inspect(), before); + apply_fixture(&mut service, vec![Mutation::SetColumnWidth { column, width: 250.0 }]); + let host = allocate_fixture(&service, Size { width: 1200.0, height: 800.0 }, Direction::Ltr, &fixture_metric_policy(&service)); + assert!(host.sections.iter().all(|card| card.outer.size.width == 250.0)); +} + +#[test] +fn allocation_sole_content_uses_assigned_width_metrics_and_fill_leaves_no_false_gap() { + for zone in [Zone::Left, Zone::Right] { + let mut service = fixture_service(false).unwrap(); + apply_fixture(&mut service, vec![fixture_open("fixture.log", "one", "one", zone, 0).unwrap()]); + let snapshot = |policy| HostGeometryPolicy { + content_revision: 11, + measure: Some(std::sync::Arc::new(AllocationMetricsFixture { + revision: 11, + policies: [(id("one"), policy)].into(), + width: None, + narrow_height: 360.0, + wide_height: 180.0, + })), + ..HostGeometryPolicy::default() + }; + for direction in [Direction::Ltr, Direction::Rtl] { + let content = allocate_fixture(&service, Size { width: 1200.0, height: 800.0 }, direction, &snapshot(SideHeightPolicy::Content)); + assert_eq!(content.sections[0].outer.size.height, 360.0); + let below = Point { x: middle(content.sections[0].outer).x, y: 600.0 }; + assert!(!content.consumes_pointer(below)); + assert!(content.usable.free.iter().any(|free| free.contains(below))); + let fill = allocate_fixture(&service, content.capacity.size, direction, &snapshot(SideHeightPolicy::Fill)); + assert_eq!(fill.sections[0].outer.size.height, 800.0); + assert!(fill.consumes_pointer(below)); + } + let column = service.layout().sections[0].column.clone().unwrap(); + apply_fixture(&mut service, vec![Mutation::SetColumnWidth { column, width: 420.0 }]); + let wide = allocate_fixture(&service, Size { width: 1200.0, height: 800.0 }, Direction::Ltr, &snapshot(SideHeightPolicy::Content)); + assert_eq!(wide.sections[0].outer.size.height, 180.0); + assert_eq!(wide.allocation_environment.content[0].request.width, 420.0); + } +} + +#[test] +fn allocation_active_available_tab_owns_policy_while_inactive_height_limit_still_applies() { + let mut service = allocation_service(|spec| { + if spec.kind.0 == "fixture.application" { + spec.max_size.height = 260.0; + } + }); + apply_fixture( + &mut service, + vec![ + fixture_open("fixture.log", "content", "group", Zone::Left, 0).unwrap(), + Mutation::Open { + kind: PanelKind::new("fixture.application").unwrap(), + instance: id("fill"), + destination: Some(Destination::JoinTab { section: section("group"), index: 1 }), + }, + ], + ); + let policy = HostGeometryPolicy { + content_revision: 3, + measure: Some(std::sync::Arc::new(AllocationMetricsFixture { + revision: 3, + policies: [(id("fill"), SideHeightPolicy::Fill)].into(), + width: None, + narrow_height: 180.0, + wide_height: 180.0, + })), + ..HostGeometryPolicy::default() + }; + let content = allocate_fixture(&service, Size { width: 1000.0, height: 800.0 }, Direction::Ltr, &policy); + assert_eq!(content.sections[0].outer.size.height, 180.0); + apply_fixture(&mut service, vec![Mutation::Activate { instance: id("fill") }]); + let fill = allocate_fixture(&service, content.capacity.size, Direction::Ltr, &policy); + assert_eq!(fill.sections[0].outer.size.height, 260.0); + service.set_availability([(id("fill"), Availability::Unavailable { reason: "fixture context".into() })].into()).unwrap(); + let available = allocate_fixture(&service, content.capacity.size, Direction::Ltr, &policy); + assert_eq!(available.sections[0].instance, id("content")); + assert_eq!(available.sections[0].outer.size.height, 180.0); +} + +#[test] +fn allocation_missing_or_stale_width_metrics_reject_before_any_candidate_is_shown() { + let mut service = fixture_service(false).unwrap(); + apply_fixture(&mut service, vec![fixture_open("fixture.log", "one", "one", Zone::Left, 0).unwrap()]); + let capacity = LogicalRect { origin: Point { x: 0.0, y: 0.0 }, size: Size { width: 1200.0, height: 800.0 } }; + let metrics = HostMetrics::default(); + assert_eq!(resolve_host_layout(&service, capacity, Direction::Ltr, metrics, &HostGeometryPolicy::default()).unwrap_err().rule, Rule::Revision); + let base = fixture_metric_policy(&service); + let request = host_measure_requests(&service, service.layout(), capacity, Direction::Ltr, metrics, &base).unwrap().remove(0); + let measured = base.measure.as_ref().unwrap().measure(&request).unwrap(); + let policy = HostGeometryPolicy { + content: vec![measured], + content_revision: 7, + identity_reservations: fixture_complete_reservations(&service), + ..HostGeometryPolicy::default() + }; + let host = resolve_host_layout(&service, capacity, Direction::Ltr, metrics, &policy).unwrap(); + let column = service.layout().sections[0].column.clone().unwrap(); + let before = service.inspect(); + let action = transaction(vec![Mutation::SetColumnWidth { column, width: 360.0 }]); + assert_eq!(prepare_host_layout(&service, &fixture_scope(&service), &host, action).unwrap_err().rule, Rule::Revision); + assert_eq!(service.inspect(), before); + let mut stale = base; + stale.content_revision = 8; + assert_eq!(resolve_host_layout(&service, capacity, Direction::Ltr, metrics, &stale).unwrap_err().rule, Rule::Revision); +} + +#[test] +fn allocation_collapse_restores_weights_and_max_limited_or_all_collapsed_stacks_leave_real_gaps() { + let mut service = allocation_service(|spec| { + spec.max_size.height = 240.0; + }); + apply_fixture( + &mut service, + vec![fixture_open("fixture.log", "one", "one", Zone::Left, 0).unwrap(), fixture_open("fixture.log", "two", "two", Zone::Left, 1).unwrap()], + ); + let policy = fixture_metric_policy(&service); + let before = service.layout().clone(); + let expanded = allocate_fixture(&service, Size { width: 1200.0, height: 900.0 }, Direction::Ltr, &policy); + assert!(expanded.sections.iter().all(|card| card.outer.size.height == 240.0)); + assert!(!expanded.consumes_pointer(Point { x: 80.0, y: 800.0 })); + apply_fixture( + &mut service, + vec![Mutation::Collapse { section: section("one"), collapsed: true }, Mutation::Collapse { section: section("two"), collapsed: true }], + ); + let collapsed = allocate_fixture(&service, expanded.capacity.size, Direction::Ltr, &policy); + assert!(collapsed.rails.is_empty() && collapsed.resolved.rails.is_empty()); + assert!(collapsed.sections.iter().all(|card| card.collapsed + && card.body.is_none() + && card.footer.is_none() + && card.outer.size.height == collapsed.metrics.header_height + && card.outer.size.width == 280.0)); + assert!(!collapsed.consumes_pointer(Point { x: 80.0, y: 200.0 })); + apply_fixture( + &mut service, + vec![Mutation::Collapse { section: section("one"), collapsed: false }, Mutation::Collapse { section: section("two"), collapsed: false }], + ); + assert_eq!(service.layout().sections, before.sections); + let restored = allocate_fixture(&service, expanded.capacity.size, Direction::Ltr, &policy); + assert_eq!(restored.sections, expanded.sections); +} + +#[test] +fn allocation_sole_transition_preserves_nonuniform_stack_weights() { + let mut initial = fixture_service(false).unwrap(); + apply_fixture( + &mut initial, + vec![fixture_open("fixture.log", "one", "one", Zone::Left, 0).unwrap(), fixture_open("fixture.log", "two", "two", Zone::Left, 1).unwrap()], + ); + let mut layout = initial.layout().clone(); + layout.sections[0].weight = 1.0; + layout.sections[1].weight = 3.0; + let mut service = LayoutService::new(synthetic_registry().unwrap(), layout, HostCapabilities::default()).unwrap(); + let before = allocate_fixture(&service, Size { width: 1200.0, height: 800.0 }, Direction::Ltr, &fixture_metric_policy(&service)); + assert!(before.sections[1].outer.size.height > before.sections[0].outer.size.height); + service.set_availability([(id("two"), Availability::Unavailable { reason: "hidden context".into() })].into()).unwrap(); + let sole = allocate_fixture(&service, before.capacity.size, Direction::Ltr, &fixture_metric_policy(&service)); + assert_eq!(sole.sections.len(), 1); + assert_eq!(sole.sections[0].outer.size.height, 240.0); + assert_eq!(service.layout().sections[1].weight, 3.0); + service.set_availability(AvailabilityMap::new()).unwrap(); + let restored = allocate_fixture(&service, before.capacity.size, Direction::Ltr, &fixture_metric_policy(&service)); + assert_eq!(restored.sections, before.sections); +} + +#[test] +fn allocation_tiny_and_zero_capacities_retain_nonoverlapping_minima_and_truthful_clips() { + let mut service = fixture_service(false).unwrap(); + apply_fixture( + &mut service, + vec![ + fixture_open("fixture.log", "left", "left", Zone::Left, 0).unwrap(), + fixture_open("fixture.log", "right", "right", Zone::Right, 1).unwrap(), + fixture_open("fixture.log", "bottom", "bottom", Zone::Bottom, 2).unwrap(), + ], + ); + let before = service.inspect(); + for direction in [Direction::Ltr, Direction::Rtl] { + for scale in [1.0, 2.0] { + for size in [Size { width: 100.0, height: 90.0 }, Size { width: 0.0, height: 0.0 }] { + let host = allocate_fixture(&service, size, direction, &fixture_metric_policy(&service)); + assert_eq!(host.sections.len(), 3); + assert!(host.extent.width > size.width && host.extent.height > size.height); + for (index, card) in host.sections.iter().enumerate() { + assert!(card.outer.size.width >= 160.0 && card.outer.size.height >= 120.0); + assert_eq!((card.outer.size.width * scale) / scale, card.outer.size.width); + for other in host.sections.iter().skip(index + 1) { + assert!(!egui_rect(card.outer).intersect(egui_rect(other.outer)).is_positive()); + } + } + assert!(host.painted.iter().chain(&host.input).all(|bounds| host.capacity.contains_rect(*bounds))); + if size.width == 0.0 { + assert!(host.painted.is_empty() && host.controls.is_empty() && host.viewport.is_none()); + } + let bottom = host.sections.iter().find(|card| card.zone == Zone::Bottom).unwrap(); + assert_eq!(bottom.outer.origin.y + bottom.outer.size.height, host.capacity.origin.y + host.extent.height); + } + } + } + assert_eq!(service.inspect(), before); +} + +#[test] +fn allocation_scroll_changes_clipped_footprints_without_changing_extent_or_render_domain() { + let mut service = fixture_service(false).unwrap(); + apply_fixture( + &mut service, + vec![ + fixture_open("fixture.log", "left", "left", Zone::Left, 0).unwrap(), + fixture_open("fixture.log", "right", "right", Zone::Right, 1).unwrap(), + ], + ); + let policy = fixture_metric_policy(&service); + let before = allocate_fixture(&service, Size { width: 100.0, height: 80.0 }, Direction::Ltr, &policy); + let scrolled = + allocate_fixture(&service, before.capacity.size, Direction::Ltr, &HostGeometryPolicy { scroll: Point { x: 999.0, y: 999.0 }, ..policy }); + assert_eq!(before.extent, scrolled.extent); + assert_eq!(before.render_domain, scrolled.render_domain); + assert!(scrolled.allocation_environment.scroll.x > 0.0); + assert_ne!(before.sections[0].outer.origin, scrolled.sections[0].outer.origin); + assert!(scrolled.painted.iter().all(|rect| scrolled.capacity.contains_rect(*rect))); +} + +#[test] +fn allocation_owned_drop_candidate_is_observational_selected_only_and_commits_exact_geometry_once() { + for direction in [Direction::Ltr, Direction::Rtl] { + let mut service = fixture_service(false).unwrap(); + apply_fixture( + &mut service, + vec![ + fixture_open("fixture.log", "target", "target", Zone::Left, 0).unwrap(), + fixture_open("fixture.log", "moving", "moving", Zone::Floating, 1).unwrap(), + ], + ); + let host = allocate_fixture(&service, Size { width: 1400.0, height: 900.0 }, direction, &fixture_metric_policy(&service)); + let before = service.inspect(); + let mut interaction = HostInteraction::default(); + fixture_press(&service, &host, &mut interaction, HostPointerTarget::Header { instance: id("moving") }); + assert!(interaction.preview().is_none()); + let target = host.sections.iter().find(|card| card.instance == id("target")).unwrap(); + let at = middle(target.outer); + let preview = fixture_move(&service, &host, &mut interaction, at); + assert!(preview.rejection.is_none(), "{preview:?}"); + assert_eq!(preview.targets.len(), 1, "only the selected successful landing is paintable"); + assert!(preview.tab_marker.is_some()); + assert_eq!(service.inspect(), before, "preview does not consume IDs or alter selection"); + let shown = preview.projected.clone().unwrap(); + let release = interaction.update(&service, &fixture_scope(&service), &host, HostPointerEvent::Release { at }); + assert!(release.action.is_none(), "runtime must consume the owned candidate"); + let candidate = release.candidate.unwrap(); + assert_eq!(candidate.layout(), &shown); + assert_eq!(candidate.prepared().layout().section(§ion("target")).unwrap().active, id("moving")); + let committed = fixture_commit(&mut service, &host, candidate); + assert_eq!(committed.sections, shown.sections); + assert!(interaction.update(&service, &fixture_scope(&service), &committed, HostPointerEvent::Release { at }).candidate.is_none()); + assert_eq!(service.inspect().revision, before.revision + 1); + } +} + +#[test] +fn allocation_repeated_column_previews_do_not_drift_proposed_section_or_column_ids() { + let mut service = fixture_service(false).unwrap(); + apply_fixture( + &mut service, + vec![ + fixture_open("fixture.log", "target", "target", Zone::Right, 0).unwrap(), + fixture_open("fixture.log", "moving", "moving", Zone::Floating, 1).unwrap(), + ], + ); + let host = allocate_fixture(&service, Size { width: 1600.0, height: 900.0 }, Direction::Ltr, &fixture_metric_policy(&service)); + let before = service.inspect(); + let mut interaction = HostInteraction::default(); + let target = host.sections.iter().find(|card| card.instance == id("target")).unwrap(); + let at = Point { x: target.outer.origin.x + 2.0, y: middle(target.outer).y }; + let mut last = None; + for _ in 0..8 { + fixture_press(&service, &host, &mut interaction, HostPointerTarget::Header { instance: id("moving") }); + let preview = fixture_move(&service, &host, &mut interaction, at); + assert!(preview.rejection.is_none(), "{preview:?}"); + if let Some(old) = &last { + assert_eq!(old, &preview); + } + last = Some(preview); + interaction.cancel(); + assert_eq!(service.inspect(), before); + } + fixture_press(&service, &host, &mut interaction, HostPointerTarget::Header { instance: id("moving") }); + let preview = fixture_move(&service, &host, &mut interaction, at); + assert_eq!(last, Some(preview)); + let release = interaction.update(&service, &fixture_scope(&service), &host, HostPointerEvent::Release { at }); + let after = fixture_commit(&mut service, &host, release.candidate.unwrap()); + let moved = after.sections.iter().find(|card| card.instance == id("moving")).unwrap(); + assert!(moved.outer.origin.x < target.outer.origin.x, "physical left of a right dock stays physical left"); +} + +#[test] +fn allocation_invisible_physical_edges_and_measured_tab_halves_preserve_rtl_and_detached_indices() { + for zone in [Zone::Left, Zone::Right] { + for direction in [Direction::Ltr, Direction::Rtl] { + let mut service = fixture_service(false).unwrap(); + apply_fixture( + &mut service, + vec![ + fixture_open("fixture.log", "first", "group", zone, 0).unwrap(), + Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("moving"), + destination: Some(Destination::JoinTab { section: section("group"), index: 1 }), + }, + Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("last"), + destination: Some(Destination::JoinTab { section: section("group"), index: 2 }), + }, + ], + ); + let column = service.layout().section(§ion("group")).unwrap().column.clone().unwrap(); + apply_fixture(&mut service, vec![Mutation::SetColumnWidth { column, width: 410.0 }]); + let mut policy = fixture_metric_policy(&service); + policy.measure = Some(std::sync::Arc::new(AllocationMetricsFixture { + revision: 7, + policies: Default::default(), + width: None, + narrow_height: 280.0, + wide_height: 280.0, + })); + let host = allocate_fixture(&service, Size { width: 1400.0, height: 900.0 }, direction, &policy); + let card = &host.sections[0]; + let targets = host_drop_targets(&service, &host, &id("moving")).unwrap(); + let strip = card.tab_strip.unwrap(); + assert!( + targets + .iter() + .filter(|target| target.priority == 2) + .all(|target| target.bounds.origin.y == strip.origin.y + 9.0 && target.bounds.size.height == (strip.size.height - 18.0).max(1.0)) + ); + assert!( + targets + .iter() + .any(|target| target.stable_key == "tab:group:1" + && target.destination == Destination::JoinTab { section: section("group"), index: 1 }), + "keep the source tab's own insertion slot after detachment" + ); + let physical_left = direction.edge(zone).unwrap() == PhysicalEdge::Left; + for left in [true, false] { + let placement = if left == physical_left { RelativePlacement::BeforeColumn } else { RelativePlacement::AfterColumn }; + let target = targets.iter().find(|target| target.id == HostDropTargetId::Relative { section: section("group"), placement }).unwrap(); + let inward = 64.0_f32.min(card.outer.size.width * 0.28); + let outward = if placement == RelativePlacement::AfterColumn { 64.0 } else { 18.0 }; + assert_eq!(target.bounds.size.width, inward + outward); + assert_eq!( + target.bounds.origin.x, + if left { card.outer.origin.x - outward } else { card.outer.origin.x + card.outer.size.width - inward } + ); + } + let before_last = + targets.iter().find(|target| target.id == HostDropTargetId::Tab { section: section("group"), before: Some(id("last")) }).unwrap(); + assert_eq!(before_last.destination, Destination::JoinTab { section: section("group"), index: 1 }, "moved tab removed before indexing"); + let mut interaction = HostInteraction::default(); + fixture_press(&service, &host, &mut interaction, HostPointerTarget::Tab { instance: id("moving") }); + let preview = fixture_move(&service, &host, &mut interaction, middle(before_last.bounds)); + assert_eq!(preview.target, Some(before_last.id.clone()), "measured tabs arbitrate ahead of top/side edges"); + assert_eq!(preview.targets.len(), 1); + interaction.cancel(); + fixture_press(&service, &host, &mut interaction, HostPointerTarget::Tab { instance: id("moving") }); + let corner = Point { + x: if physical_left { card.outer.origin.x + 45.0 } else { card.outer.origin.x + card.outer.size.width - 45.0 }, + y: card.outer.origin.y + 45.0, + }; + // Both edge distances are 45 and both region areas are 22960: + // column:group:* must sort before stack:group:above in LTR/RTL. + assert_eq!(card.outer.size, Size { width: 410.0, height: 280.0 }); + let preview = fixture_move(&service, &host, &mut interaction, corner); + assert!(preview.rejection.is_none(), "{preview:?}"); + assert_eq!(preview.target, Some(HostDropTargetId::Relative { section: section("group"), placement: RelativePlacement::BeforeColumn })); + interaction.cancel(); + fixture_press(&service, &host, &mut interaction, HostPointerTarget::Tab { instance: id("moving") }); + let inner_corner = Point { x: if physical_left { right(card.outer) - 45.0 } else { card.outer.origin.x + 45.0 }, y: corner.y }; + assert_eq!( + fixture_move(&service, &host, &mut interaction, inner_corner).target, + Some(HostDropTargetId::Relative { section: section("group"), placement: RelativePlacement::AfterColumn }), + "the wider centre-facing strip keeps the original equal-distance/area tie" + ); + } + } +} + +#[test] +fn allocation_shared_shell_gap_controls_allocation_and_keeps_compact_sashes_and_free_origins() { + for mode in [crate::shell::LayoutMode::Docked, crate::shell::LayoutMode::Floating] { + for direction in [Direction::Ltr, Direction::Rtl] { + for zone in [Zone::Left, Zone::Right] { + let gap = crate::ui_kit::Container::for_layout(mode, crate::ui_kit::Surface::Panel).gap(); + let mut service = fixture_service(false).unwrap(); + apply_fixture( + &mut service, + vec![ + fixture_open("fixture.log", "a", "a", zone, 0).unwrap(), + fixture_open("fixture.log", "b", "b", zone, 1).unwrap(), + fixture_open("fixture.log", "c", "c", zone, 2).unwrap(), + ], + ); + apply_fixture( + &mut service, + vec![ + Mutation::Move { + instance: id("c"), + destination: Destination::Relative { + section: section("a"), + placement: RelativePlacement::AfterColumn, + new_section: section("c"), + new_column: Some(ColumnId::new("inner").unwrap()), + size: Size { width: 280.0, height: 240.0 }, + }, + }, + Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("free"), + destination: Some(Destination::NewSection { + section: section("free"), + index: 3, + location: SectionLocation::Floating { origin: Point { x: 500.0, y: 300.0 } }, + size: Size { width: 280.0, height: 240.0 }, + }), + }, + ], + ); + let before = service.inspect(); + let domain = LogicalRect { origin: Point { x: 0.0, y: 30.0 }, size: Size { width: 1400.0, height: 900.0 } }; + let capacity = LogicalRect { + origin: Point { x: gap, y: domain.origin.y + gap }, + size: Size { width: domain.size.width - 2.0 * gap, height: domain.size.height - 2.0 * gap }, + }; + let metrics = HostMetrics { gap, ..HostMetrics::default() }; + let host = + resolve_host_layout_in_domain(&service, domain, capacity, &[], direction, metrics, &fixture_metric_policy(&service)).unwrap(); + let card = |name| host.sections.iter().find(|card| card.section == section(name)).unwrap().outer; + let (a, b, c) = (card("a"), card("b"), card("c")); + assert_eq!(b.origin.y - (a.origin.y + a.size.height), gap); + let (left, right) = if a.origin.x < c.origin.x { (a, c) } else { (c, a) }; + assert_eq!(right.origin.x - (left.origin.x + left.size.width), gap); + assert_eq!(host.allocation_environment.gap, gap); + assert_eq!(host.metrics.sash_width, HostMetrics::default().sash_width); + assert_eq!(card("free").origin, Point { x: 500.0, y: 300.0 }); + let sash = host.sashes.first().unwrap(); + assert!(sash.bounds.size.height > 0.0, "joined compact cards retain a real resize control"); + assert_eq!(host.hit_test(middle(sash.bounds)), Some(HostPointerTarget::Sash { first: section("a"), second: section("b") })); + if gap > 0.0 { + let gutter = LogicalRect { + origin: Point { x: left.origin.x + left.size.width + 1.0, y: capacity.origin.y + 80.0 }, + size: Size { width: gap - 2.0, height: 4.0 }, + }; + assert!(host.usable.contains_rect(gutter)); + assert!(!host.consumes_pointer(middle(gutter))); + } + assert_eq!(host.viewport, Some(domain)); + assert_eq!(service.inspect(), before, "shell fitting never rewrites free placement intent"); + } + } + } +} + +#[test] +fn allocation_workspace_edge_gutters_admit_owned_drops_while_chrome_and_hidden_cards_do_not() { + for direction in [Direction::Ltr, Direction::Rtl] { + for zone in [Zone::Left, Zone::Right] { + let mut service = fixture_service(false).unwrap(); + apply_fixture( + &mut service, + vec![ + fixture_open("fixture.log", "target", "target", zone, 0).unwrap(), + fixture_open("fixture.log", "moving", "moving", Zone::Floating, 1).unwrap(), + ], + ); + let domain = LogicalRect { origin: Point { x: 10.0, y: 20.0 }, size: Size { width: 1400.0, height: 900.0 } }; + let capacity = LogicalRect { origin: Point { x: 17.0, y: 100.0 }, size: Size { width: 1386.0, height: 813.0 } }; + let chrome = [ + LogicalRect { origin: domain.origin, size: Size { width: 1400.0, height: 73.0 } }, + LogicalRect { origin: Point { x: 10.0, y: 900.0 }, size: Size { width: 1400.0, height: 20.0 } }, + ]; + let host = resolve_host_layout_in_domain( + &service, + domain, + capacity, + &chrome, + direction, + HostMetrics { gap: 7.0, ..HostMetrics::default() }, + &fixture_metric_policy(&service), + ) + .unwrap(); + let at = Point { x: if direction.edge(zone).unwrap() == PhysicalEdge::Left { 11.0 } else { 1409.0 }, y: 650.0 }; + assert!(!capacity.contains(at)); + assert!(!host.consumes_pointer(at), "workspace bands remain invisible data"); + let before = service.inspect(); + let mut interaction = HostInteraction::default(); + fixture_press(&service, &host, &mut interaction, HostPointerTarget::Header { instance: id("moving") }); + let preview = fixture_move(&service, &host, &mut interaction, at); + assert!(preview.rejection.is_none(), "{preview:?}"); + assert_eq!(preview.target, Some(HostDropTargetId::Dock { zone, before: None })); + let released = interaction.update(&service, &fixture_scope(&service), &host, HostPointerEvent::Release { at }); + assert_eq!(released.candidate.unwrap().layout(), preview.projected.as_ref().unwrap()); + fixture_press(&service, &host, &mut interaction, HostPointerTarget::Header { instance: id("moving") }); + let blocked = fixture_move(&service, &host, &mut interaction, Point { x: 700.0, y: 910.0 }); + assert!(blocked.action.is_none() && blocked.projected.is_none()); + assert!( + interaction + .update(&service, &fixture_scope(&service), &host, HostPointerEvent::Release { at: Point { x: 700.0, y: 910.0 } }) + .candidate + .is_none() + ); + assert_eq!(service.inspect(), before); + + // Side bands stop above the final nine points, leaving both bottom + // corners to Bottom even when the opposite side is empty. + let no_status = + resolve_host_layout_in_domain(&service, domain, capacity, &chrome[..1], direction, host.metrics, &fixture_metric_policy(&service)) + .unwrap(); + for x in [domain.origin.x + 1.0, right(domain) - 1.0] { + fixture_press(&service, &no_status, &mut interaction, HostPointerTarget::Header { instance: id("moving") }); + let preview = fixture_move(&service, &no_status, &mut interaction, Point { x, y: bottom(domain) - 1.0 }); + assert!(preview.rejection.is_none(), "{preview:?}"); + assert_eq!(preview.target, Some(HostDropTargetId::Dock { zone: Zone::Bottom, before: None })); + interaction.cancel(); + } + + // An overflowed card above the visible capacity must not publish + // tab/relative targets merely because it lies in the render domain. + apply_fixture(&mut service, vec![fixture_open("fixture.log", "tail", "tail", zone, 2).unwrap()]); + let mut small_capacity = capacity; + small_capacity.size.height = 100.0; + let mut policy = fixture_metric_policy(&service); + policy.scroll.y = 147.0; + let scrolled = resolve_host_layout_in_domain(&service, domain, small_capacity, &chrome, direction, host.metrics, &policy).unwrap(); + let targets = host_drop_targets(&service, &scrolled, &id("moving")).unwrap(); + assert!(intersect_rect(scrolled.sections.iter().find(|card| card.section == section("target")).unwrap().outer, small_capacity).is_none()); + assert!(!targets.iter().any(|target| matches!(&target.id, HostDropTargetId::Relative { section: id, .. } | HostDropTargetId::Tab { section: id, .. } if *id == section("target")))); + } + } +} + +#[test] +fn allocation_centre_column_reach_uses_presented_receivers_after_source_removal() { + for direction in [Direction::Ltr, Direction::Rtl] { + for zone in [Zone::Left, Zone::Right] { + for case in ["present", "closed", "unavailable", "offscreen", "vacating", "retained-tab", "unavailable-tab", "retained-card"] { + let mut service = allocation_service(|spec| { + spec.max_size.height = 240.0; + }); + apply_fixture( + &mut service, + vec![ + fixture_open("fixture.log", "outer", "outer", zone, 0).unwrap(), + fixture_open("fixture.log", "tail", "tail", zone, 1).unwrap(), + fixture_open("fixture.log", "inner", "inner", zone, 2).unwrap(), + fixture_open("fixture.log", "moving", "moving", Zone::Floating, 3).unwrap(), + ], + ); + apply_fixture( + &mut service, + vec![ + Mutation::Move { + instance: id("inner"), + destination: Destination::Relative { + section: section("outer"), + placement: RelativePlacement::AfterColumn, + new_section: section("inner"), + new_column: Some(ColumnId::new("inner-column").unwrap()), + size: Size { width: 280.0, height: 240.0 }, + }, + }, + Mutation::Collapse { section: section("inner"), collapsed: true }, + Mutation::SetFloatingRect { + section: section("moving"), + origin: Point { x: 700.0, y: 600.0 }, + size: Size { width: 280.0, height: 240.0 }, + }, + ], + ); + match case { + "closed" => apply_fixture(&mut service, vec![Mutation::Close { instance: id("inner") }]), + "unavailable" => { + service.set_availability([(id("inner"), Availability::Unavailable { reason: "hidden fixture".into() })].into()).unwrap() + } + "retained-tab" | "unavailable-tab" => apply_fixture( + &mut service, + vec![Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("peer"), + destination: Some(Destination::JoinTab { section: section("inner"), index: 1 }), + }], + ), + "retained-card" => apply_fixture( + &mut service, + vec![Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("peer"), + destination: Some(Destination::Relative { + section: section("inner"), + placement: RelativePlacement::Below, + new_section: section("peer"), + new_column: None, + size: Size { width: 280.0, height: 240.0 }, + }), + }], + ), + _ => {} + } + if case == "unavailable-tab" { + service.set_availability([(id("peer"), Availability::Unavailable { reason: "hidden retained tab".into() })].into()).unwrap(); + } + let mut policy = fixture_metric_policy(&service); + if case == "offscreen" { + policy.scroll.y = 260.0; + } + let host = + allocate_fixture(&service, Size { width: 1600.0, height: if case == "offscreen" { 200.0 } else { 900.0 } }, direction, &policy); + if case == "closed" { + assert!( + service.layout().columns.iter().any(|column| column.id == ColumnId::new("inner-column").unwrap()), + "closed memory retains a dormant column" + ); + assert!(!host.sections.iter().any(|card| card.section == section("inner"))); + } + let moving = + if matches!(case, "vacating" | "retained-tab" | "unavailable-tab" | "retained-card") { id("inner") } else { id("moving") }; + let targets = host_drop_targets(&service, &host, &moving).unwrap(); + let tail = host.sections.iter().find(|card| card.section == section("tail")).unwrap(); + let edge = targets + .iter() + .find(|entry| entry.id == HostDropTargetId::Relative { section: section("tail"), placement: RelativePlacement::AfterColumn }) + .unwrap(); + let outward = if matches!(case, "closed" | "unavailable" | "offscreen" | "vacating" | "unavailable-tab") { 64.0 } else { 18.0 }; + assert_eq!(edge.bounds.size.width, 64.0_f32.min(tail.outer.size.width * 0.28) + outward, "{direction:?}/{zone:?}/{case}"); + let before = targets + .iter() + .find(|entry| entry.id == HostDropTargetId::Relative { section: section("tail"), placement: RelativePlacement::BeforeColumn }) + .unwrap(); + assert_eq!(before.bounds.size.width, 64.0_f32.min(tail.outer.size.width * 0.28) + 18.0); + if case == "offscreen" { + let inner = host.sections.iter().find(|card| card.section == section("inner")).unwrap(); + assert!(intersect_rect(inner.outer, host.capacity).is_none()); + assert!( + !targets + .iter() + .any(|entry| matches!(&entry.id, HostDropTargetId::Relative { section: target, .. } if *target == section("inner"))) + ); + } + if matches!(case, "retained-tab" | "retained-card") { + let receiver = if case == "retained-tab" { "inner" } else { "peer" }; + let card = host.sections.iter().find(|card| card.section == section(receiver)).unwrap(); + let edge = targets + .iter() + .find(|entry| { + entry.id == HostDropTargetId::Relative { section: section(receiver), placement: RelativePlacement::AfterColumn } + }) + .unwrap(); + assert_eq!(edge.bounds.size.width, 64.0_f32.min(card.outer.size.width * 0.28) + 64.0); + } + } + } + } +} + +#[test] +fn allocation_added_column_strip_stops_at_actual_paint_and_chrome_without_shrinking_old_band() { + for direction in [Direction::Ltr, Direction::Rtl] { + for zone in [Zone::Left, Zone::Right] { + for (case, distance, outward) in [ + ("floating", 32.0, 32.0), + ("collapsed", 40.0, 40.0), + ("chrome", 48.0, 48.0), + ("overlapping", 12.0, 18.0), + ("distant", 80.0, 64.0), + ("offscreen", 40.0, 64.0), + ("other-column", 40.0, 40.0), + ] { + let mut service = fixture_service(false).unwrap(); + apply_fixture( + &mut service, + vec![ + fixture_open("fixture.log", "target", "target", zone, 0).unwrap(), + fixture_open("fixture.log", "moving", "moving", Zone::Bottom, 1).unwrap(), + ], + ); + let size = Size { width: if case == "other-column" { 640.0 } else { 1400.0 }, height: 900.0 }; + let base = allocate_fixture(&service, size, direction, &fixture_metric_policy(&service)); + let card = base.sections.iter().find(|card| card.section == section("target")).unwrap(); + let physical_left = direction.edge(zone).unwrap() == PhysicalEdge::Left; + let at = if physical_left { right(card.outer) } else { card.outer.origin.x }; + let obstacle = LogicalRect { + origin: Point { + x: if physical_left { at + distance } else { at - distance - 160.0 }, + y: if case == "offscreen" { 1000.0 } else { card.outer.origin.y + 80.0 }, + }, + size: Size { width: 160.0, height: 120.0 }, + }; + let mut chrome = Vec::new(); + if matches!(case, "chrome" | "offscreen") { + chrome.push(obstacle); + } else if case == "other-column" { + let other = if zone == Zone::Left { Zone::Right } else { Zone::Left }; + apply_fixture(&mut service, vec![fixture_open("fixture.log", "obstacle", "obstacle", other, 2).unwrap()]); + let column = service.layout().section(§ion("obstacle")).unwrap().column.clone().unwrap(); + apply_fixture(&mut service, vec![Mutation::SetColumnWidth { column, width: 320.0 }]); + } else { + apply_fixture( + &mut service, + vec![Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("obstacle"), + destination: Some(Destination::NewSection { + section: section("obstacle"), + index: 2, + location: SectionLocation::Floating { origin: obstacle.origin }, + size: obstacle.size, + }), + }], + ); + if case == "collapsed" { + apply_fixture(&mut service, vec![Mutation::Collapse { section: section("obstacle"), collapsed: true }]); + } + } + let host = resolve_host_layout_in_domain( + &service, + base.render_domain, + base.capacity, + &chrome, + direction, + base.metrics, + &fixture_metric_policy(&service), + ) + .unwrap(); + let targets = host_drop_targets(&service, &host, &id("moving")).unwrap(); + let target = targets + .iter() + .find(|entry| entry.id == HostDropTargetId::Relative { section: section("target"), placement: RelativePlacement::AfterColumn }) + .unwrap(); + assert_eq!(target.bounds.size.width, 64.0_f32.min(card.outer.size.width * 0.28) + outward, "{direction:?}/{zone:?}/{case}"); + assert_eq!(target.bounds.origin.x, if physical_left { at - 64.0_f32.min(card.outer.size.width * 0.28) } else { at - outward }); + if matches!(case, "floating" | "collapsed" | "chrome") { + let mut interaction = HostInteraction::default(); + fixture_press(&service, &host, &mut interaction, HostPointerTarget::Header { instance: id("moving") }); + let point = |distance: f32| Point { x: at + if physical_left { distance } else { -distance }, y: obstacle.origin.y + 1.0 }; + assert_eq!(fixture_move(&service, &host, &mut interaction, point(outward - 1.0)).target, Some(target.id.clone())); + assert_ne!( + fixture_move(&service, &host, &mut interaction, point(outward)).target, + Some(target.id.clone()), + "actual obstacle boundary belongs to its paint" + ); + assert_ne!(fixture_move(&service, &host, &mut interaction, point(outward + 1.0)).target, Some(target.id.clone())); + } + } + } + } +} + +#[test] +fn allocation_non_move_controls_never_expose_drag_title_feedback() { + let mut service = fixture_service(false).unwrap(); + apply_fixture( + &mut service, + vec![fixture_open("fixture.log", "one", "one", Zone::Left, 0).unwrap(), fixture_open("fixture.log", "two", "two", Zone::Left, 1).unwrap()], + ); + let host = allocate_fixture(&service, Size { width: 1400.0, height: 900.0 }, Direction::Ltr, &fixture_metric_policy(&service)); + let before = service.inspect(); + let mut interaction = HostInteraction::default(); + let (mut resize, mut pair) = (false, false); + for control in &host.controls { + if matches!(control.target, HostPointerTarget::Header { .. } | HostPointerTarget::Tab { .. } | HostPointerTarget::Rail { .. }) { + continue; + } + resize |= matches!(control.target, HostPointerTarget::Resize { .. }); + pair |= matches!(control.target, HostPointerTarget::Sash { .. }); + let start = fixture_press(&service, &host, &mut interaction, control.target.clone()); + interaction.update(&service, &fixture_scope(&service), &host, HostPointerEvent::Move { at: Point { x: start.x + 8.0, y: start.y + 8.0 } }); + assert!(interaction.move_source().is_none() && interaction.move_position().is_none(), "{:?}", control.target); + interaction.cancel(); + } + assert!(resize && pair, "exercise both resize capture kinds as well as ordinary controls"); + assert_eq!(service.inspect(), before); +} + +#[test] +fn allocation_drag_threshold_scales_once_and_invalid_or_outside_release_discards_the_shown_candidate() { + for scale in [1.0, 2.0] { + let mut service = fixture_service(false).unwrap(); + apply_fixture( + &mut service, + vec![ + fixture_open("fixture.log", "one", "one", Zone::Left, 0).unwrap(), + fixture_open("fixture.log", "moving", "moving", Zone::Floating, 1).unwrap(), + ], + ); + let host = allocate_fixture(&service, Size { width: 1400.0, height: 900.0 }, Direction::Ltr, &fixture_metric_policy(&service)); + let before = service.inspect(); + let mut interaction = HostInteraction::default(); + let start = fixture_press(&service, &host, &mut interaction, HostPointerTarget::Header { instance: id("moving") }); + let logical = |physical_dx: f32| Point { x: start.x + physical_dx / scale, y: start.y }; + assert!(interaction.move_source().is_none() && interaction.move_position().is_none()); + assert!( + interaction.update(&service, &fixture_scope(&service), &host, HostPointerEvent::Move { at: logical(5.99 * scale) }).preview.is_none() + ); + assert!(interaction.move_source().is_none() && interaction.move_position().is_none()); + assert!(interaction.update(&service, &fixture_scope(&service), &host, HostPointerEvent::Move { at: logical(6.0 * scale) }).preview.is_some()); + assert_eq!(interaction.move_source(), Some(&id("moving"))); + assert_eq!(interaction.move_position(), Some(logical(6.0 * scale))); + let at = middle(host.sections.iter().find(|card| card.instance == id("one")).unwrap().outer); + for release_at in [Point { x: 1200.0, y: 850.0 }, Point { x: -1.0, y: 300.0 }, Point { x: f32::NAN, y: 300.0 }] { + fixture_press(&service, &host, &mut interaction, HostPointerTarget::Header { instance: id("moving") }); + let preview = fixture_move(&service, &host, &mut interaction, at); + assert!(preview.rejection.is_none()); + let release = interaction.update(&service, &fixture_scope(&service), &host, HostPointerEvent::Release { at: release_at }); + assert!(release.candidate.is_none()); + assert!(!interaction.is_captured() && interaction.preview().is_none()); + assert!(interaction.move_source().is_none() && interaction.move_position().is_none()); + assert_eq!(service.inspect(), before, "release must re-hit-test even without a final Move"); + } + } +} + +#[test] +fn allocation_transient_leave_discards_candidates_but_revalidates_capture_and_hostile_moves() { + for case in ["leave-release", "negative", "positive", "nan", "hostile", "stale"] { + let mut service = fixture_service(false).unwrap(); + apply_fixture( + &mut service, + vec![ + fixture_open("fixture.log", "target", "target", Zone::Left, 0).unwrap(), + fixture_open("fixture.log", "moving", "moving", Zone::Floating, 1).unwrap(), + ], + ); + let host = allocate_fixture(&service, Size { width: 1400.0, height: 900.0 }, Direction::Ltr, &fixture_metric_policy(&service)); + let at = middle(host.sections.iter().find(|card| card.instance == id("target")).unwrap().outer); + let mut interaction = HostInteraction::default(); + fixture_press(&service, &host, &mut interaction, HostPointerTarget::Header { instance: id("moving") }); + assert!(fixture_move(&service, &host, &mut interaction, at).rejection.is_none()); + let event = match case { + "negative" => HostPointerEvent::Move { at: Point { x: -20.0, y: -20.0 } }, + "positive" => HostPointerEvent::Move { at: Point { x: 1500.0, y: 1000.0 } }, + "nan" => HostPointerEvent::Move { at: Point { x: f32::NAN, y: at.y } }, + "hostile" => HostPointerEvent::Move { at: Point { x: MAX_LOGICAL + 1.0, y: at.y } }, + _ => HostPointerEvent::Leave, + }; + let result = interaction.update(&service, &fixture_scope(&service), &host, event); + assert!(result.preview.is_none() && result.candidate.is_none()); + assert_eq!(interaction.is_captured(), !matches!(case, "nan" | "hostile")); + assert_eq!(interaction.move_source(), (!matches!(case, "nan" | "hostile")).then(|| id("moving")).as_ref()); + assert!(interaction.move_position().is_none()); + if case == "stale" { + apply_fixture(&mut service, vec![Mutation::Focus { instance: id("target") }]); + let result = interaction.update(&service, &fixture_scope(&service), &host, HostPointerEvent::Reconcile); + assert!(result.rejection.is_some()); + assert!(!interaction.is_captured()); + assert!(interaction.move_source().is_none() && interaction.move_position().is_none()); + } else if matches!(case, "negative" | "positive") { + let preview = fixture_move(&service, &host, &mut interaction, at); + assert!(preview.rejection.is_none()); + assert_eq!(interaction.move_source(), Some(&id("moving"))); + assert_eq!(interaction.move_position(), Some(at)); + let release = interaction.update(&service, &fixture_scope(&service), &host, HostPointerEvent::Release { at }); + assert_eq!(release.candidate.as_ref().unwrap().layout(), preview.projected.as_ref().unwrap()); + } else { + let before = service.inspect(); + assert!(interaction.update(&service, &fixture_scope(&service), &host, HostPointerEvent::Release { at }).candidate.is_none()); + assert_eq!(service.inspect(), before, "a suspended candidate cannot commit on reentry Release alone"); + } + } + // A fast first sample outside still crosses the drag threshold, even when + // the pointer returns to its press position before another inside sample. + for outside in [Point { x: -20.0, y: -20.0 }, Point { x: 1500.0, y: 1000.0 }] { + let mut service = fixture_service(false).unwrap(); + apply_fixture(&mut service, vec![fixture_open("fixture.log", "moving", "moving", Zone::Left, 0).unwrap()]); + let host = allocate_fixture(&service, Size { width: 1400.0, height: 900.0 }, Direction::Ltr, &fixture_metric_policy(&service)); + let mut interaction = HostInteraction::default(); + let start = fixture_press(&service, &host, &mut interaction, HostPointerTarget::Header { instance: id("moving") }); + assert!(interaction.update(&service, &fixture_scope(&service), &host, HostPointerEvent::Move { at: outside }).preview.is_none()); + assert_eq!(interaction.move_source(), Some(&id("moving"))); + assert!(interaction.move_position().is_none()); + assert!(interaction.update(&service, &fixture_scope(&service), &host, HostPointerEvent::Move { at: start }).preview.is_some()); + } + for leave in [false, true] { + let mut service = fixture_service(false).unwrap(); + apply_fixture( + &mut service, + vec![ + fixture_open("fixture.log", "target", "target", Zone::Left, 0).unwrap(), + Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("tab"), + destination: Some(Destination::JoinTab { section: section("target"), index: 1 }), + }, + ], + ); + assert_eq!(service.layout().section(§ion("target")).unwrap().active, id("target")); + let host = allocate_fixture(&service, Size { width: 1400.0, height: 900.0 }, Direction::Ltr, &fixture_metric_policy(&service)); + let mut interaction = HostInteraction::default(); + let start = fixture_press(&service, &host, &mut interaction, HostPointerTarget::Tab { instance: id("tab") }); + if leave { + interaction.update(&service, &fixture_scope(&service), &host, HostPointerEvent::Leave); + interaction.update(&service, &fixture_scope(&service), &host, HostPointerEvent::Move { at: start }); + } + let released = interaction.update(&service, &fixture_scope(&service), &host, HostPointerEvent::Release { at: start }); + assert_eq!(released.candidate.is_some(), !leave, "an interrupted press must not become tab-click activation"); + } +} + +#[test] +fn allocation_below_extension_stops_at_actual_presented_chrome_and_ignores_offscreen_bounds() { + for direction in [Direction::Ltr, Direction::Rtl] { + for zone in [Zone::Left, Zone::Right] { + let mut service = fixture_service(false).unwrap(); + apply_fixture( + &mut service, + vec![ + fixture_open("fixture.log", "target", "target", zone, 0).unwrap(), + Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("moving"), + destination: Some(Destination::NewSection { + section: section("moving"), + index: 1, + location: SectionLocation::Floating { origin: Point { x: 600.0, y: 60.0 } }, + size: Size { width: 280.0, height: 240.0 }, + }), + }, + ], + ); + let base = allocate_fixture(&service, Size { width: 1400.0, height: 900.0 }, direction, &fixture_metric_policy(&service)); + let card = base.sections.iter().find(|card| card.section == section("target")).unwrap(); + let start = card.outer.origin.y + card.outer.size.height; + for (x, y, expected) in [ + (card.outer.origin.x, start + 160.0, start + 160.0), + (card.outer.origin.x, start - 20.0, start), + (card.outer.origin.x, 1000.0, 930.0), + (600.0, start + 160.0, 930.0), + ] { + let chrome = LogicalRect { origin: Point { x, y }, size: Size { width: 80.0, height: 40.0 } }; + let host = resolve_host_layout_in_domain( + &service, + base.render_domain, + base.capacity, + &[chrome], + direction, + base.metrics, + &base.geometry_policy, + ) + .unwrap(); + let targets = host_drop_targets(&service, &host, &id("moving")).unwrap(); + let below = targets + .iter() + .find(|target| target.id == HostDropTargetId::Relative { section: section("target"), placement: RelativePlacement::Below }) + .unwrap(); + assert_eq!(below.bounds.origin.y + below.bounds.size.height, expected); + let above = targets + .iter() + .find(|target| target.id == HostDropTargetId::Relative { section: section("target"), placement: RelativePlacement::Above }) + .unwrap(); + assert_eq!(above.bounds.size.height, 56.0_f32.min(card.outer.size.height * 0.25)); + } + } + } +} + +#[test] +fn allocation_below_extension_respects_presented_stack_and_collapsed_headers_but_skips_unavailable_members() { + for direction in [Direction::Ltr, Direction::Rtl] { + for zone in [Zone::Left, Zone::Right] { + for state in ["expanded", "collapsed", "unavailable"] { + let mut service = allocation_service(|spec| { + spec.max_size.height = 240.0; + }); + apply_fixture( + &mut service, + vec![ + fixture_open("fixture.log", "target", "target", zone, 0).unwrap(), + fixture_open("fixture.log", "obstacle", "obstacle", zone, 1).unwrap(), + Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("moving"), + destination: Some(Destination::NewSection { + section: section("moving"), + index: 2, + location: SectionLocation::Floating { origin: Point { x: 600.0, y: 60.0 } }, + size: Size { width: 280.0, height: 240.0 }, + }), + }, + ], + ); + if state == "collapsed" { + apply_fixture(&mut service, vec![Mutation::Collapse { section: section("obstacle"), collapsed: true }]); + } else if state == "unavailable" { + service.set_availability([(id("obstacle"), Availability::Unavailable { reason: "fixture hidden".into() })].into()).unwrap(); + } + let host = allocate_fixture(&service, Size { width: 1400.0, height: 900.0 }, direction, &fixture_metric_policy(&service)); + let targets = host_drop_targets(&service, &host, &id("moving")).unwrap(); + let below = targets + .iter() + .find(|entry| entry.id == HostDropTargetId::Relative { section: section("target"), placement: RelativePlacement::Below }) + .unwrap(); + let end = below.bounds.origin.y + below.bounds.size.height; + if state == "unavailable" { + assert!(!host.sections.iter().any(|card| card.section == section("obstacle"))); + assert_eq!(end, host.capacity.origin.y + host.capacity.size.height); + } else { + let obstacle = host.sections.iter().find(|card| card.section == section("obstacle")).unwrap(); + assert!(end <= obstacle.outer.origin.y, "a presented header/body or its sash bounds the clear corridor"); + } + } + } + } +} + +#[test] +fn allocation_capture_cancels_on_escape_cancel_scope_revision_availability_and_every_environment_change() { + for case in 0..13 { + let mut service = fixture_service(false).unwrap(); + apply_fixture( + &mut service, + vec![ + fixture_open("fixture.log", "target", "target", Zone::Left, 0).unwrap(), + fixture_open("fixture.log", "moving", "moving", Zone::Floating, 1).unwrap(), + ], + ); + let host = allocate_fixture(&service, Size { width: 1400.0, height: 900.0 }, Direction::Ltr, &fixture_metric_policy(&service)); + let mut interaction = HostInteraction::default(); + fixture_press(&service, &host, &mut interaction, HostPointerTarget::Header { instance: id("moving") }); + let at = middle(host.sections.iter().find(|card| card.instance == id("target")).unwrap().outer); + assert!(fixture_move(&service, &host, &mut interaction, at).rejection.is_none()); + let mut scope = fixture_scope(&service); + let mut changed = host.clone(); + let event = match case { + 0 => HostPointerEvent::Escape, + 1 => HostPointerEvent::Cancel, // blur, hidden surface and modal adapters use this same route + 2 => { + scope.viewport = ViewportId::new("other.viewport").unwrap(); + HostPointerEvent::Reconcile + } + 3 => { + apply_fixture(&mut service, vec![Mutation::Focus { instance: id("target") }]); + HostPointerEvent::Reconcile + } + 4 => { + service.set_availability([(id("moving"), Availability::Unavailable { reason: "unavailable".into() })].into()).unwrap(); + HostPointerEvent::Reconcile + } + 5 => { + changed.geometry_policy.content_revision += 1; + changed.allocation_environment.content_revision += 1; + HostPointerEvent::Reconcile + } + 6 => { + changed.metrics.header_height += 1.0; + HostPointerEvent::Reconcile + } + 7 => { + changed.direction = Direction::Rtl; + HostPointerEvent::Reconcile + } + 8 => { + changed.capacity.size.width -= 1.0; + HostPointerEvent::Reconcile + } + 9 => { + changed.geometry_policy.scroll.x = 10.0; + HostPointerEvent::Reconcile + } + 10 => HostPointerEvent::OutsidePress { at, inside_owned_overlay: false }, + 11 => { + scope.document = Some(DocumentId::new("other.document").unwrap()); + HostPointerEvent::Reconcile + } + _ => { + changed.metrics.gap += 1.0; + changed.allocation_environment.gap += 1.0; + HostPointerEvent::Reconcile + } + }; + let current = service.inspect(); + let result = interaction.update(&service, &scope, &changed, event); + assert!(result.candidate.is_none(), "case {case}"); + assert!(!interaction.is_captured() && interaction.preview().is_none(), "case {case}"); + assert!(interaction.move_source().is_none() && interaction.move_position().is_none(), "case {case}"); + assert_eq!(service.inspect(), current); + assert!(interaction.update(&service, &fixture_scope(&service), &host, HostPointerEvent::Release { at }).candidate.is_none()); + } +} + +#[test] +fn allocation_programmatic_admission_refuses_neutral_overflow_but_allows_strict_improvement_and_exemptions() { + let mut service = fixture_service(false).unwrap(); + apply_fixture( + &mut service, + vec![fixture_open("fixture.log", "one", "one", Zone::Left, 0).unwrap(), fixture_open("fixture.log", "two", "two", Zone::Right, 1).unwrap()], + ); + let host = allocate_fixture(&service, Size { width: 100.0, height: 90.0 }, Direction::Ltr, &fixture_metric_policy(&service)); + let scope = fixture_scope(&service); + let before = service.inspect(); + assert_eq!( + prepare_host_layout( + &service, + &scope, + &host, + transaction(vec![Mutation::SetSize { section: section("one"), size: service.layout().sections[0].size }]) + ) + .unwrap_err() + .rule, + Rule::NoSpace + ); + for mutation in [ + Mutation::Close { instance: id("two") }, + Mutation::Collapse { section: section("one"), collapsed: true }, + Mutation::Collapse { section: section("one"), collapsed: false }, + Mutation::Focus { instance: id("one") }, + ] { + assert!(prepare_host_layout(&service, &scope, &host, transaction(vec![mutation])).is_ok()); + } + let improved = prepare_host_layout( + &service, + &scope, + &host, + transaction(vec![Mutation::Move { instance: id("two"), destination: Destination::JoinTab { section: section("one"), index: 1 } }]), + ) + .unwrap(); + assert!(improved.layout().extent.width < host.extent.width); + assert!(improved.layout().extent.height <= host.extent.height); + assert_eq!(service.inspect(), before); +} + +#[test] +fn allocation_pin_outer_follows_sides_and_invalid_selected_drop_never_displaces_a_peer() { + let mut service = fixture_service(false).unwrap(); + apply_fixture( + &mut service, + vec![ + fixture_open("fixture.pin", "pin", "pin", Zone::Left, 0).unwrap(), + fixture_open("fixture.log", "moving", "moving", Zone::Floating, 1).unwrap(), + ], + ); + let host = allocate_fixture(&service, Size { width: 1400.0, height: 900.0 }, Direction::Ltr, &fixture_metric_policy(&service)); + let before = service.inspect(); + let card = host.sections.iter().find(|card| card.instance == id("pin")).unwrap(); + let at = Point { x: card.outer.origin.x + 2.0, y: middle(card.outer).y }; + let mut interaction = HostInteraction::default(); + fixture_press(&service, &host, &mut interaction, HostPointerTarget::Header { instance: id("moving") }); + let preview = fixture_move(&service, &host, &mut interaction, at); + assert!(preview.rejection.as_ref().is_some_and(|reason| matches!(reason.rule, Rule::PinOrder | Rule::PinConflict))); + assert!(preview.projected.is_none() && preview.targets.is_empty()); + assert!(interaction.update(&service, &fixture_scope(&service), &host, HostPointerEvent::Release { at }).candidate.is_none()); + assert_eq!(service.inspect(), before); + let candidate = prepare_host_layout( + &service, + &fixture_scope(&service), + &host, + transaction(vec![Mutation::Move { + instance: id("pin"), + destination: Destination::NewSection { + section: section("pin"), + index: 0, + location: SectionLocation::Dock { zone: Zone::Right }, + size: Size { width: 280.0, height: 240.0 }, + }, + }]), + ) + .unwrap(); + fixture_commit(&mut service, &host, candidate); + assert_eq!(service.layout().containing(&id("pin")).unwrap().location.zone(), Zone::Right); +} + +#[test] +fn allocation_paired_resize_and_double_click_transfer_owned_exact_candidates_with_composite_limits() { + for direction in [Direction::Ltr, Direction::Rtl] { + for zone in [Zone::Left, Zone::Right, Zone::Bottom] { + let mut service = fixture_service(false).unwrap(); + apply_fixture( + &mut service, + vec![fixture_open("fixture.log", "one", "one", zone, 0).unwrap(), fixture_open("fixture.log", "two", "two", zone, 1).unwrap()], + ); + let host = allocate_fixture(&service, Size { width: 1000.0, height: 800.0 }, direction, &fixture_metric_policy(&service)); + let before = service.inspect(); + let target = HostPointerTarget::Sash { first: section("one"), second: section("two") }; + let mut interaction = HostInteraction::default(); + let start = fixture_press(&service, &host, &mut interaction, target.clone()); + let at = if zone == Zone::Bottom { + Point { x: start.x + if direction == Direction::Ltr { 20.0 } else { -20.0 }, y: start.y } + } else { + Point { x: start.x, y: start.y + 20.0 } + }; + let preview = fixture_move(&service, &host, &mut interaction, at); + assert!(preview.rejection.is_none(), "{zone:?}/{direction:?}: {preview:?}"); + assert!(preview.targets.is_empty()); + assert_eq!(service.inspect(), before); + let release = interaction.update(&service, &fixture_scope(&service), &host, HostPointerEvent::Release { at }); + let committed = fixture_commit(&mut service, &host, release.candidate.unwrap()); + assert_eq!(committed.sashes[0].bounds, preview.bounds); + let axis = |size: Size| if zone == Zone::Bottom { size.width } else { size.height }; + assert_eq!( + service.layout().sections.iter().map(|section| axis(section.size)).sum::(), + host.sections.iter().map(|section| axis(section.outer.size)).sum::() + ); + let reset = interaction.update(&service, &fixture_scope(&service), &committed, HostPointerEvent::DoubleClick { target }); + assert!(reset.action.is_none()); + let restored = fixture_commit(&mut service, &committed, reset.candidate.unwrap()); + assert_eq!(restored.sashes[0].bounds, host.sashes[0].bounds); + } + } +} + +#[test] +fn allocation_full_domain_and_short_wide_inline_roles_keep_real_usable_contours_and_header_order() { + let mut service = allocation_service(|spec| { + spec.min_size.height = 40.0; + if spec.kind.0 == "fixture.log" { + spec.header_actions = + vec![HeaderActionSpec { id: ControlId::new("fixture.action").unwrap(), label_key: "ui.panel".into(), icon: "list".into() }]; + spec.features.hot_closable = true; + } + }); + apply_fixture( + &mut service, + vec![ + fixture_open("fixture.log", "one", "one", Zone::Bottom, 0).unwrap(), + Mutation::SetSize { section: section("one"), size: Size { width: 800.0, height: 64.0 } }, + ], + ); + let domain = LogicalRect { origin: Point { x: 0.0, y: 30.0 }, size: Size { width: 1400.0, height: 870.0 } }; + let capacity = LogicalRect { origin: Point { x: 0.0, y: 130.0 }, size: Size { width: 1400.0, height: 770.0 } }; + let ribbon = LogicalRect { origin: domain.origin, size: Size { width: 1400.0, height: 100.0 } }; + for direction in [Direction::Ltr, Direction::Rtl] { + let host = resolve_host_layout_in_domain( + &service, + domain, + capacity, + &[ribbon], + direction, + HostMetrics { inline_max_height: 88.0, header_height: 20.0, footer_height: 16.0, ..HostMetrics::default() }, + &fixture_metric_policy(&service), + ) + .unwrap(); + assert_eq!(host.viewport, Some(domain)); + assert!(host.usable.obstacles.contains(&ribbon)); + let card = &host.sections[0]; + assert!(card.inline && card.body.is_none() && card.footer.is_none()); + assert_eq!(card.header, card.outer, "one total row is shared by controls and inline content"); + let controls = [card.actions[0].1, card.menu, card.collapse, card.close.unwrap()]; + for pair in controls.windows(2) { + assert!(if direction == Direction::Ltr { pair[0].origin.x < pair[1].origin.x } else { pair[0].origin.x > pair[1].origin.x }); + } + assert!(host.usable.contains_rect(LogicalRect { origin: Point { x: 500.0, y: 300.0 }, size: Size { width: 40.0, height: 40.0 } })); + } +} + +#[test] +fn allocation_fill_collapse_is_header_only_and_expansion_uses_the_same_captured_policy() { + let mut service = allocation_service(|spec| { + spec.side_height_policy = SideHeightPolicy::Fill; + }); + apply_fixture(&mut service, vec![fixture_open("fixture.log", "one", "one", Zone::Right, 0).unwrap()]); + let host = allocate_fixture(&service, Size { width: 1200.0, height: 800.0 }, Direction::Rtl, &fixture_metric_policy(&service)); + assert_eq!(host.sections[0].outer.size.height, 800.0); + let weight = service.layout().sections[0].weight; + let collapse = prepare_host_layout( + &service, + &fixture_scope(&service), + &host, + transaction(vec![Mutation::Collapse { section: section("one"), collapsed: true }]), + ) + .unwrap(); + let collapsed = fixture_commit(&mut service, &host, collapse); + assert_eq!(collapsed.sections[0].outer.size.height, collapsed.metrics.header_height); + assert!(collapsed.sections[0].body.is_none() && collapsed.sections[0].footer.is_none()); + assert!(collapsed.allocation_environment.content.is_empty(), "collapsed Fill never requests hidden body metrics"); + let expand = prepare_host_layout( + &service, + &fixture_scope(&service), + &collapsed, + transaction(vec![Mutation::Collapse { section: section("one"), collapsed: false }]), + ) + .unwrap(); + let expanded = fixture_commit(&mut service, &collapsed, expand); + assert_eq!(expanded.sections, host.sections); + assert_eq!(service.layout().sections[0].weight, weight); +} + +#[test] +fn allocation_floating_resize_retains_the_fitted_visible_anchor_and_cancels_outside_release() { + let mut service = fixture_service(false).unwrap(); + apply_fixture( + &mut service, + vec![ + fixture_open("fixture.log", "one", "one", Zone::Floating, 0).unwrap(), + Mutation::SetFloatingRect { section: section("one"), origin: Point { x: 700.0, y: 500.0 }, size: Size { width: 1000.0, height: 1000.0 } }, + ], + ); + let host = allocate_fixture(&service, Size { width: 800.0, height: 600.0 }, Direction::Ltr, &fixture_metric_policy(&service)); + assert_eq!(host.sections[0].outer, host.capacity); + let before = service.inspect(); + let target = HostPointerTarget::Resize { section: section("one"), edge: HostResizeEdge::BottomRight }; + let mut interaction = HostInteraction::default(); + let start = fixture_press(&service, &host, &mut interaction, target.clone()); + let at = Point { x: start.x - 40.0, y: start.y - 30.0 }; + let preview = fixture_move(&service, &host, &mut interaction, at); + assert!(preview.rejection.is_none(), "{preview:?}"); + assert_eq!(preview.bounds.origin, host.capacity.origin); + assert_eq!(preview.bounds.size, Size { width: 760.0, height: 570.0 }); + let release = interaction.update(&service, &fixture_scope(&service), &host, HostPointerEvent::Release { at }); + fixture_commit(&mut service, &host, release.candidate.unwrap()); + assert_eq!(service.layout().sections[0].location, SectionLocation::Floating { origin: host.capacity.origin }); + let current = allocate_fixture(&service, host.capacity.size, Direction::Ltr, &fixture_metric_policy(&service)); + let start = fixture_press(&service, ¤t, &mut interaction, target); + let at = Point { x: start.x - 10.0, y: start.y - 10.0 }; + fixture_move(&service, ¤t, &mut interaction, at); + let revision = service.inspect().revision; + let result = interaction.update(&service, &fixture_scope(&service), ¤t, HostPointerEvent::Release { at: Point { x: 900.0, y: 900.0 } }); + assert!(result.candidate.is_none()); + assert_eq!(service.inspect().revision, revision); + assert_eq!(revision, before.revision + 1); +} + +#[test] +fn allocation_section_cap_refuses_split_but_lone_section_reparent_owns_reused_identity() { + let mut service = fixture_service(false).unwrap(); + for index in 0..MAX_SECTIONS { + apply_fixture(&mut service, vec![fixture_open("fixture.log", &format!("p{index}"), &format!("s{index}"), Zone::Left, index).unwrap()]); + } + apply_fixture( + &mut service, + vec![Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("extra"), + destination: Some(Destination::JoinTab { section: section("s0"), index: 1 }), + }], + ); + let host = allocate_fixture(&service, Size { width: 1400.0, height: 20000.0 }, Direction::Ltr, &fixture_metric_policy(&service)); + let before = service.inspect(); + let mut interaction = HostInteraction::default(); + fixture_press(&service, &host, &mut interaction, HostPointerTarget::Tab { instance: id("extra") }); + let at = Point { x: 1399.0, y: 500.0 }; + let preview = fixture_move(&service, &host, &mut interaction, at); + assert_eq!(preview.rejection.unwrap().rule, Rule::CollectionLimit); + assert!(interaction.update(&service, &fixture_scope(&service), &host, HostPointerEvent::Release { at }).candidate.is_none()); + assert_eq!(service.inspect(), before); + fixture_press(&service, &host, &mut interaction, HostPointerTarget::Header { instance: id("p1") }); + let preview = fixture_move(&service, &host, &mut interaction, at); + assert!(preview.rejection.is_none(), "{preview:?}"); + let release = interaction.update(&service, &fixture_scope(&service), &host, HostPointerEvent::Release { at }); + fixture_commit(&mut service, &host, release.candidate.unwrap()); + assert_eq!(service.layout().sections.len(), MAX_SECTIONS); + assert_eq!(service.layout().containing(&id("p1")).unwrap().id, section("s1")); + assert_eq!(service.layout().containing(&id("p1")).unwrap().location.zone(), Zone::Right); +} + +#[test] +fn allocation_independent_refused_command_discards_pointer_candidate_without_any_other_mutation() { + let mut service = fixture_service(false).unwrap(); + apply_fixture( + &mut service, + vec![ + fixture_open("fixture.log", "one", "one", Zone::Left, 0).unwrap(), + fixture_open("fixture.log", "moving", "moving", Zone::Floating, 1).unwrap(), + ], + ); + let host = allocate_fixture(&service, Size { width: 1400.0, height: 900.0 }, Direction::Ltr, &fixture_metric_policy(&service)); + let before = service.inspect(); + let mut interaction = HostInteraction::default(); + fixture_press(&service, &host, &mut interaction, HostPointerTarget::Header { instance: id("moving") }); + let at = middle(host.sections[0].outer); + assert!(fixture_move(&service, &host, &mut interaction, at).rejection.is_none()); + let result = interaction.prepare_command( + &service, + &fixture_scope(&service), + &host, + transaction(vec![Mutation::SetSize { section: section("one"), size: Size { width: -1.0, height: 240.0 } }]), + ); + assert!(result.is_err()); + assert!(!interaction.is_captured() && interaction.preview().is_none()); + assert!(interaction.move_source().is_none() && interaction.move_position().is_none()); + assert!(interaction.update(&service, &fixture_scope(&service), &host, HostPointerEvent::Release { at }).candidate.is_none()); + assert_eq!(service.inspect(), before); +} + +fn host_scope(h: &PanelMountHarness) -> LocalScope { + let environment = h.runtime.environment(); + LocalScope { workspace: environment.workspace.clone(), document: environment.document.clone(), viewport: environment.viewport.clone() } +} + +fn middle(rect: LogicalRect) -> Point { + Point { x: rect.origin.x + rect.size.width * 0.5, y: rect.origin.y + rect.size.height * 0.5 } +} + +fn host_logs(count: usize, zone: Zone) -> PanelMountHarness { + let mut h = PanelMountHarness::new(false).unwrap(); + for index in 0..count { + h.dispatch(vec![fixture_open("fixture.log", &format!("log-{index}"), &format!("section-{index}"), zone, index).unwrap()]).unwrap(); + } + h.tick().unwrap(); + h +} + +fn assert_host_geometry(h: &PanelMountHarness, host: &HostLayout) { + host.resolved.validate().unwrap(); + for card in &host.sections { + let slots: Vec<_> = card + .title + .into_iter() + .chain(card.tabs.iter().map(|tab| tab.bounds)) + .chain(card.tab_overflow) + .chain(card.actions.iter().map(|(_, bounds)| *bounds)) + .chain([card.menu, card.collapse]) + .chain(card.close) + .chain(card.inline_content) + .collect(); + for (index, bounds) in slots.iter().enumerate() { + assert!(card.header.contains_rect(*bounds)); + assert_eq!(bounds.origin.y, card.header.origin.y); + assert_eq!(bounds.size.height, card.header.size.height); + for other in slots.iter().skip(index + 1) { + assert!(!egui_rect(*bounds).intersect(egui_rect(*other)).is_positive(), "disjoint header targets"); + } + } + if let Some(body) = card.body { + assert_eq!(body.origin.y, bottom(card.header) + host.metrics.content_header_height); + } + } + let mut represented = std::collections::BTreeSet::new(); + for panel in &host.resolved.panels { + assert!(panel.body.is_none_or(|body| panel.outer.contains_rect(body))); + let section = h.runtime.layout().layout().section(&panel.section).unwrap(); + let (min, max) = tab_bounds(h.runtime.layout().layout(), h.runtime.layout().registry(), section).unwrap(); + assert!(panel.outer.size.width >= min.width && panel.outer.size.width <= max.width); + if !section.collapsed { + assert!(panel.outer.size.height >= min.height && panel.outer.size.height <= max.height); + } else { + assert_eq!(panel.outer.size.height, host.metrics.header_height); + } + assert!(represented.insert(panel.section.clone())); + } + for unpresented in &host.resolved.unpresented { + assert!(represented.insert(unpresented.section.clone())); + } + assert_eq!(represented.len(), h.runtime.layout().layout().sections.len(), "every section is presented or truthfully unpresented"); + for control in &host.controls { + control.bounds.validate().unwrap(); + assert!(host.capacity.contains_rect(control.bounds), "reachable control: {control:?}"); + assert!(!control.accessible_name.is_empty()); + assert!(host.painted.iter().any(|paint| paint.contains_rect(control.bounds)), "input must remain within actual paint"); + } + if let Some(viewport) = host.viewport { + viewport.validate().unwrap(); + assert_eq!(viewport, host.render_domain); + assert!(host.render_domain.contains_rect(host.capacity)); + } +} + +fn host_press(h: &PanelMountHarness, layout: &HostLayout, interaction: &mut HostInteraction, target: HostPointerTarget) -> Point { + let at = middle(layout.control(&target).expect("source chrome must exist").bounds); + let update = interaction.update(h.runtime.layout(), &host_scope(h), layout, HostPointerEvent::Press { at, target: Some(target) }); + assert!(update.action.is_none()); + assert!(update.preview.is_none()); + at +} + +fn one_mutation(action: &LayoutAction) -> &Mutation { + match action { + LayoutAction::Apply { expected_revision: Some(_), mutations } => { + assert_eq!(mutations.len(), 1, "one gesture is one atomic typed mutation"); + mutations.first().unwrap() + } + other => panic!("gesture must carry an optimistic Apply: {other:?}"), + } +} + +fn explicit_drop_point(h: &PanelMountHarness, layout: &HostLayout, instance: &InstanceId, target: &HostDropTargetId) -> Point { + let targets = host_drop_targets(h.runtime.layout(), layout, instance).unwrap(); + middle( + targets.iter().rev().find(|candidate| candidate.id == *target).unwrap_or_else(|| panic!("explicit drop target missing: {target:?}")).bounds, + ) +} + +fn assert_join_drag_action(action: &LayoutAction, instance: InstanceId, target: SectionId, index: usize) { + let LayoutAction::Apply { expected_revision: Some(_), mutations } = action else { + panic!("a shown tab landing is one optimistic transaction"); + }; + assert_eq!( + mutations, + &vec![ + Mutation::Move { instance: instance.clone(), destination: Destination::JoinTab { section: target, index } }, + Mutation::Activate { instance } + ], + "the dragged tab is visible at the previewed insertion point" + ); +} + +fn host_with_specs(edit: impl Fn(&mut PanelSpec)) -> PanelMountHarness { + let mut h = PanelMountHarness::new(false).unwrap(); + let mut registry = PanelRegistry::default(); + for spec in synthetic_registry().unwrap().specs() { + let mut spec = spec.clone(); + edit(&mut spec); + registry.register(spec).unwrap(); + } + let environment = h.runtime.environment().clone(); + h.runtime = PanelRuntime::new( + LayoutService::new(registry, Layout::empty(environment.workspace.clone()), HostCapabilities::default()).unwrap(), + environment, + ) + .unwrap(); + bind_synthetic_controllers(&mut h.runtime, &h.probe).unwrap(); + h +} + +#[test] +fn usable_region_preserves_short_panel_gaps_floating_holes_and_every_late_obstacle() { + let domain = LogicalRect { origin: Point { x: 0.0, y: 0.0 }, size: Size { width: 1000.0, height: 600.0 } }; + let obstacles = [ + LogicalRect { origin: Point { x: 0.0, y: 0.0 }, size: Size { width: 200.0, height: 120.0 } }, + LogicalRect { origin: Point { x: 800.0, y: 0.0 }, size: Size { width: 200.0, height: 240.0 } }, + LogicalRect { origin: Point { x: 450.0, y: 200.0 }, size: Size { width: 100.0, height: 100.0 } }, + ]; + let usable = resolve_usable_region(domain, &obstacles).unwrap(); + assert_eq!(usable.free.iter().map(|rect| rect.size.width * rect.size.height).sum::(), 518000.0); + for (index, piece) in usable.free.iter().enumerate() { + assert!(usable.contains_rect(*piece)); + assert!(usable.free.iter().skip(index + 1).all(|other| !egui_rect(*piece).intersect(egui_rect(*other)).is_positive())); + } + assert!(usable.free.iter().any(|rect| rect.contains(Point { x: 100.0, y: 400.0 })), "space below a short left panel remains usable"); + assert!(usable.free.iter().any(|rect| rect.contains(Point { x: 900.0, y: 400.0 })), "asymmetric right-panel height cannot discard the lower gap"); + assert!(!usable.free.iter().any(|rect| rect.contains(Point { x: 500.0, y: 250.0 })), "floating footprints remain holes"); + let footprint = usable.place_footprint(Size { width: 80.0, height: 40.0 }, Point { x: 100.0, y: 400.0 }, 10.0).unwrap(); + assert_eq!(footprint, LogicalRect { origin: Point { x: 60.0, y: 380.0 }, size: Size { width: 80.0, height: 40.0 } }); + assert!(usable.contains_rect(LogicalRect { origin: Point { x: 50.0, y: 370.0 }, size: Size { width: 100.0, height: 60.0 } })); + let fit = usable.fit_rect(2.0, Point { x: 500.0, y: 300.0 }).unwrap(); + assert!(usable.contains_rect(fit)); + assert!( + (fit.size.width - 600.0).abs() < 0.01 && (fit.size.height - 300.0).abs() < 0.01, + "model aspect must use the broad region below the floating hole: {fit:?}" + ); + assert!(usable.place_footprint(Size { width: 1001.0, height: 601.0 }, middle(domain), 0.0).is_none()); + assert_eq!(usable.fit_rect_with_clearance(2.0, middle(domain), 0.0), Some(fit)); + for aspect in [100.0, 0.01] { + let inner = usable.fit_rect_with_clearance(aspect, middle(domain), 8.0).expect("clearance must be reserved without erasing a thin fit"); + assert!((inner.size.width / inner.size.height - aspect).abs() < aspect * 0.0001); + let padded = egui_rect(inner).expand(8.0); + assert!(usable.contains_rect(logical_rect(padded))); + assert!(obstacles.iter().all(|obstacle| !padded.intersect(egui_rect(*obstacle)).is_positive())); + if aspect > 1.0 { + assert!(inner.size.width > 900.0 && inner.size.height < 16.0); + } else { + assert!(inner.size.height > 500.0 && inner.size.width < 16.0); + } + } + for clearance in [f32::NAN, -1.0, f32::INFINITY, f32::MAX, 600.0] { + assert!(usable.fit_rect_with_clearance(1.0, middle(domain), clearance).is_none()); + } + for aspect in [f32::NAN, -1.0, 0.0, f32::INFINITY] { + assert!(usable.fit_rect_with_clearance(aspect, middle(domain), 8.0).is_none()); + } + let tiny_domain = LogicalRect { origin: Point { x: 25.0, y: 35.0 }, size: Size { width: 8.0, height: 8.0 } }; + let tiny = resolve_usable_region(tiny_domain, &[]).unwrap(); + assert!(tiny.fit_rect_with_clearance(1.0, middle(tiny_domain), 4.0).is_none()); + assert!(tiny.fit_rect_with_clearance(1.0, middle(tiny_domain), 1.0).is_some()); + + let mut many = (0..20) + .map(|index| LogicalRect { origin: Point { x: index as f32 * 40.0, y: 0.0 }, size: Size { width: 20.0, height: 20.0 } }) + .collect::>(); + let late = LogicalRect { origin: Point { x: 460.0, y: 250.0 }, size: Size { width: 80.0, height: 100.0 } }; + many.push(late); + let crowded = resolve_usable_region(domain, &many).unwrap(); + assert_eq!(crowded.obstacles.len(), 21); + assert!( + crowded.free.iter().all(|piece| !egui_rect(*piece).intersect(egui_rect(late)).is_positive()), + "an obstacle after the old sixteen-entry bound must never be ignored" + ); + let placed = crowded.place_footprint(Size { width: 60.0, height: 40.0 }, middle(late), 8.0).unwrap(); + assert!(!egui_rect(placed).expand(8.0).intersect(egui_rect(late)).is_positive()); + assert_eq!(crowded.place_footprint(Size { width: 60.0, height: 40.0 }, middle(late), 8.0), Some(placed), "placement ties are stable"); +} + +/// Drives the production workspace chrome with separate press/move/release +/// RawInput frames. This is headless UI coverage, not visual evidence. +#[derive(Clone, Debug)] +struct RawModalObservation { + card: egui::Rect, + backdrop: egui::Rect, + visible: bool, + escape_events: Vec, + close_requested: bool, +} + +struct RawPanelHost { + content: PanelMountHarness, + host: WorkspacePanelHost, + ctx: egui::Context, + time: f64, + capacity: LogicalRect, + native_pixels_per_point: Option, + foreign_cover: Option, + foreign_responses: Vec, + foreign_takes_focus: bool, + foreign_raise_late: bool, + foreign_order: egui::Order, + stale_foreign_cover: Option, + stale_foreign_layer: Option, + root_layer: Option, + painted_frames: Vec, + finished_frames: Vec, + clicked_widgets: Vec, + double_clicked_widgets: Vec, + painted_menu: bool, + late_modal: bool, + reserve_escape_for_host: bool, + escape_reservations: usize, + modal_observations: Vec, + focused_response: Option, + bind_fixture_scopes: bool, +} + +impl RawPanelHost { + fn new(content: PanelMountHarness, scale: f32) -> Self { + let ctx = crate::fonts::test_context(); + ctx.enable_accesskit(); + ctx.set_pixels_per_point(scale); + Self { + content, + host: WorkspacePanelHost::new(HostOptions::default()).unwrap(), + ctx, + time: 0.0, + capacity: capacity(), + native_pixels_per_point: None, + foreign_cover: None, + foreign_responses: Vec::new(), + foreign_takes_focus: false, + foreign_raise_late: false, + foreign_order: egui::Order::Foreground, + stale_foreign_cover: None, + stale_foreign_layer: None, + root_layer: None, + painted_frames: Vec::new(), + finished_frames: Vec::new(), + clicked_widgets: Vec::new(), + double_clicked_widgets: Vec::new(), + painted_menu: false, + late_modal: false, + reserve_escape_for_host: false, + escape_reservations: 0, + modal_observations: Vec::new(), + focused_response: None, + bind_fixture_scopes: false, + } + } + + fn frame(&mut self, events: Vec, multipass: bool) -> (HostFrame, egui::FullOutput) { + let (frame, output) = self.frame_late(events, multipass, |_, _| {}); + (frame.expect("ordinary host frame remains present"), output) + } + + fn frame_late( + &mut self, + events: Vec, + multipass: bool, + mut after_show: impl FnMut(&mut PanelMountHarness, &egui::Context), + ) -> (Option, egui::FullOutput) { + self.content.tick().unwrap(); + self.time += 1.0 / 60.0; + let mut passes = 0; + let mut input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(self.capacity.size.width, self.capacity.size.height))), + events, + time: Some(self.time), + focused: true, + ..Default::default() + }; + if let Some(dpi) = self.native_pixels_per_point { + input.viewports.entry(egui::ViewportId::ROOT).or_default().native_pixels_per_point = Some(dpi); + } + // Match SolveApp's native boundary before egui validates pointer and wheel events. + crate::finite_input(&mut input); + self.foreign_responses.clear(); + self.painted_frames.clear(); + self.finished_frames.clear(); + self.clicked_widgets.clear(); + self.double_clicked_widgets.clear(); + self.modal_observations.clear(); + self.focused_response = None; + self.escape_reservations = 0; + let mut output = self.ctx.run_ui(input, |ui| { + passes += 1; + self.host.capture_metrics(&self.content.runtime, &self.content.models).unwrap(); + self.host.capture_reservations(&self.content.runtime, &self.content.catalogue).unwrap(); + self.host.prepare(&self.content.runtime, self.capacity).unwrap(); + self.root_layer = Some(ui.layer_id()); + if self.bind_fixture_scopes { + // The strict existing fake provider requires an explicit bind + // before a controller can request an overlay. Rebind the live + // owner scope for each real mount, including a post-commit pass. + let scope = host_scope(&self.content); + for instance in &self.content.runtime.layout().layout().instances { + self.content.local.bind(instance.id.clone(), scope.clone()).unwrap(); + } + } + if self.reserve_escape_for_host + && self.host.wants_escape(&self.content.runtime) + && crate::ui_kit::Container::reserve_host_escape(ui.ctx()) + { + self.escape_reservations += 1; + self.host.request_escape(); + } + let h = &mut self.content; + self.host + .show_deferred( + ui, + &mut h.runtime, + &mut h.native, + &mut ContentServices { models: &h.models, commands: &mut h.commands, local: &mut h.local }, + ) + .unwrap(); + let painted = self.host.frame().unwrap().clone(); + for control in &painted.controls { + if let Some(response) = ui.ctx().read_response(control.id) { + if response.clicked() || response.secondary_clicked() { + self.clicked_widgets.push(control.id); + } + if response.double_clicked() { + self.double_clicked_widgets.push(control.id); + } + } + } + self.painted_frames.push(painted); + // Match real late system UI: the host renders before this unrelated + // foreground container. Warmed frames establish real egui ownership. + if let Some(bounds) = self.foreign_cover { + let container = crate::ui_kit::Container::new(ui.ctx(), crate::ui_kit::Surface::Window); + let frame = container.frame(ui.ctx(), crate::theme::Tokens::get().dialog_body, crate::frame::Side::Left).inner_margin(0); + container + .area(egui::Id::unique("unrelated_test_window")) + .order(self.foreign_order) + .fixed_pos(bounds.min) + .movable(false) + .constrain(false) + .fade_in(false) + .show(ui.ctx(), |ui| { + ui.set_min_size(bounds.size()); + container.show_frame(ui, frame, bounds, |ui| { + ui.set_min_size(bounds.size()); + let response = ui.interact(bounds, ui.scope_id().with("foreign_control"), egui::Sense::click_and_drag()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, "Unrelated foreground control")); + if self.foreign_takes_focus { + response.request_focus(); + } + self.foreign_responses.push(response); + }); + let covered = bounds.intersect(ui.clip_rect()).intersect(egui_rect(self.capacity)); + if ui.is_visible() && !ui.is_sizing_pass() && covered.is_positive() { + assert!( + ui.ctx().graphics(|graphics| { + graphics.get(ui.layer_id()).is_some_and(|paint| { + paint.all_entries().any(|entry| { + let painted = + (entry.transform_after_tessellation * entry.shape.visual_bounding_rect()).intersect(entry.clip_rect); + painted.is_positive() && painted.is_finite() && painted.contains(covered.center()) + }) + }) + }), + "the foreign frame must actually paint at the covered point" + ); + } + }); + if self.foreign_raise_late { + let layer = self.foreign_responses.last().expect("actual foreign Area response").layer_id; + crate::ui_kit::Container::bring_to_front(ui.ctx(), layer); + } + } + if let Some(bounds) = self.stale_foreign_cover { + let container = crate::ui_kit::Container::new(ui.ctx(), crate::ui_kit::Surface::Window); + container + .area(egui::Id::unique("stale_third_test_window")) + .order(egui::Order::Foreground) + .fixed_pos(bounds.min) + .constrain(false) + .movable(false) + .sense(egui::Sense::hover()) + .fade_in(false) + .show(ui.ctx(), |ui| { + ui.set_min_size(bounds.size()); + self.stale_foreign_layer = Some(ui.layer_id()); + crate::ui_kit::Container::paint_frame(ui.painter(), crate::ui_kit::Container::menu_frame(), bounds); + }); + } + let modal = self.late_modal.then(|| { + let container = crate::ui_kit::Container::new(ui.ctx(), crate::ui_kit::Surface::Window); + let frame = container.frame(ui.ctx(), crate::theme::Tokens::get().dialog_body, crate::frame::Side::Left); + container.modal(egui::Id::unique("unrelated_test_modal")).frame(frame).show(ui.ctx(), |ui| { + ui.set_min_size(egui::vec2(200.0, 80.0)); + ui.label("Independent modal content"); + ( + ui.is_visible() && !ui.is_sizing_pass(), + ui.input(|input| { + input + .events + .iter() + .filter(|event| matches!(event, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. })) + .cloned() + .collect::>() + }), + ) + }) + }); + after_show(h, ui.ctx()); + self.host + .finish( + ui, + &mut h.runtime, + &mut h.native, + &mut ContentServices { models: &h.models, commands: &mut h.commands, local: &mut h.local }, + &mut h.catalogue, + ) + .unwrap(); + if let Some(modal) = modal { + // The modal receives Escape after host finish as it does in a + // late system UI path; an earlier host must not consume it. + let close_requested = modal.should_close(); + self.modal_observations.push(RawModalObservation { + card: modal.response.rect, + // Ui::response captured inside Modal::show can still carry + // the preceding pass's rectangle. The child has now dropped + // and registered its actual current-pass backdrop bounds. + backdrop: ui.ctx().read_response(modal.backdrop_response.id).unwrap().rect, + visible: modal.inner.0, + escape_events: modal.inner.1, + close_requested, + }); + } + if let Some(frame) = self.host.frame() { + self.finished_frames.push(frame.clone()); + } + self.focused_response = ui.memory(|memory| memory.focused()).and_then(|id| ui.ctx().read_response(id)); + if multipass && ui.ctx().current_pass_index() == 0 { + ui.ctx().request_discard("exercise universal host one-shot actions across egui passes"); + } + }); + // This headless fixture inspects shapes and has no texture painter. + output.textures_delta.clear(); + if multipass { + assert!(passes >= 2, "must actually exercise another egui pass"); + } + self.painted_menu |= self.host.frame().is_some_and(|frame| frame.menu_bounds.is_some()); + (self.host.frame().cloned(), output) + } + + fn at(&self, target: HostControlTarget) -> egui::Pos2 { + let bounds = self + .host + .frame() + .unwrap() + .controls + .iter() + .find(|control| control.target == target) + .unwrap_or_else(|| panic!("actual chrome control missing: {target:?}")) + .bounds; + let at = middle(bounds); + egui::pos2(at.x, at.y) + } + + fn pointer(&mut self, at: egui::Pos2, pressed: bool, multipass: bool) -> HostFrame { + self.frame( + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, + ], + multipass, + ) + .0 + } + + fn click(&mut self, target: HostControlTarget, multipass: bool) -> HostFrame { + let at = self.at(target); + self.frame(vec![egui::Event::PointerMoved(at)], false); + self.pointer(at, true, multipass); + self.pointer(at, false, multipass) + } + + fn menu(&mut self, instance: InstanceId) { + self.click(HostControlTarget::Pointer(HostPointerTarget::Menu { instance }), false); + self.frame(Vec::new(), false); + self.frame(Vec::new(), false); + assert!(self.host.frame().unwrap().menu_bounds.is_some(), "must open the real shared menu"); + } + + /// egui's first-ever Area pass is invisible measurement. Measure the + /// unrelated window away from the viewport before its first visible late + /// appearance, so covered-input cases exercise a real enabled foreign UI. + fn prime_foreign_window(&mut self) { + self.foreign_cover = Some(egui::Rect::from_min_size( + egui::pos2(self.capacity.size.width + 200.0, self.capacity.size.height + 200.0), + egui::vec2(180.0, 100.0), + )); + self.frame(Vec::new(), false); + self.frame(Vec::new(), false); + assert!(!self.foreign_responses.is_empty()); + assert!(self.foreign_responses.iter().all(egui::Response::enabled)); + self.foreign_cover = None; + self.frame(Vec::new(), false); + } + + fn prime_modal(&mut self) { + self.late_modal = true; + self.frame(Vec::new(), false); + self.frame(Vec::new(), false); + assert!(self.modal_observations.iter().all(|modal| modal.visible)); + self.late_modal = false; + self.frame(Vec::new(), false); + self.frame(Vec::new(), false); + assert!(!crate::ui_kit::Container::modal_input_blocked(&self.ctx)); + } +} + +#[test] +fn raw_host_tab_activation_renders_only_active_content_and_keeps_hidden_services_and_drafts() { + for scale in [1.0, 2.0] { + let mut h = PanelMountHarness::new(false).unwrap(); + open_editor(&mut h); + h.dispatch(vec![Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("inactive"), + destination: Some(Destination::JoinTab { section: section("editor-section"), index: 1 }), + }]) + .unwrap(); + let key = editor_key(&h); + h.probe.edit(&key, |state| state.draft = "keep this edit".into()).unwrap(); + let mut raw = RawPanelHost::new(h, scale); + raw.frame(Vec::new(), false); + let inactive_key = + ControllerKey { instance: id("inactive"), owner: ContentOwner::Workspace(raw.content.runtime.environment().workspace.clone()) }; + assert_eq!(raw.content.probe.state(&inactive_key).unwrap().renders, 0); + let editor_renders = raw.content.probe.state(&key).unwrap().renders; + raw.click(HostControlTarget::Pointer(HostPointerTarget::Tab { instance: id("inactive") }), false); + raw.frame(Vec::new(), false); + assert_eq!(raw.content.runtime.layout().layout().section(§ion("editor-section")).unwrap().active, id("inactive")); + assert!(raw.content.runtime.layout().interaction().focused.is_none(), "Activate does not manufacture keyboard focus"); + let editor_after_activation = raw.content.probe.state(&key).unwrap().renders; + assert!(editor_after_activation >= editor_renders); + let updates = raw.content.probe.state(&key).unwrap().updates; + for _ in 0..3 { + raw.frame(Vec::new(), false); + } + let state = raw.content.probe.state(&key).unwrap(); + assert_eq!(state.renders, editor_after_activation); + assert!(state.updates > updates); + assert_eq!(state.draft, "keep this edit"); + assert!(state.transaction_live); + assert_eq!((state.cancels, state.applies, state.finishes), (0, 0, 0)); + assert!(raw.content.probe.state(&inactive_key).unwrap().renders > 0); + } +} + +#[test] +fn raw_host_content_actions_commit_once_across_real_egui_multipass_and_do_not_start_drags() { + let mut h = PanelMountHarness::new(false).unwrap(); + open_editor(&mut h); + let key = editor_key(&h); + let mut raw = RawPanelHost::new(h, 2.0); + raw.frame(Vec::new(), false); + let before = raw.content.runtime.layout().inspect(); + let released = raw.click(HostControlTarget::Content { instance: id("editor"), action: ControlId::new("apply").unwrap() }, true); + assert_eq!( + released + .events + .iter() + .filter(|event| matches!(event, HostEvent::ContentAction { instance, action, result: Ok(()) } + if *instance == id("editor") && action.0 == "apply")) + .count(), + 1, + "the repeated release pass publishes the executed content outcome once" + ); + assert_eq!(raw.content.commands.calls, 1); + assert_eq!(raw.content.probe.state(&key).unwrap().applies, 1); + assert_eq!(raw.content.runtime.layout().inspect(), before); + assert!(!raw.host.interaction().is_captured()); + assert!(raw.host.frame().unwrap().preview.is_none()); + let next = raw.frame(Vec::new(), true).0; + assert!(!next.events.iter().any(|event| matches!(event, HostEvent::ContentAction { .. }))); + assert_eq!(raw.content.commands.calls, 1, "later passes/frames cannot replay a content action"); +} + +#[test] +fn raw_host_explicit_close_refusal_keeps_layout_native_resources_and_transaction_atomic() { + let mut h = PanelMountHarness::new(false).unwrap(); + open_editor(&mut h); + let key = editor_key(&h); + h.probe + .edit(&key, |state| { + state.draft = "guarded edit".into(); + state.reject_cancel = true; + }) + .unwrap(); + let mut raw = RawPanelHost::new(h, 1.0); + raw.frame(Vec::new(), false); + raw.menu(id("editor")); + let before = raw.content.runtime.layout().inspect(); + let native_commits = raw.content.native.commits; + let controllers = raw.content.runtime.controller_count(); + let frame = raw.click(HostControlTarget::Shared { instance: id("editor"), action: HostSharedAction::Close }, true); + assert_eq!(raw.content.runtime.layout().inspect(), before); + assert_eq!(raw.content.native.commits, native_commits); + assert_eq!(raw.content.runtime.controller_count(), controllers); + assert!(frame.events.iter().any(|event| matches!(event, HostEvent::Rejected { error, .. } if error.rule == Rule::Lifecycle))); + let state = raw.content.probe.state(&key).unwrap(); + assert!(state.transaction_live); + assert_eq!(state.draft, "guarded edit"); + assert_eq!(state.cancels, 0); + raw.content.probe.edit(&key, |state| state.reject_cancel = false).unwrap(); + // A refused action may leave the menu open. Open it only if needed. + raw.frame(Vec::new(), false); + if raw.host.frame().unwrap().menu_bounds.is_none() { + raw.menu(id("editor")); + } + raw.click(HostControlTarget::Shared { instance: id("editor"), action: HostSharedAction::Close }, true); + assert!(!raw.content.runtime.layout().layout().instance(&id("editor")).unwrap().requested_open); + assert_eq!(raw.content.probe.state(&key).unwrap().cancels, 1); + assert_eq!(raw.content.commands.calls, 0); +} + +#[test] +fn raw_host_shared_move_menu_is_a_pointer_independent_alternative_to_drag() { + let mut h = PanelMountHarness::new(false).unwrap(); + open_editor(&mut h); + let key = editor_key(&h); + h.probe.edit(&key, |state| state.draft = "menu move draft".into()).unwrap(); + let mut raw = RawPanelHost::new(h, 1.0); + raw.frame(Vec::new(), false); + for zone in [Zone::Right, Zone::Bottom, Zone::Floating, Zone::Left] { + raw.menu(id("editor")); + let before = raw.content.runtime.layout().inspect().revision; + raw.click(HostControlTarget::Shared { instance: id("editor"), action: HostSharedAction::Move(zone) }, true); + raw.frame(Vec::new(), false); + assert_eq!(raw.content.runtime.layout().inspect().revision, before + 1); + assert_eq!(raw.content.runtime.layout().layout().containing(&id("editor")).unwrap().location.zone(), zone); + let state = raw.content.probe.state(&key).unwrap(); + assert_eq!(state.draft, "menu move draft"); + assert!(state.transaction_live); + assert_eq!((state.applies, state.cancels, state.finishes), (0, 0, 0)); + assert_eq!(raw.content.commands.calls, 0); + } +} + +#[test] +fn raw_host_header_collapse_restore_and_hide_retain_the_draft_and_tick_hidden_services() { + let mut h = PanelMountHarness::new(false).unwrap(); + open_editor(&mut h); + let key = editor_key(&h); + h.probe + .edit(&key, |state| { + state.draft = "live hidden edit".into(); + state.reject_cancel = true; + }) + .unwrap(); + let mut raw = RawPanelHost::new(h, 2.0); + raw.frame(Vec::new(), false); + let target = HostControlTarget::Pointer(HostPointerTarget::Collapse { instance: id("editor") }); + raw.click(target.clone(), false); + raw.frame(Vec::new(), false); + let hidden = raw.content.probe.state(&key).unwrap(); + let card = raw.host.frame().unwrap().layout.sections.first().unwrap(); + assert!(card.collapsed && card.body.is_none() && card.footer.is_none()); + assert_eq!(card.outer, card.header); + for _ in 0..3 { + raw.frame(Vec::new(), false); + } + let idle = raw.content.probe.state(&key).unwrap(); + assert_eq!(idle.renders, hidden.renders); + assert!(idle.updates > hidden.updates); + raw.click(target, false); + raw.frame(Vec::new(), false); + assert!(!raw.content.runtime.layout().layout().section(§ion("editor-section")).unwrap().collapsed); + assert!(raw.content.probe.state(&key).unwrap().renders > idle.renders); + let mut layout = raw.content.runtime.layout().layout().clone(); + layout.sections.clear(); + layout.instances[0].requested_open = false; + raw.content.apply_layout(layout, None).unwrap(); + raw.frame(Vec::new(), false); + let hidden_again = raw.content.probe.state(&key).unwrap().renders; + for _ in 0..3 { + raw.frame(Vec::new(), false); + } + let state = raw.content.probe.state(&key).unwrap(); + assert_eq!(state.renders, hidden_again); + assert_eq!(state.draft, "live hidden edit"); + assert!(state.transaction_live); + assert_eq!((state.cancels, state.applies, state.finishes, state.destroys), (0, 0, 0, 0)); + assert_eq!(raw.content.commands.calls, 0); + assert!(raw.host.frame().unwrap().layout.resolved.panels.is_empty()); + assert!(!raw.content.runtime.state(&key).unwrap().presented); +} +#[test] +fn raw_host_native_prepare_failure_and_capability_false_menu_preserve_atomicity() { + for native in [false, true] { + let mut h = PanelMountHarness::new(native).unwrap(); + open_editor(&mut h); + let key = editor_key(&h); + let mut raw = RawPanelHost::new(h, 1.0); + raw.frame(Vec::new(), false); + raw.menu(id("editor")); + let control = raw + .host + .frame() + .unwrap() + .controls + .iter() + .find(|control| control.target == HostControlTarget::Shared { instance: id("editor"), action: HostSharedAction::Popout }) + .unwrap(); + assert_eq!(control.enabled, native, "native capability must be truthful"); + let before = raw.content.runtime.layout().inspect(); + let commits = raw.content.native.commits; + raw.content.native.fail_prepare = true; + let frame = raw.click(HostControlTarget::Shared { instance: id("editor"), action: HostSharedAction::Popout }, false); + assert_eq!(raw.content.runtime.layout().inspect(), before); + assert_eq!(raw.content.native.commits, commits); + assert!(raw.content.native.hosts.is_empty()); + assert_eq!(raw.content.probe.state(&key).unwrap().reparents, 0); + assert!(raw.content.probe.state(&key).unwrap().transaction_live); + if native { + assert!(frame.events.iter().any(|event| matches!(event, HostEvent::Rejected { .. }))); + } + } +} + +#[test] +fn raw_host_widget_ids_follow_semantic_instances_and_scope_not_title_or_position() { + let mut h = host_logs(2, Zone::Left); + h.tick().unwrap(); + let mut raw = RawPanelHost::new(h, 1.0); + let target = HostControlTarget::Pointer(HostPointerTarget::Header { instance: id("log-0") }); + let (frame, _) = raw.frame(Vec::new(), false); + let original = frame.controls.iter().find(|control| control.target == target).unwrap().id; + raw.content + .dispatch(vec![Mutation::Move { + instance: id("log-0"), + destination: Destination::NewSection { + section: section("moved"), + index: 1, + location: SectionLocation::Dock { zone: Zone::Right }, + size: Size { width: 320.0, height: 280.0 }, + }, + }]) + .unwrap(); + let (moved, _) = raw.frame(Vec::new(), false); + assert_eq!(moved.controls.iter().find(|control| control.target == target).unwrap().id, original); + let mut environment = raw.content.runtime.environment().clone(); + environment.viewport = ViewportId::new("other-local-window").unwrap(); + environment.window = HostId::new("other-window").unwrap(); + raw.content.runtime.set_environment(environment, &mut raw.content.local).unwrap(); + let (other_window, _) = raw.frame(Vec::new(), false); + assert_ne!( + other_window.controls.iter().find(|control| control.target == target).unwrap().id, + original, + "native/window peers must not share a widget namespace" + ); +} + +#[test] +fn raw_host_natural_edges_win_tab_borders_trailing_halves_and_corner_arbitration_at_both_scales() { + for scale in [1.0, 2.0] { + for direction in [Direction::Ltr, Direction::Rtl] { + for zone in [Zone::Left, Zone::Right] { + for case in ["tab-border", "corner", "column-inward", "outward", "outward-far", "trailing-half"] { + let mut h = host_logs(1, zone); + h.dispatch(vec![ + Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("tab-peer"), + destination: Some(Destination::JoinTab { section: section("section-0"), index: 1 }), + }, + fixture_open("fixture.log", "moving", "moving", Zone::Floating, 1).unwrap(), + Mutation::SetFloatingRect { + section: section("moving"), + origin: Point { x: 560.0, y: 400.0 }, + size: Size { width: 280.0, height: 240.0 }, + }, + ]) + .unwrap(); + let mut environment = h.runtime.environment().clone(); + environment.direction = direction; + h.runtime.set_environment(environment, &mut h.local).unwrap(); + let mut raw = RawPanelHost::new(h, scale); + let options = priority_host_options(); + raw.host = WorkspacePanelHost::new(options).unwrap(); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + let initial = raw.host.frame().unwrap().layout.clone(); + let card = initial.sections.iter().find(|card| card.section == section("section-0")).unwrap(); + let outer_left = direction.edge(zone).unwrap() == PhysicalEdge::Left; + let outer_x = if outer_left { card.outer.origin.x + 45.0 } else { card.outer.origin.x + card.outer.size.width - 45.0 }; + let tab = card.tabs.first().unwrap().bounds; + let (end, placement) = match case { + "tab-border" => (egui::pos2(outer_x, tab.origin.y + 1.0), RelativePlacement::Above), + "corner" => (egui::pos2(outer_x, card.outer.origin.y + 45.0), RelativePlacement::Above), + "column-inward" => (egui::pos2(outer_x, card.outer.origin.y + 80.0), RelativePlacement::BeforeColumn), + "outward" => ( + egui::pos2( + if outer_left { card.outer.origin.x + card.outer.size.width + 14.0 } else { card.outer.origin.x - 14.0 }, + tab.origin.y + 1.0, + ), + RelativePlacement::AfterColumn, + ), + "outward-far" => ( + egui::pos2( + if outer_left { card.outer.origin.x + card.outer.size.width + 40.0 } else { card.outer.origin.x - 40.0 }, + tab.origin.y + 1.0, + ), + RelativePlacement::AfterColumn, + ), + _ => ( + egui::pos2(tab.origin.x + tab.size.width * if direction == Direction::Ltr { 0.75 } else { 0.25 }, tab.origin.y + 10.0), + RelativePlacement::Above, + ), + }; + let start = raw.at(HostControlTarget::Pointer(HostPointerTarget::Header { instance: id("moving") })); + let before = raw.content.runtime.layout().inspect(); + let commits = raw.content.native.commits; + raw.frame(vec![egui::Event::PointerMoved(start)], false); + raw.pointer(start, true, false); + assert!(raw.host.interaction().is_captured()); + assert!(raw.frame(vec![egui::Event::PointerMoved(start + egui::vec2(5.99, 0.0))], false).0.preview.is_none()); + if case == "outward-far" { + let outside = egui::pos2(if outer_left { right(card.outer) + 65.0 } else { card.outer.origin.x - 65.0 }, end.y); + assert!( + raw.frame(vec![egui::Event::PointerMoved(outside)], false).0.preview.unwrap().action.is_none(), + "the centre strip remains bounded" + ); + } + let frame = raw.frame(vec![egui::Event::PointerMoved(end)], false).0; + let preview = frame.preview.as_ref().unwrap(); + assert!(preview.rejection.is_none(), "{scale}/{direction:?}/{zone:?}/{case}: {preview:?}"); + assert_eq!(preview.target, Some(HostDropTargetId::Relative { section: section("section-0"), placement })); + assert_eq!(preview.targets.len(), 1); + let landing = preview.projected.clone().unwrap(); + assert_eq!(raw.content.runtime.layout().inspect(), before); + let released = raw.pointer(end, false, true); + assert_eq!(released.events.iter().filter(|event| matches!(event, HostEvent::PreparedCommitted { .. })).count(), 1); + assert_eq!(raw.content.native.commits, commits + 1); + assert_eq!(raw.content.runtime.layout().inspect().revision, before.revision + 1); + raw.frame(Vec::new(), false); + assert_host_landing(&raw.host.frame().unwrap().layout, &landing); + } + } + } + } +} + +#[test] +fn raw_host_wider_perimeters_win_over_cards_tabs_and_clear_below_without_fallback() { + for scale in [1.0, 2.0] { + for direction in [Direction::Ltr, Direction::Rtl] { + for zone in [Zone::Left, Zone::Right] { + for case in ["side-edge", "side-header", "bottom-clear", "corner", "empty", "bottom-tab", "foreign-tab", "refused-bottom"] { + let mut h = host_with_specs(|spec| { + spec.min_size.height = 40.0; + if spec.kind.0 == "fixture.editor" { + spec.allowed_zones.remove(&Zone::Bottom); + } + }); + h.dispatch(vec![ + fixture_open("fixture.log", "target", "target", zone, 0).unwrap(), + Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("tab-peer"), + destination: Some(Destination::JoinTab { section: section("target"), index: 1 }), + }, + Mutation::Open { + kind: PanelKind::new(if case == "refused-bottom" { "fixture.editor" } else { "fixture.log" }).unwrap(), + instance: id("moving"), + destination: Some(Destination::NewSection { + section: section("moving"), + index: 1, + location: SectionLocation::Floating { origin: Point { x: 560.0, y: 400.0 } }, + size: Size { width: 280.0, height: 240.0 }, + }), + }, + ]) + .unwrap(); + if case == "foreign-tab" { + h.dispatch(vec![Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("moving-peer"), + destination: Some(Destination::JoinTab { section: section("moving"), index: 1 }), + }]) + .unwrap(); + } + if matches!(case, "bottom-tab" | "foreign-tab") { + h.dispatch(vec![ + fixture_open("fixture.log", "bottom", "bottom", Zone::Bottom, 2).unwrap(), + Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("bottom-peer"), + destination: Some(Destination::JoinTab { section: section("bottom"), index: 1 }), + }, + Mutation::SetBottomHeight { section: section("bottom"), height: 64.0 }, + ]) + .unwrap(); + } + let mut environment = h.runtime.environment().clone(); + environment.direction = direction; + h.runtime.set_environment(environment, &mut h.local).unwrap(); + let mut raw = RawPanelHost::new(h, scale); + // Exercise both actual shell gaps without multiplying all + // selection cases by an unrelated rendering-mode matrix. + let mode = if matches!(case, "side-edge" | "bottom-clear" | "empty") { + crate::shell::LayoutMode::Docked + } else { + crate::shell::LayoutMode::Floating + }; + mode.publish(&raw.ctx); + let gap = crate::ui_kit::Container::for_layout(mode, crate::ui_kit::Surface::Panel).gap(); + assert_eq!(gap, if mode == crate::shell::LayoutMode::Docked { 0.0 } else { 7.0 }); + let mut options = priority_host_options(); + options.metrics.gap = gap; + options.metrics.inline_max_height = 0.0; + raw.host = WorkspacePanelHost::new(options).unwrap(); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + let initial = raw.host.frame().unwrap().layout.clone(); + let card = initial.sections.iter().find(|card| card.section == section("target")).unwrap(); + let physical_left = direction.edge(zone).unwrap() == PhysicalEdge::Left; + let side_x = if physical_left { initial.render_domain.origin.x + 12.0 } else { right(initial.render_domain) - 12.0 }; + let bottom_y = (bottom(initial.capacity) + gap).min(bottom(initial.render_domain)) - 58.0; + let (end, expected_zone) = match case { + "side-edge" => (egui::pos2(side_x, card.outer.origin.y + 80.0), zone), + "side-header" => (egui::pos2(side_x, card.header.origin.y + 10.0), zone), + "bottom-clear" => (egui::pos2(middle(card.outer).x, bottom_y), Zone::Bottom), + "corner" | "refused-bottom" => (egui::pos2(side_x, bottom_y), Zone::Bottom), + "bottom-tab" | "foreign-tab" => { + let bottom = initial.sections.iter().find(|card| card.section == section("bottom")).unwrap(); + let tab = bottom.tabs.first().unwrap().bounds; + ( + egui::pos2( + tab.origin.x + tab.size.width * if direction == Direction::Ltr { 0.25 } else { 0.75 }, + tab.origin.y + 10.0, + ), + Zone::Bottom, + ) + } + _ => ( + egui::pos2( + if physical_left { right(initial.render_domain) - 48.0 } else { initial.render_domain.origin.x + 48.0 }, + 500.0, + ), + if zone == Zone::Left { Zone::Right } else { Zone::Left }, + ), + }; + let point = Point { x: end.x, y: end.y }; + let targets = host_drop_targets(raw.content.runtime.layout(), &initial, &id("moving")).unwrap(); + let side = targets.iter().find(|target| target.id == HostDropTargetId::Dock { zone, before: None }).unwrap(); + assert_eq!(side.bounds.size.width, 16.0); + let bottom = targets.iter().find(|target| target.id == HostDropTargetId::Dock { zone: Zone::Bottom, before: None }).unwrap(); + assert_eq!(bottom.bounds.size.height, 64.0); + if matches!(case, "bottom-tab" | "foreign-tab") { + assert!( + targets.iter().any(|target| target.priority == 2 && target.bounds.contains(point)), + "the perimeter overlaps an actual measured insertion half" + ); + } else if matches!(case, "bottom-clear" | "corner" | "refused-bottom") { + assert!( + targets.iter().any(|target| matches!(target.id, HostDropTargetId::Relative { placement: RelativePlacement::Below, .. }) + && target.bounds.contains(point)) + ); + } else if matches!(case, "side-edge" | "side-header") { + assert!(targets.iter().any(|target| matches!(target.id, HostDropTargetId::Relative { .. }) && target.bounds.contains(point))); + } + if case == "refused-bottom" { + assert!(side.bounds.contains(point)); + assert!( + prepare_host_layout( + raw.content.runtime.layout(), + &host_scope(&raw.content), + &initial, + transaction(vec![Mutation::Move { instance: id("moving"), destination: side.destination.clone() }]) + ) + .is_ok(), + "a lower-priority side landing would be legal" + ); + } + let before = raw.content.runtime.layout().inspect(); + let commits = raw.content.native.commits; + let start = raw.at(HostControlTarget::Pointer(if case == "foreign-tab" { + HostPointerTarget::Tab { instance: id("moving") } + } else { + HostPointerTarget::Header { instance: id("moving") } + })); + raw.frame(vec![egui::Event::PointerMoved(start)], false); + raw.pointer(start, true, false); + if case == "empty" { + let outside = egui::pos2( + if physical_left { right(initial.render_domain) - 57.0 } else { initial.render_domain.origin.x + 57.0 }, + end.y, + ); + assert!( + raw.frame(vec![egui::Event::PointerMoved(outside)], false).0.preview.unwrap().action.is_none(), + "the empty-side reach ends at 56 logical pixels" + ); + } + let (frame, output) = raw.frame(vec![egui::Event::PointerMoved(end)], false); + let preview = frame.preview.unwrap(); + assert_eq!(raw.content.runtime.layout().inspect(), before); + assert_eq!(raw.host.frame().unwrap().layout.painted, initial.painted); + assert_eq!(raw.host.frame().unwrap().layout.input, initial.input); + assert_eq!(raw.host.frame().unwrap().layout.occlusion, initial.occlusion); + if case == "refused-bottom" { + assert_eq!(preview.target, None, "structural refusal keeps the existing empty-target semantics"); + assert!(preview.rejection.is_some() && preview.projected.is_none()); + assert!(preview.targets.is_empty()); + raw.pointer(end, false, true); + assert_eq!(raw.content.runtime.layout().inspect(), before); + assert_eq!(raw.content.native.commits, commits); + } else { + assert_eq!( + preview.target, + Some(HostDropTargetId::Dock { zone: expected_zone, before: None }), + "{scale}/{direction:?}/{zone:?}/{case}: {preview:?}" + ); + assert!(preview.rejection.is_none(), "{preview:?}"); + assert_eq!(preview.targets.len(), 1); + assert!(output_paints_rect( + &output, + preview.bounds, + Some(crate::theme::Tokens::get().form_primary.gamma_multiply(0.12)), + None + )); + let shown = preview.projected.unwrap(); + let released = raw.pointer(end, false, true); + assert_eq!(released.events.iter().filter(|event| matches!(event, HostEvent::PreparedCommitted { .. })).count(), 1); + assert_eq!(raw.content.native.commits, commits + 1); + raw.frame(Vec::new(), false); + assert_host_landing(&raw.host.frame().unwrap().layout, &shown); + raw.pointer(end, false, true); + assert_eq!(raw.content.runtime.layout().inspect().revision, before.revision + 1); + } + assert_eq!(raw.content.commands.calls, 0); + } + } + } + } +} + +#[test] +fn raw_host_perimeter_anchors_survive_source_detach_and_commit_the_exact_preview_once() { + for scale in [1.0, 2.0] { + for direction in [Direction::Ltr, Direction::Rtl] { + for zone in [Zone::Left, Zone::Right] { + for (case, inset) in [("same-column", 12.0), ("sole", 12.0), ("sole", 48.0), ("retained-tab", 12.0)] { + let mut h = host_logs(1, zone); + if case == "same-column" { + h.dispatch(vec![Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("peer"), + destination: Some(Destination::Relative { + section: section("section-0"), + placement: RelativePlacement::Below, + new_section: section("peer"), + new_column: None, + size: Size { width: 280.0, height: 240.0 }, + }), + }]) + .unwrap(); + assert_eq!( + h.runtime.layout().layout().section(§ion("section-0")).unwrap().column, + h.runtime.layout().layout().section(§ion("peer")).unwrap().column + ); + } else if case == "retained-tab" { + h.dispatch(vec![ + Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("peer"), + destination: Some(Destination::JoinTab { section: section("section-0"), index: 1 }), + }, + Mutation::Activate { instance: id("log-0") }, + ]) + .unwrap(); + } + let mut environment = h.runtime.environment().clone(); + environment.direction = direction; + h.runtime.set_environment(environment, &mut h.local).unwrap(); + let mut raw = RawPanelHost::new(h, scale); + raw.host = WorkspacePanelHost::new(priority_host_options()).unwrap(); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + let initial = raw.host.frame().unwrap().layout.clone(); + assert_eq!(initial.sections.first().unwrap().section, section("section-0")); + let physical_left = direction.edge(zone).unwrap() == PhysicalEdge::Left; + let end = egui::pos2( + if physical_left { initial.render_domain.origin.x + inset } else { right(initial.render_domain) - inset }, + initial.sections[0].outer.origin.y + 80.0, + ); + let targets = host_drop_targets(raw.content.runtime.layout(), &initial, &id("log-0")).unwrap(); + let target = targets + .iter() + .find(|target| { + target.id == HostDropTargetId::Dock { zone, before: None } && target.bounds.contains(Point { x: end.x, y: end.y }) + }) + .unwrap(); + if case == "sole" { + assert!( + matches!(&target.destination, Destination::NewSection { section: receiver, location: SectionLocation::Dock { zone: dock }, .. } + if *receiver == section("section-0") && *dock == zone) + ); + } else { + let anchor = if case == "same-column" { "peer" } else { "section-0" }; + assert!( + matches!(&target.destination, Destination::Relative { section: receiver, placement: RelativePlacement::BeforeColumn, .. } + if *receiver == section(anchor)) + ); + } + let before = raw.content.runtime.layout().inspect(); + let commits = raw.content.native.commits; + let start = raw.at(HostControlTarget::Pointer(HostPointerTarget::Header { instance: id("log-0") })); + raw.frame(vec![egui::Event::PointerMoved(start)], false); + raw.pointer(start, true, false); + let (frame, output) = raw.frame(vec![egui::Event::PointerMoved(end)], false); + let preview = frame.preview.unwrap(); + assert_eq!( + preview.target, + Some(HostDropTargetId::Dock { zone, before: None }), + "{scale}/{direction:?}/{zone:?}/{case}/{inset}: {preview:?}" + ); + assert!(preview.rejection.is_none(), "{preview:?}"); + assert_eq!(preview.targets.len(), 1); + assert!(output_paints_rect(&output, preview.bounds, Some(crate::theme::Tokens::get().form_primary.gamma_multiply(0.12)), None)); + let shown = preview.projected.unwrap(); + assert_eq!(raw.content.runtime.layout().inspect(), before); + assert_eq!(raw.content.native.commits, commits); + assert_eq!(raw.host.frame().unwrap().layout.painted, initial.painted); + assert_eq!(raw.host.frame().unwrap().layout.input, initial.input); + assert_eq!(raw.host.frame().unwrap().layout.occlusion, initial.occlusion); + let released = raw.pointer(end, false, true); + assert_eq!(released.events.iter().filter(|event| matches!(event, HostEvent::PreparedCommitted { .. })).count(), 1); + assert_eq!(raw.content.native.commits, commits + 1); + raw.frame(Vec::new(), false); + assert_host_landing(&raw.host.frame().unwrap().layout, &shown); + raw.pointer(end, false, true); + assert_eq!(raw.content.native.commits, commits + 1); + let expected_revision = if case == "sole" { before.revision } else { before.revision + 1 }; + assert_eq!(raw.content.runtime.layout().inspect().revision, expected_revision); + assert_eq!(raw.content.commands.calls, 0); + } + } + } + } +} + +#[test] +fn raw_host_drag_and_pair_resize_dispatch_once_even_when_egui_repeats_the_release_pass() { + for (mode, resize) in + [(crate::shell::LayoutMode::Floating, false), (crate::shell::LayoutMode::Floating, true), (crate::shell::LayoutMode::Docked, true)] + { + let h = host_logs(2, Zone::Left); + let mut raw = RawPanelHost::new(h, 2.0); + mode.publish(&raw.ctx); + let gap = crate::ui_kit::Container::for_layout(mode, crate::ui_kit::Surface::Panel).gap(); + raw.host = WorkspacePanelHost::new(HostOptions { metrics: HostMetrics { gap, ..HostMetrics::default() }, ..HostOptions::default() }).unwrap(); + raw.frame(Vec::new(), false); + let target = if resize { + HostPointerTarget::Sash { first: section("section-0"), second: section("section-1") } + } else { + HostPointerTarget::Header { instance: id("log-0") } + }; + let start = raw.at(HostControlTarget::Pointer(target.clone())); + if resize { + let sash = raw_control(&raw, &HostControlTarget::Pointer(target)); + let layer = raw.ctx.read_response(sash.id).unwrap().layer_id; + assert_eq!(Some(layer), raw.root_layer, "dock cards and their sash share the root layer in both shell modes"); + assert_eq!(raw.ctx.layer_id_at(start), Some(layer), "the compact zero-gap seam retains its actual widget layer"); + } + let end = if resize { start + egui::vec2(0.0, 30.0) } else { egui::pos2(1399.0, 600.0) }; + let before = raw.content.runtime.layout().inspect(); + raw.pointer(start, true, false); + raw.frame(vec![egui::Event::PointerMoved(end)], false); + assert_eq!(raw.content.runtime.layout().inspect(), before); + let shown = raw.host.frame().unwrap().preview.clone().unwrap(); + let frame = raw.pointer(end, false, true); + assert_eq!(raw.content.runtime.layout().inspect().revision, before.revision + 1); + assert_eq!(frame.events.iter().filter(|event| matches!(event, HostEvent::PreparedCommitted { .. })).count(), 1); + let action = shown.action.as_ref().unwrap(); + assert!(if resize { + matches!(one_mutation(action), Mutation::ResizePair { .. }) + } else { + matches!(one_mutation(action), Mutation::Move { .. }) + }); + raw.frame(Vec::new(), true); + assert_eq!(raw.content.runtime.layout().inspect().revision, before.revision + 1); + assert_eq!(raw.content.commands.calls, 0); + } +} + +#[test] +fn raw_host_sash_double_click_resets_neighbours_through_actual_egui_responses() { + let mut h = host_logs(2, Zone::Bottom); + h.dispatch(vec![Mutation::ResizePair { + first: section("section-0"), + second: section("section-1"), + first_size: Size { width: 360.0, height: 240.0 }, + second_size: Size { width: 200.0, height: 240.0 }, + }]) + .unwrap(); + let mut raw = RawPanelHost::new(h, 1.0); + raw.frame(Vec::new(), false); + let target = HostControlTarget::Pointer(HostPointerTarget::Sash { first: section("section-0"), second: section("section-1") }); + raw.click(target.clone(), false); + raw.click(target, false); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + let sections = &raw.content.runtime.layout().layout().sections; + assert_eq!( + (sections[0].size.width, sections[1].size.width), + (698.0, 698.0), + "reset splits the actual 1396-point allocation at the default ratio" + ); + assert_eq!((sections[0].size.height, sections[1].size.height), (240.0, 240.0)); + assert_eq!(raw.host.frame().unwrap().layout.sections.iter().map(|card| card.outer.size.width).collect::>(), vec![698.0, 698.0]); + assert_eq!(raw.content.commands.calls, 0); +} + +#[test] +fn host_tiny_capacity_preserves_collapsed_headers_in_a_bounded_nonoverlapping_scroll_extent() { + let mut h = host_logs(1, Zone::Left); + h.dispatch(vec![ + fixture_open("fixture.log", "right", "right", Zone::Right, 1).unwrap(), + fixture_open("fixture.log", "bottom", "bottom", Zone::Bottom, 2).unwrap(), + ]) + .unwrap(); + h.dispatch( + h.runtime.layout().layout().sections.iter().map(|section| Mutation::Collapse { section: section.id.clone(), collapsed: true }).collect(), + ) + .unwrap(); + for (width, height) in [(32.0, 160.0), (1.0, 1.0)] { + let layout = host_layout(&h, width, height, Direction::Ltr); + assert_eq!(layout.sections.len(), 3); + assert!(layout.sections.iter().all(|section| section.collapsed && section.body.is_none() && section.outer == section.header)); + assert!(layout.overflow.is_empty() && layout.overflow_launcher.is_none() && layout.rails.is_empty()); + assert!(layout.extent.width > width); + for bounds in layout.painted.iter().chain(&layout.input).chain(&layout.occlusion) { + assert!(layout.capacity.contains_rect(*bounds)); + } + for (index, first) in layout.sections.iter().enumerate() { + for second in layout.sections.iter().skip(index + 1) { + assert!(!egui_rect(first.outer).intersect(egui_rect(second.outer)).is_positive()); + } + } + } +} +#[test] +fn raw_host_bounded_scroll_reaches_the_last_minimum_header_and_its_shared_actions() { + let mut h = host_logs(24, Zone::Left); + h.dispatch((0..24).map(|index| Mutation::Collapse { section: section(&format!("section-{index}")), collapsed: true }).collect()).unwrap(); + let mut raw = RawPanelHost::new(h, 2.0); + raw.capacity.size = Size { width: 480.0, height: 320.0 }; + raw.frame(Vec::new(), false); + let before = raw.content.runtime.layout().inspect(); + let track = raw.host.frame().unwrap().controls.iter().find(|control| control.target == HostControlTarget::Scroll { horizontal: false }).unwrap(); + assert!(track.bounds.size.width < raw.capacity.size.width / 10.0, "scroll input must not shield the canvas"); + let at = egui_rect(track.bounds).center_bottom() - egui::vec2(0.0, 1.0); + raw.pointer(at, true, false); + raw.pointer(at, false, false); + raw.frame(Vec::new(), false); + assert_eq!(raw.content.runtime.layout().inspect(), before, "presentation scroll is not layout state"); + let target = HostControlTarget::Pointer(HostPointerTarget::Menu { instance: id("log-23") }); + let header = raw_control(&raw, &target); + assert!(egui_rect(header.bounds).is_positive() && egui_rect(raw.capacity).contains_rect(egui_rect(header.bounds))); + raw.menu(id("log-23")); + assert!( + raw.host + .frame() + .unwrap() + .controls + .iter() + .any(|control| control.target == HostControlTarget::Shared { instance: id("log-23"), action: HostSharedAction::Collapse }) + ); + assert_eq!(raw.content.runtime.controller_count(), 24); + assert_eq!(raw.content.commands.calls, 0); +} +#[test] +fn host_tab_overflow_accounts_for_every_tab_and_preserves_active_selection() { + let mut h = host_logs(1, Zone::Left); + for index in 1..MAX_TABS { + h.dispatch(vec![Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id(&format!("log-{index}")), + destination: Some(Destination::JoinTab { section: section("section-0"), index }), + }]) + .unwrap(); + } + h.dispatch(vec![ + Mutation::Activate { instance: id("log-31") }, + Mutation::SetSize { section: section("section-0"), size: Size { width: 160.0, height: 240.0 } }, + ]) + .unwrap(); + for collapsed in [false, true] { + h.dispatch(vec![Mutation::Collapse { section: section("section-0"), collapsed }]).unwrap(); + for direction in [Direction::Ltr, Direction::Rtl] { + let layout = host_layout(&h, 800.0, 600.0, direction); + assert_host_geometry(&h, &layout); + let group = &layout.sections[0]; + let overflow = group.tab_overflow.expect("compact overflow stays reachable"); + assert_eq!(overflow.size.width, layout.metrics.control_extent); + assert_eq!(group.tabs.len() + group.hidden_tabs.len(), MAX_TABS); + let all = + group.tabs.iter().map(|tab| tab.instance.clone()).chain(group.hidden_tabs.iter().cloned()).collect::>(); + assert_eq!(all.len(), MAX_TABS, "neither truncation nor duplicated active tab"); + assert!(group.tabs.iter().any(|tab| tab.instance == id("log-31")), "active tab fits beside compact overflow"); + assert_eq!(layout.resolved.panels[0].instance, id("log-31")); + assert_eq!(group.tab_strip.unwrap().origin.y, group.header.origin.y); + let grip = group.title.unwrap(); + assert_eq!( + if direction == Direction::Ltr { grip.origin.x } else { right(grip) }, + if direction == Direction::Ltr { group.header.origin.x } else { right(group.header) } + ); + } + } +} + +type HostSlotTrace = std::rc::Rc, egui::Rect)>>>; + +struct LongPanelChrome { + inner: Box, + slots: HostSlotTrace, +} + +#[derive(Default)] +struct LeafInputState { + body_text: String, + overlay_text: String, + popup_text: String, + body: Option, + overlay: Option, + popup: Option, +} +type LeafInputProbe = std::rc::Rc>>; + +/// Reuse the existing controller's lifecycle/commands and add real text-edit +/// leaves. Input ownership comes from their actual egui responses and the same +/// local Overlay requests a controller uses in production. +struct LeafInputController { + inner: Box, + leaves: LeafInputProbe, +} + +impl PanelController for LeafInputController { + 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) + } + fn presentation(&self) -> PanelPresentation { + self.inner.presentation() + } + fn prepare_lifecycle(&self, event: &LifecycleEvent) -> PanelResult<()> { + self.inner.prepare_lifecycle(event) + } + fn lifecycle(&mut self, event: &LifecycleEvent) { + self.inner.lifecycle(event); + } + fn action(&mut self, owner: &ContentOwner, action: &ControlId, services: &mut ContentServices<'_>) -> PanelResult<()> { + self.inner.action(owner, action, services) + } + fn render(&mut self, slot: ContentSlot, ui: &mut egui::Ui, context: &PanelContext, services: &mut ContentServices<'_>) -> PanelResult<()> { + self.inner.render(slot, ui, context, services)?; + if slot != ContentSlot::Body || !ui.is_visible() || ui.is_sizing_pass() { + return Ok(()); + } + let mut leaves = self.leaves.borrow_mut(); + let leaf = leaves.entry(context.instance.clone()).or_default(); + leaf.body = Some(crate::ui_kit::cell_editor(ui, ui.scope_id().with("actual_body_leaf"), &mut leaf.body_text, "Body text", false)); + let scope = LocalScope { workspace: context.workspace.clone(), document: context.document.clone(), viewport: context.viewport.clone() }; + let region = if context.instance == id("document-body") { + // This second controller's overlay is an actual leaf on its mounted + // Surface layer; it is outside the current left-hand Peek. + let response = + crate::ui_kit::cell_editor(ui, ui.scope_id().with("actual_other_overlay"), &mut leaf.overlay_text, "Other owner overlay text", false); + let bounds = logical_rect(response.rect); + leaf.overlay = Some(response); + Some(bounds) + } else if context.instance == id("editor") { + // A current-Peek-owned popup extends beyond the card, with explicit + // local-service metadata rather than title/geometry-based ownership. + let bounds = LogicalRect { origin: Point { x: 440.0, y: 650.0 }, size: Size { width: 220.0, height: 90.0 } }; + let container = crate::ui_kit::Container::new(ui.ctx(), crate::ui_kit::Surface::Popup); + let frame = crate::ui_kit::Container::menu_frame(); + container + .area(ui.scope_id().with("actual_owned_overlay")) + .order(egui::Order::Foreground) + .fixed_pos(egui_rect(bounds).min) + .movable(false) + .constrain(false) + .fade_in(false) + .show(ui.ctx(), |ui| { + ui.set_min_size(egui_rect(bounds).size()); + container.show_frame(ui, frame, egui_rect(bounds), |ui| { + leaf.overlay = Some(crate::ui_kit::cell_editor( + ui, + ui.scope_id().with("actual_owned_overlay_leaf"), + &mut leaf.overlay_text, + "Peek owner overlay text", + false, + )); + }); + }); + Some(bounds) + } else { + None + }; + if let Some(bounds) = region { + services.local.request( + &scope, + LocalRequest::Overlay { + instance: context.instance.clone(), + region: InputRegion { + control: ControlId::new("actual-leaf-overlay")?, + role: InputRole::Overlay, + bounds, + keyboard_focusable: true, + accessible_name: format!("Owned overlay for {}", context.instance.0), + }, + }, + )?; + } + if context.instance == id("document-body") { + let bounds = LogicalRect { origin: Point { x: 800.0, y: 650.0 }, size: Size { width: 220.0, height: 90.0 } }; + let container = crate::ui_kit::Container::new(ui.ctx(), crate::ui_kit::Surface::Popup); + let frame = crate::ui_kit::Container::menu_frame(); + let mut layer = None; + container + .area(ui.scope_id().with("actual_other_floating_overlay")) + .order(egui::Order::Foreground) + .fixed_pos(egui_rect(bounds).min) + .movable(false) + .constrain(false) + .fade_in(false) + .show(ui.ctx(), |ui| { + ui.set_min_size(egui_rect(bounds).size()); + if !ui.is_visible() || ui.is_sizing_pass() { + return; + } + container.show_frame(ui, frame, egui_rect(bounds), |ui| { + let response = crate::ui_kit::cell_editor( + ui, + ui.scope_id().with("actual_other_popup_leaf"), + &mut leaf.popup_text, + "Other owner floating overlay text", + false, + ); + layer = Some(response.layer_id); + leaf.popup = Some(response); + }); + }); + if let Some(layer) = layer { + services.local.request_overlay_layer( + &scope, + &context.instance, + InputRegion { + control: ControlId::new("actual-floating-leaf-overlay")?, + role: InputRole::Overlay, + bounds, + keyboard_focusable: true, + accessible_name: "Other owner's actual floating overlay".into(), + }, + layer, + )?; + } + } + Ok(()) + } +} + +fn raw_leaf_fixture(scale: f32) -> (RawPanelHost, LeafInputProbe) { + let mut content = PanelMountHarness::without_content(false).unwrap(); + let leaves = LeafInputProbe::default(); + for kind in ["fixture.editor", "fixture.log"] { + let create = fixture_controller_binding(&content.probe, true, Ownership::Document).create; + let trace = leaves.clone(); + content + .runtime + .register( + PanelKind::new(kind).unwrap(), + ControllerBinding { + ownership: Ownership::Document, + create: Box::new(move |instance, owner| { + Ok(Box::new(LeafInputController { inner: create(instance, owner)?, leaves: trace.clone() })) + }), + }, + ) + .unwrap(); + } + open_editor(&mut content); + content + .dispatch(vec![ + fixture_open("fixture.log", "document-body", "document-body-section", Zone::Right, 0).unwrap(), + fixture_open("fixture.log", "next-header", "next-header-section", Zone::Left, 1).unwrap(), + Mutation::SetSize { section: section("document-body-section"), size: Size { width: 320.0, height: 360.0 } }, + Mutation::Collapse { section: section("editor-section"), collapsed: true }, + Mutation::Collapse { section: section("next-header-section"), collapsed: true }, + ]) + .unwrap(); + let scope = host_scope(&content); + for instance in &content.runtime.layout().layout().instances { + content.local.bind(instance.id.clone(), scope.clone()).unwrap(); + } + let key = editor_key(&content); + content.probe.edit(&key, |state| state.draft = "Expanded content retains this independent edit".into()).unwrap(); + let mut raw = RawPanelHost::new(content, scale); + raw.bind_fixture_scopes = true; + raw.prime_foreign_window(); + raw.frame(Vec::new(), false); + raw.click(HostControlTarget::Pointer(HostPointerTarget::Collapse { instance: id("editor") }), false); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + assert!(!raw.content.runtime.layout().layout().containing(&id("editor")).unwrap().collapsed); + assert!(leaves.borrow()[&id("editor")].body.as_ref().unwrap().enabled()); + assert!(leaves.borrow()[&id("editor")].overlay.as_ref().unwrap().enabled()); + let popup = leaves.borrow()[&id("document-body")].popup.clone().expect("the other controller must paint its actual floating text editor"); + assert!(popup.enabled()); + assert!( + raw.host.frame().unwrap().layout.sections.iter().all(|card| !egui_rect(card.outer).contains(popup.rect.center())), + "the proven overlay is outside both mounted cards" + ); + (raw, leaves) +} + +#[derive(Clone, Copy, Debug)] +enum LeafRoute { + OtherBody, + CurrentBody, + OwnOverlay, + OtherOverlay, + OtherPopup, + OtherApply, + ForeignWindow, + WarmedPopupCover, + LatePopupCover, + NextHeader, +} + +#[test] +fn real_body_and_overlay_leaves_keep_input_and_retained_headers_under_foreign_layers() { + for scale in [1.0, 2.0] { + for route in [ + LeafRoute::OtherBody, + LeafRoute::CurrentBody, + LeafRoute::OwnOverlay, + LeafRoute::OtherOverlay, + LeafRoute::OtherPopup, + LeafRoute::OtherApply, + LeafRoute::ForeignWindow, + LeafRoute::WarmedPopupCover, + LeafRoute::LatePopupCover, + LeafRoute::NextHeader, + ] { + let (mut raw, leaves) = raw_leaf_fixture(scale); + let owner = if matches!(route, LeafRoute::CurrentBody | LeafRoute::OwnOverlay) { id("editor") } else { id("document-body") }; + let leaf = match route { + LeafRoute::OtherApply | LeafRoute::NextHeader => None, + LeafRoute::OwnOverlay | LeafRoute::OtherOverlay => leaves.borrow()[&owner].overlay.clone(), + LeafRoute::OtherPopup | LeafRoute::WarmedPopupCover | LeafRoute::LatePopupCover => leaves.borrow()[&owner].popup.clone(), + _ => leaves.borrow()[&owner].body.clone(), + }; + let at = match route { + LeafRoute::OtherApply => { + raw.at(HostControlTarget::Content { instance: id("document-body"), action: ControlId::new("apply").unwrap() }) + } + LeafRoute::NextHeader => raw.at(HostControlTarget::Pointer(HostPointerTarget::Collapse { instance: id("next-header") })), + _ => leaf.as_ref().unwrap().rect.center(), + }; + raw.frame(vec![egui::Event::PointerMoved(at)], false); + if matches!(route, LeafRoute::ForeignWindow | LeafRoute::WarmedPopupCover) { + raw.foreign_cover = Some(egui::Rect::from_center_size(at, egui::vec2(140.0, 70.0))); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + } + let editor = editor_key(&raw.content); + let other = ControllerKey { instance: id("document-body"), owner: raw.content.runtime.instance_owner(&id("document-body")).unwrap() }; + let prior_editor = raw.content.probe.state(&editor).unwrap(); + let prior_other = raw.content.probe.state(&other).unwrap(); + let before = raw.content.runtime.layout().inspect(); + let commits = raw.content.native.commits; + let expected = if matches!(route, LeafRoute::NextHeader) { + raw.content + .runtime + .layout() + .project(LayoutAction::Apply { + expected_revision: Some(before.revision), + mutations: vec![Mutation::Collapse { section: section("next-header-section"), collapsed: false }], + }) + .unwrap() + } else { + before.layout.clone() + }; + if matches!(route, LeafRoute::LatePopupCover) { + raw.foreign_cover = Some(egui::Rect::from_center_size(at, egui::vec2(140.0, 70.0))); + } + raw.pointer(at, true, false); + assert_eq!(raw.content.runtime.layout().inspect(), before, "press alone never changes panel placement"); + if let Some(leaf) = &leaf { + let actual = raw.ctx.read_response(leaf.id).unwrap(); + if matches!(route, LeafRoute::ForeignWindow | LeafRoute::WarmedPopupCover) { + assert!(!actual.is_pointer_button_down_on()); + assert!(raw.foreign_responses.iter().any(egui::Response::is_pointer_button_down_on)); + } else if !matches!(route, LeafRoute::LatePopupCover) { + assert!(actual.is_pointer_button_down_on(), "actual leaf receives {route:?}"); + assert_eq!(raw.ctx.memory(|memory| memory.focused()), Some(leaf.id)); + } + } + raw.pointer(at, false, true); + if let Some(leaf) = &leaf + && !matches!(route, LeafRoute::ForeignWindow | LeafRoute::WarmedPopupCover | LeafRoute::LatePopupCover) + { + raw.frame(vec![egui::Event::Text("typed into the real leaf".into())], false); + assert_eq!(raw.ctx.memory(|memory| memory.focused()), Some(leaf.id)); + let inputs = leaves.borrow(); + let value = &inputs[&owner]; + let text = if matches!(route, LeafRoute::OwnOverlay | LeafRoute::OtherOverlay) { + &value.overlay_text + } else if matches!(route, LeafRoute::OtherPopup) { + &value.popup_text + } else { + &value.body_text + }; + assert_eq!(text, "typed into the real leaf"); + } + raw.pointer(at, false, true); + raw.frame(Vec::new(), true); + let restored = matches!(route, LeafRoute::NextHeader); + assert_eq!(raw.content.runtime.layout().inspect().revision, before.revision + u64::from(restored)); + assert_eq!(raw.content.runtime.layout().layout(), &expected); + assert_eq!(raw.content.native.commits, commits + u64::from(restored)); + assert!(!raw.host.interaction().is_captured()); + assert_eq!(raw.content.commands.calls, u64::from(matches!(route, LeafRoute::OtherApply))); + for (key, prior) in [(&editor, &prior_editor), (&other, &prior_other)] { + let after = raw.content.probe.state(key).unwrap(); + assert_eq!(after.draft, prior.draft); + assert_eq!( + (after.reparents, after.cancels, after.finishes, after.destroys), + (prior.reparents, prior.cancels, prior.finishes, prior.destroys) + ); + assert!(after.transaction_live); + } + } + } +} +fn scroll_real_host_popup_to_end(raw: &mut RawPanelHost) { + let at = egui_rect(raw.host.frame().unwrap().menu_bounds.unwrap()).center(); + raw.frame( + vec![ + egui::Event::PointerMoved(at), + egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -3000.0), + modifiers: egui::Modifiers::NONE, + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + }, + ], + false, + ); + for _ in 0..12 { + raw.frame(Vec::new(), false); + } +} + +#[derive(Clone, Copy, Debug)] +enum MenuRoute { + CurrentPanelApply, + CurrentTabs, + OtherMove, + KeyboardMove, + OtherApply, + CloseRefusal, + LateWindow, + LateModal, + OtherHeaderMenu, +} + +#[test] +fn actual_popup_actions_preserve_retained_owners_and_respect_late_layers_and_lifecycle_refusals() { + for scale in [1.0, 2.0] { + for route in [ + MenuRoute::CurrentPanelApply, + MenuRoute::CurrentTabs, + MenuRoute::OtherMove, + MenuRoute::KeyboardMove, + MenuRoute::OtherApply, + MenuRoute::CloseRefusal, + MenuRoute::LateWindow, + MenuRoute::LateModal, + MenuRoute::OtherHeaderMenu, + ] { + let (mut raw, _) = raw_leaf_fixture(scale); + if matches!(route, MenuRoute::LateModal) { + raw.prime_modal(); + } + if matches!(route, MenuRoute::CurrentTabs) { + let mut mutations = (0..8) + .map(|index| Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id(&format!("retained-tab-{index}")), + destination: Some(Destination::JoinTab { section: section("editor-section"), index: index + 1 }), + }) + .collect::>(); + mutations.push(Mutation::Activate { instance: id("editor") }); + raw.content.dispatch(mutations).unwrap(); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + raw.click(HostControlTarget::Pointer(HostPointerTarget::TabOverflow { section: section("editor-section") }), false); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + } else { + raw.menu(if matches!(route, MenuRoute::CurrentPanelApply) { + id("editor") + } else if matches!(route, MenuRoute::OtherHeaderMenu) { + id("next-header") + } else { + id("document-body") + }); + } + assert!(raw.host.frame().unwrap().menu_bounds.is_some()); + if matches!(route, MenuRoute::CurrentPanelApply | MenuRoute::OtherApply | MenuRoute::CloseRefusal) { + scroll_real_host_popup_to_end(&mut raw); + } + let target = match route { + MenuRoute::CurrentPanelApply => HostControlTarget::Content { instance: id("editor"), action: ControlId::new("apply").unwrap() }, + MenuRoute::CurrentTabs => HostControlTarget::PanelMenu { instance: id("editor") }, + MenuRoute::OtherApply => HostControlTarget::Content { instance: id("document-body"), action: ControlId::new("apply").unwrap() }, + MenuRoute::CloseRefusal => HostControlTarget::Shared { instance: id("document-body"), action: HostSharedAction::Close }, + MenuRoute::OtherHeaderMenu => HostControlTarget::Shared { instance: id("next-header"), action: HostSharedAction::Collapse }, + _ => HostControlTarget::Shared { instance: id("document-body"), action: HostSharedAction::Move(Zone::Bottom) }, + }; + let frame = raw.host.frame().unwrap(); + let menu = frame.menu_bounds.unwrap(); + let source = frame + .controls + .iter() + .find(|control| { + control.target == target + && menu.contains_rect(control.bounds) + && raw.ctx.read_response(control.id).is_some_and(|response| response.layer_id.order == egui::Order::Foreground) + }) + .unwrap() + .clone(); + assert!(source.enabled); + let editor = editor_key(&raw.content); + let other = ControllerKey { instance: id("document-body"), owner: raw.content.runtime.instance_owner(&id("document-body")).unwrap() }; + if matches!(route, MenuRoute::CloseRefusal) { + raw.content.probe.edit(&other, |state| state.reject_cancel = true).unwrap(); + } + let old_editor = raw.content.probe.state(&editor).unwrap(); + let old_other = raw.content.probe.state(&other).unwrap(); + let before = raw.content.runtime.layout().inspect(); + let commits = raw.content.native.commits; + let at = egui_rect(source.bounds).center(); + let keyboard = matches!(route, MenuRoute::KeyboardMove); + if keyboard { + raw.ctx.memory_mut(|memory| memory.request_focus(source.id)); + raw.frame(Vec::new(), false); + } else { + raw.frame(vec![egui::Event::PointerMoved(at)], false); + raw.pointer(at, true, false); + assert_eq!(raw.content.runtime.layout().inspect(), before); + assert!(raw.ctx.read_response(source.id).unwrap().is_pointer_button_down_on()); + } + if matches!(route, MenuRoute::LateWindow) { + raw.foreign_cover = Some(egui::Rect::from_center_size(at, egui::vec2(140.0, 60.0))); + } + if matches!(route, MenuRoute::LateModal) { + raw.late_modal = true; + } + let released = raw + .frame( + if keyboard { vec![host_key(egui::Key::Enter, true)] } else { vec![egui::Event::PointerMoved(at), button_event(at, false)] }, + true, + ) + .0; + let rejected = matches!(route, MenuRoute::CloseRefusal | MenuRoute::LateWindow | MenuRoute::LateModal); + let structural = !rejected && matches!(route, MenuRoute::OtherMove | MenuRoute::KeyboardMove | MenuRoute::OtherHeaderMenu); + assert_eq!(raw.content.runtime.layout().inspect().revision, before.revision + u64::from(structural)); + assert_eq!(raw.content.native.commits, commits + u64::from(structural)); + if structural { + assert_eq!(released.events.iter().filter(|event| matches!(event, HostEvent::Committed { .. })).count(), 1); + if matches!(route, MenuRoute::OtherHeaderMenu) { + assert!(!raw.content.runtime.layout().layout().containing(&id("next-header")).unwrap().collapsed); + } else { + assert_eq!(raw.content.runtime.layout().layout().containing(&id("document-body")).unwrap().location.zone(), Zone::Bottom); + } + } else { + assert_eq!(raw.content.runtime.layout().inspect(), before); + } + if matches!(route, MenuRoute::CloseRefusal) { + assert!(released.events.iter().any(|event| matches!(event, HostEvent::Rejected { error, .. } if error.rule == Rule::Lifecycle))); + } + let apply_editor = matches!(route, MenuRoute::CurrentPanelApply); + let apply_other = matches!(route, MenuRoute::OtherApply); + assert_eq!(raw.content.commands.calls, u64::from(apply_editor || apply_other)); + assert_eq!(raw.content.probe.state(&editor).unwrap().applies, old_editor.applies + u64::from(apply_editor)); + assert_eq!(raw.content.probe.state(&other).unwrap().applies, old_other.applies + u64::from(apply_other)); + for (key, prior) in [(&editor, &old_editor), (&other, &old_other)] { + let state = raw.content.probe.state(key).unwrap(); + assert_eq!(state.draft, prior.draft); + assert_eq!((state.cancels, state.finishes, state.destroys), (prior.cancels, prior.finishes, prior.destroys)); + assert!(state.transaction_live); + } + raw.foreign_cover = None; + raw.late_modal = false; + raw.frame(vec![host_key(egui::Key::Enter, false)], false); + raw.pointer(at, false, true); + raw.frame(Vec::new(), true); + assert_eq!(raw.content.runtime.layout().inspect().revision, before.revision + u64::from(structural)); + assert_eq!(raw.content.commands.calls, u64::from(apply_editor || apply_other)); + } + } +} +impl PanelController for LongPanelChrome { + 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) + } + fn presentation(&self) -> PanelPresentation { + let mut presentation = self.inner.presentation(); + presentation.title = "日本語の長いパネル名 العربية עברית ".repeat(3); + for action in &mut presentation.actions { + action.label = format!("{} {}", action.id.0, "Long localized action 日本語 العربية ".repeat(3)); + } + // Dynamic availability must reach both the footer and shared action menu. + let finish = presentation.actions.iter_mut().find(|action| action.id.0 == "finish").unwrap(); + finish.enabled = false; + finish.disabled_reason = Some("Synthetic unavailable content action".into()); + presentation + } + 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.slots.borrow_mut().push((slot, context.flow, context.usable_body, ui.clip_rect())); + self.inner.render(slot, ui, context, services) + } + fn action(&mut self, owner: &ContentOwner, action: &ControlId, services: &mut ContentServices<'_>) -> PanelResult<()> { + self.inner.action(owner, action, services) + } +} + +fn host_with_slot_trace() -> (PanelMountHarness, HostSlotTrace) { + let mut h = PanelMountHarness::without_content(false).unwrap(); + let binding = fixture_controller_binding(&h.probe, true, Ownership::Document); + let create = binding.create; + let slots = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let trace = slots.clone(); + h.runtime + .register( + PanelKind::new("fixture.editor").unwrap(), + ControllerBinding { + ownership: Ownership::Document, + create: Box::new(move |instance, owner| Ok(Box::new(LongPanelChrome { inner: create(instance, owner)?, slots: trace.clone() }))), + }, + ) + .unwrap(); + open_editor(&mut h); + (h, slots) +} + +#[test] +fn raw_host_long_localized_chrome_keeps_slots_bounded_and_exposes_scrolled_and_disabled_actions() { + for scale in [1.0, 2.0] { + let (mut h, slots) = host_with_slot_trace(); + h.dispatch(vec![Mutation::SetSize { section: section("editor-section"), size: Size { width: 160.0, height: 120.0 } }]).unwrap(); + let mut raw = RawPanelHost::new(h, scale); + raw.frame(Vec::new(), false); + assert!( + raw.host + .frame() + .unwrap() + .controls + .iter() + .any(|control| control.target == HostControlTarget::Pointer(HostPointerTarget::Menu { instance: id("editor") })), + "long title cannot cover the menu" + ); + for (_, _, body, clip) in slots.borrow().iter() { + assert!(clip.is_finite() && clip.is_positive()); + let outer = raw.host.frame().unwrap().layout.sections[0].outer; + if let Some(body) = body { + assert!(outer.contains_rect(*body)); + } + assert!( + egui::Rect::from_min_size(egui::pos2(outer.origin.x, outer.origin.y), egui::vec2(outer.size.width, outer.size.height)) + .contains_rect(*clip) + ); + } + raw.menu(id("editor")); + let bounds = raw.host.frame().unwrap().menu_bounds.unwrap(); + let at = middle(bounds); + raw.frame( + vec![ + egui::Event::PointerMoved(egui::pos2(at.x, at.y)), + egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -3000.0), + modifiers: egui::Modifiers::NONE, + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + }, + ], + false, + ); + for _ in 0..24 { + raw.frame(Vec::new(), false); + } + let finish = HostControlTarget::Content { instance: id("editor"), action: ControlId::new("finish").unwrap() }; + assert!( + raw.host.frame().unwrap().controls.iter().any(|control| control.target == finish && !control.enabled), + "disabled actions stay inspectable after menu scroll" + ); + raw.click(finish, false); + assert_eq!(raw.content.probe.state(&editor_key(&raw.content)).unwrap().finishes, 0); + assert_eq!(raw.content.commands.calls, 0); + } +} + +#[test] +fn raw_host_floating_tall_and_wide_content_receives_logical_body_and_retains_controller_identity() { + let (mut h, slots) = host_with_slot_trace(); + h.dispatch(vec![move_editor(Zone::Floating)]).unwrap(); + let key = editor_key(&h); + let mut raw = RawPanelHost::new(h, 2.0); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + let count = raw.content.runtime.controller_count(); + for (size, flow) in [(Size { width: 240.0, height: 600.0 }, Flow::Tall), (Size { width: 600.0, height: 240.0 }, Flow::Wide)] { + raw.content.dispatch(vec![Mutation::SetSize { section: section("editor-moved"), size }]).unwrap(); + slots.borrow_mut().clear(); + let (frame, _) = raw.frame(Vec::new(), false); + let geometry = &frame.layout.resolved.panels[0]; + assert_eq!(geometry.outer.size, size, "logical dimensions are not multiplied by scale"); + assert!(geometry.outer.contains_rect(geometry.body.unwrap())); + let trace = slots.borrow(); + assert!(trace.iter().any(|(slot, _, _, _)| *slot == ContentSlot::Body)); + assert!(trace.iter().all(|(_, actual_flow, body, _)| *actual_flow == flow && *body == geometry.body)); + assert_eq!(raw.content.runtime.controller_count(), count); + assert_eq!(raw.content.probe.state(&key).unwrap().cancels, 0); + assert!(raw.content.probe.state(&key).unwrap().transaction_live); + assert_eq!(frame.layout.viewport, Some(frame.layout.render_domain)); + assert!(frame.layout.reservations.contains(&geometry.outer), "a visible floating card occupies usable space without cropping rendering"); + assert!(!frame.layout.usable.contains_rect(geometry.outer)); + } +} + +#[test] +fn raw_host_combined_native_dpi_and_ui_zoom_apply_scale_once_to_geometry_and_threshold() { + let h = host_logs(1, Zone::Right); + let mut raw = RawPanelHost::new(h, 1.0); + raw.native_pixels_per_point = Some(2.0); + raw.ctx.set_zoom_factor(1.5); + let (frame, output) = raw.frame(Vec::new(), false); + assert_eq!(output.pixels_per_point, 3.0, "exercise native DPI and UI zoom together"); + assert_eq!(frame.layout.sections[0].outer.size, Size { width: 280.0, height: 240.0 }); + let at = raw.at(HostControlTarget::Pointer(HostPointerTarget::Header { instance: id("log-0") })); + raw.pointer(at, true, false); + assert!(raw.frame(vec![egui::Event::PointerMoved(at + egui::vec2(5.99, 0.0))], false).0.preview.is_none()); + assert!(raw.frame(vec![egui::Event::PointerMoved(at + egui::vec2(6.0, 0.0))], false).0.preview.is_some()); + assert_eq!(raw.content.runtime.layout().layout().sections[0].size, Size { width: 280.0, height: 240.0 }); +} + +#[test] +fn host_intersected_minimum_and_maximum_are_honoured_at_the_exact_capacity_boundary() { + let mut h = host_with_specs(|spec| { + if spec.kind.0 == "fixture.editor" { + spec.max_size = Size { width: 300.0, height: 400.0 }; + } + if spec.kind.0 == "fixture.log" { + spec.min_size = Size { width: 200.0, height: 180.0 }; + } + }); + open_editor(&mut h); + h.dispatch(vec![ + Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("log"), + destination: Some(Destination::JoinTab { section: section("editor-section"), index: 1 }), + }, + Mutation::SetSize { section: section("editor-section"), size: Size { width: 200.0, height: 180.0 } }, + ]) + .unwrap(); + let metrics = HostMetrics { header_height: 16.0, footer_height: 16.0, ..HostMetrics::default() }; + let before = h.runtime.layout().inspect(); + // Minima remain mounted on a clipped scroll canvas, with no invented + // central viewport reservation and no hidden overflow replacement. + for width in [200.0, 199.0, 160.0] { + let capacity = LogicalRect { origin: Point { x: 0.0, y: 0.0 }, size: Size { width, height: 180.0 } }; + let layout = resolve_host_layout(h.runtime.layout(), capacity, Direction::Ltr, metrics, &fixture_metric_policy(h.runtime.layout())).unwrap(); + assert_eq!(layout.resolved.panels.len(), 1); + assert_eq!(layout.extent.width, 200.0_f32.max(width)); + assert_eq!(layout.resolved.panels[0].outer.size.width, 200.0); + assert_eq!(layout.viewport, Some(capacity)); + assert!(layout.resolved.panels[0].painted.iter().all(|bounds| intersect_rect(capacity, *bounds) == Some(*bounds))); + assert_eq!(h.runtime.layout().inspect(), before); + } + h.dispatch(vec![Mutation::SetSize { section: section("editor-section"), size: Size { width: 300.0, height: 400.0 } }]).unwrap(); + let layout = host_layout(&h, 2000.0, 1600.0, Direction::Ltr); + assert_eq!( + layout.resolved.panels[0].outer.size, + Size { width: 300.0, height: 240.0 }, + "sole Content keeps measured height within composite maxima" + ); + assert_eq!(h.runtime.layout().layout().section(§ion("editor-section")).unwrap().preferred_extent, Some(400.0)); +} + +#[test] +fn host_metrics_and_public_geometry_reject_hostile_values_before_pointer_arithmetic() { + let h = host_logs(1, Zone::Left); + for field in 0..7 { + let mut metrics = HostMetrics::default(); + match field { + 0 => metrics.header_height = f32::NAN, + 1 => metrics.footer_height = -1.0, + 2 => metrics.control_extent = 0.0, + 3 => metrics.min_viewport.width = f32::INFINITY, + 4 => metrics.gap = f32::NAN, + 5 => metrics.gap = -1.0, + _ => metrics.gap = 257.0, + } + assert_eq!( + resolve_host_layout(h.runtime.layout(), capacity(), Direction::Ltr, metrics, &HostGeometryPolicy::default()).unwrap_err().rule, + Rule::Bounds + ); + } + let mut layout = host_layout(&h, 1280.0, 800.0, Direction::Ltr); + let mut interaction = HostInteraction::default(); + host_press(&h, &layout, &mut interaction, HostPointerTarget::Header { instance: id("log-0") }); + layout.capacity.size.width = f32::NAN; + let update = interaction.update(h.runtime.layout(), &host_scope(&h), &layout, HostPointerEvent::Move { at: Point { x: 640.0, y: 400.0 } }); + assert!(update.action.is_none()); + assert_eq!(update.rejection.unwrap().rule, Rule::Bounds); + assert!(!interaction.is_captured()); +} + +#[test] +fn raw_host_header_drag_joins_content_and_body_drags_cannot_rearrange_panels() { + for scale in [1.0, 2.0] { + let h = host_logs(2, Zone::Left); + let mut raw = RawPanelHost::new(h, scale); + raw.frame(Vec::new(), false); + let start = raw.at(HostControlTarget::Pointer(HostPointerTarget::Header { instance: id("log-0") })); + let target = explicit_drop_point( + &raw.content, + &raw.host.frame().unwrap().layout, + &id("log-0"), + &HostDropTargetId::Tab { section: section("section-1"), before: None }, + ); + let end = egui::pos2(target.x, target.y); + raw.pointer(start, true, false); + let preview = raw.frame(vec![egui::Event::PointerMoved(end)], false).0.preview.unwrap(); + assert_join_drag_action(preview.action.as_ref().unwrap(), id("log-0"), section("section-1"), 1); + let projected = preview.projected.unwrap(); + raw.pointer(end, false, false); + raw.frame(Vec::new(), false); + let group = raw.content.runtime.layout().layout().containing(&id("log-0")).unwrap(); + assert_eq!(group.tabs, vec![id("log-1"), id("log-0")]); + assert_eq!(group.active, id("log-0"), "the explicit drag landing activates the moved tab in the same transaction"); + assert_eq!(raw.content.runtime.layout().layout().sections.len(), 1); + assert_host_landing(&raw.host.frame().unwrap().layout, &projected); + let before = raw.content.runtime.layout().inspect(); + let body = raw.host.frame().unwrap().layout.sections[0].body.unwrap(); + let body = middle(body); + let start = egui::pos2(body.x, body.y); + raw.pointer(start, true, false); + raw.frame(vec![egui::Event::PointerMoved(start + egui::vec2(400.0, 200.0))], false); + raw.pointer(start + egui::vec2(400.0, 200.0), false, false); + assert_eq!(raw.content.runtime.layout().inspect(), before); + assert!(!raw.host.interaction().is_captured()); + assert!(raw.host.frame().unwrap().preview.is_none()); + } +} + +fn raw_clear_below_host(scale: f32, direction: Direction, zone: Zone, obstacle: &str) -> RawPanelHost { + let mut h = host_logs(1, zone); + h.dispatch(vec![Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("moving"), + destination: Some(Destination::NewSection { + section: section("moving"), + index: 1, + location: SectionLocation::Floating { origin: Point { x: 560.0, y: 80.0 } }, + size: Size { width: 280.0, height: 240.0 }, + }), + }]) + .unwrap(); + if obstacle == "bottom" { + h.dispatch(vec![fixture_open("fixture.log", "obstacle", "obstacle", Zone::Bottom, 2).unwrap()]).unwrap(); + } else if matches!(obstacle, "floating" | "collapsed") { + h.dispatch(vec![Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("obstacle"), + destination: Some(Destination::NewSection { + section: section("obstacle"), + index: 2, + location: SectionLocation::Floating { + origin: Point { x: if direction.edge(zone).unwrap() == PhysicalEdge::Left { 20.0 } else { 1100.0 }, y: 650.0 }, + }, + size: Size { width: 280.0, height: 240.0 }, + }), + }]) + .unwrap(); + if obstacle == "collapsed" { + h.dispatch(vec![Mutation::Collapse { section: section("obstacle"), collapsed: true }]).unwrap(); + } + } + let mut environment = h.runtime.environment().clone(); + environment.direction = direction; + h.runtime.set_environment(environment, &mut h.local).unwrap(); + let mut raw = RawPanelHost::new(h, scale); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + raw +} + +#[test] +fn raw_below_short_card_previews_and_commits_halfway_through_clear_space_before_actual_obstacles() { + for scale in [1.0, 2.0] { + for direction in [Direction::Ltr, Direction::Rtl] { + for zone in [Zone::Left, Zone::Right] { + for obstacle in ["none", "bottom", "floating", "collapsed"] { + let mut raw = raw_clear_below_host(scale, direction, zone, obstacle); + let initial = raw.host.frame().unwrap().layout.clone(); + let card = initial.sections.iter().find(|card| card.section == section("section-0")).unwrap(); + let card_bottom = card.outer.origin.y + card.outer.size.height; + let end_y = initial + .sections + .iter() + .find(|card| card.section == section("obstacle")) + .map_or(initial.capacity.origin.y + initial.capacity.size.height, |card| card.outer.origin.y); + let at = Point { x: middle(card.outer).x, y: (card_bottom + end_y) / 2.0 }; + assert!(at.y > card_bottom + 100.0, "exercise well below the old inside-only band"); + assert!(!initial.consumes_pointer(at)); + assert!(!initial.painted.iter().any(|bounds| bounds.contains(at))); + let target = HostDropTargetId::Relative { section: section("section-0"), placement: RelativePlacement::Below }; + let targets = host_drop_targets(raw.content.runtime.layout(), &initial, &id("moving")).unwrap(); + let below = targets.iter().find(|entry| entry.id == target).unwrap(); + assert_eq!(below.bounds.origin.y + below.bounds.size.height, end_y); + let start = raw.at(HostControlTarget::Pointer(HostPointerTarget::Header { instance: id("moving") })); + raw.pointer(start, true, false); + // The obstacle boundary itself must never select the extended region. + let boundary = egui::pos2(at.x, end_y); + let blocked = raw.frame(vec![egui::Event::PointerMoved(boundary)], false).0; + assert_ne!(blocked.preview.and_then(|preview| preview.target), Some(target.clone())); + let end = egui::pos2(at.x, at.y); + let preview = raw.frame(vec![egui::Event::PointerMoved(end)], false).0.preview.unwrap(); + assert!(preview.rejection.is_none(), "{obstacle}/{zone:?}/{direction:?}: {preview:?}"); + assert_eq!(preview.target, Some(target)); + let shown = preview.projected.unwrap(); + let before = raw.content.runtime.layout().inspect(); + let frame = raw + .frame( + vec![egui::Event::PointerButton { + pos: end, + button: egui::PointerButton::Primary, + pressed: false, + modifiers: egui::Modifiers::NONE, + }], + true, + ) + .0; + assert_eq!(frame.events.iter().filter(|event| matches!(event, HostEvent::PreparedCommitted { .. })).count(), 1); + assert_eq!(raw.content.runtime.layout().inspect().revision, before.revision + 1); + raw.frame(Vec::new(), false); + assert_host_landing(&raw.host.frame().unwrap().layout, &shown); + } + } + } + } +} + +#[test] +fn raw_drag_title_tracks_only_the_source_text_without_changing_host_state_or_footprints() { + fn feedback(output: &egui::FullOutput, title: &str, source: egui::Rect, ink: egui::Color32, faded: bool, badge: bool) { + let t = crate::theme::Tokens::get(); + let (mut originals, mut badges, mut others) = (0, 0, 0); + for clipped in &output.shapes { + crate::test_support::each_shape(&clipped.shape, &mut |shape| { + if let egui::Shape::Text(text) = shape { + if text.galley.job.text == title { + let original = source.contains(text.pos); + let expected = if original { ink.gamma_multiply(if faded { 0.5 } else { 1.0 }) } else { t.form_ink }; + assert!(text.galley.job.sections.iter().all(|section| section.format.color == expected)); + if original { + originals += 1; + } else { + badges += 1; + } + } else if matches!(text.galley.job.text.as_str(), "Specimen peer" | "Specimen other") { + assert!(text.galley.job.sections.iter().all(|section| section.format.color == t.form_ink)); + others += 1; + } + } + }); + } + assert_eq!((originals, badges), (1, usize::from(badge))); + assert!(others > 0, "retain full ink on other panel/tab headings"); + } + for (scale, direction) in [(1.0, Direction::Ltr), (2.0, Direction::Rtl)] { + for group in [false, true] { + let mut h = PanelMountHarness::new(false).unwrap(); + open_editor(&mut h); + h.dispatch(vec![fixture_open("fixture.log", "other", "other", Zone::Right, 1).unwrap()]).unwrap(); + if group { + h.dispatch(vec![ + Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("peer"), + destination: Some(Destination::JoinTab { section: section("editor-section"), index: 1 }), + }, + Mutation::Activate { instance: id("peer") }, + ]) + .unwrap(); + } + let mut environment = h.runtime.environment().clone(); + environment.direction = direction; + h.runtime.set_environment(environment, &mut h.local).unwrap(); + let key = editor_key(&h); + h.probe.edit(&key, |state| state.draft = "retained through cosmetic drag feedback".into()).unwrap(); + let mut raw = RawPanelHost::new(h, scale); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + let before = raw.content.runtime.layout().inspect(); + let controllers = raw.content.runtime.controller_count(); + let native_commits = raw.content.native.commits; + let initial = raw.host.frame().unwrap().layout.clone(); + let target = HostControlTarget::Pointer(if group { + HostPointerTarget::Tab { instance: id("editor") } + } else { + HostPointerTarget::Header { instance: id("editor") } + }); + let source = egui_rect(raw.host.frame().unwrap().controls.iter().find(|control| control.target == target).unwrap().bounds); + let controls = raw.host.frame().unwrap().controls.iter().map(|control| (control.id, control.bounds)).collect::>(); + let title = raw.content.runtime.instance_presentation(&id("editor")).unwrap().title; + let ink = crate::theme::Tokens::get().form_primary; // Editor declares attention. + let start = raw.at(target); + raw.pointer(start, true, false); + let below = raw.frame(vec![egui::Event::PointerMoved(start + egui::vec2(5.99, 0.0))], false); + feedback(&below.1, &title, source, ink, false, false); + let threshold = raw.frame(vec![egui::Event::PointerMoved(start + egui::vec2(6.0, 0.0))], false); + assert_eq!(raw.host.interaction().move_source(), Some(&id("editor"))); + assert!(threshold.1.viewport_output.get(&egui::ViewportId::ROOT).unwrap().repaint_delay.is_zero()); + // Source text was already painted before input; the requested next + // pass dims it, including when there is no candidate animation. + let at = egui::pos2(700.0, 500.0); // Clear canvas, no landing. + let held = raw.frame(vec![egui::Event::PointerMoved(at)], false); + feedback(&held.1, &title, source, ink, true, true); + let invalid = raw.frame(Vec::new(), false); + assert!(invalid.0.preview.as_ref().unwrap().action.is_none()); + feedback(&invalid.1, &title, source, ink, true, true); + let left = raw.frame(vec![egui::Event::PointerGone], false); + feedback(&left.1, &title, source, ink, true, false); + assert!(raw.host.interaction().move_position().is_none()); + let returned = raw.frame(vec![egui::Event::PointerMoved(at)], false); + feedback(&returned.1, &title, source, ink, true, true); + let cancelled = raw.frame(vec![host_key(egui::Key::Escape, true), button_event(at, false)], false); + assert!(cancelled.1.viewport_output.get(&egui::ViewportId::ROOT).unwrap().repaint_delay.is_zero()); + let restored = raw.frame(vec![host_key(egui::Key::Escape, false)], false); + feedback(&restored.1, &title, source, ink, false, false); + assert_eq!(raw.content.runtime.layout().inspect(), before); + assert_eq!(raw.content.runtime.controller_count(), controllers); + assert_eq!(raw.content.native.commits, native_commits); + assert_eq!(raw.content.commands.calls, 0); + assert_eq!(raw.content.probe.state(&key).unwrap().draft, "retained through cosmetic drag feedback"); + let actual = &raw.host.frame().unwrap().layout; + assert_eq!(actual.sections, initial.sections); + assert_eq!(actual.painted, initial.painted); + assert_eq!(actual.input, initial.input); + assert_eq!(actual.occlusion, initial.occlusion); + assert_eq!(actual.reservations, initial.reservations); + assert_eq!(actual.usable, initial.usable); + assert_eq!(actual.render_domain, initial.render_domain); + assert_eq!(raw.host.frame().unwrap().controls.iter().map(|control| (control.id, control.bounds)).collect::>(), controls); + } + } +} + +#[test] +fn raw_pointer_leave_and_outside_moves_resume_with_a_fresh_candidate_and_release_once() { + for scale in [1.0, 2.0] { + for direction in [Direction::Ltr, Direction::Rtl] { + for leave in ["gone", "negative", "positive"] { + let mut raw = raw_clear_below_host(scale, direction, Zone::Left, "bottom"); + let initial = raw.host.frame().unwrap().layout.clone(); + let card = initial.sections.iter().find(|card| card.section == section("section-0")).unwrap(); + let old = middle(card.outer); + let bottom_y = initial.sections.iter().find(|card| card.section == section("obstacle")).unwrap().outer.origin.y; + let end = egui::pos2(old.x, (card.outer.origin.y + card.outer.size.height + bottom_y) / 2.0); + let start = raw.at(HostControlTarget::Pointer(HostPointerTarget::Header { instance: id("moving") })); + raw.pointer(start, true, false); + let old_preview = raw.frame(vec![egui::Event::PointerMoved(egui::pos2(old.x, old.y))], false).0.preview.unwrap(); + assert!(old_preview.action.is_some()); + let mut events = Vec::new(); + if leave != "gone" { + events.push(egui::Event::PointerMoved(if leave == "negative" { egui::pos2(-20.0, -20.0) } else { egui::pos2(1500.0, 1100.0) })); + } + events.push(egui::Event::PointerGone); + let left = raw.frame(events, false).0; + assert!(raw.ctx.input(|input| input.pointer.primary_down())); + assert!(raw.host.interaction().is_captured()); + assert!(left.preview.is_none() && raw.host.interaction().preview().is_none()); + assert!(raw.frame(Vec::new(), false).0.preview.is_none()); + let before = raw.content.runtime.layout().inspect(); + let preview = raw.frame(vec![egui::Event::PointerMoved(end)], false).0.preview.unwrap(); + assert!(preview.rejection.is_none()); + assert_ne!(preview.target, old_preview.target); + assert_eq!(preview.target, Some(HostDropTargetId::Relative { section: section("section-0"), placement: RelativePlacement::Below })); + assert_eq!(raw.content.runtime.layout().inspect(), before); + let shown = preview.projected.unwrap(); + let released = raw + .frame( + vec![egui::Event::PointerButton { + pos: end, + button: egui::PointerButton::Primary, + pressed: false, + modifiers: egui::Modifiers::NONE, + }], + true, + ) + .0; + assert_eq!(released.events.iter().filter(|event| matches!(event, HostEvent::PreparedCommitted { .. })).count(), 1); + assert!(!raw.host.interaction().is_captured()); + raw.frame(Vec::new(), false); + assert_host_landing(&raw.host.frame().unwrap().layout, &shown); + assert_eq!(raw.content.runtime.layout().inspect().revision, before.revision + 1); + } + } + } +} + +#[test] +fn raw_suspended_drag_cancels_on_outside_release_escape_focus_modal_or_window_change() { + for case in ["release", "escape", "focus", "modal", "window", "primary-up", "release-only"] { + let mut raw = raw_clear_below_host(1.0, Direction::Ltr, Zone::Left, "none"); + let card = raw.host.frame().unwrap().layout.sections.iter().find(|card| card.section == section("section-0")).unwrap(); + let at = middle(card.outer); + let end = egui::pos2(at.x, at.y); + let start = raw.at(HostControlTarget::Pointer(HostPointerTarget::Header { instance: id("moving") })); + raw.pointer(start, true, false); + assert!(raw.frame(vec![egui::Event::PointerMoved(end)], false).0.preview.unwrap().action.is_some()); + raw.frame(vec![egui::Event::PointerGone], false); + let before = raw.content.runtime.layout().inspect(); + match case { + "release" => { + raw.pointer(egui::pos2(-20.0, -20.0), false, false); + } + "escape" => { + raw.frame(vec![host_key(egui::Key::Escape, true)], false); + } + "focus" => { + raw.frame(vec![egui::Event::WindowFocused(false)], false); + } + "modal" => { + raw.late_modal = true; + raw.frame(Vec::new(), false); + raw.late_modal = false; + } + "window" => { + let mut environment = raw.content.runtime.environment().clone(); + environment.window = HostId::new("reentry.foreign-window").unwrap(); + raw.content.runtime.set_environment(environment, &mut raw.content.local).unwrap(); + raw.frame(Vec::new(), false); + } + "primary-up" => { + // Simulate a backend updating real egui pointer state without + // forwarding a release event to this host's raw event stream. + raw.ctx.input_mut(|input| input.pointer = Default::default()); + raw.frame(vec![egui::Event::PointerMoved(end)], false); + } + _ => { + raw.frame( + vec![egui::Event::PointerButton { + pos: end, + button: egui::PointerButton::Primary, + pressed: false, + modifiers: egui::Modifiers::NONE, + }], + false, + ); + } + } + assert!(!raw.host.interaction().is_captured(), "{case}"); + assert!(raw.host.interaction().preview().is_none(), "{case}"); + assert!(raw.host.interaction().move_source().is_none() && raw.host.interaction().move_position().is_none(), "{case}"); + raw.frame(vec![egui::Event::PointerMoved(end)], false); + raw.pointer(end, false, false); + assert_eq!(raw.content.runtime.layout().inspect(), before, "{case}"); + assert!(raw.host.frame().unwrap().preview.is_none(), "{case}"); + } +} + +#[test] +fn raw_host_inactive_tab_widget_drag_obeys_threshold_and_moves_only_its_retained_editor() { + for scale in [1.0, 2.0] { + let mut h = PanelMountHarness::new(false).unwrap(); + open_editor(&mut h); + h.dispatch(vec![ + Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("source-active"), + destination: Some(Destination::JoinTab { section: section("editor-section"), index: 1 }), + }, + Mutation::Activate { instance: id("source-active") }, + fixture_open("fixture.log", "destination-active", "destination", Zone::Right, 1).unwrap(), + Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("destination-inactive"), + destination: Some(Destination::JoinTab { section: section("destination"), index: 1 }), + }, + ]) + .unwrap(); + let key = editor_key(&h); + h.probe.edit(&key, |state| state.draft = "inactive editor draft survives its tab drag".into()).unwrap(); + let mut raw = RawPanelHost::new(h, scale); + let (initial, output) = raw.frame(Vec::new(), false); + let target = HostControlTarget::Pointer(HostPointerTarget::Tab { instance: id("editor") }); + let widget = initial.controls.iter().find(|control| control.target == target).expect("inactive editor has a published Tab widget"); + assert_eq!(widget.role, InputRole::Tab); + assert!(widget.enabled); + assert!( + output + .platform_output + .accesskit_update + .as_ref() + .unwrap() + .nodes + .iter() + .any(|(_, node)| { node.role() == egui::accesskit::Role::Button && node.label() == Some(widget.accessible_name.as_str()) }), + "published Tab metadata must correspond to an actual egui widget" + ); + let start = raw.at(target); + let before = raw.content.runtime.layout().inspect(); + let controllers = raw.content.runtime.controller_count(); + let native_commits = raw.content.native.commits; + let editor = raw.content.probe.state(&key).unwrap(); + assert!(!raw.content.runtime.state(&key).unwrap().presented, "drag starts from an inactive tab"); + + // Only RawInput reaches the renderer here: no typed Press/Move/Release + // or direct LayoutAction is used to manufacture the gesture outcome. + raw.frame(vec![egui::Event::PointerMoved(start)], false); + let pressed = raw.pointer(start, true, false); + assert!(raw.host.interaction().is_captured()); + assert!(pressed.preview.is_none()); + let jitter = raw.frame(vec![egui::Event::PointerMoved(start + egui::vec2(5.99, 0.0))], false).0; + assert!(jitter.preview.is_none()); + assert_eq!(raw.content.runtime.layout().inspect(), before); + let threshold = raw.frame(vec![egui::Event::PointerMoved(start + egui::vec2(6.0, 0.0))], false).0; + assert!(threshold.preview.is_some(), "the real tab starts at six logical points at scale {scale}"); + assert_eq!(raw.content.runtime.layout().inspect(), before); + + let destination = explicit_drop_point( + &raw.content, + &initial.layout, + &id("editor"), + &HostDropTargetId::Tab { section: section("destination"), before: None }, + ); + let end = egui::pos2(destination.x, destination.y); + let (moving, output) = raw.frame(vec![egui::Event::PointerMoved(end)], false); + let preview = moving.preview.as_ref().unwrap(); + assert!(preview.rejection.is_none()); + assert_eq!(preview.destination, Some(Destination::JoinTab { section: section("destination"), index: 2 })); + let projected = preview.projected.clone().unwrap(); + assert!(output_paints_rect(&output, preview.bounds, Some(crate::theme::Tokens::get().form_primary.gamma_multiply(0.12)), None)); + assert!( + output_paints_rect(&output, preview.tab_marker.unwrap(), Some(crate::theme::Tokens::get().form_primary), None), + "paint the actual inserted-tab edge, not a nominal body highlight" + ); + assert_eq!(raw.content.runtime.layout().inspect(), before, "preview cannot activate the tab or change layout"); + assert_eq!(raw.content.native.commits, native_commits); + assert_eq!(raw.content.commands.calls, 0); + + let released = raw.pointer(end, false, true); + let committed = released + .events + .iter() + .filter_map(|event| if let HostEvent::PreparedCommitted { reply } = event { Some(reply) } else { None }) + .collect::>(); + assert_eq!(committed.len(), 1, "one real tab drop commits once across repeated egui passes"); + assert_eq!(raw.content.native.commits, native_commits + 1); + assert!(raw.finished_frames.len() >= 2, "the release really repeats the host callback"); + assert_eq!( + raw.finished_frames[0].layout.geometry_policy.identity_reservations.replacement_ownership, + initial.layout.geometry_policy.identity_reservations.replacement_ownership + ); + assert_ne!( + released.layout.geometry_policy.identity_reservations.replacement_ownership, + initial.layout.geometry_policy.identity_reservations.replacement_ownership, + "the repeated callback recaptured the changed tab ownership and discarded its old geometry" + ); + let regions = released + .events + .iter() + .filter_map(|event| match event { + HostEvent::Regions { revision, painted, reservations, .. } => Some((revision, painted, reservations)), + _ => None, + }) + .collect::>(); + assert_eq!(regions.len(), 1, "outcome restoration cannot resurrect an earlier pass's Regions"); + assert_eq!(*regions[0].0, before.revision + 1); + assert_eq!(*regions[0].0, released.layout.revision); + assert_eq!(regions[0].1, &released.layout.painted); + assert_eq!(regions[0].2, &released.layout.reservations); + assert_join_drag_action(preview.action.as_ref().unwrap(), id("editor"), section("destination"), 2); + assert_eq!(committed[0].revision, before.revision + 1); + let next = raw.frame(Vec::new(), true).0; + assert!(!next.events.iter().any(|event| matches!(event, HostEvent::Committed { .. } | HostEvent::PreparedCommitted { .. }))); + assert_eq!(raw.content.native.commits, native_commits + 1, "the next frame cannot execute the release again"); + let layout = raw.content.runtime.layout().layout(); + let source = layout.section(§ion("editor-section")).unwrap(); + assert_eq!(source.tabs, vec![id("source-active")]); + assert_eq!(source.active, id("source-active")); + let destination = layout.section(§ion("destination")).unwrap(); + assert_eq!(destination.tabs, vec![id("destination-active"), id("destination-inactive"), id("editor")]); + assert_eq!(destination.active, id("editor")); + assert_eq!(layout.sections.len(), 2); + assert_eq!(raw.content.runtime.layout().inspect().revision, before.revision + 1); + assert_host_landing(&raw.host.frame().unwrap().layout, &projected); + assert!(!raw.host.interaction().is_captured()); + assert_eq!(raw.content.runtime.controller_count(), controllers); + let retained = raw.content.probe.state(&key).unwrap(); + assert_eq!(retained.draft, editor.draft); + assert_eq!(retained.transaction_live, editor.transaction_live); + assert_eq!( + (retained.applies, retained.cancels, retained.finishes, retained.reopens, retained.destroys), + (editor.applies, editor.cancels, editor.finishes, editor.reopens, editor.destroys) + ); + assert_eq!(retained.reparents, editor.reparents + 1); + assert!(retained.renders > editor.renders, "the retained inactive editor becomes the visible landing without recreation"); + assert!(retained.updates > editor.updates); + assert_eq!(raw.content.commands.calls, 0); + } +} + +#[test] +fn raw_host_action_menu_and_close_button_drags_never_capture_panels_or_commit_content() { + for scale in [1.0, 2.0] { + for target in [ + HostControlTarget::Content { instance: id("editor"), action: ControlId::new("apply").unwrap() }, + HostControlTarget::Pointer(HostPointerTarget::Menu { instance: id("editor") }), + HostControlTarget::Shared { instance: id("editor"), action: HostSharedAction::Close }, + ] { + let mut h = PanelMountHarness::new(false).unwrap(); + open_editor(&mut h); + let key = editor_key(&h); + h.probe.edit(&key, |state| state.draft = "buttons cannot drag or commit this draft".into()).unwrap(); + let mut raw = RawPanelHost::new(h, scale); + raw.frame(Vec::new(), false); + if matches!(&target, HostControlTarget::Shared { action: HostSharedAction::Close, .. }) { + raw.menu(id("editor")); + } + let control = raw + .host + .frame() + .unwrap() + .controls + .iter() + .find(|control| control.target == target) + .expect("button must be genuinely painted and published"); + assert_eq!(control.role, InputRole::Action); + assert!(control.enabled); + let start = raw.at(target.clone()); + let end = egui::pos2(raw.capacity.origin.x + raw.capacity.size.width * 0.6, raw.capacity.origin.y + raw.capacity.size.height * 0.6); + let before = raw.content.runtime.layout().inspect(); + let controllers = raw.content.runtime.controller_count(); + let native_commits = raw.content.native.commits; + let editor = raw.content.probe.state(&key).unwrap(); + raw.frame(vec![egui::Event::PointerMoved(start)], false); + let assert_protected = |raw: &RawPanelHost, frame: HostFrame| { + assert!(!raw.host.interaction().is_captured(), "button press/move/release cannot capture a panel: {target:?}"); + assert!(frame.preview.is_none(), "dragging a button cannot preview a panel move: {target:?}, scale {scale}"); + assert!( + frame.events.iter().all(|event| !matches!( + event, + HostEvent::Committed { .. } | HostEvent::PreparedCommitted { .. } | HostEvent::ContentAction { .. } + )), + "button drag dispatched an action: {target:?}" + ); + assert_eq!(frame.reply, before); + }; + let frame = raw.pointer(start, true, false); + assert_protected(&raw, frame); + let frame = raw.frame(vec![egui::Event::PointerMoved(start + egui::vec2(8.0, 0.0))], false).0; + assert_protected(&raw, frame); + let frame = raw.frame(vec![egui::Event::PointerMoved(end)], false).0; + assert_protected(&raw, frame); + let frame = raw.pointer(end, false, true); + assert_protected(&raw, frame); + assert!(!raw.host.interaction().is_captured()); + raw.frame(Vec::new(), false); + assert_eq!(raw.content.runtime.layout().inspect(), before); + assert_eq!(raw.content.runtime.controller_count(), controllers); + assert_eq!(raw.content.native.commits, native_commits); + assert_eq!(raw.content.commands.calls, 0); + let retained = raw.content.probe.state(&key).unwrap(); + assert_eq!(retained.draft, editor.draft); + assert_eq!(retained.transaction_live, editor.transaction_live); + assert_eq!( + (retained.applies, retained.cancels, retained.finishes, retained.reopens, retained.reparents, retained.destroys), + (editor.applies, editor.cancels, editor.finishes, editor.reopens, editor.reparents, editor.destroys) + ); + assert!(retained.updates > editor.updates); + } + } +} + +#[test] +fn raw_host_rtl_reduced_motion_and_maximum_length_identities_keep_distinct_immediate_controls() { + let mut h = PanelMountHarness::new(false).unwrap(); + let prefix = "a".repeat(MAX_ID_BYTES - 1); + let first = id(&format!("{prefix}b")); + let second = id(&format!("{prefix}c")); + h.dispatch(vec![ + fixture_open("fixture.log", &first.0, "first", Zone::Left, 0).unwrap(), + fixture_open("fixture.log", &second.0, "second", Zone::Left, 1).unwrap(), + ]) + .unwrap(); + let mut environment = h.runtime.environment().clone(); + environment.direction = Direction::Rtl; + environment.motion = Motion::Reduced; + h.runtime.set_environment(environment, &mut h.local).unwrap(); + let mut raw = RawPanelHost::new(h, 2.0); + let (frame, _) = raw.frame(Vec::new(), false); + let header = |instance: InstanceId| HostControlTarget::Pointer(HostPointerTarget::Header { instance }); + let a = frame.controls.iter().find(|control| control.target == header(first.clone())).unwrap(); + let b = frame.controls.iter().find(|control| control.target == header(second.clone())).unwrap(); + assert_ne!(a.id, b.id, "full typed identity must survive the wire ID length limit"); + assert!(a.bounds.origin.x > raw.capacity.size.width / 2.0, "logical Left paints on the physical right"); + raw.menu(first.clone()); + raw.click(HostControlTarget::Shared { instance: first.clone(), action: HostSharedAction::Collapse }, false); + assert!(raw.content.runtime.layout().layout().containing(&first).unwrap().collapsed, "reduced motion cannot defer the state commit"); + raw.frame(Vec::new(), false); + raw.click(HostControlTarget::Pointer(HostPointerTarget::Collapse { instance: first.clone() }), false); + assert!(!raw.content.runtime.layout().layout().containing(&first).unwrap().collapsed); + assert_eq!(raw.content.runtime.controller_count(), 2); + assert_eq!(raw.content.commands.calls, 0); +} + fn id(value: &str) -> InstanceId { InstanceId::new(value).unwrap() } @@ -11,6 +4254,97 @@ fn section(value: &str) -> SectionId { fn capacity() -> LogicalRect { LogicalRect { origin: Point { x: 0.0, y: 0.0 }, size: Size { width: 1400.0, height: 1000.0 } } } + +#[test] +fn in_app_reconciliation_does_not_deactivate_a_peer_native_viewport() { + let mut h = PanelMountHarness::new(true).unwrap(); + open_editor(&mut h); + h.dispatch(vec![fixture_open("fixture.log", "native-log", "native-section", Zone::Right, 1).unwrap()]).unwrap(); + h.dispatch(vec![Mutation::Move { + instance: id("native-log"), + destination: Destination::NewSection { + section: section("native-section-moved"), + index: 1, + location: SectionLocation::Window { + host: HostId::new("peer-native").unwrap(), + origin: Point { x: 0.0, y: 0.0 }, + return_to: DockReturn { + zone: Zone::Right, + index: 1, + size: Size { width: 280.0, height: 240.0 }, + collapsed: false, + join: None, + section: None, + column: None, + column_index: 0, + column_width: None, + weight: 1.0, + preferred_extent: None, + extent_priority: 0, + }, + }, + size: Size { width: 280.0, height: 240.0 }, + }, + }]) + .unwrap(); + h.mount(capacity()).unwrap(); + let native_key = ControllerKey { instance: id("native-log"), owner: ContentOwner::Workspace(h.runtime.environment().workspace.clone()) }; + let native_state = h.runtime.state(&native_key).unwrap().clone(); + assert!(native_state.presented && native_state.activated); + let scope = h.local.scopes.get(&id("native-log")).unwrap().clone(); + h.local.request(&scope, LocalRequest::KeyboardOwner { instance: id("native-log"), control: ControlId::new("draft").unwrap() }).unwrap(); + let mut root_only = resolve_geometry(h.runtime.layout(), capacity(), Direction::Ltr, 48.0).unwrap(); + root_only.panels.retain(|panel| panel.zone != Zone::Window); + for resolved in [root_only, ResolvedLayout::default()] { + h.runtime + .mount_in_app(&resolved, &mut h.host, &mut ContentServices { models: &h.models, commands: &mut h.commands, local: &mut h.local }) + .unwrap(); + assert_eq!(h.runtime.state(&native_key), Some(&native_state), "complete root mount must preserve peer presentation"); + assert_eq!(h.local.keyboard.get(&scope).unwrap().0, id("native-log")); + } + assert!(!h.runtime.state(&editor_key(&h)).unwrap().presented, "an empty root frame releases root presentation"); + assert!(h.probe.state(&editor_key(&h)).unwrap().transaction_live); +} + +#[test] +fn prepared_host_moves_are_observational_and_retained_sink_revalidates_the_revision() { + let mut h = PanelMountHarness::new(false).unwrap(); + open_editor(&mut h); + h.mount(capacity()).unwrap(); + let key = editor_key(&h); + h.probe + .edit(&key, |state| { + state.draft = "unsaved user draft".into(); + state.reject_cancel = true; + }) + .unwrap(); + let before = h.runtime.layout().inspect(); + let controllers = h.runtime.controller_count(); + let native_commits = h.native.commits; + let preview = LayoutAction::Apply { expected_revision: Some(before.revision), mutations: vec![move_editor(Zone::Bottom)] }; + for _ in 0..4 { + let prepared = h.runtime.layout().prepare(preview.clone()).unwrap(); + assert_eq!(prepared.layout().containing(&id("editor")).unwrap().location.zone(), Zone::Bottom); + assert_eq!(h.runtime.layout().inspect(), before); + assert_eq!(h.runtime.controller_count(), controllers); + assert_eq!(h.native.commits, native_commits); + assert_eq!(h.commands.calls, 0); + assert_eq!(h.probe.state(&key).unwrap().reparents, 0); + } + h.dispatch(vec![Mutation::Collapse { section: section("editor-section"), collapsed: true }]).unwrap(); + let live = h.runtime.layout().inspect(); + let result = { + let mut services = ContentServices { models: &h.models, commands: &mut h.commands, local: &mut h.local }; + let mut sink = RuntimeActionSink { runtime: &mut h.runtime, native: &mut h.native, services: &mut services }; + sink.dispatch(preview) + }; + assert_eq!(result.unwrap_err().rule, Rule::Revision); + assert_eq!(h.runtime.layout().inspect(), live); + assert_eq!(h.probe.state(&key).unwrap().draft, "unsaved user draft"); + assert_eq!(h.probe.state(&key).unwrap().reparents, 0); + assert_eq!(h.probe.state(&key).unwrap().cancels, 0); + assert_eq!(h.commands.calls, 0); +} fn editor_key(h: &PanelMountHarness) -> ControllerKey { ControllerKey { instance: id("editor"), owner: ContentOwner::Document(h.runtime.environment().document.clone().unwrap()) } } @@ -42,7 +4376,7 @@ fn mount_harness_uses_real_controller_slots_and_usable_presentation_context() { assert!(h.host.slot_calls >= 3); assert_eq!(h.host.slot_calls % 3, 0); let record = h.host.mounts.back().unwrap(); - assert_eq!(record.context.usable_body.size.height, 192.0); + assert_eq!(record.context.usable_body.unwrap().size.height, 192.0); assert_eq!(record.context.flow, Flow::Tall); assert_eq!(record.presentation.actions.len(), 3); assert!(h.probe.state(&editor_key(&h)).unwrap().renders >= 1); @@ -572,7 +4906,20 @@ fn native_preflight_failure_and_close_redock_preserve_controller_identity() { location: SectionLocation::Window { host: HostId::new("native-host").unwrap(), origin: Point { x: 0.0, y: 0.0 }, - return_to: DockReturn { zone: Zone::Left, index: 0, size: Size { width: 280.0, height: 240.0 }, collapsed: false, join: None }, + return_to: DockReturn { + zone: Zone::Left, + index: 0, + size: Size { width: 280.0, height: 240.0 }, + collapsed: false, + join: None, + section: None, + column: None, + column_index: 0, + column_width: None, + weight: 1.0, + preferred_extent: None, + extent_priority: 0, + }, }, size: Size { width: 400.0, height: 300.0 }, }, @@ -730,7 +5077,7 @@ fn mount_rejects_duplicate_inactive_or_invalid_regions() { ); assert_eq!(h.host.slot_calls, 0); resolved.panels.pop(); - resolved.panels.first_mut().unwrap().body.size.height = f32::INFINITY; + resolved.panels.first_mut().unwrap().body.as_mut().unwrap().size.height = f32::INFINITY; assert_eq!( h.runtime .mount(&resolved, &mut h.host, &mut ContentServices { models: &h.models, commands: &mut h.commands, local: &mut h.local }) @@ -763,6 +5110,147 @@ fn shutdown_is_atomic_and_explicit_owner_destruction_does_not_reset_layout() { assert_eq!(h.runtime.controller_count(), 1); } +#[test] +fn shutdown_restored_windows_with_in_app_adapter_releases_controllers_and_local_services() { + let mut h = restored_window_shutdown_fixture(false); + let key = editor_key(&h); + let layout = h.runtime.layout().inspect(); + let releases = h.local.releases; + let scopes = h.local.scopes.clone(); + let keyboard = h.local.keyboard.clone(); + let requests = h.local.requests.clone(); + let mut native = InAppNativeAdapter; + assert!(!native.capabilities().native_windows); + h.probe.edit(&key, |state| state.reject_cancel = true).unwrap(); + assert_eq!(h.runtime.shutdown_with_native(&mut native, &mut h.local).unwrap_err().rule, Rule::Lifecycle); + assert_eq!(h.runtime.controller_count(), 2); + assert!(h.runtime.require_live().is_ok()); + assert_eq!(h.runtime.layout().inspect(), layout); + assert_eq!(h.local.releases, releases); + assert_eq!(h.local.scopes, scopes); + assert_eq!(h.local.keyboard, keyboard); + assert_eq!(h.local.requests, requests); + assert_eq!(h.probe.state(&key).unwrap().destroys, 0); + assert!(h.probe.state(&key).unwrap().transaction_live); + + h.probe.edit(&key, |state| state.reject_cancel = false).unwrap(); + h.runtime.shutdown_with_native(&mut native, &mut h.local).unwrap(); + assert_eq!(h.runtime.controller_count(), 0); + assert_eq!(h.runtime.require_live().unwrap_err().rule, Rule::Lifecycle); + assert_eq!(h.runtime.layout().inspect(), layout); + assert_eq!(h.local.releases, releases + 2); + assert!(h.local.scopes.is_empty()); + assert!(h.local.keyboard.is_empty()); + assert!(h.local.requests.is_empty()); + let log = ControllerKey { instance: id("log"), owner: ContentOwner::Workspace(h.runtime.environment().workspace.clone()) }; + for controller in [&key, &log] { + let state = h.probe.state(controller).unwrap(); + assert_eq!(state.destroys, 1); + assert!(state.last_state.unwrap().destroyed); + } + assert_eq!(h.probe.state(&key).unwrap().cancels, 1); + assert!(!h.probe.state(&key).unwrap().transaction_live); + h.runtime.shutdown_with_native(&mut native, &mut h.local).unwrap(); + assert_eq!(h.local.releases, releases + 2, "repeated shutdown is inert"); + assert_eq!(h.probe.state(&key).unwrap().destroys, 1); +} + +#[test] +fn shutdown_native_release_refusal_preserves_controllers_local_services_and_hosts() { + let mut h = restored_window_shutdown_fixture(true); + let effects: Vec<_> = h + .runtime + .layout() + .layout() + .sections + .iter() + .map(|section| { + let SectionLocation::Window { host, .. } = §ion.location else { panic!("restored fixture must contain only native placements") }; + HostEffect::CreateNative { host: host.clone(), section: section.id.clone() } + }) + .collect(); + // Synthetic adapter ownership only; no OS windows are created by this test. + h.native.prepare(&effects).unwrap(); + h.native.commit(&effects); + assert_eq!(h.native.hosts.len(), 2); + let key = editor_key(&h); + let layout = h.runtime.layout().inspect(); + let hosts = h.native.hosts.clone(); + let commits = h.native.commits; + let releases = h.local.releases; + let scopes = h.local.scopes.clone(); + let keyboard = h.local.keyboard.clone(); + let requests = h.local.requests.clone(); + h.native.fail_prepare = true; + h.probe.edit(&key, |state| state.reject_cancel = true).unwrap(); + assert_eq!(h.runtime.shutdown_with_native(&mut h.native, &mut h.local).unwrap_err().rule, Rule::Lifecycle); + h.probe.edit(&key, |state| state.reject_cancel = false).unwrap(); + assert_eq!(h.runtime.shutdown_with_native(&mut h.native, &mut h.local).unwrap_err().rule, Rule::Capability); + assert_eq!(h.runtime.controller_count(), 2); + assert!(h.runtime.require_live().is_ok()); + assert_eq!(h.runtime.layout().inspect(), layout); + assert_eq!(h.native.hosts, hosts); + assert_eq!(h.native.commits, commits); + assert_eq!(h.local.releases, releases); + assert_eq!(h.local.scopes, scopes); + assert_eq!(h.local.keyboard, keyboard); + assert_eq!(h.local.requests, requests); + assert_eq!(h.probe.state(&key).unwrap().destroys, 0); + assert!(h.probe.state(&key).unwrap().transaction_live); + + h.native.fail_prepare = false; + h.runtime.shutdown_with_native(&mut h.native, &mut h.local).unwrap(); + assert!(h.native.hosts.is_empty()); + assert_eq!(h.native.commits, commits + 1); + assert_eq!(h.runtime.controller_count(), 0); + assert_eq!(h.runtime.require_live().unwrap_err().rule, Rule::Lifecycle); + assert_eq!(h.runtime.layout().inspect(), layout); + assert_eq!(h.local.releases, releases + 2); + assert!(h.local.scopes.is_empty()); + assert!(h.local.keyboard.is_empty()); + assert!(h.local.requests.is_empty()); + assert_eq!(h.probe.state(&key).unwrap().destroys, 1); + assert_eq!(h.probe.state(&key).unwrap().cancels, 1); + let log = ControllerKey { instance: id("log"), owner: ContentOwner::Workspace(h.runtime.environment().workspace.clone()) }; + assert_eq!(h.probe.state(&log).unwrap().destroys, 1); + h.runtime.shutdown_with_native(&mut h.native, &mut h.local).unwrap(); + assert_eq!(h.native.commits, commits + 1); + assert_eq!(h.local.releases, releases + 2); +} + +fn restored_window_shutdown_fixture(native: bool) -> PanelMountHarness { + let mut source = PanelMountHarness::new(true).unwrap(); + open_editor(&mut source); + source.dispatch(vec![fixture_open("fixture.log", "log", "log-section", Zone::Right, 0).unwrap()]).unwrap(); + let saved = source + .runtime + .layout() + .project(transaction(vec![ + native_placement("editor", "native-editor", "editor-host", 0), + native_placement("log", "native-log", "log-host", 1), + ])) + .unwrap(); + let registry = source.runtime.layout().registry().clone(); + let bytes = encode(&LayoutEnvelope::new(saved.clone()), ®istry).unwrap(); + let restored = decode(&bytes, ®istry, source.runtime.layout().layout()).unwrap(); + assert!(restored.notice.is_none()); + assert_eq!(restored.envelope.layout, saved); + let mut h = PanelMountHarness::without_content(native).unwrap(); + h.runtime = + PanelRuntime::new(LayoutService::new(registry, restored.envelope.layout, h.native.capabilities()).unwrap(), h.runtime.environment().clone()) + .unwrap(); + bind_synthetic_controllers(&mut h.runtime, &h.probe).unwrap(); + h.tick().unwrap(); + assert_eq!(h.runtime.controller_count(), 2); + for (instance, host) in [("editor", "editor-host"), ("log", "log-host")] { + let mut scope = runtime_scope(&h.runtime); + scope.viewport = ViewportId::new(host).unwrap(); + h.local.bind(id(instance), scope.clone()).unwrap(); + h.local.request(&scope, LocalRequest::KeyboardOwner { instance: id(instance), control: ControlId::new("draft").unwrap() }).unwrap(); + } + h +} + #[test] fn runtime_action_sink_and_native_service_scopes_use_the_shared_interfaces() { let mut h = PanelMountHarness::new(true).unwrap(); @@ -781,7 +5269,20 @@ fn runtime_action_sink_and_native_service_scopes_use_the_shared_interfaces() { location: SectionLocation::Window { host: HostId::new("native-viewport").unwrap(), origin: Point { x: 0.0, y: 0.0 }, - return_to: DockReturn { zone: Zone::Left, index: 0, size: Size { width: 280.0, height: 240.0 }, collapsed: false, join: None }, + return_to: DockReturn { + zone: Zone::Left, + index: 0, + size: Size { width: 280.0, height: 240.0 }, + collapsed: false, + join: None, + section: None, + column: None, + column_index: 0, + column_width: None, + weight: 1.0, + preferred_extent: None, + extent_priority: 0, + }, }, size: Size { width: 280.0, height: 240.0 }, }, @@ -806,7 +5307,7 @@ fn egui_host_uses_logical_bounds_at_two_hundred_percent_scale() { let ctx = egui::Context::default(); ctx.set_pixels_per_point(2.0); let mut failure = None; - 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| { let mut host = EguiPanelHost { ui }; if let Err(reason) = @@ -816,6 +5317,7 @@ fn egui_host_uses_logical_bounds_at_two_hundred_percent_scale() { } }); }); + output.textures_delta.clear(); assert!(failure.is_none(), "{failure:?}"); assert_eq!(resolved.panels.first().unwrap().outer.size, Size { width: 160.0, height: 120.0 }); assert!(h.probe.state(&editor_key(&h)).unwrap().renders >= 1); @@ -859,7 +5361,7 @@ fn solve_app_integration_is_opt_in_and_cannot_dirty_or_mutate_document() { }), ) .unwrap(); - super::app::tick_app(&mut app); + super::app::tick_app(&mut app, &egui::Context::default()); assert_eq!(app.panel_runtime().unwrap().controller_count(), 2, "the synthetic and real document retain separate controller owners"); assert!(std::sync::Arc::ptr_eq(&doc, &app.session.doc)); assert!(std::sync::Arc::ptr_eq(&model, &app.session.model.state())); @@ -1083,12 +5585,43 @@ fn snapshot_native_transitions_stage_effects_without_canceling_editors() { h.tick().unwrap(); let key = editor_key(&h); h.probe.edit(&key, |s| s.reject_cancel = true).unwrap(); - let mut native_layout = h.runtime.layout().layout().clone(); - native_layout.sections.first_mut().unwrap().location = SectionLocation::Window { + let location = SectionLocation::Window { host: HostId::new("snapshot-host").unwrap(), origin: Point { x: 0.0, y: 0.0 }, - return_to: DockReturn { zone: Zone::Left, index: 0, size: Size { width: 280.0, height: 240.0 }, collapsed: false, join: None }, + return_to: DockReturn { + zone: Zone::Left, + index: 0, + size: Size { width: 280.0, height: 240.0 }, + collapsed: false, + join: None, + section: None, + column: None, + column_index: 0, + column_width: None, + weight: 1.0, + preferred_extent: None, + extent_priority: 0, + }, }; + let native_layout = h + .runtime + .layout() + .project(transaction(vec![Mutation::Move { + instance: id("editor"), + destination: Destination::NewSection { + section: section("editor-section"), + index: 0, + location, + size: Size { width: 280.0, height: 240.0 }, + }, + }])) + .unwrap(); + assert!(native_layout.sections[0].column.is_none()); + let SectionLocation::Window { return_to, .. } = &native_layout.sections[0].location else { + panic!("projected native fixture must retain its dock return"); + }; + assert_eq!(return_to.column, h.runtime.layout().layout().sections[0].column); + assert!(return_to.column.is_some()); let reply = h.apply_layout(native_layout.clone(), None).unwrap(); assert!(reply.effects.iter().any(|e| matches!(e, HostEffect::CreateNative { .. }))); assert_eq!(h.native.hosts.len(), 1); @@ -1130,7 +5663,7 @@ fn egui_reference_host_rejects_sparse_or_no_input_geometry_before_widget_work() resolved.validate().unwrap(); let ctx = egui::Context::default(); let mut failure = None; - 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| { let before = ui.min_rect(); let mut host = EguiPanelHost { ui }; @@ -1141,6 +5674,7 @@ fn egui_reference_host_rejects_sparse_or_no_input_geometry_before_widget_work() assert_eq!(host.ui.min_rect(), before); }); }); + output.textures_delta.clear(); assert_eq!(failure.unwrap().rule, Rule::Capability); assert_eq!(h.probe.state(&editor_key(&h)).unwrap().renders, 0); } @@ -1155,7 +5689,7 @@ fn normal_egui_mount_preserves_the_parent_clip() { let ctx = egui::Context::default(); let parent = egui::Rect::from_min_max(egui::pos2(30.0, 40.0), egui::pos2(150.0, 160.0)); let mut failure = None; - 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| { ui.set_clip_rect(ui.clip_rect().intersect(parent)); let mut host = EguiPanelHost { ui }; @@ -1165,6 +5699,7 @@ fn normal_egui_mount_preserves_the_parent_clip() { .err(); }); }); + output.textures_delta.clear(); assert!(failure.is_none(), "{failure:?}"); let clip = h.probe.state(&editor_key(&h)).unwrap().last_clip.unwrap(); assert!(parent.contains_rect(clip)); @@ -1197,6 +5732,26 @@ fn panel_command_native_move() -> serde_json::Value { "size":{"width":280,"height":240}}}) } +fn prepare_app_commands(app: &mut crate::SolveApp) { + if !app.universal_panel_host_enabled() { + app.enable_universal_panel_host(HostOptions::default()).unwrap(); + } + app.panel_runtime.as_mut().unwrap().prepare_host(&app.session, capacity()).unwrap(); +} + +#[test] +fn application_structural_commands_require_a_captured_host_environment() { + let PanelMountHarness { runtime, .. } = PanelMountHarness::new(false).unwrap(); + let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + app.enable_panel_runtime(runtime, Box::new(FakeAppPanelServices { models: FakeModels { editable: true }, ..Default::default() })).unwrap(); + assert_eq!(app.run_panel_command("panel.open", &panel_command_editor()).unwrap_err().rule, Rule::Availability); + app.enable_universal_panel_host(HostOptions::default()).unwrap(); + assert_eq!(app.run_panel_command("panel.open", &panel_command_editor()).unwrap_err().rule, Rule::Availability); + prepare_app_commands(&mut app); + app.run_panel_command("panel.open", &panel_command_editor()).unwrap(); + assert_eq!(app.panel_runtime().unwrap().layout().layout().sections.len(), 1); +} + #[test] fn panel_commands_use_runtime_guards_and_keep_every_authoritative_state_on_preflight_failure() { use commands::LayoutCatalogue; @@ -1354,6 +5909,7 @@ fn solve_app_panel_commands_use_injected_services_without_document_camera_or_cac .unwrap(); let catalogue = fixture_command_catalogue(app.panel_runtime().unwrap().layout().registry()).unwrap(); app.panel_runtime_mut().unwrap().set_command_adapters(Box::new(catalogue), Box::new(FakeNativeAdapter::new(false))).unwrap(); + prepare_app_commands(&mut app); app.run("panel.open", panel_command_editor()).unwrap(); let key = ControllerKey { instance: id("editor"), owner: ContentOwner::Document(DocumentId::new(app.session.document_id.clone()).unwrap()) }; probe.edit(&key, |s| s.draft = "app command draft".into()).unwrap(); @@ -1390,6 +5946,7 @@ impl AppPanelServices for ForwardingAppServices { #[test] fn solve_app_forwards_dispatch_mount_content_switch_and_ticks_to_its_injected_provider() { let PanelMountHarness { runtime, probe, .. } = PanelMountHarness::new(false).unwrap(); + let catalogue = fixture_command_catalogue(runtime.layout().registry()).unwrap(); let trace = std::rc::Rc::new(std::cell::RefCell::new(ForwardingTrace::default())); let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), Default::default()); let revision = app.session.revision; @@ -1407,6 +5964,8 @@ fn solve_app_forwards_dispatch_mount_content_switch_and_ticks_to_its_injected_pr }), ) .unwrap(); + app.panel_runtime_mut().unwrap().set_command_adapters(Box::new(catalogue), Box::new(InAppNativeAdapter)).unwrap(); + prepare_app_commands(&mut app); app.dispatch_panel_layout(transaction(vec![ fixture_open("fixture.editor", "editor", "editor-section", Zone::Left, 0).unwrap(), fixture_open("fixture.log", "log", "log-section", Zone::Right, 1).unwrap(), @@ -1418,24 +5977,25 @@ fn solve_app_forwards_dispatch_mount_content_switch_and_ticks_to_its_injected_pr let saved = app.panel_runtime().unwrap().layout().layout().clone(); let resolved = resolve_geometry(app.panel_runtime().unwrap().layout(), capacity(), Direction::Ltr, 48.0).unwrap(); let mut host = FakePanelHost::default(); + app.disable_universal_panel_host().unwrap(); app.mount_panels(&resolved, &mut host).unwrap(); + prepare_app_commands(&mut app); assert!(!host.mounts.is_empty()); app.panel_content_action(&id("editor"), &ControlId::new("apply").unwrap()).unwrap(); assert_eq!(probe.state(&key).unwrap().applies, 1); - let mut other = saved.clone(); - other.workspace = WorkspaceId::new("app-workspace-two").unwrap(); - app.dispatch_panel_layout(LayoutAction::Replace { - expected_revision: Some(app.panel_runtime().unwrap().layout().inspect().revision), - layout: other.clone(), - }) - .unwrap(); + app.run_panel_command("layout.save", &serde_json::json!({"name":"Forwarding retained owners"})).unwrap(); + app.run_panel_command("layout.workspace.select", &serde_json::json!({"workspace":"fixture.other"})).unwrap(); + app.run_panel_command("layout.apply", &serde_json::json!({"name":"Forwarding retained owners"})).unwrap(); app.tick_panel_runtime().unwrap(); assert_eq!(app.panel_runtime().unwrap().controller_count(), 3); - app.dispatch_panel_layout(LayoutAction::Replace { expected_revision: None, layout: Layout::empty(other.workspace) }).unwrap(); + prepare_app_commands(&mut app); + app.dispatch_panel_layout(LayoutAction::Replace { expected_revision: None, layout: Layout::empty(WorkspaceId::new("fixture.other").unwrap()) }) + .unwrap(); let updates = probe.state(&key).unwrap().updates; app.tick_panel_runtime().unwrap(); assert!(probe.state(&key).unwrap().updates > updates); - app.dispatch_panel_layout(LayoutAction::Replace { expected_revision: None, layout: saved.clone() }).unwrap(); + prepare_app_commands(&mut app); + app.run_panel_command("layout.workspace.select", &serde_json::json!({"workspace":"fixture.workspace"})).unwrap(); app.tick_panel_runtime().unwrap(); assert_eq!(probe.state(&key).unwrap().draft, "draft through app"); assert!(probe.state(&key).unwrap().transaction_live); @@ -1499,6 +6059,7 @@ fn current_context_app() -> (crate::SolveApp, FixtureProbe) { }), ) .unwrap(); + prepare_app_commands(&mut app); (app, probe) } fn context_control(app: &mut crate::SolveApp, method: &str, params: serde_json::Value) -> serde_json::Value { @@ -1512,6 +6073,7 @@ fn context_control(app: &mut crate::SolveApp, method: &str, params: serde_json:: #[test] fn application_command_query_and_failure_refresh_same_named_document_before_any_tick() { let (mut app, probe) = current_context_app(); + prepare_app_commands(&mut app); app.run("panel.open", panel_command_editor()).unwrap(); let a = ControllerKey { instance: id("editor"), owner: ContentOwner::Document(DocumentId::new("context-a").unwrap()) }; probe.edit(&a, |state| state.draft = "document A draft".into()).unwrap(); @@ -1539,6 +6101,7 @@ fn application_command_query_and_failure_refresh_same_named_document_before_any_ #[test] fn application_atomic_boundary_refreshes_same_document_context_for_query_and_mutation() { let (mut app, _) = current_context_app(); + prepare_app_commands(&mut app); app.run("panel.open", panel_command_editor()).unwrap(); app.run("parameters.change", serde_json::json!({"name":"fixture_editable","expression":0})).unwrap(); let query = app.run_panel_batch(&[serde_json::json!({"command":"panel.list","params":null})]).unwrap(); @@ -1564,6 +6127,7 @@ fn application_atomic_boundary_refreshes_same_document_context_for_query_and_mut #[test] fn unsupported_atomic_intent_mixtures_refuse_before_context_or_controller_publication() { let (mut app, probe) = current_context_app(); + prepare_app_commands(&mut app); app.run("panel.open", panel_command_editor()).unwrap(); let key = ControllerKey { instance: id("editor"), owner: ContentOwner::Document(DocumentId::new("context-a").unwrap()) }; let before = app.panel_runtime().unwrap().layout().inspect(); @@ -1589,6 +6153,7 @@ fn unsupported_atomic_intent_mixtures_refuse_before_context_or_controller_public fn sequential_application_routes_refresh_after_file_new_and_same_document_model_changes() { for method in ["engine.script", "engine.batch"] { let (mut app, probe) = current_context_app(); + prepare_app_commands(&mut app); app.run("panel.open", panel_command_editor()).unwrap(); let a = ControllerKey { instance: id("editor"), owner: ContentOwner::Document(DocumentId::new("context-a").unwrap()) }; probe.edit(&a, |state| state.draft = "same instance, outgoing owner".into()).unwrap(); @@ -1652,6 +6217,7 @@ fn solve_app_gui_and_command_routes_share_native_owner_and_refuse_adapter_hot_sw let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), Default::default()); app.enable_panel_runtime(runtime, Box::new(FakeAppPanelServices { models: FakeModels { editable: true }, ..Default::default() })).unwrap(); app.panel_runtime_mut().unwrap().set_command_adapters(Box::new(catalogue), Box::new(SharedCommandNative(native.clone()))).unwrap(); + prepare_app_commands(&mut app); app.run("panel.open", panel_command_editor()).unwrap(); let key = ControllerKey { instance: id("editor"), owner: ContentOwner::Document(DocumentId::new(app.session.document_id.clone()).unwrap()) }; probe @@ -1661,6 +6227,7 @@ fn solve_app_gui_and_command_routes_share_native_owner_and_refuse_adapter_hot_sw }) .unwrap(); let destination: Destination = serde_json::from_value(panel_command_native_move()["destination"].clone()).unwrap(); + prepare_app_commands(&mut app); app.dispatch_panel_layout(transaction(vec![Mutation::Move { instance: id("editor"), destination }])).unwrap(); assert_eq!(native.borrow().hosts.len(), 1); assert!( @@ -1677,6 +6244,7 @@ fn solve_app_gui_and_command_routes_share_native_owner_and_refuse_adapter_hot_sw native.borrow_mut().fail_prepare = true; let before = app.panel_runtime().unwrap().layout().inspect(); let hosts = native.borrow().hosts.clone(); + prepare_app_commands(&mut app); assert_eq!( app.dispatch_panel_layout(transaction(vec![Mutation::NativeClose { host: HostId::new("native-host").unwrap() }])).unwrap_err().rule, Rule::Capability @@ -1684,8 +6252,5556 @@ fn solve_app_gui_and_command_routes_share_native_owner_and_refuse_adapter_hot_sw assert_eq!(app.panel_runtime().unwrap().layout().inspect(), before); assert_eq!(native.borrow().hosts, hosts); native.borrow_mut().fail_prepare = false; + prepare_app_commands(&mut app); app.dispatch_panel_layout(transaction(vec![Mutation::NativeClose { host: HostId::new("native-host").unwrap() }])).unwrap(); assert!(native.borrow().hosts.is_empty(), "GUI redocks the command-created host through the same owner"); assert_eq!(probe.state(&key).unwrap().draft, "native draft"); assert_eq!(probe.state(&key).unwrap().cancels, 0); } + +#[derive(Default)] +struct BoundaryObservation { + document: Option, + editable: std::collections::BTreeMap, + refreshes: usize, + fail_refresh: bool, + fail_factory: bool, + commands: Vec, + keyboard: std::collections::BTreeMap, + releases: Vec<(LocalScope, InstanceId)>, + factory_keys: Vec, + model_reads: Vec, +} +type BoundaryProbe = std::rc::Rc>; +struct BoundaryModels(BoundaryProbe); +impl PanelModels for BoundaryModels { + fn read(&self, owner: &ContentOwner, key: &str) -> PanelResult { + if key != "fixture.editable" { + return Err(error(Rule::MissingTarget, "unknown boundary model key")); + } + let mut state = self.0.borrow_mut(); + state.model_reads.push(owner.clone()); + let available = match owner { + ContentOwner::Document(document) => state.editable.get(document).copied().unwrap_or(false), + _ => true, + }; + Ok(serde_json::json!(available)) + } +} +struct BoundaryCommands(BoundaryProbe); +impl ContentCommandSink for BoundaryCommands { + fn execute(&mut self, owner: &ContentOwner, _command: &str, _input: serde_json::Value) -> PanelResult { + let mut state = self.0.borrow_mut(); + if matches!(owner, ContentOwner::Document(document) if Some(document) != state.document.as_ref()) { + return Err(error(Rule::Placement, "content command addressed the outgoing document")); + } + state.commands.push(owner.clone()); + Ok(serde_json::Value::Null) + } +} +struct BoundaryLocal(BoundaryProbe); +impl PanelLocalServices for BoundaryLocal { + fn request(&mut self, scope: &LocalScope, request: LocalRequest) -> PanelResult<()> { + scope.validate()?; + request.validate()?; + let mut state = self.0.borrow_mut(); + if scope.document != state.document { + return Err(error(Rule::Placement, "local request addressed the outgoing document")); + } + if let LocalRequest::KeyboardOwner { instance, .. } = request { + state.keyboard.insert(scope.clone(), instance); + } + Ok(()) + } + fn release(&mut self, scope: &LocalScope, instance: &InstanceId) { + let mut state = self.0.borrow_mut(); + if state.keyboard.get(scope) == Some(instance) { + state.keyboard.remove(scope); + } + state.releases.push((scope.clone(), instance.clone())); + } +} +struct BoundaryServices { + trace: BoundaryProbe, + models: BoundaryModels, + commands: BoundaryCommands, + local: BoundaryLocal, +} +impl BoundaryServices { + fn new(trace: BoundaryProbe) -> Self { + Self { models: BoundaryModels(trace.clone()), commands: BoundaryCommands(trace.clone()), local: BoundaryLocal(trace.clone()), trace } + } +} +impl AppPanelServices for BoundaryServices { + fn refresh_read_only(&mut self, session: &solidcraft_engine::Session) -> PanelResult<()> { + let mut state = self.trace.borrow_mut(); + state.refreshes += 1; + if state.fail_refresh { + return Err(error(Rule::Availability, "boundary refresh refused")); + } + let document = DocumentId::new(session.document_id.clone())?; + state.editable.entry(document.clone()).or_insert(true); + state.document = Some(document); + Ok(()) + } + fn services(&mut self) -> ContentServices<'_> { + ContentServices { models: &self.models, commands: &mut self.commands, local: &mut self.local } + } +} + +fn boundary_app() -> (crate::scenario::Harness, FixtureProbe, BoundaryProbe) { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + let PanelMountHarness { mut runtime, probe, .. } = PanelMountHarness::without_content(true).unwrap(); + let trace = BoundaryProbe::default(); + for (kind, editor, ownership) in + [("fixture.editor", true, Ownership::Document), ("fixture.log", false, Ownership::Workspace), ("fixture.pin", false, Ownership::Workspace)] + { + let binding = fixture_controller_binding(&probe, editor, ownership); + let create = binding.create; + let failure = trace.clone(); + runtime + .register( + PanelKind::new(kind).unwrap(), + ControllerBinding { + ownership, + create: Box::new(move |instance, owner| { + failure.borrow_mut().factory_keys.push(ControllerKey { instance: instance.id.clone(), owner: owner.clone() }); + if editor && failure.borrow().fail_factory { + return Err(error(Rule::Lifecycle, "incoming factory refused")); + } + create(instance, owner) + }), + }, + ) + .unwrap(); + } + h.app.enable_panel_runtime(runtime, Box::new(BoundaryServices::new(trace.clone()))).unwrap(); + prepare_app_commands(&mut h.app); + h.app.dispatch_panel_layout(transaction(vec![fixture_open("fixture.editor", "editor", "editor-section", Zone::Left, 0).unwrap()])).unwrap(); + h.frames(3); + (h, probe, trace) +} + +fn app_editor_key(app: &crate::SolveApp) -> ControllerKey { + ControllerKey { instance: id("editor"), owner: ContentOwner::Document(DocumentId::new(app.session.document_id.clone()).unwrap()) } +} + +/// Exercises the real app ordering: logic has ALREADY ticked, then a control/ +/// shortcut changes Session, then app UI (including app-bar tabs) mounts the host. +fn boundary_frame(h: &mut crate::scenario::Harness, events: Vec, mut after_logic: impl FnMut(&mut crate::SolveApp)) -> egui::FullOutput { + let time = h.ctx.input(|input| input.time) + 1.0 / 60.0; + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0))), + events, + time: Some(time), + focused: true, + ..Default::default() + }, + |ui| { + h.app.logic(ui.ctx()); + if ui.ctx().current_pass_index() == 0 { + after_logic(&mut h.app); + } + h.app.ui(ui); + }, + ); + output.textures_delta.clear(); + output +} + +fn app_control(app: &crate::SolveApp, target: HostControlTarget) -> HostFrameControl { + app.universal_panel_frame().unwrap().controls.iter().find(|control| control.target == target).unwrap().clone() +} +fn button_event(at: egui::Pos2, pressed: bool) -> egui::Event { + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE } +} + +#[test] +fn same_frame_session_switch_after_logic_cancels_old_capture_menu_focus_and_routes_incoming_actions() { + for captured in [false, true] { + let (mut h, probe, trace) = boundary_app(); + let old_key = app_editor_key(&h.app); + probe.edit(&old_key, |state| state.draft = "outgoing draft survives same-frame switch".into()).unwrap(); + let header = app_control(&h.app, HostControlTarget::Pointer(HostPointerTarget::Header { instance: id("editor") })); + let at = egui_rect(header.bounds).center(); + h.ctx.memory_mut(|memory| memory.request_focus(header.id)); + h.frames(1); + let old_scope = runtime_scope(h.app.panel_runtime().unwrap()); + h.app + .panel_runtime_mut() + .unwrap() + .with_services(|_, services| { + services.local.request(&old_scope, LocalRequest::KeyboardOwner { instance: id("editor"), control: ControlId::new("draft").unwrap() }) + }) + .unwrap(); + if captured { + h.frame_with(vec![egui::Event::PointerMoved(at), button_event(at, true)]); + h.frame_with(vec![egui::Event::PointerMoved(at + egui::vec2(8.0, 0.0))]); + assert!(h.app.panel_runtime_mut().unwrap().host().unwrap().interaction().is_captured()); + } else { + let menu = app_control(&h.app, HostControlTarget::Pointer(HostPointerTarget::Menu { instance: id("editor") })); + let at = egui_rect(menu.bounds).center(); + h.frame_with(vec![egui::Event::PointerMoved(at), button_event(at, true)]); + h.frame_with(vec![button_event(at, false)]); + h.frames(2); + assert!(h.app.universal_panel_frame().unwrap().menu_bounds.is_some()); + } + let before = probe.state(&old_key).unwrap(); + let old_focus = h.ctx.memory(|memory| memory.focused()); + let saved = h.app.panel_runtime().unwrap().layout().layout().clone(); + let drop = egui::pos2(1500.0, 600.0); + let incoming_session = solidcraft_engine::Session::default(); + let document = incoming_session.doc.clone(); + let model = incoming_session.model.state(); + let undo = incoming_session.undo.len(); + let dirty = incoming_session.is_dirty(); + let mut incoming = Some(incoming_session); + let mut switched_revision = None; + let output = boundary_frame(&mut h, vec![egui::Event::PointerMoved(drop), button_event(drop, false)], |app| { + crate::documents::open_tab(app, incoming.take().unwrap()).unwrap(); + app.home.open = false; + switched_revision = Some(app.session.revision); + }); + let revision = switched_revision.unwrap(); + assert!(!output.shapes.is_empty(), "the real app UI path was traversed headlessly"); + let incoming_key = app_editor_key(&h.app); + assert_ne!(incoming_key.owner, old_key.owner); + assert_eq!(h.app.panel_runtime().unwrap().environment().document, Some(DocumentId::new(h.app.session.document_id.clone()).unwrap())); + let frame = h.app.universal_panel_frame().unwrap(); + assert!(frame.preview.is_none() && frame.menu_bounds.is_none()); + assert!(!h.app.panel_runtime_mut().unwrap().host().unwrap().interaction().is_captured()); + assert_eq!(h.app.panel_runtime().unwrap().layout().layout(), &saved, "old release cannot move incoming content"); + assert_ne!(app_control(&h.app, header.target).id, header.id); + assert_ne!(h.ctx.memory(|memory| memory.focused()), Some(header.id)); + if let Some(old_focus) = old_focus { + assert_ne!(h.ctx.memory(|memory| memory.focused()), Some(old_focus)); + } + assert!(!trace.borrow().keyboard.contains_key(&old_scope)); + let old = probe.state(&old_key).unwrap(); + assert_eq!(old.updates, before.updates + 1, "only the one logic tick updates outgoing services"); + assert_eq!(old.renders, before.renders, "outgoing owner cannot render after the Session switch"); + assert_eq!(old.draft, before.draft); + assert_eq!((old.cancels, old.applies, old.destroys), (0, 0, 0)); + let incoming = probe.state(&incoming_key).unwrap(); + assert_eq!(incoming.updates, 0, "boundary reconciliation must not add a background tick"); + assert!(incoming.renders > 0, "incoming retained owner renders in the SAME frame"); + let updates = old.updates; + h.app.panel_content_action(&id("editor"), &ControlId::new("apply").unwrap()).unwrap(); + h.app.dispatch_panel_layout(transaction(vec![Mutation::Focus { instance: id("editor") }])).unwrap(); + assert_eq!(probe.state(&incoming_key).unwrap().applies, 1); + assert_eq!(probe.state(&old_key).unwrap().applies, 0); + assert_eq!(probe.state(&old_key).unwrap().updates, updates); + assert_eq!(probe.state(&incoming_key).unwrap().updates, 0); + assert_eq!(trace.borrow().commands, vec![incoming_key.owner]); + assert_eq!(h.app.session.revision, revision); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(h.app.session.is_dirty(), dirty); + assert!(std::sync::Arc::ptr_eq(&document, &h.app.session.doc)); + assert!(std::sync::Arc::ptr_eq(&model, &h.app.session.model.state())); + } +} + +#[test] +fn same_frame_refresh_refusal_fails_closed_before_render_dispatch_or_content_action() { + for factory_refusal in [false, true] { + let (mut h, probe, trace) = boundary_app(); + let key = app_editor_key(&h.app); + probe.edit(&key, |state| state.draft = "retained through refresh refusal".into()).unwrap(); + let header = app_control(&h.app, HostControlTarget::Pointer(HostPointerTarget::Header { instance: id("editor") })); + let at = egui_rect(header.bounds).center(); + h.frame_with(vec![egui::Event::PointerMoved(at), button_event(at, true)]); + let before = probe.state(&key).unwrap(); + let saved = h.app.panel_runtime().unwrap().layout().inspect(); + let mut incoming = Some(solidcraft_engine::Session::default()); + boundary_frame(&mut h, vec![button_event(at + egui::vec2(500.0, 0.0), false)], |app| { + crate::documents::open_tab(app, incoming.take().unwrap()).unwrap(); + app.home.open = false; + if factory_refusal { + trace.borrow_mut().fail_factory = true; + } else { + trace.borrow_mut().fail_refresh = true; + } + }); + assert!(h.app.universal_panel_frame().is_none()); + assert!(!h.app.panel_runtime_mut().unwrap().host().unwrap().interaction().is_captured()); + let expected = if factory_refusal { Rule::Lifecycle } else { Rule::Availability }; + assert_eq!(h.app.panel_content_action(&id("editor"), &ControlId::new("apply").unwrap()).unwrap_err().rule, expected); + assert_eq!(h.app.dispatch_panel_layout(transaction(vec![Mutation::Close { instance: id("editor") }])).unwrap_err().rule, expected); + assert_eq!(h.app.panel_runtime().unwrap().layout().inspect(), saved); + assert_eq!(h.app.panel_runtime().unwrap().controller_count(), 1, "a refused incoming factory cannot publish another retained owner"); + let after = probe.state(&key).unwrap(); + assert_eq!(after.updates, before.updates + 1); + assert_eq!(after.renders, before.renders); + assert_eq!(after.draft, before.draft); + assert_eq!((after.applies, after.cancels, after.destroys), (0, 0, 0)); + assert!(!h.app.panel_runtime().unwrap().state(&key).unwrap().presented); + assert!(trace.borrow().commands.is_empty()); + trace.borrow_mut().fail_refresh = false; + trace.borrow_mut().fail_factory = false; + h.frames(1); + assert_eq!(probe.state(&key).unwrap().draft, before.draft); + assert!(h.app.panel_runtime().unwrap().state(&app_editor_key(&h.app)).unwrap().presented); + } +} + +#[test] +fn same_frame_programmatic_actions_and_mount_reconcile_a_switch_after_host_preparation() { + let (mut h, probe, trace) = boundary_app(); + let old_key = app_editor_key(&h.app); + let before = probe.state(&old_key).unwrap(); + let mut incoming = Some(solidcraft_engine::Session::default()); + let time = h.ctx.input(|input| input.time) + 1.0 / 60.0; + let mut output = + h.ctx.run_ui(egui::RawInput { screen_rect: Some(egui_rect(capacity())), time: Some(time), focused: true, ..Default::default() }, |ui| { + h.app.logic(ui.ctx()); + if ui.ctx().current_pass_index() == 0 { + h.app.panel_runtime.as_mut().unwrap().prepare_host(&h.app.session, capacity()).unwrap(); + crate::documents::open_tab(&mut h.app, incoming.take().unwrap()).unwrap(); + h.app.home.open = false; + // Neither call may borrow outgoing cached models/owner services, and + // neither is allowed to add another background tick. + h.app.panel_content_action(&id("editor"), &ControlId::new("apply").unwrap()).unwrap(); + h.app.dispatch_panel_layout(transaction(vec![Mutation::Focus { instance: id("editor") }])).unwrap(); + } + h.app.panel_runtime.as_mut().unwrap().show_host(&h.app.session, ui).unwrap(); + }); + output.textures_delta.clear(); + let incoming_key = app_editor_key(&h.app); + assert_ne!(old_key.owner, incoming_key.owner); + assert_eq!(probe.state(&old_key).unwrap().updates, before.updates + 1); + assert_eq!(probe.state(&old_key).unwrap().renders, before.renders); + assert_eq!(probe.state(&old_key).unwrap().applies, 0); + assert_eq!(probe.state(&incoming_key).unwrap().updates, 0); + assert_eq!(probe.state(&incoming_key).unwrap().applies, 1); + assert!(probe.state(&incoming_key).unwrap().renders > 0); + assert_eq!(trace.borrow().commands, vec![incoming_key.owner]); + assert_eq!(h.app.panel_runtime().unwrap().environment().document, Some(DocumentId::new(h.app.session.document_id.clone()).unwrap())); + let incoming_header = app_control(&h.app, HostControlTarget::Pointer(HostPointerTarget::Header { instance: id("editor") })); + assert_eq!( + h.ctx.memory(|memory| memory.focused()), + Some(incoming_header.id), + "explicit incoming Focus targets the current owner's actual widget" + ); +} + +#[test] +fn same_frame_current_document_availability_is_reconciled_without_another_service_tick() { + let (mut h, probe, trace) = boundary_app(); + let key = app_editor_key(&h.app); + let document = DocumentId::new(h.app.session.document_id.clone()).unwrap(); + let before = probe.state(&key).unwrap(); + boundary_frame(&mut h, Vec::new(), |_| { + trace.borrow_mut().editable.insert(document.clone(), false); + }); + assert_eq!(probe.state(&key).unwrap().updates, before.updates + 1); + assert_eq!(probe.state(&key).unwrap().renders, before.renders); + assert!(!h.app.universal_panel_frame().unwrap().layout.resolved.panels.iter().any(|panel| panel.instance == id("editor"))); + assert_eq!(h.app.panel_content_action(&id("editor"), &ControlId::new("apply").unwrap()).unwrap_err().rule, Rule::Availability); + assert_eq!(probe.state(&key).unwrap().updates, before.updates + 1); + assert!(trace.borrow().commands.is_empty()); +} + +#[derive(Clone)] +struct SharedNative(std::rc::Rc>); +impl NativeHostAdapter for SharedNative { + fn capabilities(&self) -> HostCapabilities { + self.0.borrow().capabilities.clone() + } + fn prepare(&self, effects: &[HostEffect]) -> PanelResult<()> { + self.0.borrow().prepare(effects) + } + fn commit(&mut self, effects: &[HostEffect]) { + self.0.borrow_mut().commit(effects); + } +} + +fn native_placement(instance: &str, section_id: &str, host_id: &str, index: usize) -> Mutation { + Mutation::Move { + instance: id(instance), + destination: Destination::NewSection { + section: section(section_id), + index, + location: SectionLocation::Window { + host: HostId::new(host_id).unwrap(), + origin: Point { x: 0.0, y: 0.0 }, + return_to: DockReturn { + zone: Zone::Left, + index: 0, + size: Size { width: 280.0, height: 240.0 }, + collapsed: false, + join: None, + section: None, + column: None, + column_index: 0, + column_width: None, + weight: 1.0, + preferred_extent: None, + extent_priority: 0, + }, + }, + size: Size { width: 280.0, height: 240.0 }, + }, + } +} + +#[test] +fn app_native_owner_is_persistent_with_host_off_or_on_and_refusals_preserve_resources() { + for shared_host in [false, true] { + let PanelMountHarness { runtime, probe, .. } = PanelMountHarness::new(true).unwrap(); + let trace = BoundaryProbe::default(); + let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + app.enable_panel_runtime(runtime, Box::new(BoundaryServices::new(trace.clone()))).unwrap(); + prepare_app_commands(&mut app); + app.dispatch_panel_layout(transaction(vec![fixture_open("fixture.editor", "editor", "editor-section", Zone::Left, 0).unwrap()])).unwrap(); + + let key = app_editor_key(&app); + probe.edit(&key, |state| state.draft = "native owner retains this draft".into()).unwrap(); + let action = transaction(vec![native_placement("editor", "native-editor", "owned-native", 0)]); + let before = app.panel_runtime().unwrap().layout().inspect(); + assert_eq!(app.dispatch_panel_layout(action.clone()).unwrap_err().rule, Rule::Capability, "default owner cannot create native resources"); + assert_eq!(app.panel_runtime().unwrap().layout().inspect(), before); + let invalid = std::rc::Rc::new(std::cell::RefCell::new(FakeNativeAdapter::new(true))); + invalid.borrow_mut().capabilities.max_native_hosts = MAX_SECTIONS + 1; + assert_eq!(app.set_panel_native_adapter(Box::new(SharedNative(invalid.clone()))).unwrap_err().rule, Rule::Capability); + assert!(!app.panel_runtime_mut().unwrap().native_capabilities().native_windows); + assert!(invalid.borrow().hosts.is_empty()); + let native = std::rc::Rc::new(std::cell::RefCell::new(FakeNativeAdapter::new(true))); + app.set_panel_native_adapter(Box::new(SharedNative(native.clone()))).unwrap(); + native.borrow_mut().fail_prepare = true; + assert_eq!(app.dispatch_panel_layout(action.clone()).unwrap_err().rule, Rule::Capability); + assert_eq!(app.panel_runtime().unwrap().layout().inspect(), before); + assert!(native.borrow().hosts.is_empty()); + assert_eq!(native.borrow().commits, 0); + native.borrow_mut().fail_prepare = false; + prepare_app_commands(&mut app); + app.dispatch_panel_layout(action).unwrap(); + assert_eq!(native.borrow().hosts.get(&HostId::new("owned-native").unwrap()), Some(§ion("native-editor"))); + if !shared_host { + app.disable_universal_panel_host().unwrap(); + } + let after_create = app.panel_runtime().unwrap().layout().inspect(); + let commits = native.borrow().commits; + let replacement = std::rc::Rc::new(std::cell::RefCell::new(FakeNativeAdapter::new(true))); + assert_eq!(app.set_panel_native_adapter(Box::new(SharedNative(replacement.clone()))).unwrap_err().rule, Rule::Lifecycle); + assert!(replacement.borrow().hosts.is_empty()); + assert_eq!(native.borrow().hosts.len(), 1); + probe.edit(&key, |state| state.reject_cancel = true).unwrap(); + assert_eq!(app.disable_panel_runtime().unwrap_err().rule, Rule::Lifecycle); + assert_eq!(app.panel_runtime().unwrap().layout().inspect(), after_create); + assert_eq!(native.borrow().commits, commits); + assert_eq!(native.borrow().hosts.len(), 1); + assert_eq!(probe.state(&key).unwrap().destroys, 0); + probe.edit(&key, |state| state.reject_cancel = false).unwrap(); + native.borrow_mut().fail_prepare = true; + assert_eq!(app.disable_panel_runtime().unwrap_err().rule, Rule::Capability); + assert_eq!(app.panel_runtime().unwrap().layout().inspect(), after_create); + assert_eq!(native.borrow().commits, commits); + assert_eq!(probe.state(&key).unwrap().destroys, 0); + native.borrow_mut().fail_prepare = false; + app.disable_panel_runtime().unwrap(); + assert!(app.panel_runtime().is_none()); + assert!(native.borrow().hosts.is_empty(), "the SAME installed owner releases its native resources"); + assert_eq!(native.borrow().commits, commits + 1); + assert_eq!(probe.state(&key).unwrap().draft, "native owner retains this draft"); + assert_eq!(probe.state(&key).unwrap().destroys, 1); + } +} + +fn mount_app_root(app: &mut crate::SolveApp, ctx: &egui::Context) { + let session = &app.session; + let integration = app.panel_runtime.as_mut().unwrap(); + integration.prepare_host(session, capacity()).unwrap(); + let mut output = ctx.run_ui(egui::RawInput { screen_rect: Some(egui_rect(capacity())), focused: true, ..Default::default() }, |ui| { + integration.show_host(session, ui).unwrap(); + }); + output.textures_delta.clear(); +} + +#[test] +fn app_root_and_native_cohorts_alternate_mounts_without_releasing_other_hosts() { + let (mut h, probe, trace) = boundary_app(); + let native = std::rc::Rc::new(std::cell::RefCell::new(FakeNativeAdapter::new(true))); + h.app.set_panel_native_adapter(Box::new(SharedNative(native.clone()))).unwrap(); + h.app + .dispatch_panel_layout(transaction(vec![ + fixture_open("fixture.log", "native-a", "a", Zone::Right, 1).unwrap(), + fixture_open("fixture.log", "native-b", "b", Zone::Right, 2).unwrap(), + ])) + .unwrap(); + h.app + .dispatch_panel_layout(transaction(vec![ + native_placement("native-a", "native-section-a", "host-a", 1), + native_placement("native-b", "native-section-b", "host-b", 2), + ])) + .unwrap(); + let all = resolve_geometry(h.app.panel_runtime().unwrap().layout(), capacity(), Direction::Ltr, 48.0).unwrap(); + let frame_for = |instance: &str| ResolvedLayout { + panels: all.panels.iter().filter(|panel| panel.instance == id(instance)).cloned().collect(), + ..Default::default() + }; + let frame_a = frame_for("native-a"); + let frame_b = frame_for("native-b"); + assert_eq!((frame_a.panels.len(), frame_b.panels.len()), (1, 1)); + let host_a = HostId::new("host-a").unwrap(); + let host_b = HostId::new("host-b").unwrap(); + let mut renderer_a = FakePanelHost::default(); + let mut renderer_b = FakePanelHost::default(); + mount_app_root(&mut h.app, &h.ctx); + h.app.mount_native_panels(&host_a, &frame_a, &mut renderer_a).unwrap(); + h.app.mount_native_panels(&host_b, &frame_b, &mut renderer_b).unwrap(); + let root_key = app_editor_key(&h.app); + let workspace = h.app.panel_runtime().unwrap().environment().workspace.clone(); + let a_key = ControllerKey { instance: id("native-a"), owner: ContentOwner::Workspace(workspace.clone()) }; + let b_key = ControllerKey { instance: id("native-b"), owner: ContentOwner::Workspace(workspace) }; + let root_scope = runtime_scope(h.app.panel_runtime().unwrap()); + let mut a_scope = root_scope.clone(); + a_scope.viewport = ViewportId::new("host-a").unwrap(); + let mut b_scope = root_scope.clone(); + b_scope.viewport = ViewportId::new("host-b").unwrap(); + for (scope, instance) in [(&root_scope, "editor"), (&a_scope, "native-a"), (&b_scope, "native-b")] { + h.app + .panel_runtime_mut() + .unwrap() + .with_services(|_, services| { + services.local.request(scope, LocalRequest::KeyboardOwner { instance: id(instance), control: ControlId::new("draft").unwrap() }) + }) + .unwrap(); + } + let keyboard = trace.borrow().keyboard.clone(); + let releases = trace.borrow().releases.len(); + for _ in 0..3 { + h.app.mount_native_panels(&host_b, &frame_b, &mut renderer_b).unwrap(); + mount_app_root(&mut h.app, &h.ctx); + h.app.mount_native_panels(&host_a, &frame_a, &mut renderer_a).unwrap(); + for key in [&root_key, &a_key, &b_key] { + let state = h.app.panel_runtime().unwrap().state(key).unwrap(); + assert!(state.presented && state.activated, "partial viewport frames cannot deactivate {key:?}"); + } + assert_eq!(trace.borrow().keyboard, keyboard); + assert_eq!(trace.borrow().releases.len(), releases); + } + assert!(renderer_a.mounts.iter().all(|record| record.context.native_host.as_ref() == Some(&host_a) && record.context.viewport.0 == host_a.0)); + assert!(renderer_b.mounts.iter().all(|record| record.context.native_host.as_ref() == Some(&host_b) && record.context.viewport.0 == host_b.0)); + assert_eq!(h.app.mount_native_panels(&host_a, &frame_b, &mut renderer_a).unwrap_err().rule, Rule::Placement); + assert_eq!(trace.borrow().keyboard, keyboard, "a foreign cohort rejects before lifecycle/local release"); + h.app.mount_native_panels(&host_a, &ResolvedLayout::default(), &mut renderer_a).unwrap(); + assert!(!h.app.panel_runtime().unwrap().state(&a_key).unwrap().presented); + assert!(h.app.panel_runtime().unwrap().state(&root_key).unwrap().presented); + assert!(h.app.panel_runtime().unwrap().state(&b_key).unwrap().presented); + assert!(!trace.borrow().keyboard.contains_key(&a_scope)); + assert_eq!(trace.borrow().keyboard.get(&root_scope), Some(&id("editor"))); + assert_eq!(trace.borrow().keyboard.get(&b_scope), Some(&id("native-b"))); + h.app.disable_universal_panel_host().unwrap(); + assert!(!h.app.panel_runtime().unwrap().state(&root_key).unwrap().presented); + assert!(h.app.panel_runtime().unwrap().state(&b_key).unwrap().presented); + assert!(!trace.borrow().keyboard.contains_key(&root_scope)); + assert_eq!(trace.borrow().keyboard.get(&b_scope), Some(&id("native-b"))); + assert_eq!( + h.app.mount_panels(&frame_b, &mut renderer_b).unwrap_err().rule, + Rule::Placement, + "generic root mounting cannot masquerade as a partial native frame even with the shared host off" + ); + assert!(h.app.panel_runtime().unwrap().state(&b_key).unwrap().presented); + assert_eq!(trace.borrow().keyboard.get(&b_scope), Some(&id("native-b"))); + assert_eq!(native.borrow().hosts.len(), 2, "unmounting presentation is not native resource teardown"); + assert_eq!(probe.state(&root_key).unwrap().cancels, 0); + h.app.disable_panel_runtime().unwrap(); + assert!(native.borrow().hosts.is_empty()); + assert!(trace.borrow().keyboard.is_empty()); +} + +#[test] +fn foreign_foreground_widgets_block_raw_header_and_sash_presses_at_both_scales() { + for scale in [1.0, 2.0] { + for sash in [false, true] { + for (same_frame_release, warm_cover) in [(false, false), (false, true), (true, false), (true, true)] { + let mut content = PanelMountHarness::new(false).unwrap(); + open_editor(&mut content); + content.dispatch(vec![fixture_open("fixture.log", "neighbour", "neighbour-section", Zone::Left, 1).unwrap()]).unwrap(); + let key = editor_key(&content); + content.probe.edit(&key, |state| state.draft = "foreign window must not move this".into()).unwrap(); + let mut raw = RawPanelHost::new(content, scale); + raw.prime_foreign_window(); + raw.frame(Vec::new(), false); + let target = if sash { + let sash = raw.host.frame().unwrap().layout.sashes.first().unwrap(); + HostControlTarget::Pointer(HostPointerTarget::Sash { first: sash.first.clone(), second: sash.second.clone() }) + } else { + HostControlTarget::Pointer(HostPointerTarget::Header { instance: id("editor") }) + }; + let at = raw.at(target.clone()); + let cover = egui::Rect::from_center_size(at, egui::vec2(180.0, 80.0)); + if warm_cover { + raw.foreign_cover = Some(cover); + } + raw.frame(Vec::new(), false); + raw.frame(vec![egui::Event::PointerMoved(at)], false); + let control = raw.host.frame().unwrap().controls.iter().find(|control| control.target == target).unwrap(); + let response = raw.ctx.read_response(control.id).unwrap(); + if warm_cover { + assert_ne!(raw.ctx.layer_id_at(at), Some(response.layer_id), "real unrelated Area covers the host control"); + } + raw.foreign_cover = Some(cover); + let before = raw.content.runtime.layout().inspect(); + let state = raw.content.probe.state(&key).unwrap(); + let native_commits = raw.content.native.commits; + let drop = if sash { at + egui::vec2(0.0, 160.0) } else { egui::pos2(raw.capacity.size.width - 1.0, 550.0) }; + if same_frame_release { + raw.frame( + vec![egui::Event::PointerMoved(at), button_event(at, true), egui::Event::PointerMoved(drop), button_event(drop, false)], + true, + ); + } else { + raw.pointer(at, true, true); + if warm_cover { + assert!( + raw.foreign_responses.iter().any(|response| response.is_pointer_button_down_on()), + "actual foreign widget receives the press" + ); + } + assert!(!raw.host.interaction().is_captured(), "covered chrome must not capture raw input"); + raw.frame(vec![egui::Event::PointerMoved(drop)], false); + raw.pointer(drop, false, true); + } + assert_eq!(raw.content.runtime.layout().inspect(), before, "foreign input cannot mutate header/sash placement"); + assert!(!raw.host.interaction().is_captured()); + assert!(raw.host.frame().unwrap().preview.is_none()); + assert!( + !raw.host + .frame() + .unwrap() + .events + .iter() + .any(|event| matches!(event, HostEvent::Committed { .. } | HostEvent::PreparedCommitted { .. })) + ); + assert_eq!(raw.content.native.commits, native_commits); + let after = raw.content.probe.state(&key).unwrap(); + assert_eq!(after.draft, state.draft); + assert_eq!( + (after.cancels, after.reparents, after.applies, after.destroys), + (state.cancels, state.reparents, state.applies, state.destroys) + ); + assert_eq!(raw.content.commands.calls, 0); + } + } + } +} + +#[test] +fn overlapping_floating_sections_route_only_the_actual_top_widget_at_both_scales() { + for scale in [1.0, 2.0] { + for top_body_covers_header in [false, true] { + let mut content = PanelMountHarness::new(false).unwrap(); + open_editor(&mut content); + content + .dispatch(vec![ + Mutation::Move { + instance: id("editor"), + destination: Destination::NewSection { + section: section("editor-floating"), + index: 0, + location: SectionLocation::Floating { origin: Point { x: 200.0, y: 200.0 } }, + size: Size { width: 320.0, height: 280.0 }, + }, + }, + fixture_open("fixture.log", "top", "top-floating", Zone::Floating, 1).unwrap(), + ]) + .unwrap(); + let top_origin = if top_body_covers_header { Point { x: 200.0, y: 100.0 } } else { Point { x: 200.0, y: 200.0 } }; + content + .dispatch(vec![Mutation::Move { + instance: id("top"), + destination: Destination::NewSection { + section: section("top-floating"), + index: 1, + location: SectionLocation::Floating { origin: top_origin }, + size: Size { width: 320.0, height: 360.0 }, + }, + }]) + .unwrap(); + let key = editor_key(&content); + content.probe.edit(&key, |state| state.draft = "bottom floating draft".into()).unwrap(); + let mut raw = RawPanelHost::new(content, scale); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + let lower = HostControlTarget::Pointer(HostPointerTarget::Header { instance: id("editor") }); + let at = raw.at(lower.clone()); + raw.frame(vec![egui::Event::PointerMoved(at)], false); + let lower_id = raw.host.frame().unwrap().controls.iter().find(|control| control.target == lower).unwrap().id; + assert_ne!(raw.ctx.layer_id_at(at), Some(raw.ctx.read_response(lower_id).unwrap().layer_id)); + let before = raw.content.runtime.layout().inspect(); + let native_commits = raw.content.native.commits; + raw.pointer(at, true, true); + assert!(!raw.ctx.read_response(lower_id).unwrap().is_pointer_button_down_on()); + if top_body_covers_header { + assert!(!raw.host.interaction().is_captured()); + } else { + assert!(raw.host.interaction().is_captured(), "top card's own header can capture"); + } + let drop = egui::pos2(raw.capacity.size.width - 1.0, 550.0); + raw.frame(vec![egui::Event::PointerMoved(drop)], false); + raw.pointer(drop, false, true); + assert_eq!(raw.content.runtime.layout().layout().containing(&id("editor")).unwrap().location.zone(), Zone::Floating); + if top_body_covers_header { + assert_eq!(raw.content.runtime.layout().inspect(), before); + assert_eq!(raw.content.native.commits, native_commits); + } else { + assert_eq!(raw.content.runtime.layout().layout().containing(&id("top")).unwrap().location.zone(), Zone::Right); + assert_eq!(raw.content.runtime.layout().inspect().revision, before.revision + 1); + } + assert_eq!(raw.content.probe.state(&key).unwrap().draft, "bottom floating draft"); + assert_eq!(raw.content.probe.state(&key).unwrap().reparents, 1, "only the initial explicit fixture move reparents the lower editor"); + assert_eq!(raw.content.commands.calls, 0); + } + // A floating body also covers a dock sash on a different real egui + // layer. Resizing the obscured dock must not start underneath it. + let mut content = PanelMountHarness::new(false).unwrap(); + open_editor(&mut content); + content + .dispatch(vec![ + fixture_open("fixture.log", "neighbour", "neighbour-section", Zone::Left, 1).unwrap(), + fixture_open("fixture.log", "top", "top-floating", Zone::Floating, 2).unwrap(), + ]) + .unwrap(); + let mut raw = RawPanelHost::new(content, scale); + raw.frame(Vec::new(), false); + let sash = raw.host.frame().unwrap().layout.sashes.first().unwrap().clone(); + let target = HostControlTarget::Pointer(HostPointerTarget::Sash { first: sash.first, second: sash.second }); + let at = raw.at(target.clone()); + raw.content + .dispatch(vec![Mutation::Move { + instance: id("top"), + destination: Destination::NewSection { + section: section("top-floating"), + index: 2, + location: SectionLocation::Floating { origin: Point { x: 0.0, y: at.y - 100.0 } }, + size: Size { width: 320.0, height: 360.0 }, + }, + }]) + .unwrap(); + raw.frame(Vec::new(), false); + raw.frame(vec![egui::Event::PointerMoved(at)], false); + let source = raw.host.frame().unwrap().controls.iter().find(|control| control.target == target).unwrap(); + assert_ne!(raw.ctx.layer_id_at(at), Some(raw.ctx.read_response(source.id).unwrap().layer_id)); + let before = raw.content.runtime.layout().inspect(); + raw.pointer(at, true, false); + assert!(!raw.host.interaction().is_captured()); + raw.frame(vec![egui::Event::PointerMoved(at + egui::vec2(0.0, 100.0))], false); + raw.pointer(at + egui::vec2(0.0, 100.0), false, true); + assert_eq!(raw.content.runtime.layout().inspect(), before); + } +} + +#[test] +fn genuine_host_capture_survives_out_of_bounds_motion_and_a_foreign_release_layer() { + for scale in [1.0, 2.0] { + let mut content = PanelMountHarness::new(false).unwrap(); + open_editor(&mut content); + let mut raw = RawPanelHost::new(content, scale); + raw.prime_foreign_window(); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + let at = raw.at(HostControlTarget::Pointer(HostPointerTarget::Header { instance: id("editor") })); + raw.frame(vec![egui::Event::PointerMoved(at)], false); + let before = raw.content.runtime.layout().inspect(); + raw.pointer(at, true, false); + assert!(raw.host.interaction().is_captured()); + raw.frame(vec![egui::Event::PointerMoved(egui::pos2(-40.0, raw.capacity.size.height + 50.0))], false); + assert!(raw.host.interaction().is_captured(), "out-of-bounds movement retains a genuine capture"); + let drop = egui::pos2(raw.capacity.size.width - 1.0, 550.0); + raw.foreign_cover = Some(egui::Rect::from_center_size(drop, egui::vec2(80.0, 100.0))); + raw.frame(vec![egui::Event::PointerMoved(drop)], false); + raw.frame(Vec::new(), false); + assert!(raw.host.interaction().is_captured()); + raw.pointer(drop, false, true); + assert_eq!(raw.content.runtime.layout().layout().containing(&id("editor")).unwrap().location.zone(), Zone::Right); + assert_eq!(raw.content.runtime.layout().inspect().revision, before.revision + 1); + assert!(!raw.host.interaction().is_captured()); + assert_eq!(raw.content.commands.calls, 0); + } +} + +/// Every resize test starts from the actual mounted card, including a side +/// restored by one click on its full-width header. +fn raw_resize_card(scale: f32, restored_side: bool) -> (RawPanelHost, HostControlTarget) { + let mut content = host_with_specs(|spec| { + spec.max_size = Size { width: 360.0, height: 360.0 }; + }); + open_editor(&mut content); + let key = editor_key(&content); + content.probe.edit(&key, |state| state.draft = "card resize retains this transaction".into()).unwrap(); + if restored_side { + content.dispatch(vec![Mutation::Collapse { section: section("editor-section"), collapsed: true }]).unwrap(); + } else { + content + .dispatch(vec![Mutation::Move { + instance: id("editor"), + destination: Destination::NewSection { + section: section("editor-section"), + index: 0, + location: SectionLocation::Floating { origin: Point { x: 200.0, y: 180.0 } }, + size: Size { width: 280.0, height: 240.0 }, + }, + }]) + .unwrap(); + } + let mut raw = RawPanelHost::new(content, scale); + raw.prime_foreign_window(); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + if restored_side { + raw.click(HostControlTarget::Pointer(HostPointerTarget::Collapse { instance: id("editor") }), false); + } + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + let card = raw.host.frame().unwrap().layout.sections.iter().find(|card| card.section == section("editor-section")).unwrap(); + assert!(!card.peek); + let target = raw + .host + .frame() + .unwrap() + .controls + .iter() + .find(|control| { + matches!(&control.target, + HostControlTarget::Pointer(HostPointerTarget::Resize { section: target, .. }) if *target == section("editor-section") + ) + }) + .expect("mounted card must publish its resize control") + .target + .clone(); + (raw, target) +} + +fn resize_card_delta(target: &HostControlTarget, extent: f32) -> egui::Vec2 { + match target { + HostControlTarget::Pointer(HostPointerTarget::Resize { edge, .. }) => match edge { + HostResizeEdge::Left => egui::vec2(-extent, 0.0), + HostResizeEdge::Right => egui::vec2(extent, 0.0), + HostResizeEdge::Top => egui::vec2(0.0, -extent), + HostResizeEdge::Bottom => egui::vec2(0.0, extent), + HostResizeEdge::BottomRight => egui::vec2(extent, extent), + }, + _ => panic!("expected an actual card resize control"), + } +} + +fn raw_control(raw: &RawPanelHost, target: &HostControlTarget) -> HostFrameControl { + raw.host.frame().unwrap().controls.iter().find(|control| control.target == *target).unwrap().clone() +} + +fn assert_host_landing(actual: &HostLayout, shown: &HostLayout) { + assert_eq!(actual.sections, shown.sections); + assert_eq!(actual.resolved.panels, shown.resolved.panels); + assert_eq!(actual.extent, shown.extent); + assert_eq!(actual.capacity, shown.capacity); + assert_eq!(actual.render_domain, shown.render_domain); + assert_eq!(actual.allocation_environment.scroll, shown.allocation_environment.scroll); +} + +fn output_paints_rect(output: &egui::FullOutput, bounds: LogicalRect, fill: Option, stroke: Option) -> bool { + fn matches( + shape: &egui::Shape, + transform: egui::emath::TSTransform, + bounds: egui::Rect, + fill: Option, + stroke: Option, + ) -> bool { + match shape { + egui::Shape::Rect(rect) => { + transform * rect.rect == bounds && fill.is_none_or(|ink| rect.fill == ink) && stroke.is_none_or(|ink| rect.stroke.color == ink) + } + egui::Shape::Vec(shapes) => shapes.iter().any(|shape| matches(shape, transform, bounds, fill, stroke)), + _ => false, + } + } + output.shapes.iter().any(|shape| matches(&shape.shape, shape.transform_after_tessellation, egui_rect(bounds), fill, stroke)) +} + +#[test] +fn raw_split_preview_paints_the_exact_landing_and_changed_neighbours_before_one_commit() { + for scale in [1.0, 2.0] { + for direction in [Direction::Ltr, Direction::Rtl] { + let mut content = PanelMountHarness::new(false).unwrap(); + open_editor(&mut content); + content + .dispatch(vec![ + move_editor(Zone::Floating), + fixture_open("fixture.log", "target-0", "target-0", Zone::Right, 1).unwrap(), + fixture_open("fixture.log", "target-1", "target-1", Zone::Right, 2).unwrap(), + ]) + .unwrap(); + let mut environment = content.runtime.environment().clone(); + environment.direction = direction; + content.runtime.set_environment(environment, &mut content.local).unwrap(); + let mut raw = RawPanelHost::new(content, scale); + raw.capacity.size = Size { width: 900.0, height: 600.0 }; + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + let initial = raw.host.frame().unwrap().layout.clone(); + let before = raw.content.runtime.layout().inspect(); + let at = raw.at(HostControlTarget::Pointer(HostPointerTarget::Header { instance: id("editor") })); + let end = explicit_drop_point( + &raw.content, + &initial, + &id("editor"), + &HostDropTargetId::Relative { section: section("target-1"), placement: RelativePlacement::BeforeColumn }, + ); + raw.frame(vec![egui::Event::PointerMoved(at)], false); + raw.pointer(at, true, false); + let (moving, output) = raw.frame(vec![egui::Event::PointerMoved(egui::pos2(end.x, end.y))], false); + let preview = moving.preview.unwrap(); + assert!(preview.rejection.is_none()); + let projected = preview.projected.unwrap(); + assert!(output_paints_rect(&output, preview.bounds, Some(crate::theme::Tokens::get().form_primary.gamma_multiply(0.12)), None)); + let changed = projected + .sections + .iter() + .filter(|card| { + card.instance != id("editor") && initial.sections.iter().any(|old| old.section == card.section && old.outer != card.outer) + }) + .collect::>(); + assert!(!changed.is_empty()); + for card in changed { + assert!(output_paints_rect(&output, card.outer, None, Some(crate::theme::Tokens::get().form_primary.gamma_multiply(0.7)))); + } + assert_eq!(raw.content.runtime.layout().inspect(), before); + assert_eq!(raw.host.frame().unwrap().layout.usable, initial.usable, "landing paint never commits the candidate usable region"); + raw.pointer(egui::pos2(end.x, end.y), false, true); + raw.frame(Vec::new(), false); + assert_host_landing(&raw.host.frame().unwrap().layout, &projected); + assert_eq!(raw.content.runtime.layout().inspect().revision, before.revision + 1); + raw.pointer(egui::pos2(end.x, end.y), false, true); + assert_eq!(raw.content.runtime.layout().inspect().revision, before.revision + 1); + assert_eq!(raw.content.commands.calls, 0); + } + } +} + +#[test] +fn raw_join_activates_the_moved_tab_without_resizing_flash_in_floating_or_collapsed_header_hosts() { + for scale in [1.0, 2.0] { + for direction in [Direction::Ltr, Direction::Rtl] { + for restored_side in [false, true] { + let mut content = PanelMountHarness::new(false).unwrap(); + open_editor(&mut content); + if restored_side { + content + .dispatch(vec![ + move_editor(Zone::Right), + fixture_open("fixture.log", "landing", "landing-section", Zone::Left, 1).unwrap(), + Mutation::Collapse { section: section("landing-section"), collapsed: true }, + ]) + .unwrap(); + } else { + content + .dispatch(vec![ + move_editor(Zone::Right), + fixture_open("fixture.log", "landing", "landing-section", Zone::Floating, 1).unwrap(), + Mutation::SetFloatingRect { + section: section("landing-section"), + origin: Point { x: 500.0, y: 300.0 }, + size: Size { width: 280.0, height: 240.0 }, + }, + ]) + .unwrap(); + } + let mut environment = content.runtime.environment().clone(); + environment.direction = direction; + content.runtime.set_environment(environment, &mut content.local).unwrap(); + let key = editor_key(&content); + content.probe.edit(&key, |state| state.draft = "the visible landing reuses this editor".into()).unwrap(); + let mut raw = RawPanelHost::new(content, scale); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + let before = raw.content.runtime.layout().inspect(); + let retained = raw.content.probe.state(&key).unwrap(); + let controllers = raw.content.runtime.controller_count(); + let start = raw.at(HostControlTarget::Pointer(HostPointerTarget::Header { instance: id("editor") })); + let end = explicit_drop_point( + &raw.content, + &raw.host.frame().unwrap().layout, + &id("editor"), + &HostDropTargetId::Tab { section: section("landing-section"), before: None }, + ); + raw.frame(vec![egui::Event::PointerMoved(start)], false); + raw.pointer(start, true, false); + let moving = raw.frame(vec![egui::Event::PointerMoved(egui::pos2(end.x, end.y))], false).0; + let preview = moving.preview.unwrap(); + assert!(preview.rejection.is_none()); + let expected_mutations = vec![ + Mutation::Move { instance: id("editor"), destination: Destination::JoinTab { section: section("landing-section"), index: 1 } }, + Mutation::Activate { instance: id("editor") }, + ]; + assert_eq!(preview.action, Some(LayoutAction::Apply { expected_revision: Some(before.revision), mutations: expected_mutations })); + let projected = preview.projected.unwrap(); + assert_eq!(projected.sections.iter().find(|card| card.section == section("landing-section")).unwrap().instance, id("editor")); + assert_eq!(raw.content.runtime.layout().inspect(), before); + raw.pointer(egui::pos2(end.x, end.y), false, false); + let landing = raw.content.runtime.layout().layout().section(§ion("landing-section")).unwrap(); + assert_eq!(landing.active, id("editor")); + assert_eq!(landing.collapsed, restored_side); + assert!(raw.content.runtime.layout().interaction().peek.is_none()); + let first_landing = raw.frame(Vec::new(), false).0; + let card = first_landing.layout.sections.iter().find(|card| card.instance == id("editor")).unwrap(); + assert_eq!(card.outer, preview.bounds); + assert!(!card.peek); + assert!( + first_landing.layout.painted.contains(&card.outer), + "changing the active tab cannot recreate the section Area's invisible sizing pass" + ); + assert!(first_landing.layout.input.contains(&card.outer)); + let surface = raw_control(&raw, &HostControlTarget::Pointer(HostPointerTarget::Surface { instance: id("editor") })); + assert!(raw.ctx.read_response(surface.id).unwrap().enabled()); + assert_host_landing(&first_landing.layout, &projected); + raw.pointer(egui::pos2(end.x, end.y), false, true); + assert_eq!(raw.content.runtime.layout().inspect().revision, before.revision + 1); + assert_eq!(raw.content.runtime.controller_count(), controllers); + let after = raw.content.probe.state(&key).unwrap(); + assert_eq!(after.draft, retained.draft); + assert!(after.transaction_live); + assert_eq!( + (after.applies, after.cancels, after.finishes, after.destroys), + (retained.applies, retained.cancels, retained.finishes, retained.destroys) + ); + assert_eq!(raw.content.commands.calls, 0); + } + } + } +} + +fn assert_no_host_mutation(raw: &RawPanelHost, before: &LayoutReply, native_commits: u64) { + assert_eq!(&raw.content.runtime.layout().inspect(), before); + assert_eq!(raw.content.native.commits, native_commits); + assert_eq!(raw.content.commands.calls, 0); + assert!(!raw.host.interaction().is_captured()); + assert!(raw.host.frame().unwrap().preview.is_none()); + assert!( + !raw.host + .frame() + .unwrap() + .events + .iter() + .any(|event| matches!(event, HostEvent::Committed { .. } | HostEvent::PreparedCommitted { .. } | HostEvent::ContentAction { .. })) + ); +} + +fn assert_modal_preserves_painted_host_geometry(raw: &RawPanelHost) { + let painted = &raw.painted_frames[0]; + let finished = &raw.finished_frames[0]; + assert_eq!(finished.layout.painted, painted.layout.painted); + assert_eq!(finished.layout.input, painted.layout.input); + assert_eq!(finished.layout.occlusion, painted.layout.occlusion); + assert_eq!(finished.layout.reservations, painted.layout.reservations); + assert_eq!(finished.layout.viewport, painted.layout.viewport); + assert_eq!(finished.menu_bounds, painted.menu_bounds, "the current painted menu region is truthful even when its pending state is cancelled"); +} + +#[test] +fn late_shared_modal_backdrop_cancels_capture_while_ordinary_windows_preserve_real_release() { + for scale in [1.0, 2.0] { + for resize in [false, true] { + // Ordinary foreign Window; late returning Modal; first sizing Modal; + // already visible Modal before release of the old host capture. + for mode in 0..4 { + let (mut raw, target) = if resize { + raw_resize_card(scale, false) + } else { + let mut content = PanelMountHarness::new(false).unwrap(); + open_editor(&mut content); + let mut raw = RawPanelHost::new(content, scale); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + (raw, HostControlTarget::Pointer(HostPointerTarget::Header { instance: id("editor") })) + }; + raw.prime_foreign_window(); + if mode == 1 || mode == 3 { + raw.prime_modal(); + } + let key = editor_key(&raw.content); + raw.content.probe.edit(&key, |state| state.draft = "modal never cancels this live edit".into()).unwrap(); + let retained = raw.content.probe.state(&key).unwrap(); + let controllers = raw.content.runtime.controller_count(); + let before = raw.content.runtime.layout().inspect(); + let commits = raw.content.native.commits; + let at = raw.at(target.clone()); + raw.frame(vec![egui::Event::PointerMoved(at)], false); + raw.pointer(at, true, false); + assert!(raw.host.interaction().is_captured()); + let end = if resize { at + resize_card_delta(&target, 36.0) } else { egui::pos2(raw.capacity.size.width - 1.0, 550.0) }; + let preview = raw.frame(vec![egui::Event::PointerMoved(end)], false).0.preview.unwrap(); + assert!(preview.rejection.is_none() && preview.action.is_some()); + assert_eq!(raw.content.runtime.layout().inspect(), before); + if mode == 0 { + raw.foreign_cover = Some(egui::Rect::from_center_size(end, egui::vec2(100.0, 80.0))); + } else { + raw.late_modal = true; + } + if mode == 3 { + raw.frame(Vec::new(), false); + assert_no_host_mutation(&raw, &before, commits); + assert_modal_preserves_painted_host_geometry(&raw); + } + let updates = raw.content.probe.state(&key).unwrap().updates; + let mut events = vec![egui::Event::PointerMoved(end), button_event(end, false)]; + if mode == 3 { + events.push(host_key(egui::Key::Escape, true)); + } + raw.frame(events, true); + assert_eq!( + raw.content.probe.state(&key).unwrap().updates, + updates + 1, + "modal paint and extra egui passes cannot add a service tick" + ); + if mode == 0 { + assert_eq!(raw.content.runtime.layout().inspect().revision, before.revision + 1); + assert_eq!(raw.content.native.commits, commits + 1); + assert!( + raw.host + .frame() + .unwrap() + .events + .iter() + .any(|event| matches!(event, HostEvent::PreparedCommitted { reply } if reply.revision == before.revision + 1)) + ); + } else { + assert_no_host_mutation(&raw, &before, commits); + assert_modal_preserves_painted_host_geometry(&raw); + assert!(!raw.modal_observations.is_empty()); + for modal in &raw.modal_observations { + assert!(!modal.card.contains(end), "the modal card itself is away from the host release"); + assert!(modal.backdrop.contains(end), "its actual shared backdrop supplies modality"); + } + if mode == 2 { + assert!(!raw.modal_observations[0].visible, "the first sizing pass still blocks by actual modal show intent"); + } + if mode == 1 || mode == 3 { + assert!(raw.modal_observations[0].visible); + } + if mode == 3 { + assert!( + raw.modal_observations.iter().any(|modal| modal.close_requested), + "a warmed active modal receives Escape after host finish" + ); + } + } + raw.late_modal = false; + raw.foreign_cover = None; + raw.frame(vec![host_key(egui::Key::Escape, false)], false); + raw.frame(Vec::new(), false); + raw.pointer(end, false, true); + raw.frame(Vec::new(), true); + if mode == 0 { + assert_eq!(raw.content.runtime.layout().inspect().revision, before.revision + 1); + } else { + assert_no_host_mutation(&raw, &before, commits); + } + let after = raw.content.probe.state(&key).unwrap(); + assert_eq!(after.draft, retained.draft); + assert!(after.transaction_live); + assert_eq!( + (after.cancels, after.applies, after.finishes, after.destroys), + (retained.cancels, retained.applies, retained.finishes, retained.destroys) + ); + if mode != 0 { + assert_eq!(after.reparents, retained.reparents); + } + assert_eq!(raw.content.runtime.controller_count(), controllers); + assert!(raw.content.native.hosts.is_empty()); + assert_eq!(raw.content.commands.calls, 0); + } + } + } +} + +#[test] +fn late_shared_modal_discards_pointer_and_keyboard_intents_without_latent_actions() { + for scale in [1.0, 2.0] { + for keyboard in [false, true] { + for action in 0..3 { + let mut content = PanelMountHarness::new(false).unwrap(); + open_editor(&mut content); + let mut raw = RawPanelHost::new(content, scale); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + raw.prime_modal(); + let key = editor_key(&raw.content); + raw.content.probe.edit(&key, |state| state.draft = "early host intent cannot cross a late modal".into()).unwrap(); + if action == 2 { + raw.menu(id("editor")); + } + let target = match action { + 0 => HostControlTarget::Pointer(HostPointerTarget::Menu { instance: id("editor") }), + 1 => HostControlTarget::Content { instance: id("editor"), action: ControlId::new("apply").unwrap() }, + _ => HostControlTarget::Shared { instance: id("editor"), action: HostSharedAction::Move(Zone::Right) }, + }; + let widget = raw_control(&raw, &target); + assert!(widget.enabled); + let at = raw.at(target); + if keyboard { + raw.ctx.memory_mut(|memory| memory.request_focus(widget.id)); + raw.frame(Vec::new(), false); + assert_eq!(raw.ctx.memory(|memory| memory.focused()), Some(widget.id)); + } else { + raw.frame(vec![egui::Event::PointerMoved(at)], false); + raw.pointer(at, true, false); + } + let before = raw.content.runtime.layout().inspect(); + let commits = raw.content.native.commits; + let retained = raw.content.probe.state(&key).unwrap(); + let controllers = raw.content.runtime.controller_count(); + raw.late_modal = true; + let events = + if keyboard { vec![host_key(egui::Key::Enter, true)] } else { vec![egui::Event::PointerMoved(at), button_event(at, false)] }; + raw.frame(events, true); + assert!( + raw.clicked_widgets.contains(&widget.id), + "the earlier real response must queue an intent before the late modal blocks finish" + ); + assert_no_host_mutation(&raw, &before, commits); + assert_modal_preserves_painted_host_geometry(&raw); + assert!(raw.modal_observations[0].visible); + assert!(!raw.modal_observations[0].card.contains(at)); + assert!(raw.modal_observations[0].backdrop.contains(at)); + raw.late_modal = false; + raw.frame(vec![host_key(egui::Key::Enter, false)], false); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), true); + assert_no_popup(raw.host.frame().unwrap()); + assert_no_host_mutation(&raw, &before, commits); + let after = raw.content.probe.state(&key).unwrap(); + assert_eq!(after.draft, retained.draft); + assert_eq!( + (after.reparents, after.cancels, after.applies, after.finishes, after.destroys), + (retained.reparents, retained.cancels, retained.applies, retained.finishes, retained.destroys) + ); + assert!(after.transaction_live); + assert_eq!(raw.content.runtime.controller_count(), controllers); + } + } + } +} + +#[test] +fn shared_modal_receives_reserved_escape_once_and_keeps_the_restored_header_and_live_edit() { + for scale in [1.0, 2.0] { + for restored_side in [false, true] { + let mut content = PanelMountHarness::new(false).unwrap(); + open_editor(&mut content); + let mut raw = RawPanelHost::new(content, scale); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + raw.prime_modal(); + let key = editor_key(&raw.content); + raw.content.probe.edit(&key, |state| state.draft = "Escape belongs to the modal, not this transaction".into()).unwrap(); + // egui derives repeat from held-key state. Establish the first + // keydown before opening a host transient, then test a real repeat. + raw.frame(vec![host_key(egui::Key::Escape, true)], false); + if restored_side { + raw.content.dispatch(vec![Mutation::Collapse { section: section("editor-section"), collapsed: true }]).unwrap(); + raw.frame(Vec::new(), false); + raw.click(HostControlTarget::Pointer(HostPointerTarget::Collapse { instance: id("editor") }), false); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + assert!(!raw.content.runtime.layout().layout().containing(&id("editor")).unwrap().collapsed); + // Expanding restores content without a transient. Reserve + // Escape for a real capture on the restored header instead. + let at = raw.at(HostControlTarget::Pointer(HostPointerTarget::Header { instance: id("editor") })); + raw.pointer(at, true, false); + assert!(raw.host.interaction().is_captured()); + } else { + raw.menu(id("editor")); + } + let before = raw.content.runtime.layout().inspect(); + let commits = raw.content.native.commits; + let retained = raw.content.probe.state(&key).unwrap(); + let escape = egui::Event::Key { + key: egui::Key::Escape, + physical_key: Some(egui::Key::Escape), + pressed: true, + repeat: true, + modifiers: egui::Modifiers::NONE, + }; + raw.reserve_escape_for_host = true; + raw.late_modal = true; + let mut events = vec![escape.clone()]; + if restored_side { + let at = raw.at(HostControlTarget::Pointer(HostPointerTarget::Header { instance: id("editor") })); + events.push(button_event(at, false)); + } + raw.frame(events, false); + assert_eq!(raw.escape_reservations, 1, "match the shell reserving Escape before a late modal appears"); + assert_eq!( + raw.modal_observations[0].escape_events, + vec![escape.clone()], + "transfer the original event without losing its physical/repeat metadata" + ); + assert_no_host_mutation(&raw, &before, commits); + assert_modal_preserves_painted_host_geometry(&raw); + raw.frame(vec![host_key(egui::Key::Escape, false)], true); + assert_eq!(raw.escape_reservations, 0); + assert!(raw.modal_observations.iter().all(|modal| modal.escape_events.is_empty())); + assert_no_popup(raw.host.frame().unwrap()); + let mut first_press = escape.clone(); + if let egui::Event::Key { repeat, .. } = &mut first_press { + *repeat = false; + } + raw.frame(vec![first_press.clone()], true); + assert_eq!(raw.escape_reservations, 0, "an active modal prevents host reservation"); + assert_eq!(raw.modal_observations[0].escape_events, vec![first_press]); + assert!( + raw.modal_observations.iter().any(|modal| modal.close_requested), + "a warmed active modal handles Escape normally after host finish" + ); + assert!(raw.modal_observations.iter().all(|modal| modal.escape_events.len() <= 1)); + raw.late_modal = false; + raw.frame(vec![host_key(egui::Key::Escape, false)], false); + raw.frame(Vec::new(), true); + assert_no_host_mutation(&raw, &before, commits); + assert_no_popup(raw.host.frame().unwrap()); + let after = raw.content.probe.state(&key).unwrap(); + assert_eq!(after.draft, retained.draft); + assert!(after.transaction_live); + assert_eq!( + (after.reparents, after.cancels, after.applies, after.finishes, after.destroys), + (retained.reparents, retained.cancels, retained.applies, retained.finishes, retained.destroys) + ); + } + } +} + +#[test] +fn raw_floating_and_restored_side_resize_widgets_own_the_card_layer_at_both_scales() { + for scale in [1.0, 2.0] { + for restored_side in [false, true] { + let (mut raw, target) = raw_resize_card(scale, restored_side); + let key = editor_key(&raw.content); + let retained = raw.content.probe.state(&key).unwrap(); + let controllers = raw.content.runtime.controller_count(); + let native_commits = raw.content.native.commits; + let original = raw_control(&raw, &target); + let native_hosts = raw.content.native.hosts.clone(); + for extent in [36.0, 84.0, -260.0] { + let at = raw.at(target.clone()); + let (_, output) = raw.frame(vec![egui::Event::PointerMoved(at)], false); + let control = raw_control(&raw, &target); + let response = raw.ctx.read_response(control.id).unwrap(); + let surface = raw_control(&raw, &HostControlTarget::Pointer(HostPointerTarget::Surface { instance: id("editor") })); + assert!(response.enabled()); + assert_eq!(response.rect, egui_rect(control.bounds)); + assert_eq!(response.layer_id, raw.ctx.read_response(surface.id).unwrap().layer_id); + assert_eq!(raw.ctx.layer_id_at(at), Some(response.layer_id)); + assert_eq!(Some(response.layer_id) == raw.root_layer, restored_side, "restored side cards use the root; floating uses its Area"); + assert_eq!(control.id, original.id); + assert_eq!(control.accessible_name, original.accessible_name); + assert!( + output + .platform_output + .accesskit_update + .as_ref() + .unwrap() + .nodes + .iter() + .any(|(_, node)| node.label() == Some(control.accessible_name.as_str())) + ); + let before = raw.content.runtime.layout().inspect(); + raw.pointer(at, true, false); + assert!(raw.host.interaction().is_captured()); + let end = at + resize_card_delta(&target, extent); + let preview = raw.frame(vec![egui::Event::PointerMoved(end)], false).0.preview.unwrap(); + assert!(preview.rejection.is_none()); + assert!(preview.action.is_some(), "motion reaches a different registered bound"); + assert_eq!(raw.content.runtime.layout().inspect(), before); + raw.pointer(end, false, true); + let committed = raw + .host + .frame() + .unwrap() + .events + .iter() + .filter_map(|event| match event { + HostEvent::PreparedCommitted { reply } => Some(reply), + _ => None, + }) + .collect::>(); + assert_eq!(committed.len(), 1); + assert_eq!(committed[0].revision, before.revision + 1); + assert!(raw.host.frame().unwrap().events.iter().all(|event| match event { + HostEvent::PreparedCommitted { reply } => reply.effects.is_empty(), + _ => true, + })); + assert_eq!(raw.content.runtime.layout().inspect().revision, before.revision + 1); + raw.frame(Vec::new(), false); + let card = raw.host.frame().unwrap().layout.sections.iter().find(|card| card.section == section("editor-section")).unwrap(); + assert_eq!(card.outer, preview.bounds, "the visible committed card equals the final preview"); + if extent == 84.0 { + assert_eq!(card.outer.size.width, 360.0); + if !restored_side { + assert_eq!(card.outer.size.height, 360.0); + } + } + if extent == -260.0 { + assert_eq!(card.outer.size.width, 160.0); + if !restored_side { + assert_eq!(card.outer.size.height, 120.0); + } + } + let resized = raw_control(&raw, &target); + assert_eq!(resized.id, original.id); + assert_ne!(resized.bounds, control.bounds); + assert_eq!(raw.ctx.read_response(resized.id).unwrap().rect, egui_rect(resized.bounds)); + raw.pointer(end, false, true); + assert_eq!(raw.content.runtime.layout().inspect().revision, before.revision + 1); + } + let after = raw.content.probe.state(&key).unwrap(); + assert_eq!(after.draft, retained.draft); + assert_eq!( + (after.reparents, after.cancels, after.applies, after.finishes, after.destroys), + (retained.reparents, retained.cancels, retained.applies, retained.finishes, retained.destroys) + ); + assert_eq!(raw.content.runtime.controller_count(), controllers); + assert_eq!(raw.content.native.commits, native_commits + 3, "one adapter commit per accepted resize, with no native effects"); + assert_eq!(raw.content.native.hosts, native_hosts); + assert!(after.transaction_live); + assert_eq!(raw.content.commands.calls, 0); + } + } +} + +#[test] +fn raw_card_resize_rejects_foreign_initial_presses_but_keeps_real_capture() { + for scale in [1.0, 2.0] { + for restored_side in [false, true] { + for warm_cover in [false, true] { + let (mut raw, target) = raw_resize_card(scale, restored_side); + let at = raw.at(target.clone()); + raw.frame(vec![egui::Event::PointerMoved(at)], false); + let source = raw_control(&raw, &target); + let before = raw.content.runtime.layout().inspect(); + let native_commits = raw.content.native.commits; + raw.foreign_cover = Some(egui::Rect::from_center_size(at, egui::vec2(100.0, 100.0))); + if warm_cover { + raw.frame(Vec::new(), false); + } + raw.pointer(at, true, true); + assert_ne!(raw.ctx.layer_id_at(at), Some(raw.ctx.read_response(source.id).unwrap().layer_id)); + assert!(!raw.host.interaction().is_captured()); + let end = at + resize_card_delta(&target, 32.0); + raw.frame(vec![egui::Event::PointerMoved(end)], false); + raw.pointer(end, false, true); + assert_no_host_mutation(&raw, &before, native_commits); + raw.foreign_cover = None; + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + raw.frame(vec![egui::Event::PointerMoved(at)], false); + raw.pointer(at, true, false); + assert!(raw.host.interaction().is_captured()); + let outside = egui::pos2(raw.capacity.size.width + 80.0, raw.capacity.size.height + 80.0); + raw.frame(vec![egui::Event::PointerMoved(outside)], false); + assert!(raw.host.interaction().is_captured()); + let preview = raw.frame(vec![egui::Event::PointerMoved(end)], false).0.preview.unwrap(); + raw.foreign_cover = Some(egui::Rect::from_center_size(end, egui::vec2(100.0, 100.0))); + raw.pointer(end, false, true); + assert_eq!(raw.content.runtime.layout().inspect().revision, before.revision + 1); + assert!(!raw.host.interaction().is_captured()); + assert!( + raw.host + .frame() + .unwrap() + .events + .iter() + .any(|event| matches!(event, HostEvent::PreparedCommitted { reply } if reply.revision == before.revision + 1)) + ); + raw.frame(Vec::new(), false); + assert_eq!( + raw.host.frame().unwrap().layout.sections.iter().find(|card| card.section == section("editor-section")).unwrap().outer, + preview.bounds + ); + raw.pointer(end, false, true); + assert_eq!(raw.content.runtime.layout().inspect().revision, before.revision + 1); + assert_eq!(raw.content.native.commits, native_commits + 1); + assert!(raw.content.native.hosts.is_empty()); + } + } + } +} + +#[derive(Clone, Copy, Debug)] +enum PopupFixture { + Menu, + Header, + Tab, + CollapsedHeader, + Tabs, + ScrolledMenu, + CompactTabs, +} + +fn raw_popup_fixture(scale: f32, fixture: PopupFixture) -> (RawPanelHost, HostControlTarget, egui::PointerButton) { + let mut content = host_logs(if matches!(fixture, PopupFixture::ScrolledMenu) { 24 } else { 1 }, Zone::Left); + if matches!(fixture, PopupFixture::Tab | PopupFixture::Tabs | PopupFixture::CompactTabs) { + for index in 1..MAX_TABS { + content + .dispatch(vec![Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id(&format!("tab-{index}")), + destination: Some(Destination::JoinTab { section: section("section-0"), index }), + }]) + .unwrap(); + } + content + .dispatch(vec![ + Mutation::Activate { instance: id("log-0") }, + Mutation::SetSize { + section: section("section-0"), + size: Size { width: if matches!(fixture, PopupFixture::CompactTabs) { 240.0 } else { 160.0 }, height: 240.0 }, + }, + ]) + .unwrap(); + } + if matches!(fixture, PopupFixture::CollapsedHeader | PopupFixture::ScrolledMenu) { + content + .dispatch( + content + .runtime + .layout() + .layout() + .sections + .iter() + .map(|section| Mutation::Collapse { section: section.id.clone(), collapsed: true }) + .collect(), + ) + .unwrap(); + } + let pointer = match fixture { + PopupFixture::Menu => HostPointerTarget::Menu { instance: id("log-0") }, + PopupFixture::Header | PopupFixture::CollapsedHeader => HostPointerTarget::Header { instance: id("log-0") }, + PopupFixture::Tab => HostPointerTarget::Tab { instance: id("log-0") }, + PopupFixture::Tabs | PopupFixture::CompactTabs => HostPointerTarget::TabOverflow { section: section("section-0") }, + PopupFixture::ScrolledMenu => HostPointerTarget::Menu { instance: id("log-23") }, + }; + let mut raw = RawPanelHost::new(content, scale); + if matches!(fixture, PopupFixture::ScrolledMenu) { + raw.capacity.size = Size { width: 480.0, height: 320.0 }; + } + raw.prime_foreign_window(); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + if matches!(fixture, PopupFixture::ScrolledMenu) { + let bounds = raw + .host + .frame() + .unwrap() + .controls + .iter() + .find(|control| control.target == HostControlTarget::Scroll { horizontal: false }) + .unwrap() + .bounds; + let at = egui_rect(bounds).center_bottom() - egui::vec2(0.0, 1.0); + raw.pointer(at, true, false); + raw.pointer(at, false, false); + raw.frame(Vec::new(), false); + } + let target = HostControlTarget::Pointer(pointer); + assert!(raw_control(&raw, &target).enabled); + let button = if matches!(fixture, PopupFixture::Header | PopupFixture::Tab | PopupFixture::CollapsedHeader) { + egui::PointerButton::Secondary + } else { + egui::PointerButton::Primary + }; + (raw, target, button) +} +fn popup_button(at: egui::Pos2, button: egui::PointerButton, pressed: bool) -> egui::Event { + egui::Event::PointerButton { pos: at, button, pressed, modifiers: egui::Modifiers::NONE } +} + +fn host_key(key: egui::Key, pressed: bool) -> egui::Event { + egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE } +} + +fn assert_no_popup(frame: &HostFrame) { + assert!(frame.menu_bounds.is_none()); + assert!(!frame.controls.iter().any(|control| matches!(control.target, HostControlTarget::PanelMenu { .. } | HostControlTarget::Shared { .. }))); +} + +fn open_root_popup(raw: &mut RawPanelHost, source: &HostControlTarget, button: egui::PointerButton, multipass: bool) { + let previously_painted = raw.painted_menu; + let at = raw.at(source.clone()); + raw.frame(vec![egui::Event::PointerMoved(at)], false); + raw.frame(vec![popup_button(at, button, true)], false); + raw.frame(vec![popup_button(at, button, false)], multipass); + assert_no_popup(&raw.painted_frames[0]); + assert_no_popup(&raw.finished_frames[0]); + raw.frame(Vec::new(), false); + if !multipass && !previously_painted { + assert_no_popup(raw.host.frame().unwrap()); + } + raw.frame(Vec::new(), false); + assert!(raw.host.frame().unwrap().menu_bounds.is_some(), "accepted popup is published after it actually paints"); +} + +#[test] +fn late_first_appearance_window_blocks_all_root_popup_open_intents() { + for scale in [1.0, 2.0] { + for fixture in [ + PopupFixture::Menu, + PopupFixture::Header, + PopupFixture::Tab, + PopupFixture::CollapsedHeader, + PopupFixture::Tabs, + PopupFixture::ScrolledMenu, + PopupFixture::CompactTabs, + ] { + for same_frame in [false, true] { + let (mut raw, source, button) = raw_popup_fixture(scale, fixture); + let at = raw.at(source.clone()); + raw.frame(vec![egui::Event::PointerMoved(at)], false); + let source_id = raw_control(&raw, &source).id; + let before = raw.content.runtime.layout().inspect(); + let commits = raw.content.native.commits; + if !same_frame { + raw.frame(vec![popup_button(at, button, true)], false); + } + raw.foreign_cover = Some(egui::Rect::from_center_size(at, egui::vec2(100.0, 80.0))); + let mut events = vec![egui::Event::PointerMoved(at)]; + if same_frame { + events.push(popup_button(at, button, true)); + } + events.push(popup_button(at, button, false)); + raw.frame(events, true); + assert_ne!(raw.ctx.layer_id_at(at), Some(raw.ctx.read_response(source_id).unwrap().layer_id)); + for painted in &raw.painted_frames { + assert_no_popup(painted); + } + for finished in &raw.finished_frames { + assert_no_popup(finished); + } + assert_no_host_mutation(&raw, &before, commits); + raw.foreign_cover = None; + raw.frame(Vec::new(), true); + assert_no_popup(raw.host.frame().unwrap()); + raw.frame(vec![popup_button(at, button, false)], true); + assert_no_popup(raw.host.frame().unwrap()); + assert_no_host_mutation(&raw, &before, commits); + + // A fresh real source press after the covered gesture succeeds. + raw.frame(Vec::new(), false); + open_root_popup(&mut raw, &source, button, true); + let bounds = raw.host.frame().unwrap().menu_bounds; + raw.frame(Vec::new(), true); + assert_eq!(raw.host.frame().unwrap().menu_bounds, bounds); + raw.frame(vec![host_key(egui::Key::Escape, true)], true); + raw.frame(vec![host_key(egui::Key::Escape, false)], false); + assert_no_popup(raw.host.frame().unwrap()); + open_root_popup(&mut raw, &source, button, false); + let outside = egui::pos2(-20.0, -20.0); + raw.pointer(outside, true, true); + raw.pointer(outside, false, false); + raw.frame(Vec::new(), false); + assert_no_popup(raw.host.frame().unwrap()); + } + // Header/tab/collapsed-header context menus use secondary pointer activation; + // the primary menu and overflow buttons also expose keyboard clicks. + if matches!(fixture, PopupFixture::Menu | PopupFixture::Tabs | PopupFixture::ScrolledMenu | PopupFixture::CompactTabs) { + for key in [egui::Key::Enter, egui::Key::Space] { + for late_focus in [false, true] { + let (mut raw, source, _) = raw_popup_fixture(scale, fixture); + let control = raw_control(&raw, &source); + raw.ctx.memory_mut(|memory| memory.request_focus(control.id)); + raw.frame(Vec::new(), false); + if late_focus { + raw.foreign_cover = Some(egui::Rect::from_min_size( + egui::pos2(raw.capacity.size.width - 100.0, raw.capacity.size.height - 100.0), + egui::vec2(80.0, 80.0), + )); + raw.foreign_takes_focus = true; + } + raw.frame(vec![host_key(key, true)], true); + assert_no_popup(&raw.painted_frames[0]); + assert_no_popup(&raw.finished_frames[0]); + raw.foreign_cover = None; + raw.foreign_takes_focus = false; + raw.frame(vec![host_key(key, false)], false); + raw.frame(Vec::new(), true); + if late_focus { + assert_no_popup(raw.host.frame().unwrap()); + } else { + assert!(raw.host.frame().unwrap().menu_bounds.is_some()); + } + assert_eq!(raw.content.commands.calls, 0); + } + } + } + } + } + // Keyboard header restoration must recheck actual current focus too. + for scale in [1.0, 2.0] { + for late_focus in [false, true] { + let (mut raw, _, _) = raw_popup_fixture(scale, PopupFixture::CollapsedHeader); + let target = HostControlTarget::Pointer(HostPointerTarget::Collapse { instance: id("log-0") }); + let source_id = raw_control(&raw, &target).id; + raw.ctx.memory_mut(|memory| memory.request_focus(source_id)); + raw.frame(Vec::new(), false); + let before = raw.content.runtime.layout().inspect(); + if late_focus { + raw.foreign_cover = Some(egui::Rect::from_min_size(egui::pos2(800.0, 600.0), egui::vec2(80.0, 80.0))); + raw.foreign_takes_focus = true; + } + raw.frame(vec![host_key(egui::Key::Enter, true)], true); + raw.foreign_cover = None; + raw.foreign_takes_focus = false; + raw.frame(vec![host_key(egui::Key::Enter, false)], true); + if late_focus { + assert_eq!(raw.content.runtime.layout().inspect(), before); + } else { + assert!(!raw.content.runtime.layout().layout().containing(&id("log-0")).unwrap().collapsed); + } + } + } +} + +#[test] +fn late_first_appearance_window_blocks_nested_popup_navigation() { + for scale in [1.0, 2.0] { + for fixture in [PopupFixture::Tabs, PopupFixture::CompactTabs] { + for same_frame in [false, true] { + let (mut raw, source, button) = raw_popup_fixture(scale, fixture); + open_root_popup(&mut raw, &source, button, false); + // Both Areas can be raised by this press frame. Warm the + // foreign Area after the popup so their actual stable pair + // order puts the returning window above the popup as well. + raw.prime_foreign_window(); + raw.frame(Vec::new(), false); + let target = HostControlTarget::PanelMenu { instance: id("log-0") }; + let row = raw_control(&raw, &target); + let original_layer = raw.ctx.read_response(row.id).unwrap().layer_id; + let at = raw.at(target.clone()); + let original_bounds = raw.host.frame().unwrap().menu_bounds; + let original_rows = raw + .host + .frame() + .unwrap() + .controls + .iter() + .filter(|control| matches!(control.target, HostControlTarget::PanelMenu { .. })) + .cloned() + .collect::>(); + let before = raw.content.runtime.layout().inspect(); + let commits = raw.content.native.commits; + raw.frame(vec![egui::Event::PointerMoved(at)], false); + if !same_frame { + raw.pointer(at, true, false); + } + raw.foreign_cover = Some(egui::Rect::from_center_size(at, egui::vec2(100.0, 40.0))); + let mut events = vec![egui::Event::PointerMoved(at)]; + if same_frame { + events.push(button_event(at, true)); + } + events.push(button_event(at, false)); + raw.frame(events, true); + let foreign = raw.foreign_responses.first().expect("the late real Window must actually render"); + assert!(foreign.enabled() && foreign.interact_rect.contains(at)); + assert_ne!(foreign.layer_id, raw.ctx.read_response(row.id).unwrap().layer_id); + assert_eq!(raw.ctx.layer_id_at(at), Some(foreign.layer_id), "the actual enabled foreign Window must own the covered point"); + for painted in &raw.painted_frames { + assert_eq!(painted.menu_bounds, original_bounds); + } + for finished in &raw.finished_frames { + assert_eq!(finished.menu_bounds, original_bounds); + } + raw.foreign_cover = None; + let mut actual_rows = std::collections::HashMap::new(); + let _ = raw.frame_late(Vec::new(), true, |_, ctx| { + // Snapshot the current painted pass before egui swaps its + // response maps at end_pass; outside reads can be stale. + actual_rows.clear(); + for original in &original_rows { + if let Some(response) = ctx.read_response(original.id) { + actual_rows.insert(original.id, response); + } + } + }); + assert_eq!(raw.host.frame().unwrap().menu_bounds, original_bounds); + let unchanged_source = raw_control(&raw, &target); + assert_eq!(unchanged_source.id, row.id, "blocked input must retain the exact root menu source"); + assert_eq!(actual_rows.get(&unchanged_source.id).unwrap().layer_id, original_layer); + for original in &original_rows { + if let Some(current) = raw.host.frame().unwrap().controls.iter().find(|control| control.target == original.target) { + assert_eq!(current.id, original.id); + } else { + // Text/scroll layout can move a partially visible last + // row below the clip. It may disappear from published + // controls only if its real response is now clipped. + let clipped = actual_rows.get(&original.id).expect("the root menu still creates its clipped row in the current pass"); + assert!( + !clipped.interact_rect.intersect(egui_rect(original_bounds.unwrap())).is_positive(), + "blocked input cannot remove a still-visible root menu row: {:?}", + original.target + ); + } + } + assert!( + !raw.host.frame().unwrap().controls.iter().any(|control| matches!( + control.target, + HostControlTarget::Shared { action: HostSharedAction::Move(_) | HostSharedAction::Close | HostSharedAction::Collapse, .. } + )), + "a list may expose Focus, but must not have navigated into panel actions" + ); + assert_no_host_mutation(&raw, &before, commits); + raw.frame(Vec::new(), false); + raw.click(target.clone(), true); + assert!(raw.painted_frames[0].controls.iter().any(|control| control.target == target)); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + assert!( + raw.host + .frame() + .unwrap() + .controls + .iter() + .any(|control| matches!(control.target, HostControlTarget::Shared { action: HostSharedAction::Move(_), .. })) + ); + assert!(!raw.host.frame().unwrap().controls.iter().any(|control| control.target == target)); + raw.frame(Vec::new(), true); + assert_eq!(raw.content.runtime.layout().inspect(), before); + } + for cancel in [0, 1, 2] { + let (mut raw, source, button) = raw_popup_fixture(scale, fixture); + open_root_popup(&mut raw, &source, button, false); + raw.frame(Vec::new(), false); + let target = HostControlTarget::PanelMenu { instance: id("log-0") }; + let row = raw_control(&raw, &target); + raw.ctx.memory_mut(|memory| memory.request_focus(row.id)); + raw.frame(Vec::new(), false); + let mut events = vec![host_key(egui::Key::Enter, true)]; + if cancel == 1 { + events.push(host_key(egui::Key::Escape, true)); + } + if cancel == 2 { + raw.content.tick().unwrap(); + raw.host.capture_metrics(&raw.content.runtime, &raw.content.models).unwrap(); + raw.host.prepare(&raw.content.runtime, raw.capacity).unwrap(); + raw.time += 1.0 / 60.0; + let mut output = raw.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui_rect(raw.capacity)), + events, + time: Some(raw.time), + focused: true, + ..Default::default() + }, + |ui| { + let h = &mut raw.content; + let mut services = ContentServices { models: &h.models, commands: &mut h.commands, local: &mut h.local }; + raw.host.show_deferred(ui, &mut h.runtime, &mut h.native, &mut services).unwrap(); + let mut environment = h.runtime.environment().clone(); + environment.document = Some(DocumentId::new("new-popup-context").unwrap()); + h.runtime.set_environment(environment, services.local).unwrap(); + assert_eq!( + raw.host.finish(ui, &mut h.runtime, &mut h.native, &mut services, &mut h.catalogue).unwrap_err().rule, + Rule::Placement + ); + }, + ); + output.textures_delta.clear(); + assert!(raw.host.frame().is_none(), "pending navigation is invalidated with its owner scope"); + } else { + raw.frame(events, true); + } + raw.frame(vec![host_key(egui::Key::Enter, false), host_key(egui::Key::Escape, false)], true); + if cancel == 0 { + assert!(raw.host.frame().unwrap().controls.iter().any(|control| matches!(control.target, HostControlTarget::Shared { .. }))); + let outside = egui::pos2(-20.0, -20.0); + raw.pointer(outside, true, true); + raw.pointer(outside, false, false); + raw.frame(Vec::new(), true); + } + assert_no_popup(raw.host.frame().unwrap()); + assert_eq!(raw.content.commands.calls, 0); + } + } + } +} + +#[test] +fn tick_failed_document_refresh_preserves_old_owners_and_attempts_services_once() { + for scale in [1.0, 2.0] { + for captured in [false, true] { + let (mut h, probe, trace) = boundary_app(); + h.ctx.set_pixels_per_point(scale); + h.app + .dispatch_panel_layout(transaction(vec![fixture_open("fixture.log", "zz-workspace", "workspace-section", Zone::Right, 0).unwrap()])) + .unwrap(); + h.frames(2); + let old_key = app_editor_key(&h.app); + let environment = h.app.panel_runtime().unwrap().environment().clone(); + let workspace_key = ControllerKey { instance: id("zz-workspace"), owner: ContentOwner::Workspace(environment.workspace.clone()) }; + probe + .edit(&old_key, |state| { + state.draft = "A draft survives failed B refresh".into(); + state.fail_update = true; + }) + .unwrap(); + let scope = runtime_scope(h.app.panel_runtime().unwrap()); + h.app + .panel_runtime_mut() + .unwrap() + .with_services(|_, services| { + services.local.request(&scope, LocalRequest::KeyboardOwner { instance: id("editor"), control: ControlId::new("draft").unwrap() }) + }) + .unwrap(); + let target = HostControlTarget::Pointer(if captured { + HostPointerTarget::Header { instance: id("editor") } + } else { + HostPointerTarget::Menu { instance: id("editor") } + }); + let control = app_control(&h.app, target); + let at = egui_rect(control.bounds).center(); + h.ctx.memory_mut(|memory| memory.request_focus(control.id)); + // Establish transient ownership before enabling the service failure. + probe.edit(&old_key, |state| state.fail_update = false).unwrap(); + h.frame_with(vec![egui::Event::PointerMoved(at), button_event(at, true)]); + if captured { + h.frame_with(vec![egui::Event::PointerMoved(at + egui::vec2(12.0, 0.0))]); + assert!(h.app.panel_runtime_mut().unwrap().host().unwrap().interaction().is_captured()); + } else { + h.frame_with(vec![button_event(at, false)]); + h.frames(2); + assert!(h.app.universal_panel_frame().unwrap().menu_bounds.is_some()); + } + probe.edit(&old_key, |state| state.fail_update = true).unwrap(); + let old = probe.state(&old_key).unwrap(); + let workspace = probe.state(&workspace_key).unwrap(); + let layout = h.app.panel_runtime().unwrap().layout().layout().clone(); + let factory_keys = trace.borrow().factory_keys.clone(); + let controllers = h.app.panel_runtime().unwrap().controller_count(); + let incoming = solidcraft_engine::Session::default(); + crate::documents::open_tab(&mut h.app, incoming).unwrap(); + h.app.home.open = false; + // Switching documents has its own revision invalidation. The + // refresh/layout boundary below must preserve this switched state. + let document = h.app.session.doc.clone(); + let model = h.app.session.model.state(); + let revision = h.app.session.revision; + let undo = h.app.session.undo.len(); + let dirty = h.app.session.is_dirty(); + let incoming_key = app_editor_key(&h.app); + assert_ne!(incoming_key.owner, old_key.owner); + trace.borrow_mut().fail_refresh = true; + trace.borrow_mut().model_reads.clear(); + let time = h.ctx.input(|input| input.time) + 1.0 / 60.0; + let mut passes = 0; + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui_rect(capacity())), time: Some(time), focused: true, ..Default::default() }, + |ui| { + passes += 1; + h.app.logic(ui.ctx()); + h.app.ui(ui); + // Repeated same-frame boundaries must fail before admitting B, + // and never turn reconciliation into another background tick. + let expected = error(Rule::Availability, "boundary refresh refused"); + assert_eq!(h.app.panel_content_action(&id("editor"), &ControlId::new("apply").unwrap()).unwrap_err(), expected); + assert_eq!(h.app.dispatch_panel_layout(transaction(vec![Mutation::Close { instance: id("editor") }])).unwrap_err(), expected); + assert_eq!(h.app.panel_runtime.as_mut().unwrap().prepare_host(&h.app.session, capacity()).unwrap_err(), expected); + assert_eq!(h.app.mount_panels(&ResolvedLayout::default(), &mut FakePanelHost::default()).unwrap_err(), expected); + if ui.ctx().current_pass_index() == 0 { + ui.ctx().request_discard("failed refresh still receives one retained-service tick"); + } + }, + ); + output.textures_delta.clear(); + assert!(passes >= 2); + assert_eq!(h.app.panel_runtime.as_ref().unwrap().last_error(), Some(&error(Rule::Availability, "boundary refresh refused"))); + assert_eq!(h.app.panel_runtime().unwrap().environment(), &environment); + assert_eq!(trace.borrow().document, environment.document); + assert_eq!(trace.borrow().factory_keys, factory_keys); + assert_eq!(h.app.panel_runtime().unwrap().controller_count(), controllers); + assert!(probe.state(&incoming_key).is_err()); + assert!(trace.borrow().model_reads.iter().all(|owner| owner != &incoming_key.owner)); + assert!(trace.borrow().commands.is_empty()); + assert_eq!(h.app.panel_runtime().unwrap().layout().layout(), &layout); + let errors = h.app.panel_runtime().unwrap().update_errors(); + assert_eq!(errors.len(), 1); + assert_eq!(errors[0].controller.as_ref(), Some(&old_key)); + assert_eq!(errors[0].error, error(Rule::Lifecycle, "synthetic service update failed")); + assert!(h.app.universal_panel_frame().is_none()); + assert!(!h.app.panel_runtime_mut().unwrap().host().unwrap().interaction().is_captured()); + assert_ne!(h.ctx.memory(|memory| memory.focused()), Some(control.id)); + assert!(!trace.borrow().keyboard.contains_key(&scope)); + for (key, before) in [(&old_key, &old), (&workspace_key, &workspace)] { + let after = probe.state(key).unwrap(); + assert_eq!(after.updates, before.updates + 1, "every retained service gets one attempt, even after another fails"); + assert_eq!(after.renders, before.renders); + assert!(!h.app.panel_runtime().unwrap().state(key).unwrap().presented); + assert_eq!( + (after.cancels, after.applies, after.finishes, after.destroys), + (before.cancels, before.applies, before.finishes, before.destroys) + ); + } + assert_eq!(probe.state(&old_key).unwrap().draft, old.draft); + assert!(probe.state(&old_key).unwrap().transaction_live); + assert_eq!(h.app.session.revision, revision); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(h.app.session.is_dirty(), dirty); + assert!(std::sync::Arc::ptr_eq(&document, &h.app.session.doc)); + assert!(std::sync::Arc::ptr_eq(&model, &h.app.session.model.state())); + + trace.borrow_mut().fail_refresh = false; + probe.edit(&old_key, |state| state.fail_update = false).unwrap(); + let time = time + 1.0 / 60.0; + let mut output = h.ctx.run_ui( + egui::RawInput { screen_rect: Some(egui_rect(capacity())), time: Some(time), focused: true, ..Default::default() }, + |ui| { + h.app.logic(ui.ctx()); + h.app.ui(ui); + if ui.ctx().current_pass_index() == 0 { + ui.ctx().request_discard("recovery mounts must not add a service update"); + } + }, + ); + output.textures_delta.clear(); + assert_eq!(trace.borrow().document, Some(DocumentId::new(h.app.session.document_id.clone()).unwrap())); + assert_eq!(h.app.panel_runtime().unwrap().environment().document, trace.borrow().document); + assert_eq!(trace.borrow().factory_keys.iter().filter(|key| **key == incoming_key).count(), 1); + let current = probe.state(&incoming_key).unwrap(); + assert_eq!(current.updates, 1); + assert!(current.renders > 0); + assert_eq!(probe.state(&old_key).unwrap().updates, old.updates + 2); + assert_eq!(probe.state(&old_key).unwrap().renders, old.renders); + assert_eq!(probe.state(&workspace_key).unwrap().updates, workspace.updates + 2); + assert!(h.app.panel_runtime().unwrap().update_errors().is_empty()); + h.app.panel_content_action(&id("editor"), &ControlId::new("apply").unwrap()).unwrap(); + assert_eq!(trace.borrow().commands, vec![incoming_key.owner.clone()]); + assert_eq!(probe.state(&incoming_key).unwrap().applies, 1); + assert_eq!(probe.state(&incoming_key).unwrap().updates, 1); + assert_eq!(probe.state(&old_key).unwrap().draft, old.draft); + assert_eq!(h.app.panel_runtime().unwrap().layout().layout(), &layout); + } + } + // Explicit tick's returned error is examined in a separate fresh app so it + // cannot accidentally grant the automatic-frame assertion an extra update. + let (mut h, probe, trace) = boundary_app(); + let key = app_editor_key(&h.app); + let environment = h.app.panel_runtime().unwrap().environment().clone(); + probe.edit(&key, |state| state.fail_update = true).unwrap(); + crate::documents::open_tab(&mut h.app, solidcraft_engine::Session::default()).unwrap(); + trace.borrow_mut().fail_refresh = true; + assert_eq!(h.app.tick_panel_runtime().unwrap_err(), error(Rule::Availability, "boundary refresh refused")); + assert_eq!(h.app.panel_runtime().unwrap().environment(), &environment); + assert_eq!(h.app.panel_runtime().unwrap().update_errors()[0].controller.as_ref(), Some(&key)); +} + +#[test] +fn late_first_appearance_window_blocks_sash_double_click_reset() { + for scale in [1.0, 2.0] { + for cover_on_press in [false, true] { + let mut content = host_logs(2, Zone::Bottom); + content + .dispatch(vec![Mutation::ResizePair { + first: section("section-0"), + second: section("section-1"), + first_size: Size { width: 360.0, height: 240.0 }, + second_size: Size { width: 200.0, height: 240.0 }, + }]) + .unwrap(); + let mut raw = RawPanelHost::new(content, scale); + raw.prime_foreign_window(); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + let target = HostControlTarget::Pointer(HostPointerTarget::Sash { first: section("section-0"), second: section("section-1") }); + raw.click(target.clone(), false); + let at = raw.at(target.clone()); + let before = raw.content.runtime.layout().inspect(); + let native_commits = raw.content.native.commits; + let cover = egui::Rect::from_center_size(at, egui::vec2(100.0, 80.0)); + if cover_on_press { + raw.foreign_cover = Some(cover); + } + raw.pointer(at, true, false); + raw.foreign_cover = Some(cover); + raw.pointer(at, false, true); + assert_no_host_mutation(&raw, &before, native_commits); + raw.foreign_cover = None; + raw.frame(Vec::new(), true); + raw.pointer(at, false, true); + assert_no_host_mutation(&raw, &before, native_commits); + // Expire the earlier click's time window, then prove real response + // double-click remains a single ResetPair through release multipass. + raw.time += 1.0; + raw.frame(Vec::new(), false); + raw.click(target.clone(), false); + raw.click(target, true); + assert_eq!(raw.content.runtime.layout().inspect().revision, before.revision + 1); + let commits = raw + .host + .frame() + .unwrap() + .events + .iter() + .filter_map(|event| match event { + HostEvent::PreparedCommitted { reply } => Some(reply), + _ => None, + }) + .collect::>(); + assert_eq!(commits.len(), 1); + assert_eq!(commits[0].revision, before.revision + 1); + let sections = &raw.content.runtime.layout().layout().sections; + assert_eq!((sections[0].size.width, sections[1].size.width), (698.0, 698.0)); + raw.frame(Vec::new(), true); + assert_eq!(raw.host.frame().unwrap().layout.sections.iter().map(|card| card.outer.size.width).collect::>(), vec![698.0, 698.0]); + raw.pointer(at, false, true); + assert_eq!(raw.content.runtime.layout().inspect().revision, before.revision + 1); + assert_eq!(raw.content.native.commits, native_commits + 1); + assert!(raw.content.native.hosts.is_empty()); + assert_eq!(raw.content.commands.calls, 0); + } + } +} + +#[test] +fn exhausted_single_pass_sizing_and_collapsed_headers_publish_only_actual_footprints() { + for scale in [1.0, 2.0] { + let mut content = host_logs(1, Zone::Floating); + content.dispatch(vec![Mutation::Focus { instance: id("log-0") }]).unwrap(); + let mut raw = RawPanelHost::new(content, scale); + raw.ctx.options_mut(|options| options.max_passes = 1.try_into().unwrap()); + let sizing = raw.frame(Vec::new(), false).0; + assert_eq!(raw.painted_frames.len(), 1); + let card = sizing.layout.sections.iter().find(|card| card.instance == id("log-0")).unwrap(); + assert_eq!(sizing.layout.resolved.panels.len(), 1, "intended geometry survives invisible measurement"); + for regions in [&sizing.layout.painted, &sizing.layout.input, &sizing.layout.occlusion, &sizing.layout.reservations] { + assert!(!regions.iter().any(|bounds| egui_rect(*bounds).intersect(egui_rect(card.outer)).is_positive())); + } + assert!(sizing.controls.is_empty(), "no metadata-only controls from an invisible Area"); + let key = ControllerKey { instance: id("log-0"), owner: raw.content.runtime.instance_owner(&id("log-0")).unwrap() }; + assert_eq!(raw.content.probe.state(&key).unwrap().renders, 0, "measurement must not render hidden content"); + let visible = raw.frame(Vec::new(), false).0; + assert!(visible.layout.painted.contains(&card.outer)); + assert!(visible.layout.input.contains(&card.outer)); + assert!(visible.layout.occlusion.contains(&card.outer)); + let focused = raw.ctx.memory(|memory| memory.focused()).unwrap(); + assert!(visible.controls.iter().any(|control| control.id == focused && control.enabled)); + assert!(raw.content.probe.state(&key).unwrap().renders > 0); + + let mut side = RawPanelHost::new(host_logs(1, Zone::Left), scale); + side.ctx.options_mut(|options| options.max_passes = 1.try_into().unwrap()); + side.frame(Vec::new(), false); + let focus = side.content.dispatch(vec![Mutation::Focus { instance: id("log-0") }]).unwrap(); + side.host.note_reply(&focus); + side.content.dispatch(vec![Mutation::Collapse { section: section("section-0"), collapsed: true }]).unwrap(); + let collapsed = side.frame(Vec::new(), false).0; + let header = collapsed.layout.sections.first().unwrap(); + assert!(header.collapsed && header.body.is_none() && header.footer.is_none()); + assert_eq!(header.outer, header.header); + assert_eq!(collapsed.layout.painted, vec![header.outer]); + assert_eq!(collapsed.layout.input, vec![header.outer]); + assert!(collapsed.controls.iter().any(|control| matches!(&control.target, + HostControlTarget::Pointer(HostPointerTarget::Collapse { instance }) if *instance == id("log-0")))); + let hidden_renders = side + .content + .probe + .state(&ControllerKey { instance: id("log-0"), owner: side.content.runtime.instance_owner(&id("log-0")).unwrap() }) + .unwrap() + .renders; + side.frame(Vec::new(), false); + assert_eq!( + side.content + .probe + .state(&ControllerKey { instance: id("log-0"), owner: side.content.runtime.instance_owner(&id("log-0")).unwrap() }) + .unwrap() + .renders, + hidden_renders + ); + + let mut popup = RawPanelHost::new(host_logs(1, Zone::Left), scale); + popup.ctx.options_mut(|options| options.max_passes = 1.try_into().unwrap()); + popup.frame(Vec::new(), false); + popup.frame(Vec::new(), false); + popup.click(HostControlTarget::Pointer(HostPointerTarget::Menu { instance: id("log-0") }), false); + assert_no_popup(popup.host.frame().unwrap()); + popup.frame(Vec::new(), false); + assert_no_popup(popup.host.frame().unwrap()); + assert!(popup.host.frame().unwrap().owned_overlays.is_empty()); + popup.frame(Vec::new(), false); + assert!(popup.host.frame().unwrap().menu_bounds.is_some()); + assert!(popup.host.frame().unwrap().controls.iter().any(|control| matches!(control.target, HostControlTarget::Shared { .. }))); + } +} +#[test] +fn explicit_late_foreign_raise_blocks_popup_actions_but_lower_and_background_layers_do_not() { + fn assert_selected_panel_menu(raw: &mut RawPanelHost) { + assert!( + raw.host.frame().unwrap().controls.iter().any(|control| { + control.target == HostControlTarget::Shared { instance: id("log-0"), action: HostSharedAction::Move(Zone::Right) } + }) + ); + assert!(!raw.host.frame().unwrap().controls.iter().any(|control| control.target == HostControlTarget::PanelMenu { instance: id("log-0") })); + let inactive_identity = + |control: &HostFrameControl| matches!(&control.target, HostControlTarget::PanelMenu { instance } if *instance != id("log-0")); + let menu_at = egui_rect(raw.host.frame().unwrap().menu_bounds.unwrap()).center(); + for _ in 0..8 { + if raw.host.frame().unwrap().controls.iter().any(inactive_identity) { + break; + } + raw.frame(review_wheel(menu_at, -120.0), false); + } + assert!(raw.host.frame().unwrap().controls.iter().any(inactive_identity), "inactive tab identities remain reachable by scrolling"); + } + for scale in [1.0, 2.0] { + for nested in [false, true] { + for order in [egui::Order::Foreground, egui::Order::Background] { + for raise in [false, true] { + let (mut raw, source, button) = raw_popup_fixture(scale, if nested { PopupFixture::Tabs } else { PopupFixture::Menu }); + raw.foreign_order = order; + raw.foreign_cover = Some(egui::Rect::from_min_size(egui::pos2(900.0, 700.0), egui::vec2(100.0, 80.0))); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + // Keep the sized foreign Area continuously visible while + // the newer popup establishes its higher stack position. + open_root_popup(&mut raw, &source, button, false); + let target = if nested { + HostControlTarget::PanelMenu { instance: id("log-0") } + } else { + HostControlTarget::Shared { instance: id("log-0"), action: HostSharedAction::Move(Zone::Right) } + }; + let at = raw.at(target.clone()); + raw.foreign_cover = Some(egui::Rect::from_center_size(at, egui::vec2(100.0, 40.0))); + raw.frame(vec![egui::Event::PointerMoved(at)], false); + let source_widget = raw_control(&raw, &target); + let source_layer = raw.ctx.read_response(source_widget.id).unwrap().layer_id; + assert_eq!(raw.ctx.layer_id_at(at), Some(source_layer), "an unraised lower foreign Area cannot block the popup"); + assert!(raw.foreign_responses.iter().all(egui::Response::enabled)); + let before = raw.content.runtime.layout().inspect(); + let bounds = raw.host.frame().unwrap().menu_bounds; + let commits = raw.content.native.commits; + raw.pointer(at, true, false); + assert!(raw.ctx.read_response(source_widget.id).unwrap().is_pointer_button_down_on()); + raw.foreign_raise_late = raise; + raw.pointer(at, false, true); + let blocked = raise && order == egui::Order::Foreground; + if blocked { + assert_no_host_mutation(&raw, &before, commits); + assert_eq!(raw.host.frame().unwrap().menu_bounds, bounds); + } else if nested { + assert_eq!(raw.content.runtime.layout().inspect(), before); + } else { + assert_eq!(raw.content.runtime.layout().inspect().revision, before.revision + 1); + assert_eq!(raw.content.runtime.layout().layout().containing(&id("log-0")).unwrap().location.zone(), Zone::Right); + assert_eq!(raw.content.native.commits, commits + 1); + } + raw.foreign_raise_late = false; + raw.foreign_cover = None; + raw.frame(Vec::new(), true); + raw.pointer(at, false, true); + if blocked { + assert_no_host_mutation(&raw, &before, commits); + assert_eq!(raw.host.frame().unwrap().menu_bounds, bounds); + assert!(raw.host.frame().unwrap().controls.iter().any(|control| control.target == target)); + } else if nested { + assert_selected_panel_menu(&mut raw); + } else { + assert_eq!(raw.content.runtime.layout().inspect().revision, before.revision + 1); + } + assert_eq!(raw.content.commands.calls, 0); + assert!(raw.content.native.hosts.is_empty()); + } + } + } + } + // A third, now-undrawn Area can mask the stored order of the two live + // layers in layer_id_at. Compare their real stored ranks, independently of + // whichever stale third layer happens to be returned at the pointer. + for scale in [1.0, 2.0] { + for raise in [false, true] { + let (mut raw, source, button) = raw_popup_fixture(scale, PopupFixture::Tabs); + raw.ctx.global_style_mut(|style| style.interaction.interact_radius = 6.0); + raw.foreign_cover = Some(egui::Rect::from_min_size(egui::pos2(900.0, 700.0), egui::vec2(100.0, 80.0))); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + open_root_popup(&mut raw, &source, button, false); + let target = HostControlTarget::PanelMenu { instance: id("log-0") }; + let at = raw.at(target.clone()); + raw.foreign_cover = Some(egui::Rect::from_center_size(at, egui::vec2(100.0, 40.0))); + raw.frame(vec![egui::Event::PointerMoved(at)], false); + let widget = raw_control(&raw, &target); + let source_layer = raw.ctx.read_response(widget.id).unwrap().layer_id; + assert_eq!(raw.ctx.layer_id_at(at), Some(source_layer)); + // This real tiny hover-only Area contributes layer geometry while + // leaving the nearby source button eligible for egui's six-point + // interaction radius. The click proof below guards that premise. + raw.stale_foreign_cover = Some(egui::Rect::from_center_size(at, egui::vec2(1.0, 1.0))); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + let stale = raw.stale_foreign_layer.unwrap(); + assert_ne!(stale, source_layer); + assert_eq!(raw.ctx.layer_id_at(at), Some(stale)); + raw.stale_foreign_cover = None; + raw.foreign_raise_late = raise; + let before = raw.content.runtime.layout().inspect(); + let bounds = raw.host.frame().unwrap().menu_bounds; + let commits = raw.content.native.commits; + raw.frame(vec![egui::Event::PointerMoved(at), button_event(at, true), button_event(at, false)], false); + assert!(raw.clicked_widgets.contains(&widget.id), "the real popup response must offer an action before deferred layer validation"); + raw.foreign_raise_late = false; + raw.foreign_cover = None; + raw.frame(Vec::new(), true); + if raise { + assert_no_host_mutation(&raw, &before, commits); + assert_eq!(raw.host.frame().unwrap().menu_bounds, bounds); + assert!(raw.host.frame().unwrap().controls.iter().any(|control| control.target == target)); + } else { + assert_eq!(raw.content.runtime.layout().inspect(), before); + assert_selected_panel_menu(&mut raw); + } + } + } +} + +#[test] +fn native_reply_capabilities_match_live_sink_across_prepare_show_finish_stale_and_error_paths() { + for layout_native in [false, true] { + for adapter_native in [false, true] { + let mut content = PanelMountHarness::new(layout_native).unwrap(); + open_editor(&mut content); + content.native = FakeNativeAdapter::new(adapter_native); + if adapter_native { + content.native.capabilities.max_native_hosts = 3; + } + let authority = content.runtime.layout().inspect().capabilities; + let native = content.native.capabilities(); + let expected = HostCapabilities { + native_windows: authority.native_windows && native.native_windows, + persistence: authority.persistence, + max_native_hosts: authority.max_native_hosts.min(native.max_native_hosts), + }; + let mut raw = RawPanelHost::new(content, 1.0); + raw.host.capture_metrics(&raw.content.runtime, &raw.content.models).unwrap(); + raw.host.prepare(&raw.content.runtime, raw.capacity).unwrap(); + assert!(!raw.host.frame().unwrap().reply.capabilities.native_windows, "standalone first prepare has no native owner yet"); + raw.frame(Vec::new(), true); + for frame in raw.painted_frames.iter().chain(&raw.finished_frames) { + assert_eq!(frame.reply.capabilities, expected); + } + raw.host.capture_metrics(&raw.content.runtime, &raw.content.models).unwrap(); + raw.host.prepare(&raw.content.runtime, raw.capacity).unwrap(); + assert_eq!(raw.host.frame().unwrap().reply.capabilities, expected, "a capable first show must recover from prepare's conservative false"); + let inspected = raw.content.command("layout.get", &serde_json::json!({})).unwrap(); + assert_eq!(inspected["state"]["capabilities"], serde_json::to_value(&expected).unwrap()); + let sink_reply = { + let h = &mut raw.content; + RuntimeActionSink { + runtime: &mut h.runtime, + native: &mut h.native, + services: &mut ContentServices { models: &h.models, commands: &mut h.commands, local: &mut h.local }, + } + .inspect() + }; + assert_eq!(sink_reply.capabilities, expected); + raw.frame_late(Vec::new(), true, |h, ctx| { + if ctx.current_pass_index() == 0 { + h.dispatch(vec![Mutation::Collapse { section: section("editor-section"), collapsed: true }]).unwrap(); + } + }); + for frame in raw.painted_frames.iter().chain(&raw.finished_frames) { + assert_eq!(frame.reply.capabilities, expected); + } + assert!( + raw.finished_frames[0].events.iter().any(|event| matches!(event, HostEvent::Rejected { error, .. } if error.rule == Rule::Revision)) + ); + raw.content.dispatch(vec![Mutation::Collapse { section: section("editor-section"), collapsed: false }]).unwrap(); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + raw.menu(id("editor")); + let popout = HostControlTarget::Shared { instance: id("editor"), action: HostSharedAction::Popout }; + assert_eq!(raw_control(&raw, &popout).enabled, expected.native_windows); + raw.content.native.fail_prepare = true; + let before = raw.content.runtime.layout().inspect(); + raw.click(popout, true); + for frame in raw.painted_frames.iter().chain(&raw.finished_frames) { + assert_eq!(frame.reply.capabilities, expected); + } + assert_eq!(raw.content.runtime.layout().inspect(), before); + if expected.native_windows { + assert!( + raw.host + .frame() + .unwrap() + .events + .iter() + .any(|event| matches!(event, HostEvent::Rejected { error, .. } if error.rule == Rule::Capability)) + ); + } + } + } + // App preparation already knows its persistent native owner before painting. + for native in [false, true] { + let (mut h, _, _) = boundary_app(); + let adapter = std::rc::Rc::new(std::cell::RefCell::new(FakeNativeAdapter::new(native))); + h.app.set_panel_native_adapter(Box::new(SharedNative(adapter))).unwrap(); + h.app.panel_runtime.as_mut().unwrap().prepare_host(&h.app.session, capacity()).unwrap(); + let command = h.app.run_panel_command("layout.get", &serde_json::json!({})).unwrap(); + assert_eq!(serde_json::to_value(&h.app.universal_panel_frame().unwrap().reply.capabilities).unwrap(), command["state"]["capabilities"]); + assert_eq!(h.app.universal_panel_frame().unwrap().reply.capabilities.native_windows, native); + } +} + +// Review integration fixtures retain diagnostic identity through preparation. +// These cases are source-only until root runs the complete integration gate. +#[derive(Default)] +struct ReviewCohortTrace { + factories: Vec<(ControllerKey, usize)>, + measures: Vec, + providers: Vec<(usize, std::sync::Arc)>, + lifecycle: Vec<(usize, LifecycleEvent)>, + actions: Vec<(ControllerKey, usize)>, + unavailable: std::collections::BTreeSet, + availability_reads: usize, + disabled: bool, + metric_revision: u64, + editors: Vec<(egui::Id, ContentSlot, egui::Rect, String)>, + wrap_rows: Vec, + consume_wheel: bool, + child_scroll: std::collections::BTreeMap, +} +type ReviewTrace = std::rc::Rc>; +#[derive(Debug)] +struct ReviewMetrics { + revision: u64, + height: f32, + policy: SideHeightPolicy, +} +impl HostContentMetrics for ReviewMetrics { + fn revision(&self) -> u64 { + self.revision + } + fn measure(&self, request: &ContentMeasureRequest) -> PanelResult { + Ok(SideContentMeasure { request: request.clone(), needed_height: self.height.max(request.chrome_height), policy: self.policy }) + } +} +struct ReviewController { + inner: Box, + key: ControllerKey, + serial: usize, + trace: ReviewTrace, + draft: String, +} +impl PanelController for ReviewController { + fn availability(&self, owner: &ContentOwner, models: &dyn PanelModels) -> Availability { + let unavailable = { + let mut trace = self.trace.borrow_mut(); + trace.availability_reads += 1; + trace.unavailable.contains(&self.key) + }; + if unavailable { Availability::Unavailable { reason: "review owner unavailable".into() } } else { self.inner.availability(owner, models) } + } + fn measure(&self, _owner: &ContentOwner, _models: &dyn PanelModels, spec: &PanelSpec) -> PanelResult> { + let mut trace = self.trace.borrow_mut(); + trace.measures.push(self.serial); + let wrapping = self.key.instance.0 == "wrapping-editor"; + let characters = if wrapping { self.draft.chars().count() } else { 0 }; + // Explicit bounded preferred height, not a product intrinsic measurer. + let provider: std::sync::Arc = std::sync::Arc::new(ReviewMetrics { + revision: trace.metric_revision + self.serial as u64 * 1024 + ((characters as u64) << 32), + height: 240.0 + self.serial as f32 + characters as f32, + policy: spec.side_height_policy, + }); + trace.providers.push((self.serial, provider.clone())); + Ok(provider) + } + fn measurement_revision(&self, _owner: &ContentOwner, _models: &dyn PanelModels, _spec: &PanelSpec) -> PanelResult { + let characters = if self.key.instance.0 == "wrapping-editor" { self.draft.chars().count() } else { 0 }; + Ok(self.trace.borrow().metric_revision + self.serial as u64 * 1024 + ((characters as u64) << 32)) + } + fn update(&mut self, owner: &ContentOwner, services: &mut ContentServices<'_>) -> PanelResult<()> { + self.inner.update(owner, services) + } + fn presentation(&self) -> PanelPresentation { + let mut presentation = self.inner.presentation(); + presentation.actions.push(RuntimeAction { + id: ControlId::new("pulse").unwrap(), + label: "review pulse".into(), + enabled: !self.trace.borrow().disabled, + disabled_reason: self.trace.borrow().disabled.then(|| "review binding disabled".into()), + }); + presentation + } + fn prepare_lifecycle(&self, event: &LifecycleEvent) -> PanelResult<()> { + self.inner.prepare_lifecycle(event) + } + fn lifecycle(&mut self, event: &LifecycleEvent) { + self.trace.borrow_mut().lifecycle.push((self.serial, event.clone())); + 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)?; + let consume_wheel = self.trace.borrow().consume_wheel; + if slot == ContentSlot::Body { + if self.key.instance.0 == "inline-editor" || self.key.instance.0 == "wrapping-editor" { + let editor_id = egui::Id::unique(("review-inline-editor", &self.key)); + let response = if self.key.instance.0 == "wrapping-editor" { + crate::ui_kit::text_area(ui, "Review wrapping editor", editor_id, &mut self.draft, 1, 1024) + } else { + crate::ui_kit::bounded_cell_editor(ui, editor_id, &mut self.draft, "Review editable value", false, 4096) + }; + if self.key.instance.0 == "wrapping-editor" { + let tokens = crate::theme::Tokens::get(); + let width = (response.rect.width() - 2.0 * tokens.form_inset).max(1.0); + let galley = + ui.fonts_mut(|fonts| fonts.layout(self.draft.clone(), egui::FontId::monospace(tokens.font_label), tokens.form_ink, width)); + self.trace.borrow_mut().wrap_rows.push(galley.rows.len()); + } + self.trace.borrow_mut().editors.push((response.id, slot, response.rect, self.draft.clone())); + } else if consume_wheel { + let child = egui::ScrollArea::vertical() + .id_salt(("review-child-scroll", &self.key)) + .auto_shrink([false, false]) + .max_height(ui.available_height().max(1.0)) + .show(ui, |ui| { + ui.label("Real child scroll content"); + ui.add_space(1200.0); + }); + self.trace + .borrow_mut() + .child_scroll + .insert(self.key.instance.clone(), (child.inner_rect.intersect(ui.clip_rect()), child.state.unclamped_offset().y)); + } + } + Ok(()) + } + fn action(&mut self, owner: &ContentOwner, action: &ControlId, services: &mut ContentServices<'_>) -> PanelResult<()> { + if action.0 == "pulse" { + self.trace.borrow_mut().actions.push((self.key.clone(), self.serial)); + Ok(()) + } else { + self.inner.action(owner, action, services) + } + } +} +fn review_cohort_host(edit: impl Fn(&mut PanelSpec)) -> (PanelMountHarness, ReviewTrace) { + review_cohort_host_with_layout(edit, |_| {}) +} +fn review_cohort_host_with_layout(edit: impl Fn(&mut PanelSpec), setup: impl FnOnce(&mut LayoutService)) -> (PanelMountHarness, ReviewTrace) { + let mut h = PanelMountHarness::without_content(false).unwrap(); + let environment = h.runtime.environment().clone(); + let mut registry = PanelRegistry::default(); + for original in synthetic_registry().unwrap().specs() { + let mut spec = original.clone(); + spec.header_actions.push(HeaderActionSpec { id: ControlId::new("pulse").unwrap(), label_key: "ui.panel".into(), icon: "list".into() }); + spec.features.hot_closable = true; + edit(&mut spec); + registry.register(spec).unwrap(); + } + let mut service = LayoutService::new(registry, Layout::empty(environment.workspace.clone()), HostCapabilities::default()).unwrap(); + setup(&mut service); + h.runtime = PanelRuntime::new(service, environment).unwrap(); + let trace = ReviewTrace::default(); + for (kind, editor, ownership) in [("fixture.log", false, Ownership::Workspace), ("fixture.editor", true, Ownership::Document)] { + let binding = fixture_controller_binding(&h.probe, editor, ownership); + let create = binding.create; + let trace = trace.clone(); + h.runtime + .register( + PanelKind::new(kind).unwrap(), + ControllerBinding { + ownership, + create: Box::new(move |instance, owner| { + let key = ControllerKey { instance: instance.id.clone(), owner: owner.clone() }; + let serial = trace.borrow().factories.len() + 1; + let inner = create(instance, owner)?; + trace.borrow_mut().factories.push((key.clone(), serial)); + let draft = if key.instance.0 == "wrapping-editor" { "short" } else { "retained editable value" }.into(); + Ok(Box::new(ReviewController { inner, key, serial, trace: trace.clone(), draft })) + }), + }, + ) + .unwrap(); + } + (h, trace) +} +fn review_header_action(instance: &str) -> LayoutAction { + transaction(vec![Mutation::HeaderAction { instance: id(instance), action: ControlId::new("pulse").unwrap() }]) +} + +#[test] +fn captured_incoming_workspace_cohort_is_created_measured_and_committed_exactly_once() { + let (mut h, trace) = review_cohort_host(|_| {}); + h.dispatch(vec![fixture_open("fixture.log", "log", "log", Zone::Left, 0).unwrap()]).unwrap(); + h.tick().unwrap(); + let mut host = WorkspacePanelHost::new(HostOptions::default()).unwrap(); + host.capture_metrics(&h.runtime, &h.models).unwrap(); + host.capture_reservations(&h.runtime, &h.catalogue).unwrap(); + host.prepare(&h.runtime, capacity()).unwrap(); + let mut incoming = h.runtime.layout().layout().clone(); + incoming.workspace = WorkspaceId::new("review.incoming").unwrap(); + let action = LayoutAction::Replace { expected_revision: Some(h.runtime.layout().inspect().revision), layout: incoming }; + let count = trace.borrow().factories.len(); + let measures = trace.borrow().measures.len(); + let mut services = ContentServices { models: &h.models, commands: &mut h.commands, local: &mut h.local }; + { + let mut live = RuntimeActionSink { runtime: &mut h.runtime, native: &mut h.native, services: &mut services }; + let mut sink = super::app::AdmittedActionSink { live: &mut live, host: Some(&mut host), proposal: std::cell::RefCell::new(None) }; + let first = sink.project(action.clone()).unwrap(); + assert_eq!(sink.project(action.clone()).unwrap(), first); + assert_eq!(trace.borrow().factories.len(), count + 1); + assert_eq!(trace.borrow().measures.len(), measures + 1); + sink.dispatch(action).unwrap(); + } + let serial = trace.borrow().factories.last().unwrap().1; + assert_eq!(trace.borrow().factories.len(), count + 1); + assert_eq!(trace.borrow().measures.len(), measures + 1); + assert!(trace.borrow().lifecycle.iter().any(|(id, event)| *id == serial && matches!(event, LifecycleEvent::State(_)))); + assert_eq!(h.runtime.controller_count(), 2, "outgoing and incoming workspace controllers remain retained"); + assert_eq!(h.runtime.environment().workspace.0, "review.incoming"); +} + +#[test] +fn proposed_unavailable_and_unbound_owners_remain_requested_open_without_false_bodies() { + let (mut h, trace) = review_cohort_host(|_| {}); + let mut incoming_service = fixture_service(false).unwrap(); + apply_fixture( + &mut incoming_service, + vec![ + fixture_open("fixture.log", "log", "log", Zone::Left, 0).unwrap(), + fixture_open("fixture.application", "unbound", "unbound", Zone::Right, 1).unwrap(), + ], + ); + h.apply_layout(incoming_service.layout().clone(), None).unwrap(); + h.tick().unwrap(); + let mut host = WorkspacePanelHost::new(HostOptions::default()).unwrap(); + host.capture_metrics(&h.runtime, &h.models).unwrap(); + host.capture_reservations(&h.runtime, &h.catalogue).unwrap(); + host.prepare(&h.runtime, capacity()).unwrap(); + let mut incoming = h.runtime.layout().layout().clone(); + incoming.workspace = WorkspaceId::new("review.unavailable").unwrap(); + trace.borrow_mut().unavailable.insert(ControllerKey { instance: id("log"), owner: ContentOwner::Workspace(incoming.workspace.clone()) }); + let proposal = h + .runtime + .prepare_host_proposal( + host.command_reference(&h.runtime).unwrap(), + LayoutAction::Replace { expected_revision: None, layout: incoming }, + &h.models, + ) + .unwrap(); + h.runtime + .commit_host_proposal(proposal, &mut h.native, &mut ContentServices { models: &h.models, commands: &mut h.commands, local: &mut h.local }) + .unwrap(); + assert!(h.runtime.layout().layout().instances.iter().all(|instance| instance.requested_open)); + assert!(h.runtime.layout().layout().instances.iter().all(|instance| h.runtime.layout().availability(&instance.id) != Availability::Available)); + host.capture_metrics(&h.runtime, &h.models).unwrap(); + host.capture_reservations(&h.runtime, &h.catalogue).unwrap(); + host.prepare(&h.runtime, capacity()).unwrap(); + assert!(host.frame().unwrap().layout.resolved.panels.is_empty()); +} + +#[test] +fn raw_available_fallback_mounts_and_owns_actions_without_rewriting_remembered_active() { + for scale in [1.0, 2.0] { + let (mut h, trace) = review_cohort_host(|_| {}); + h.dispatch(vec![ + fixture_open("fixture.log", "a", "group", Zone::Left, 0).unwrap(), + Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("b"), + destination: Some(Destination::JoinTab { section: section("group"), index: 1 }), + }, + Mutation::Activate { instance: id("a") }, + ]) + .unwrap(); + let key = ControllerKey { instance: id("a"), owner: ContentOwner::Workspace(h.runtime.environment().workspace.clone()) }; + trace.borrow_mut().unavailable.insert(key.clone()); + let mut raw = RawPanelHost::new(h, scale); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + assert_eq!(raw.host.frame().unwrap().layout.sections[0].instance, id("b")); + let b = ControllerKey { instance: id("b"), owner: key.owner.clone() }; + assert!(raw.content.runtime.state(&b).unwrap().activated); + raw.click(HostControlTarget::Pointer(HostPointerTarget::HeaderAction { instance: id("b"), action: ControlId::new("pulse").unwrap() }), true); + assert_eq!(trace.borrow().actions.len(), 1); + assert_eq!(trace.borrow().actions[0].0, b); + assert_eq!(raw.content.runtime.layout().layout().section(§ion("group")).unwrap().active, id("a")); + assert_eq!( + raw.content + .dispatch(match review_header_action("a") { + LayoutAction::Apply { mutations, .. } => mutations, + other => panic!("header action fixture must use Apply: {other:?}"), + }) + .unwrap_err() + .rule, + Rule::Availability + ); + trace.borrow_mut().unavailable.remove(&key); + raw.frame(Vec::new(), false); + assert_eq!(raw.host.frame().unwrap().layout.sections[0].instance, id("a")); + assert_eq!(raw.content.runtime.controller_count(), 2); + } +} + +#[test] +fn raw_widget_and_pointer_storage_refusal_preserve_layout_controllers_drafts_and_native_owner() { + for pointer in [false, true] { + let mut h = host_logs(2, Zone::Left); + open_editor(&mut h); + let key = editor_key(&h); + h.probe.edit(&key, |state| state.draft = "storage refusal retains this draft".into()).unwrap(); + let mut raw = RawPanelHost::new(h, 1.0); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + let before = raw.content.runtime.layout().inspect(); + let count = raw.content.runtime.controller_count(); + let commits = raw.content.native.commits; + raw.content.catalogue.fail_stage = true; + if pointer { + let target = raw.host.frame().unwrap().layout.sashes[0].clone(); + let start = raw.at(HostControlTarget::Pointer(HostPointerTarget::Sash { first: target.first, second: target.second })); + raw.pointer(start, true, false); + raw.frame(vec![egui::Event::PointerMoved(start + egui::vec2(0.0, 24.0))], false); + raw.pointer(start + egui::vec2(0.0, 24.0), false, false); + } else { + raw.click(HostControlTarget::Pointer(HostPointerTarget::Collapse { instance: id("log-0") }), false); + } + assert_host_mutation_refused(&raw, &before, count, commits); + assert_eq!(raw.content.probe.state(&key).unwrap().draft, "storage refusal retains this draft"); + assert!( + raw.host.frame().unwrap().events.iter().any(|event| matches!(event, HostEvent::Rejected { error, .. } if error.rule == Rule::Capability)) + ); + } +} +fn assert_host_mutation_refused(raw: &RawPanelHost, before: &LayoutReply, controllers: usize, native_commits: u64) { + assert_eq!(&raw.content.runtime.layout().inspect(), before); + assert_eq!(raw.content.runtime.controller_count(), controllers); + assert_eq!(raw.content.native.commits, native_commits); +} + +#[test] +fn raw_registered_header_action_ignores_overflow_storage_but_honours_binding_and_close_permission() { + for scale in [1.0, 2.0] { + let (mut h, trace) = review_cohort_host(|spec| { + spec.features.closable = false; + spec.features.hot_closable = true; + }); + h.dispatch(vec![fixture_open("fixture.log", "log", "log", Zone::Left, 0).unwrap()]).unwrap(); + let mut raw = RawPanelHost::new(h, scale); + raw.capacity.size = Size { width: 400.0, height: 130.0 }; + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + let pulse = HostControlTarget::Pointer(HostPointerTarget::HeaderAction { instance: id("log"), action: ControlId::new("pulse").unwrap() }); + let close = HostControlTarget::Pointer(HostPointerTarget::Close { instance: id("log") }); + assert!(!raw_control(&raw, &close).enabled, "hot close visibility does not grant close permission"); + raw.content.catalogue.fail_stage = true; + raw.click(pulse.clone(), false); + assert_eq!(trace.borrow().actions.len(), 1); + trace.borrow_mut().disabled = true; + raw.frame(Vec::new(), false); + assert!(!raw_control(&raw, &pulse).enabled); + raw.click(pulse, false); + assert_eq!(trace.borrow().actions.len(), 1); + raw.click(close, false); + assert!(raw.content.runtime.layout().layout().instance(&id("log")).unwrap().requested_open); + } +} + +#[test] +fn deferred_widget_metric_change_discards_old_geometry_and_requires_fresh_paint() { + let (mut h, trace) = review_cohort_host(|_| {}); + h.dispatch(vec![fixture_open("fixture.log", "log", "log", Zone::Left, 0).unwrap()]).unwrap(); + let mut raw = RawPanelHost::new(h, 1.0); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + let target = HostControlTarget::Pointer(HostPointerTarget::Collapse { instance: id("log") }); + let at = raw.at(target); + raw.pointer(at, true, false); + let before = raw.content.runtime.layout().inspect(); + let commits = raw.content.native.commits; + let trace_after = trace.clone(); + // Change immutable snapshot source after paint and before late dispatch. + let (frame, _) = raw.frame_late(vec![button_event(at, false)], false, move |_, _| { + trace_after.borrow_mut().metric_revision += 1; + }); + assert!(frame.is_none(), "a changed snapshot invalidates the old painted frame"); + assert!(!raw.host.interaction().is_captured(), "discarded geometry cannot retain the provisional release candidate"); + assert_eq!(raw.content.runtime.layout().inspect(), before); + let fresh = raw.frame(Vec::new(), false).0; + assert!(fresh.preview.is_none()); + assert!(!fresh.events.iter().any(|event| matches!(event, HostEvent::Committed { .. } | HostEvent::PreparedCommitted { .. }))); + assert_eq!(raw.content.native.commits, commits); + assert!(!raw.content.runtime.layout().layout().section(§ion("log")).unwrap().collapsed); +} + +#[test] +fn rejected_batch_cancels_capture_before_parse_without_refreshing_owners_or_context() { + let (mut h, probe, trace) = boundary_app(); + let header = app_control(&h.app, HostControlTarget::Pointer(HostPointerTarget::Header { instance: id("editor") })); + let at = egui_rect(header.bounds).center(); + boundary_frame(&mut h, vec![egui::Event::PointerMoved(at), button_event(at, true)], |_| {}); + assert!(h.app.panel_runtime.as_ref().unwrap().host().unwrap().interaction().is_captured()); + let before = h.app.panel_runtime().unwrap().layout().inspect(); + let refreshes = trace.borrow().refreshes; + let factories = trace.borrow().factory_keys.clone(); + let key = app_editor_key(&h.app); + let draft = probe.state(&key).unwrap().draft; + let refusal = + h.app.run_panel_batch(&[serde_json::json!({"command":"panel.close","params":{"target":{"type":"instance","id":"editor"},"unknown":true}})]); + assert!(refusal.is_err()); + assert!(!h.app.panel_runtime.as_ref().unwrap().host().unwrap().interaction().is_captured()); + assert_eq!(h.app.panel_runtime().unwrap().layout().inspect(), before); + assert_eq!(trace.borrow().refreshes, refreshes); + assert_eq!(trace.borrow().factory_keys, factories); + assert_eq!(probe.state(&key).unwrap().draft, draft); +} + +#[test] +fn raw_allocated_pair_endpoints_and_capped_third_have_exact_numeric_deltas() { + for scale in [1.0, 2.0] { + for direction in [Direction::Ltr, Direction::Rtl] { + for bottom in [false, true] { + for endpoint in [120.0, 676.0] { + let zone = if bottom { Zone::Bottom } else { Zone::Left }; + let mut h = host_with_specs(|spec| { + spec.min_size = Size { width: 120.0, height: 120.0 }; + spec.max_size = Size { width: 2000.0, height: 2000.0 }; + }); + h.dispatch(vec![ + fixture_open("fixture.log", "one", "one", zone, 0).unwrap(), + fixture_open("fixture.log", "two", "two", zone, 1).unwrap(), + ]) + .unwrap(); + let mut environment = h.runtime.environment().clone(); + environment.direction = direction; + h.runtime.set_environment(environment, &mut h.local).unwrap(); + let mut raw = RawPanelHost::new(h, scale); + raw.capacity.size = if bottom { Size { width: 800.0, height: 1000.0 } } else { Size { width: 1000.0, height: 800.0 } }; + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + let cards = &raw.host.frame().unwrap().layout.sections; + let axis = |size: Size| if bottom { size.width } else { size.height }; + assert_eq!((axis(cards[0].outer.size), axis(cards[1].outer.size)), (398.0, 398.0)); + let at = raw.at(HostControlTarget::Pointer(HostPointerTarget::Sash { first: section("one"), second: section("two") })); + raw.pointer(at, true, false); + let delta = endpoint - 398.0; + let end = if bottom { + at + egui::vec2(if direction == Direction::Rtl { -delta } else { delta }, 0.0) + } else { + at + egui::vec2(0.0, delta) + }; + let shown = raw.frame(vec![egui::Event::PointerMoved(end)], false).0.preview.unwrap().projected.unwrap(); + assert_eq!((axis(shown.sections[0].outer.size), axis(shown.sections[1].outer.size)), (endpoint, 796.0 - endpoint)); + raw.pointer(end, false, false); + raw.frame(Vec::new(), false); + let actual = &raw.host.frame().unwrap().layout; + assert_eq!((axis(actual.sections[0].outer.size), axis(actual.sections[1].outer.size)), (endpoint, 796.0 - endpoint)); + assert!( + raw.content + .runtime + .layout() + .layout() + .sections + .iter() + .all(|section| section.preferred_extent.is_none() && section.extent_priority == 0), + "ordinary weighted endpoints do not author preference tiers" + ); + } + } + let mut h = host_with_specs(|spec| { + spec.min_size.height = 120.0; + spec.max_size.height = 2000.0; + if spec.kind.0 == "fixture.editor" { + spec.max_size.height = 200.0; + spec.default_size.height = 200.0; + } + }); + h.dispatch(vec![ + Mutation::Open { + kind: PanelKind::new("fixture.editor").unwrap(), + instance: id("one"), + destination: Some(Destination::NewSection { + section: section("one"), + index: 0, + location: SectionLocation::Dock { zone: Zone::Left }, + size: Size { width: 280.0, height: 200.0 }, + }), + }, + fixture_open("fixture.log", "two", "two", Zone::Left, 1).unwrap(), + fixture_open("fixture.log", "three", "three", Zone::Left, 2).unwrap(), + ]) + .unwrap(); + let mut environment = h.runtime.environment().clone(); + environment.direction = direction; + h.runtime.set_environment(environment, &mut h.local).unwrap(); + let mut raw = RawPanelHost::new(h, scale); + raw.capacity.size.height = 800.0; + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + let before = raw.host.frame().unwrap().layout.sections.clone(); + assert_eq!(before.iter().map(|card| card.outer.size.height).collect::>(), vec![200.0, 296.0, 296.0]); + let at = raw.at(HostControlTarget::Pointer(HostPointerTarget::Sash { first: section("one"), second: section("two") })); + raw.pointer(at, true, false); + let end = at - egui::vec2(0.0, 20.0); + let shown = raw.frame(vec![egui::Event::PointerMoved(end)], false).0.preview.unwrap().projected.unwrap(); + for (card, expected) in shown.sections.iter().take(2).zip([180.0_f32, 316.0]) { + let actual = card.outer.size.height; + // The allocator rounds surplus inward when resolving the resized pair. + assert!(actual.to_bits().abs_diff(expected.to_bits()) <= 2, "actual {actual}, expected {expected} within two f32 ULPs"); + } + assert_eq!(shown.sections[2].outer, before[2].outer, "unrelated capped allocation stays fixed"); + raw.pointer(end, false, false); + raw.frame(Vec::new(), false); + assert_host_landing(&raw.host.frame().unwrap().layout, &shown); + assert_eq!(raw.host.frame().unwrap().layout.sections[2].outer, before[2].outer, "unrelated capped allocation stays fixed after commit"); + assert!( + raw.content + .runtime + .layout() + .layout() + .sections + .iter() + .all(|section| section.preferred_extent.is_none() && section.extent_priority == 0) + ); + } + } +} + +#[test] +fn raw_explicit_extent_survives_collapse_sole_content_and_return_to_stack() { + let mut h = host_logs(2, Zone::Left); + h.dispatch(vec![Mutation::SetSize { section: section("section-0"), size: Size { width: 280.0, height: 400.0 } }]).unwrap(); + let weights = h.runtime.layout().layout().sections.iter().map(|section| section.weight).collect::>(); + let mut raw = RawPanelHost::new(h, 1.0); + raw.capacity.size.height = 800.0; + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + assert_eq!(raw.host.frame().unwrap().layout.sections.iter().map(|card| card.outer.size.height).collect::>(), vec![400.0, 396.0]); + raw.click(HostControlTarget::Pointer(HostPointerTarget::Collapse { instance: id("log-0") }), false); + raw.frame(Vec::new(), false); + assert_eq!(raw.host.frame().unwrap().layout.sections[0].outer.size.height, raw.host.frame().unwrap().layout.metrics.header_height); + raw.click(HostControlTarget::Pointer(HostPointerTarget::Collapse { instance: id("log-0") }), false); + raw.frame(Vec::new(), false); + assert_eq!(raw.host.frame().unwrap().layout.sections[0].outer.size.height, 400.0); + raw.content.dispatch(vec![Mutation::Close { instance: id("log-1") }]).unwrap(); + raw.frame(Vec::new(), false); + assert_eq!(raw.host.frame().unwrap().layout.sections[0].outer.size.height, 240.0, "sole Content reports bounded preferred outer height"); + assert_eq!(raw.content.runtime.layout().layout().section(§ion("section-0")).unwrap().preferred_extent, Some(400.0)); + raw.content.dispatch(vec![Mutation::Open { kind: PanelKind::new("fixture.log").unwrap(), instance: id("log-1"), destination: None }]).unwrap(); + raw.frame(Vec::new(), false); + assert_eq!(raw.host.frame().unwrap().layout.sections.iter().map(|card| card.outer.size.height).collect::>(), vec![400.0, 396.0]); + assert_eq!(raw.content.runtime.layout().layout().sections.iter().map(|section| section.weight).collect::>(), weights); +} + +#[test] +fn raw_close_keeps_original_lifecycle_intent_and_refuses_a_live_editor_guard() { + let mut h = host_with_specs(|spec| spec.features.hot_closable = true); + open_editor(&mut h); + let key = editor_key(&h); + h.probe + .edit(&key, |state| { + state.reject_cancel = true; + state.draft = "guarded retained transaction".into(); + }) + .unwrap(); + let mut raw = RawPanelHost::new(h, 1.0); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + let before = raw.content.runtime.layout().inspect(); + raw.click(HostControlTarget::Pointer(HostPointerTarget::Close { instance: id("editor") }), false); + assert_eq!(raw.content.runtime.layout().inspect(), before); + assert_eq!(raw.content.probe.state(&key).unwrap().cancels, 0); + assert_eq!(raw.content.probe.state(&key).unwrap().draft, "guarded retained transaction"); + assert!(raw.host.frame().unwrap().events.iter().any(|event| matches!(event, HostEvent::Rejected { error, .. } if error.rule == Rule::Lifecycle))); +} + +#[test] +fn raw_tiny_scroll_uses_real_card_layer_and_uncovered_content_gap_stays_navigable() { + for scale in [1.0, 2.0] { + for direction in [Direction::Ltr, Direction::Rtl] { + let mut content = host_logs(4, Zone::Left); + let mut environment = content.runtime.environment().clone(); + environment.direction = direction; + content.runtime.set_environment(environment, &mut content.local).unwrap(); + let mut raw = RawPanelHost::new(content, scale); + raw.capacity.size = Size { width: 600.0, height: 180.0 }; + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + let frame = raw.host.frame().unwrap(); + assert_eq!(frame.layout.sections.len(), 4); + assert!(frame.layout.extent.height >= 4.0 * 120.0 + 12.0); + let at = egui_rect(frame.layout.sections[0].outer).center(); + let before = frame.layout.geometry_policy.scroll.y; + raw.frame( + vec![ + egui::Event::PointerMoved(at), + egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -72.0), + modifiers: egui::Modifiers::NONE, + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + }, + ], + false, + ); + raw.frame(Vec::new(), false); + assert!(raw.host.frame().unwrap().layout.geometry_policy.scroll.y > before, "real Area-owned wheel reaches the host canvas"); + assert!(raw.host.frame().unwrap().layout.input.iter().all(|bounds| intersect_rect(raw.capacity, *bounds) == Some(*bounds))); + let mut sole = RawPanelHost::new(host_logs(1, Zone::Left), scale); + let mut environment = sole.content.runtime.environment().clone(); + environment.direction = direction; + sole.content.runtime.set_environment(environment, &mut sole.content.local).unwrap(); + sole.frame(Vec::new(), false); + sole.frame(Vec::new(), false); + let card = sole.host.frame().unwrap().layout.sections[0].outer; + let gap = Point { x: middle(card).x, y: card.origin.y + card.size.height + 24.0 }; + let frame = sole.host.frame().unwrap(); + assert!(frame.layout.usable.contains_rect(LogicalRect { origin: gap, size: Size { width: 4.0, height: 4.0 } })); + assert!(!frame.layout.input.iter().any(|bounds| bounds.contains(gap))); + assert_eq!(frame.layout.viewport, Some(sole.capacity)); + } + } +} + +#[test] +#[ignore = "opt-in resolver measurement; root records machine/profile after source review"] +fn host_resolver_measurement_exercise_for_twenty_four_panels() { + use std::hint::black_box; + use std::time::Instant; + let mut h = host_logs(24, Zone::Left); + for index in 1..24 { + if index % 6 == 0 { + h.dispatch(vec![Mutation::Move { + instance: id(&format!("log-{index}")), + destination: Destination::Relative { + section: section(&format!("section-{}", index - 1)), + placement: RelativePlacement::AfterColumn, + new_section: section(&format!("section-{index}")), + new_column: Some(ColumnId::new(format!("measurement.column.{index}")).unwrap()), + size: Size { width: 280.0, height: 240.0 }, + }, + }]) + .unwrap(); + } + if index % 5 == 0 { + h.dispatch(vec![Mutation::Collapse { section: section(&format!("section-{index}")), collapsed: true }]).unwrap(); + } + } + for index in [1, 9, 17] { + h.dispatch(vec![Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id(&format!("measurement.tab.{index}")), + destination: Some(Destination::JoinTab { section: section(&format!("section-{index}")), index: 1 }), + }]) + .unwrap(); + } + let snapshot_started = Instant::now(); + let provider = h.runtime.capture_metrics(&h.models).unwrap(); + let reservations = fixture_complete_reservations(h.runtime.layout()); + let policy = HostGeometryPolicy { + content_revision: provider.revision(), + measure: Some(provider), + identity_reservations: reservations, + ..Default::default() + }; + let snapshot_cost = snapshot_started.elapsed(); + let before = h.runtime.layout().inspect(); + let domain = LogicalRect { origin: Point { x: 0.0, y: 32.0 }, size: Size { width: 1800.0, height: 1000.0 } }; + let capacity = LogicalRect { origin: Point { x: 0.0, y: 96.0 }, size: Size { width: 1800.0, height: 936.0 } }; + let chrome = [LogicalRect { origin: domain.origin, size: Size { width: 1800.0, height: 64.0 } }]; + for direction in [Direction::Ltr, Direction::Rtl] { + let mut samples = Vec::new(); + for _ in 0..200 { + let started = Instant::now(); + let layout = black_box( + resolve_host_layout_in_domain( + black_box(h.runtime.layout()), + domain, + capacity, + &chrome, + direction, + HostMetrics::default(), + black_box(&policy), + ) + .unwrap(), + ); + samples.push(started.elapsed()); + assert_eq!(layout.sections.len(), 24); + assert_eq!(layout.viewport, Some(domain)); + } + samples.sort(); + eprintln!( + "resolver measurement os={} arch={} profile={} direction={direction:?} samples={} median={:?} range={:?}..{:?} snapshot={snapshot_cost:?}; observational target <0.2ms, no timing gate", + std::env::consts::OS, + std::env::consts::ARCH, + if cfg!(debug_assertions) { "debug" } else { "release" }, + samples.len(), + samples[samples.len() / 2], + samples.first(), + samples.last() + ); + } + assert_eq!(h.runtime.layout().inspect(), before); +} + +#[test] +fn cached_command_proposal_is_discarded_on_metric_change_without_a_second_factory() { + let (mut h, trace) = review_cohort_host(|_| {}); + h.dispatch(vec![fixture_open("fixture.log", "log", "log", Zone::Left, 0).unwrap()]).unwrap(); + h.tick().unwrap(); + let mut host = WorkspacePanelHost::new(HostOptions::default()).unwrap(); + host.capture_metrics(&h.runtime, &h.models).unwrap(); + host.capture_reservations(&h.runtime, &h.catalogue).unwrap(); + host.prepare(&h.runtime, capacity()).unwrap(); + let action = transaction(vec![Mutation::Collapse { section: section("log"), collapsed: true }]); + let before = h.runtime.layout().inspect(); + let factories = trace.borrow().factories.len(); + let mut services = ContentServices { models: &h.models, commands: &mut h.commands, local: &mut h.local }; + { + let mut live = RuntimeActionSink { runtime: &mut h.runtime, native: &mut h.native, services: &mut services }; + let mut sink = super::app::AdmittedActionSink { live: &mut live, host: Some(&mut host), proposal: std::cell::RefCell::new(None) }; + sink.project(action.clone()).unwrap(); + trace.borrow_mut().metric_revision += 1; + sink.host.as_mut().unwrap().capture_metrics(sink.live.runtime, sink.live.services.models).unwrap(); + assert_eq!(sink.dispatch(action).unwrap_err().rule, Rule::Revision); + assert!(sink.proposal.borrow().is_none()); + } + assert_eq!(h.runtime.layout().inspect(), before); + assert_eq!(trace.borrow().factories.len(), factories); +} + +#[test] +fn command_storage_refusal_uses_the_same_host_admission_before_any_runtime_publication() { + let (mut h, trace) = review_cohort_host(|_| {}); + h.dispatch(vec![fixture_open("fixture.log", "log", "log", Zone::Left, 0).unwrap()]).unwrap(); + h.tick().unwrap(); + let mut host = WorkspacePanelHost::new(HostOptions::default()).unwrap(); + host.capture_metrics(&h.runtime, &h.models).unwrap(); + host.capture_reservations(&h.runtime, &h.catalogue).unwrap(); + host.prepare(&h.runtime, capacity()).unwrap(); + let before = h.runtime.layout().inspect(); + let controllers = h.runtime.controller_count(); + let factories = trace.borrow().factories.len(); + let commits = h.native.commits; + h.catalogue.fail_stage = true; + let registry = h.runtime.layout().registry().clone(); + let mut services = ContentServices { models: &h.models, commands: &mut h.commands, local: &mut h.local }; + { + let mut live = RuntimeActionSink { runtime: &mut h.runtime, native: &mut h.native, services: &mut services }; + let mut sink = super::app::AdmittedActionSink { live: &mut live, host: Some(&mut host), proposal: std::cell::RefCell::new(None) }; + assert_eq!( + commands::execute_layout_action( + transaction(vec![Mutation::Collapse { section: section("log"), collapsed: true }]), + &mut commands::PanelCommandContext { sink: &mut sink, registry: ®istry, catalogue: &mut h.catalogue, web: false } + ) + .unwrap_err() + .rule, + Rule::Capability + ); + } + assert_eq!(h.runtime.layout().inspect(), before); + assert_eq!(h.runtime.controller_count(), controllers); + assert_eq!(trace.borrow().factories.len(), factories); + assert_eq!(h.native.commits, commits); +} + +#[test] +fn standalone_registered_action_needs_neither_host_environment_nor_layout_store() { + let (mut h, trace) = review_cohort_host(|_| {}); + h.dispatch(vec![fixture_open("fixture.log", "log", "log", Zone::Left, 0).unwrap()]).unwrap(); + let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + app.enable_panel_runtime(h.runtime, Box::new(FakeAppPanelServices { models: FakeModels { editable: true }, ..Default::default() })).unwrap(); + let mut catalogue = commands::InMemoryCatalogue::default(); + catalogue.fail_stage = true; + app.panel_runtime_mut().unwrap().set_command_adapters(Box::new(catalogue), Box::new(InAppNativeAdapter)).unwrap(); + app.run_panel_command("panel.action", &serde_json::json!({"target":{"type":"instance","id":"log"},"action":"pulse"})).unwrap(); + assert_eq!(trace.borrow().actions.len(), 1); + assert!(!app.universal_panel_host_enabled()); + assert_eq!( + app.dispatch_panel_layout(transaction(vec![Mutation::SetSize { section: section("log"), size: Size { width: 280.0, height: 300.0 } }])) + .unwrap_err() + .rule, + Rule::Availability + ); + assert_eq!( + app.dispatch_panel_layout(transaction(vec![ + Mutation::HeaderAction { instance: id("log"), action: ControlId::new("pulse").unwrap() }, + Mutation::Collapse { section: section("log"), collapsed: true } + ])) + .unwrap_err() + .rule, + Rule::Capability + ); + assert_eq!(trace.borrow().actions.len(), 1); +} + +#[test] +fn raw_inline_title_actions_editor_and_system_slots_mirror_and_keep_editor_identity() { + for scale in [1.0, 2.0] { + for direction in [Direction::Ltr, Direction::Rtl] { + let (mut h, trace) = review_cohort_host(|spec| { + spec.min_size.height = 40.0; + }); + h.dispatch(vec![ + fixture_open("fixture.editor", "inline-editor", "inline", Zone::Bottom, 0).unwrap(), + Mutation::SetSize { section: section("inline"), size: Size { width: 800.0, height: 64.0 } }, + ]) + .unwrap(); + let mut environment = h.runtime.environment().clone(); + environment.direction = direction; + h.runtime.set_environment(environment, &mut h.local).unwrap(); + let mut raw = RawPanelHost::new(h, scale); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + let card = raw.host.frame().unwrap().layout.sections[0].clone(); + assert!(card.inline && card.body.is_none() && card.footer.is_none()); + assert_eq!(card.outer.size.height, 64.0); + let shared_title = card.title.expect("inline composition retains the actual shared title/grip"); + let slots = [shared_title, card.actions[0].1, card.inline_content.unwrap(), card.menu, card.collapse, card.close.unwrap()]; + for pair in slots.windows(2) { + if direction == Direction::Ltr { + assert!(pair[0].origin.x + pair[0].size.width <= pair[1].origin.x); + } else { + assert!(pair[1].origin.x + pair[1].size.width <= pair[0].origin.x); + } + } + let title = raw_control(&raw, &HostControlTarget::Pointer(HostPointerTarget::Header { instance: id("inline-editor") })); + assert_eq!(title.bounds, shared_title, "actual shared title/grip keeps the dedicated slot"); + let start = egui_rect(title.bounds).center(); + raw.pointer(start, true, false); + raw.frame(vec![egui::Event::PointerMoved(start + egui::vec2(6.0, 0.0))], false); + assert!(raw.host.interaction().is_captured()); + raw.frame(vec![host_key(egui::Key::Escape, true), button_event(start, false)], false); + raw.frame(vec![host_key(egui::Key::Escape, false)], false); + let (editor_id, _, bounds, _) = trace.borrow().editors.last().unwrap().clone(); + let at = bounds.center(); + raw.pointer(at, true, false); + raw.frame(vec![egui::Event::PointerMoved(at + egui::vec2(12.0, 0.0))], false); + assert!(!raw.host.interaction().is_captured(), "editing never starts title drag"); + raw.pointer(at + egui::vec2(12.0, 0.0), false, false); + raw.ctx.memory_mut(|memory| memory.request_focus(editor_id)); + raw.frame(vec![egui::Event::Text(" changed".into())], false); + let caret = egui::TextEdit::load_state(&raw.ctx, editor_id).unwrap().cursor.char_range(); + let draft = trace.borrow().editors.last().unwrap().3.clone(); + assert!(draft.contains("changed")); + let count = raw.content.runtime.controller_count(); + raw.content + .dispatch(vec![Mutation::Move { + instance: id("inline-editor"), + destination: Destination::NewSection { + section: section("inline"), + index: 0, + location: SectionLocation::Dock { zone: Zone::Right }, + size: Size { width: 280.0, height: 300.0 }, + }, + }]) + .unwrap(); + raw.frame(Vec::new(), false); + assert!(!raw.host.frame().unwrap().layout.sections[0].inline); + assert_eq!(trace.borrow().editors.last().unwrap().0, editor_id); + assert_eq!(trace.borrow().editors.last().unwrap().3, draft); + assert_eq!(egui::TextEdit::load_state(&raw.ctx, editor_id).unwrap().cursor.char_range(), caret); + assert_eq!(raw.content.runtime.controller_count(), count); + + // The same retained editor also composes with header tabs. Give + // both labels room, retaining actual editable inline content. + let mut options = HostOptions::default(); + options.metrics.inline_title_width = 256.0; + raw.host = WorkspacePanelHost::new(options).unwrap(); + raw.content + .dispatch(vec![ + Mutation::Move { + instance: id("inline-editor"), + destination: Destination::NewSection { + section: section("inline"), + index: 0, + location: SectionLocation::Dock { zone: Zone::Bottom }, + size: Size { width: 800.0, height: 64.0 }, + }, + }, + Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("inline-peer"), + destination: Some(Destination::JoinTab { section: section("inline"), index: 1 }), + }, + Mutation::Activate { instance: id("inline-editor") }, + ]) + .unwrap(); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + let card = raw.host.frame().unwrap().layout.sections[0].clone(); + assert!(card.inline && card.inline_content.is_some()); + assert_eq!(card.header, card.outer); + assert_eq!(card.tabs.len(), 2); + assert_host_geometry(&raw.content, &raw.host.frame().unwrap().layout); + assert_eq!(trace.borrow().editors.last().unwrap().0, editor_id); + assert_eq!(trace.borrow().editors.last().unwrap().3, draft); + let grip = HostControlTarget::Pointer(HostPointerTarget::Header { instance: id("inline-editor") }); + let start = raw.at(grip); + raw.pointer(start, true, false); + raw.frame(vec![egui::Event::PointerMoved(start + egui::vec2(6.0, 0.0))], false); + assert!(raw.host.interaction().is_captured(), "the separate group grip drags the active tab"); + raw.frame(vec![host_key(egui::Key::Escape, true), button_event(start, false)], false); + raw.frame(vec![host_key(egui::Key::Escape, false)], false); + let start = raw.at(HostControlTarget::Pointer(HostPointerTarget::Tab { instance: id("inline-peer") })); + let first = raw.host.frame().unwrap().layout.sections[0].tabs[0].bounds; + let end = egui::pos2(first.origin.x + first.size.width * if direction == Direction::Ltr { 0.25 } else { 0.75 }, middle(first).y); + raw.pointer(start, true, false); + let preview = raw.frame(vec![egui::Event::PointerMoved(end)], false).0.preview.unwrap(); + assert!(preview.rejection.is_none()); + assert_eq!(preview.destination, Some(Destination::JoinTab { section: section("inline"), index: 0 })); + let shown = preview.projected.unwrap(); + let before = raw.content.runtime.layout().inspect(); + let commits = raw.content.native.commits; + raw.pointer(end, false, false); + raw.frame(Vec::new(), false); + assert_host_landing(&raw.host.frame().unwrap().layout, &shown); + assert_eq!(raw.content.runtime.layout().inspect().revision, before.revision + 1); + assert_eq!(raw.content.native.commits, commits + 1); + assert_eq!(raw.content.runtime.layout().layout().sections[0].tabs, vec![id("inline-peer"), id("inline-editor")]); + raw.click(HostControlTarget::Pointer(HostPointerTarget::Collapse { instance: id("inline-peer") }), false); + raw.frame(Vec::new(), false); + let card = &raw.host.frame().unwrap().layout.sections[0]; + assert!(card.collapsed && card.body.is_none()); + assert_eq!(card.header, card.outer); + assert_eq!(card.tabs.len(), 2); + raw.click(HostControlTarget::Pointer(HostPointerTarget::Tab { instance: id("inline-editor") }), false); + raw.frame(Vec::new(), false); + assert!(raw.host.frame().unwrap().layout.sections[0].collapsed); + assert_eq!(raw.content.runtime.layout().layout().sections[0].active, id("inline-editor")); + raw.click(HostControlTarget::Pointer(HostPointerTarget::Collapse { instance: id("inline-editor") }), false); + raw.frame(Vec::new(), false); + assert!(raw.host.frame().unwrap().layout.sections[0].inline); + assert_eq!(trace.borrow().editors.last().unwrap().0, editor_id); + assert_eq!(trace.borrow().editors.last().unwrap().3, draft); + assert_eq!(raw.content.runtime.controller_count(), count + 1); + } + } +} + +#[test] +fn zero_saved_stack_weight_is_transiently_content_or_fill_when_sole() { + for fill in [false, true] { + let mut service = allocation_service(|spec| { + spec.side_height_policy = if fill { SideHeightPolicy::Fill } else { SideHeightPolicy::Content }; + }); + apply_fixture( + &mut service, + vec![ + fixture_open("fixture.log", "one", "one", Zone::Left, 0).unwrap(), + fixture_open("fixture.log", "two", "two", Zone::Left, 1).unwrap(), + ], + ); + let host = allocate_fixture(&service, Size { width: 1000.0, height: 800.0 }, Direction::Ltr, &fixture_metric_policy(&service)); + let a = host.sections[0].outer.size; + let b = host.sections[1].outer.size; + let candidate = prepare_host_layout( + &service, + &fixture_scope(&service), + &host, + transaction(vec![Mutation::ResizePair { + first: section("one"), + second: section("two"), + first_size: Size { height: 120.0, ..a }, + second_size: Size { height: 676.0, ..b }, + }]), + ) + .unwrap(); + fixture_commit(&mut service, &host, candidate); + let saved = service.layout().section(§ion("one")).unwrap().weight; + assert_eq!(saved, 0.0); + apply_fixture(&mut service, vec![Mutation::Close { instance: id("two") }]); + let sole = allocate_fixture(&service, Size { width: 1000.0, height: 800.0 }, Direction::Ltr, &fixture_metric_policy(&service)); + assert_eq!(sole.sections[0].outer.size.height, if fill { 800.0 } else { 240.0 }); + assert_eq!(service.layout().section(§ion("one")).unwrap().weight, saved); + apply_fixture(&mut service, vec![Mutation::Open { kind: PanelKind::new("fixture.log").unwrap(), instance: id("two"), destination: None }]); + let stacked = allocate_fixture(&service, Size { width: 1000.0, height: 800.0 }, Direction::Ltr, &fixture_metric_policy(&service)); + assert_eq!(stacked.sections.iter().map(|card| card.outer.size.height).collect::>(), vec![120.0, 676.0]); + } +} + +#[test] +fn raw_full_envelope_reservations_skip_quarantine_and_native_return_ids_and_cancel_idle_capture() { + let mut h = host_logs(2, Zone::Left); + h.dispatch(vec![ + Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("moving"), + destination: Some(Destination::JoinTab { section: section("section-0"), index: 1 }), + }, + Mutation::Activate { instance: id("moving") }, + ]) + .unwrap(); + let reserved_section = next_host_section_id(h.runtime.layout().layout(), &HostIdentityReservations::default()).unwrap(); + let reserved_column = next_host_column_id(h.runtime.layout().layout(), &HostIdentityReservations::default()).unwrap(); + let mut envelope = LayoutEnvelope::new(h.runtime.layout().layout().clone()); + let pending = serde_json::json!({"id":"extension","kind":"extension.panel","requested_open":false,"memory":{ + "section":reserved_section,"section_index":2,"tab_index":0,"size":{"width":280,"height":240},"collapsed":false,"weight":1, + "preferred_extent":null,"column":null,"column_index":0,"column_width":null, + "location":{"type":"window","host":"return-host","origin":{"x":20,"y":30},"return_to":{ + "section":"review.return","zone":"left","index":2,"column":reserved_column,"column_index":1,"column_width":280, + "size":{"width":280,"height":240},"collapsed":false,"weight":1,"preferred_extent":null + }}}}); + envelope.quarantine.push(QuarantinedPanel { + instance: id("extension"), + kind: PanelKind::new("extension.panel").unwrap(), + instance_data: pending, + section: None, + }); + let ownership = ReplacementIdentityOwnership::from_layout(&envelope.layout).unwrap(); + let mut captured = host_identity_reservations(&envelope).unwrap(); + assert_eq!(captured.replacement_ownership.as_ref(), Some(&ownership)); + assert_eq!(captured.preparation_context().unwrap().replacement_ownership.as_ref(), Some(&ownership)); + assert!(!ownership.sections.contains_key(&reserved_section)); + assert!(!ownership.columns.contains_key(&reserved_column)); + let mut other = allocation_service(|_| {}); + apply_fixture(&mut other, vec![fixture_open("fixture.log", "other", "other", Zone::Right, 0).unwrap()]); + captured.include_layout(other.layout()).unwrap(); + assert!(captured.sections.contains(§ion("other"))); + assert_eq!(captured.replacement_ownership.as_ref(), Some(&ownership), "live reservations cannot grant incoming ownership"); + h.catalogue.remember(&envelope, None, h.runtime.layout().registry()).unwrap(); + let mut raw = RawPanelHost::new(h, 1.0); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + let reservations = &raw.host.frame().unwrap().layout.geometry_policy.identity_reservations; + assert!(reservations.sections.contains(&reserved_section) && reservations.columns.contains(&reserved_column)); + let start = raw.at(HostControlTarget::Pointer(HostPointerTarget::Header { instance: id("moving") })); + let landing = explicit_drop_point( + &raw.content, + &raw.host.frame().unwrap().layout, + &id("moving"), + &HostDropTargetId::Relative { section: section("section-1"), placement: RelativePlacement::AfterColumn }, + ); + let at = egui::pos2(landing.x, landing.y); + raw.pointer(start, true, false); + let shown = raw.frame(vec![egui::Event::PointerMoved(at)], false).0.preview.unwrap(); + let action = shown.action.clone().unwrap(); + if let LayoutAction::Apply { mutations, .. } = &action { + let destination = mutations + .iter() + .find_map(|mutation| match mutation { + Mutation::Move { destination, .. } => Some(destination), + _ => None, + }) + .unwrap(); + let Destination::Relative { new_section, new_column, .. } = destination else { + panic!("relative column landing required"); + }; + assert_ne!(new_section, &reserved_section); + assert_ne!(new_column.as_ref(), Some(&reserved_column)); + } + assert_eq!(raw.frame(vec![egui::Event::PointerMoved(at)], false).0.preview.unwrap().action, Some(action)); + raw.pointer(at, false, false); + raw.frame(Vec::new(), false); + let before = raw.content.runtime.layout().inspect(); + let start = raw.at(HostControlTarget::Pointer(HostPointerTarget::Header { instance: id("moving") })); + raw.pointer(start, true, false); + raw.frame(vec![egui::Event::PointerMoved(start + egui::vec2(6.0, 0.0))], false); + assert!(raw.host.interaction().is_captured()); + let mut changed = LayoutEnvelope::new(before.layout.clone()); + changed.quarantine = envelope.quarantine; + changed.quarantine[0].instance_data["memory"]["location"]["return_to"]["column"] = serde_json::json!("review.changed.return.column"); + raw.content.catalogue.remember(&changed, None, raw.content.runtime.layout().registry()).unwrap(); + raw.frame(Vec::new(), false); + assert!(!raw.host.interaction().is_captured()); + assert!(raw.host.frame().unwrap().preview.is_none()); + assert_eq!(raw.content.runtime.layout().inspect(), before); +} + +#[test] +fn atomic_batch_growing_projections_reuse_one_private_cohort_and_measure_each_new_controller_once() { + let (mut h, trace) = review_cohort_host(|_| {}); + let mut host = WorkspacePanelHost::new(HostOptions::default()).unwrap(); + host.capture_metrics(&h.runtime, &h.models).unwrap(); + host.capture_reservations(&h.runtime, &h.catalogue).unwrap(); + host.prepare(&h.runtime, capacity()).unwrap(); + let registry = h.runtime.layout().registry().clone(); + let mut services = ContentServices { models: &h.models, commands: &mut h.commands, local: &mut h.local }; + { + let mut live = RuntimeActionSink { runtime: &mut h.runtime, native: &mut h.native, services: &mut services }; + let mut sink = super::app::AdmittedActionSink { live: &mut live, host: Some(&mut host), proposal: std::cell::RefCell::new(None) }; + let result = commands::execute_batch( + &[ + serde_json::json!({"command":"panel.open","params":{"kind":"fixture.log","instance":"one","destination":{ + "type":"new_section","section":"one","index":0,"location":{"type":"dock","zone":"left"},"size":{"width":280,"height":240}}}}), + serde_json::json!({"command":"panel.open","params":{"kind":"fixture.log","instance":"two","destination":{ + "type":"new_section","section":"two","index":1,"location":{"type":"dock","zone":"left"},"size":{"width":280,"height":240}}}}), + serde_json::json!({"command":"layout.get"}), + ], + &mut commands::PanelCommandContext { sink: &mut sink, registry: ®istry, catalogue: &mut h.catalogue, web: false }, + ) + .unwrap(); + assert_eq!(result["completed"], 3); + } + assert_eq!(trace.borrow().factories.len(), 2); + assert_eq!(trace.borrow().measures, vec![1, 2]); + assert_eq!(h.runtime.controller_count(), 2); + assert_eq!(h.runtime.layout().layout().sections.len(), 2); + assert_eq!(h.native.commits, 1, "only the final owned candidate commits"); +} + +// Immutable-provider drift is injected inside the real catalogue boundary. This +// fixture intentionally uses PanelController's default live revision fallback. +#[derive(Default)] +struct ImmutableSourceTrace { + factories: Vec<(ControllerKey, usize)>, + measured: Vec<(ControllerKey, usize)>, +} +type ImmutableTrace = std::rc::Rc>; +struct SharedHeightModels(std::rc::Rc>); +impl PanelModels for SharedHeightModels { + fn read(&self, _owner: &ContentOwner, key: &str) -> PanelResult { + match key { + "review.height" => Ok(serde_json::json!(self.0.get())), + "fixture.editable" => Ok(serde_json::json!(true)), + _ => Err(error(Rule::MissingTarget, "unknown measurement fixture model")), + } + } +} +struct ImmutableSourceController { + inner: Box, + key: ControllerKey, + identity: usize, + trace: ImmutableTrace, +} +impl PanelController for ImmutableSourceController { + 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) + } + fn presentation(&self) -> PanelPresentation { + self.inner.presentation() + } + fn measure(&self, owner: &ContentOwner, models: &dyn PanelModels, spec: &PanelSpec) -> PanelResult> { + let height = models.read(owner, "review.height")?.as_u64().ok_or_else(|| error(Rule::Bounds, "height fixture requires an integer"))?; + self.trace.borrow_mut().measured.push((self.key.clone(), self.identity)); + Ok(std::sync::Arc::new(ReviewMetrics { revision: height, height: height as f32, 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) + } + fn action(&mut self, owner: &ContentOwner, action: &ControlId, services: &mut ContentServices<'_>) -> PanelResult<()> { + self.inner.action(owner, action, services) + } +} +struct SharedHeightServices { + models: SharedHeightModels, + commands: FakeContentCommands, + local: FakeLocalServices, +} +impl AppPanelServices for SharedHeightServices { + fn refresh_read_only(&mut self, _session: &solidcraft_engine::Session) -> PanelResult<()> { + Ok(()) + } + fn services(&mut self) -> ContentServices<'_> { + ContentServices { models: &self.models, commands: &mut self.commands, local: &mut self.local } + } +} +struct SourceDriftCatalogue { + inner: commands::InMemoryCatalogue, + source: std::rc::Rc>, + change_to: Option, + prepared: std::rc::Rc>, + published: std::rc::Rc>, + observed: std::rc::Rc>, +} +impl commands::LayoutCatalogue for SourceDriftCatalogue { + fn state(&self) -> &commands::CatalogueState { + commands::LayoutCatalogue::state(&self.inner) + } + fn prepare(&mut self, next: commands::CatalogueState) -> PanelResult { + self.prepared.set(self.prepared.get() + 1); + let prepared = commands::LayoutCatalogue::prepare(&mut self.inner, next)?; + if let Some(height) = self.change_to { + self.source.set(height); + } + *self.observed.borrow_mut() = commands::LayoutCatalogue::state(&self.inner).clone(); + Ok(prepared) + } + fn publish(&mut self, prepared: commands::PreparedCatalogue) { + self.published.set(self.published.get() + 1); + commands::LayoutCatalogue::publish(&mut self.inner, prepared); + *self.observed.borrow_mut() = commands::LayoutCatalogue::state(&self.inner).clone(); + } +} + +#[test] +fn immutable_metric_drift_inside_catalogue_prepare_rejects_retained_and_staged_owner_without_publication() { + use commands::LayoutCatalogue; + for incoming_owner in [false, true] { + for drift in [false, true] { + let h = PanelMountHarness::without_content(false).unwrap(); + let mut service = fixture_service(false).unwrap(); + apply_fixture(&mut service, vec![fixture_open("fixture.log", "log", "log", Zone::Left, 0).unwrap()]); + let mut catalogue = fixture_command_catalogue(service.registry()).unwrap(); + let mut incoming = service.layout().clone(); + incoming.workspace = WorkspaceId::new("fixture.other").unwrap(); + catalogue.remember(&LayoutEnvelope::new(incoming), None, service.registry()).unwrap(); + let catalogue_before = catalogue.state().clone(); + let observed = std::rc::Rc::new(std::cell::RefCell::new(catalogue_before.clone())); + let prepared = std::rc::Rc::new(std::cell::Cell::new(0)); + let published = std::rc::Rc::new(std::cell::Cell::new(0)); + let source = std::rc::Rc::new(std::cell::Cell::new(240)); + let trace = ImmutableTrace::default(); + let mut runtime = PanelRuntime::new(service, h.runtime.environment().clone()).unwrap(); + let binding = fixture_controller_binding(&h.probe, false, Ownership::Workspace); + let create = binding.create; + let factory_trace = trace.clone(); + runtime + .register( + PanelKind::new("fixture.log").unwrap(), + ControllerBinding { + ownership: Ownership::Workspace, + create: Box::new(move |instance, owner| { + let key = ControllerKey { instance: instance.id.clone(), owner: owner.clone() }; + let identity = factory_trace.borrow().factories.len() + 1; + let inner = create(instance, owner)?; + factory_trace.borrow_mut().factories.push((key.clone(), identity)); + Ok(Box::new(ImmutableSourceController { inner, key, identity, trace: factory_trace.clone() })) + }), + }, + ) + .unwrap(); + let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), Default::default()); + app.enable_panel_runtime( + runtime, + Box::new(SharedHeightServices { + models: SharedHeightModels(source.clone()), + commands: Default::default(), + local: Default::default(), + }), + ) + .unwrap(); + let native = std::rc::Rc::new(std::cell::RefCell::new(FakeNativeAdapter::new(false))); + app.panel_runtime_mut() + .unwrap() + .set_command_adapters( + Box::new(SourceDriftCatalogue { + inner: catalogue, + source: source.clone(), + change_to: drift.then_some(360), + prepared: prepared.clone(), + published: published.clone(), + observed: observed.clone(), + }), + Box::new(SharedCommandNative(native.clone())), + ) + .unwrap(); + prepare_app_commands(&mut app); + let before = app.panel_runtime().unwrap().layout().inspect(); + let count = app.panel_runtime().unwrap().controller_count(); + let factories = trace.borrow().factories.len(); + let doc = app.session.doc.clone(); + let model = app.session.model.state(); + let revision = app.session.revision; + let undo = app.session.undo.len(); + let dirty = app.session.is_dirty(); + let result = if incoming_owner { + app.run_panel_command("layout.workspace.select", &serde_json::json!({"workspace":"fixture.other"})) + } else { + app.run_panel_command( + "panel.move", + &serde_json::json!({"target":{"type":"instance","id":"log"},"destination":{ + "type":"new_section","section":"log","index":0,"location":{"type":"dock","zone":"right"},"size":{"width":280,"height":240}}}), + ) + }; + assert_eq!(prepared.get(), 1, "the injected real catalogue boundary was exercised"); + if drift { + assert_eq!(result.unwrap_err().rule, Rule::Revision); + assert_eq!(app.panel_runtime().unwrap().layout().inspect(), before); + assert_eq!(app.panel_runtime().unwrap().controller_count(), count); + assert_eq!(*observed.borrow(), catalogue_before); + assert_eq!(published.get(), 0); + assert_eq!(native.borrow().commits, 0); + assert!(native.borrow().hosts.is_empty()); + } else { + result.unwrap(); + assert_eq!(published.get(), 1); + assert_eq!(native.borrow().commits, 1); + } + assert_eq!(trace.borrow().factories.len(), factories + usize::from(incoming_owner)); + let target = ControllerKey { + instance: id("log"), + owner: ContentOwner::Workspace(WorkspaceId::new(if incoming_owner { "fixture.other" } else { "fixture.workspace" }).unwrap()), + }; + let identity = trace.borrow().factories.iter().find(|(key, _)| *key == target).unwrap().1; + let measures = trace.borrow().measured.iter().filter(|(key, _)| *key == target).cloned().collect::>(); + assert!(measures.len() >= 2, "live source validation rereads the same controller after projection"); + assert!(measures.iter().all(|(_, measured)| *measured == identity)); + if drift && incoming_owner { + assert!(h.probe.state(&target).is_err(), "staged owner was never published"); + } + assert!(std::sync::Arc::ptr_eq(&app.session.doc, &doc)); + assert!(std::sync::Arc::ptr_eq(&app.session.model.state(), &model)); + assert_eq!(app.session.revision, revision); + assert_eq!(app.session.undo.len(), undo); + assert_eq!(app.session.is_dirty(), dirty); + } + } +} + +#[test] +fn home_visibility_transition_discards_shown_candidate_and_unmounts_without_stopping_retained_services() { + for paint_home in [false, true] { + let (mut h, probe, trace) = boundary_app(); + let key = app_editor_key(&h.app); + probe.edit(&key, |state| state.draft = "Home retains this live draft".into()).unwrap(); + let scope = runtime_scope(h.app.panel_runtime().unwrap()); + h.app + .panel_runtime_mut() + .unwrap() + .with_services(|_, services| { + services.local.request(&scope, LocalRequest::KeyboardOwner { instance: id("editor"), control: ControlId::new("draft").unwrap() }) + }) + .unwrap(); + let header = app_control(&h.app, HostControlTarget::Pointer(HostPointerTarget::Header { instance: id("editor") })); + let start = egui_rect(header.bounds).center(); + let frame = h.app.universal_panel_frame().unwrap(); + let landing = host_drop_targets(h.app.panel_runtime().unwrap().layout(), &frame.layout, &id("editor")) + .unwrap() + .into_iter() + .find(|target| matches!(&target.id, HostDropTargetId::Dock { zone: Zone::Right, .. }) && target.rejection.is_none()) + .unwrap(); + let end = egui_rect(landing.bounds).center(); + h.frame_with(vec![egui::Event::PointerMoved(start), button_event(start, true)]); + h.frame_with(vec![egui::Event::PointerMoved(end)]); + let preview = h.app.universal_panel_frame().unwrap().preview.as_ref().unwrap(); + assert!(preview.action.is_some() && preview.projected.is_some() && preview.rejection.is_none()); + let before = h.app.panel_runtime().unwrap().layout().inspect(); + let count = h.app.panel_runtime().unwrap().controller_count(); + let state = probe.state(&key).unwrap(); + if paint_home { + h.app.home.show(h.app.session.revision); + h.frames(2); // lib.rs must observe Home even without ui.home. + } else { + set_home_without_paint(&mut h, true); // no intervening paint required + } + assert!(!h.app.panel_runtime_mut().unwrap().host().unwrap().interaction().is_captured()); + assert!(h.app.universal_panel_frame().is_none()); + assert!(!h.app.panel_runtime().unwrap().state(&key).unwrap().presented); + assert!(!h.app.panel_runtime().unwrap().state(&key).unwrap().activated); + assert!(trace.borrow().keyboard.is_empty(), "hidden owners release local keyboard input"); + let hidden = probe.state(&key).unwrap(); + h.frames(2); + assert!(probe.state(&key).unwrap().updates > hidden.updates); + assert_eq!(probe.state(&key).unwrap().renders, state.renders, "hidden bodies do not render while services tick"); + set_home_without_paint(&mut h, false); + h.frames(2); + h.frame_with(vec![egui::Event::PointerMoved(end), button_event(end, false)]); + assert_eq!(h.app.panel_runtime().unwrap().layout().inspect(), before, "release cannot resurrect the old landing"); + assert_eq!(h.app.panel_runtime().unwrap().controller_count(), count); + assert!(!h.app.panel_runtime_mut().unwrap().host().unwrap().interaction().is_captured()); + let retained = probe.state(&key).unwrap(); + assert_eq!(retained.draft, state.draft); + assert_eq!(retained.cancels, state.cancels); + assert_eq!(retained.destroys, state.destroys); + assert!(retained.transaction_live); + } +} + +#[test] +fn home_open_close_between_paint_and_finish_discards_real_deferred_widget_intent() { + let (mut h, probe, _) = boundary_app(); + let key = app_editor_key(&h.app); + let collapse = app_control(&h.app, HostControlTarget::Pointer(HostPointerTarget::Collapse { instance: id("editor") })); + let at = egui_rect(collapse.bounds).center(); + h.frame_with(vec![egui::Event::PointerMoved(at), button_event(at, true)]); + let before = h.app.panel_runtime().unwrap().layout().inspect(); + let draft = probe.state(&key).unwrap(); + let layout = h.app.universal_panel_frame().unwrap().layout.clone(); + let time = h.ctx.input(|input| input.time) + 1.0 / 60.0; + let mut output = h.ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0))), + time: Some(time), + focused: true, + events: vec![button_event(at, false)], + ..Default::default() + }, + |ui| { + h.app.logic(ui.ctx()); + let integration = h.app.panel_runtime.as_mut().unwrap(); + integration.prepare_host_in_domain(&h.app.session, layout.render_domain, layout.capacity, &layout.chrome_obstacles).unwrap(); + integration.show_host_deferred(&h.app.session, ui).unwrap(); + assert!(ui.ctx().read_response(collapse.id).unwrap().clicked(), "actual egui collapse click is pending"); + assert!(integration.host().unwrap().has_pending()); + for open in [true, false] { + let (request, _) = crate::control::ControlRequest::new("ui.home", serde_json::json!({"open":open})); + let _reply = crate::control::handle(&mut h.app, ui.ctx(), &request); + } + let integration = h.app.panel_runtime.as_mut().unwrap(); + assert!(!integration.host().unwrap().has_pending()); + integration.finish_host(&h.app.session, ui).unwrap(); + }, + ); + output.textures_delta.clear(); + assert_eq!(h.app.panel_runtime().unwrap().layout().inspect(), before); + assert!(h.app.universal_panel_frame().is_none()); + h.frames(2); + assert_eq!(h.app.panel_runtime().unwrap().layout().inspect(), before); + assert_eq!(probe.state(&key).unwrap().draft, draft.draft); + assert_eq!(probe.state(&key).unwrap().cancels, draft.cancels); +} + +#[test] +fn wrapping_editor_keeps_keyboard_caret_and_identity_through_metric_and_reservation_invalidation() { + for scale in [1.0, 2.0] { + let (mut h, trace) = review_cohort_host(|_| {}); + h.dispatch(vec![fixture_open("fixture.editor", "wrapping-editor", "wrapping", Zone::Left, 0).unwrap()]).unwrap(); + let mut raw = RawPanelHost::new(h, scale); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + let editor = trace.borrow().editors.last().unwrap().clone(); + let at = editor.2.center(); + raw.pointer(at, true, false); + raw.pointer(at, false, false); + raw.ctx.memory_mut(|memory| memory.request_focus(editor.0)); + raw.frame(Vec::new(), false); + let initial_rows = *trace.borrow().wrap_rows.last().unwrap(); + let before = raw.content.runtime.layout().inspect(); + let metric_revision = raw.host.frame().unwrap().layout.geometry_policy.content_revision; + let (stale, _) = raw.frame_late(vec![egui::Event::Text(" more wrapped words".repeat(12))], false, |_, _| {}); + assert!(stale.is_none(), "new text invalidates the old metric geometry"); + assert_eq!(raw.ctx.memory(|memory| memory.focused()), Some(editor.0)); + assert!(*trace.borrow().wrap_rows.last().unwrap() > initial_rows, "the actual multiline editor now wraps"); + let caret = egui::TextEdit::load_state(&raw.ctx, editor.0).unwrap().cursor.char_range(); + let draft = trace.borrow().editors.last().unwrap().3.clone(); + raw.frame(Vec::new(), false); + assert_ne!(raw.host.frame().unwrap().layout.geometry_policy.content_revision, metric_revision); + assert_eq!(raw.ctx.memory(|memory| memory.focused()), Some(editor.0)); + assert_eq!(egui::TextEdit::load_state(&raw.ctx, editor.0).unwrap().cursor.char_range(), caret); + assert_eq!(trace.borrow().editors.last().unwrap().0, editor.0); + assert_eq!(trace.borrow().editors.last().unwrap().3, draft); + let mut envelope = LayoutEnvelope::new(raw.content.runtime.layout().layout().clone()); + let mut pending = envelope.layout.instances[0].clone(); + pending.id = id("focus-extension"); + pending.kind = PanelKind::new("extension.focus").unwrap(); + pending.requested_open = false; + pending.memory.section = section("focus-reserved-section"); + envelope.quarantine.push(QuarantinedPanel { + instance: pending.id.clone(), + kind: pending.kind.clone(), + instance_data: serde_json::to_value(pending).unwrap(), + section: None, + }); + raw.content.catalogue.remember(&envelope, None, raw.content.runtime.layout().registry()).unwrap(); + raw.frame(Vec::new(), false); + assert_eq!(raw.ctx.memory(|memory| memory.focused()), Some(editor.0), "reservation-only invalidation preserves eligible focus"); + assert_eq!(egui::TextEdit::load_state(&raw.ctx, editor.0).unwrap().cursor.char_range(), caret); + let (stale, _) = raw.frame_late(vec![egui::Event::Text(" continued typing".into())], false, |_, _| {}); + assert!(stale.is_none()); + assert_eq!(raw.ctx.memory(|memory| memory.focused()), Some(editor.0)); + assert!(trace.borrow().editors.last().unwrap().3.contains("continued typing")); + assert_eq!(raw.content.runtime.layout().inspect(), before); + let saved_caret = egui::TextEdit::load_state(&raw.ctx, editor.0).unwrap().cursor.char_range(); + let mut environment = raw.content.runtime.environment().clone(); + environment.document = Some(DocumentId::new("focus-next-document").unwrap()); + raw.content.runtime.set_environment(environment, &mut raw.content.local).unwrap(); + raw.frame(Vec::new(), false); + assert_ne!(raw.ctx.memory(|memory| memory.focused()), Some(editor.0), "owner change still releases keyboard input"); + assert_eq!(egui::TextEdit::load_state(&raw.ctx, editor.0).unwrap().cursor.char_range(), saved_caret); + assert_eq!(raw.content.runtime.controller_count(), 2, "old owner draft/controller remain retained"); + } +} + +fn set_home_without_paint(h: &mut crate::scenario::Harness, open: bool) { + let (request, _) = crate::control::ControlRequest::new("ui.home", serde_json::json!({"open":open})); + match crate::control::handle(&mut h.app, &h.ctx, &request) { + crate::control::Outcome::Done(value) => assert_eq!(value["ok"], true), + _ => panic!("Home must complete synchronously without a screenshot"), + } +} +fn review_wheel(at: egui::Pos2, delta: f32) -> Vec { + vec![ + egui::Event::PointerMoved(at), + egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, delta), + modifiers: egui::Modifiers::NONE, + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + }, + ] +} + +#[test] +fn raw_clipped_header_body_surface_keeps_wheel_fallback_and_real_child_consumption_wins() { + for scale in [1.0, 2.0] { + let (mut h, trace) = review_cohort_host(|spec| { + spec.min_size.height = 200.0; + spec.default_size.height = 240.0; + }); + h.dispatch( + (0..3) + .map(|index| fixture_open("fixture.log", &format!("wheel-{index}"), &format!("wheel-{index}"), Zone::Left, index).unwrap()) + .collect(), + ) + .unwrap(); + let mut raw = RawPanelHost::new(h, scale); + raw.capacity.size = Size { width: 600.0, height: 260.0 }; + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + let first = raw.host.frame().unwrap().layout.sections[0].clone(); + let initial_body = egui_rect(first.body.expect("expanded first card has a real body")).intersect(egui_rect(raw.capacity)); + let shift = first.header.origin.y + first.header.size.height - raw.capacity.origin.y + 2.0; + raw.frame(review_wheel(initial_body.center(), -shift), false); + for _ in 0..8 { + raw.frame(Vec::new(), false); + } + let frame = raw.host.frame().unwrap(); + let first = frame.layout.sections.iter().find(|card| card.instance == id("wheel-0")).unwrap(); + assert!(first.header.origin.y + first.header.size.height <= raw.capacity.origin.y); + assert!( + !frame.controls.iter().any(|control| control.target == HostControlTarget::Pointer(HostPointerTarget::Header { instance: id("wheel-0") })), + "the header response really is clipped away" + ); + let body = egui_rect(first.body.unwrap()).intersect(egui_rect(raw.capacity)); + assert!(body.is_positive()); + let surface = raw_control(&raw, &HostControlTarget::Pointer(HostPointerTarget::Surface { instance: id("wheel-0") })); + assert!(raw.ctx.read_response(surface.id).unwrap().interact_rect.contains(body.center()), "visible body has an actual current card response"); + let before = frame.layout.geometry_policy.scroll.y; + raw.frame(review_wheel(body.center(), -12.0), false); + raw.frame(Vec::new(), false); + assert!(raw.host.frame().unwrap().layout.geometry_policy.scroll.y > before, "body wheel must work with no Header control"); + for _ in 0..8 { + raw.frame(Vec::new(), false); + } + let frame = raw.host.frame().unwrap(); + let first = frame.layout.sections.iter().find(|card| card.instance == id("wheel-0")).unwrap(); + let body = egui_rect(first.body.expect("first body remains mounted after host scrolling")).intersect(egui_rect(raw.capacity)); + assert!(body.is_positive(), "host scrolling must leave a visible body for the child wheel fixture"); + let surface = raw_control(&raw, &HostControlTarget::Pointer(HostPointerTarget::Surface { instance: id("wheel-0") })); + assert!(raw.ctx.read_response(surface.id).unwrap().interact_rect.contains(body.center()), "the clipped body still has an actual response"); + trace.borrow_mut().consume_wheel = true; + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + let child = trace.borrow().child_scroll[&id("wheel-0")]; + assert!(child.0.is_positive()); + let host_offset = raw.host.frame().unwrap().layout.geometry_policy.scroll.y; + raw.frame(review_wheel(child.0.center(), -12.0), false); + raw.frame(Vec::new(), false); + assert!(trace.borrow().child_scroll[&id("wheel-0")].1 > child.1, "the real inner ScrollArea consumed the wheel"); + assert!( + (raw.host.frame().unwrap().layout.geometry_policy.scroll.y - host_offset).abs() < 0.001, + "consumed child input cannot also scroll the host" + ); + } +} + +#[test] +fn uncovered_content_gap_routes_actual_wheel_to_the_existing_camera_path_at_both_scales() { + for scale in [1.0, 2.0] { + let (mut h, _, _) = boundary_app(); + h.ctx.set_pixels_per_point(scale); + h.frames(2); + let frame = h.app.universal_panel_frame().unwrap(); + let card = &frame.layout.sections[0]; + let at = egui::pos2(card.outer.origin.x + card.outer.size.width / 2.0, card.outer.origin.y + card.outer.size.height + 32.0); + let point = Point { x: at.x, y: at.y }; + assert!(frame.layout.capacity.contains(point)); + assert!(!frame.layout.input.iter().any(|bounds| bounds.contains(point))); + assert!(frame.layout.usable.contains_rect(LogicalRect { origin: point, size: Size { width: 2.0, height: 2.0 } })); + let before = h.app.panel_runtime().unwrap().layout().inspect(); + let camera = h.app.cam; + h.frame_with(review_wheel(at, -72.0)); + h.frames(3); + assert_ne!(h.app.cam, camera, "the existing navigation handler receives the uncovered gap wheel"); + assert_eq!(h.app.panel_runtime().unwrap().layout().inspect(), before); + } +} + +fn priority_host_options() -> HostOptions { + HostOptions { + metrics: HostMetrics { + header_height: 24.0, + footer_height: 8.0, + control_extent: 24.0, + sash_width: 4.0, + inline_max_height: 88.0, + ..HostMetrics::default() + }, + content_header_height: 0.0, + ..Default::default() + } +} +fn priority_raw_stack(scale: f32, direction: Direction, zone: Zone, capacity_extent: f32) -> (RawPanelHost, ReviewTrace) { + let (mut h, trace) = review_cohort_host(|spec| { + spec.min_size = Size { width: 120.0, height: 120.0 }; + spec.default_size = Size { width: 280.0, height: 200.0 }; + spec.max_size = Size { width: MAX_LOGICAL, height: MAX_LOGICAL }; + }); + h.dispatch( + (0..3).map(|index| fixture_open("fixture.log", &format!("priority-{index}"), &format!("priority-{index}"), zone, index).unwrap()).collect(), + ) + .unwrap(); + // Imported/common-tier preferences deliberately do not simulate three + // sequential SetSize commands, which would author three different ranks. + let mut layout = h.runtime.layout().layout().clone(); + for section in &mut layout.sections { + section.size = if zone == Zone::Bottom { Size { width: 200.0, height: 200.0 } } else { Size { width: 280.0, height: 200.0 } }; + section.preferred_extent = Some(200.0); + section.extent_priority = 0; + section.weight = 1.0; + } + for instance in &mut layout.instances { + instance.memory.size = if zone == Zone::Bottom { Size { width: 200.0, height: 200.0 } } else { Size { width: 280.0, height: 200.0 } }; + instance.memory.preferred_extent = Some(200.0); + instance.memory.extent_priority = 0; + instance.memory.weight = 1.0; + } + h.apply_layout(layout, None).unwrap(); + let mut environment = h.runtime.environment().clone(); + environment.direction = direction; + h.runtime.set_environment(environment, &mut h.local).unwrap(); + let mut raw = RawPanelHost::new(h, scale); + raw.host = WorkspacePanelHost::new(priority_host_options()).unwrap(); + raw.capacity.size = + if zone == Zone::Bottom { Size { width: capacity_extent, height: 800.0 } } else { Size { width: 1000.0, height: capacity_extent } }; + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + (raw, trace) +} +fn priority_axis(size: Size, zone: Zone) -> f32 { + if zone == Zone::Bottom { size.width } else { size.height } +} +fn assert_priority_number(actual: f32, expected: f32) { + assert!((actual - expected).abs() <= 0.002, "actual {actual}, expected {expected}"); +} +fn assert_priority_geometry(raw: &RawPanelHost, zone: Zone, direction: Direction, extents: [f32; 3]) { + let host = &raw.host.frame().unwrap().layout; + let mut offset = 0.0; + for (index, expected) in extents.into_iter().enumerate() { + let card = host.sections.iter().find(|card| card.section == section(&format!("priority-{index}"))).unwrap(); + let logical_origin = if zone != Zone::Bottom { + card.outer.origin.y - host.capacity.origin.y + } else if direction == Direction::Ltr { + card.outer.origin.x - host.capacity.origin.x + } else { + host.capacity.origin.x + host.capacity.size.width - card.outer.origin.x - card.outer.size.width + }; + assert_priority_number(priority_axis(card.outer.size, zone), expected); + assert_priority_number(logical_origin, offset); + offset += expected + 4.0; + } + assert_eq!(host.viewport, Some(host.render_domain)); + assert_eq!(host.extent, host.capacity.size); +} +fn raw_priority_pair_edit(raw: &mut RawPanelHost, first: usize, second: usize, zone: Zone, direction: Direction, wanted: f32) -> HostLayout { + let first_id = section(&format!("priority-{first}")); + let second_id = section(&format!("priority-{second}")); + let before = raw.content.runtime.layout().inspect(); + let commits = raw.content.native.commits; + let card = raw.host.frame().unwrap().layout.sections.iter().find(|card| card.section == first_id).unwrap(); + let delta = wanted - priority_axis(card.outer.size, zone); + let at = raw.at(HostControlTarget::Pointer(HostPointerTarget::Sash { first: first_id, second: second_id })); + raw.pointer(at, true, false); + let end = if zone == Zone::Bottom { + at + egui::vec2(if direction == Direction::Rtl { -delta } else { delta }, 0.0) + } else { + at + egui::vec2(0.0, delta) + }; + let preview = raw.frame(vec![egui::Event::PointerMoved(end)], false).0.preview.expect("actual sash movement has a candidate"); + assert!(preview.rejection.is_none(), "{preview:?}"); + let shown = preview.projected.unwrap(); + assert_eq!(raw.content.runtime.layout().inspect(), before); + let release = raw.pointer(end, false, false); + assert_eq!(release.events.iter().filter(|event| matches!(event, HostEvent::PreparedCommitted { .. })).count(), 1); + assert!(!release.events.iter().any(|event| matches!(event, HostEvent::Rejected { .. }))); + assert_eq!(raw.content.runtime.layout().inspect().revision, before.revision + 1); + assert_eq!(raw.content.native.commits, commits + 1); + raw.frame(Vec::new(), false); + shown +} + +#[test] +fn raw_underfilled_explicit_pair_edits_keep_real_gap_and_newest_overlapping_tier_on_compression() { + for scale in [1.0, 2.0] { + for direction in [Direction::Ltr, Direction::Rtl] { + for zone in [Zone::Left, Zone::Bottom] { + let (mut raw, trace) = priority_raw_stack(scale, direction, zone, 1000.0); + let factories = trace.borrow().factories.clone(); + assert_priority_geometry(&raw, zone, direction, [200.0, 200.0, 200.0]); + assert!(raw.content.runtime.layout().layout().sections.iter().all(|section| section.extent_priority == 0)); + let third = raw.host.frame().unwrap().layout.sections.iter().find(|card| card.section == section("priority-2")).unwrap().outer; + let shown = raw_priority_pair_edit(&mut raw, 0, 1, zone, direction, 180.0); + assert_priority_number(priority_axis(shown.sections[0].outer.size, zone), 180.0); + assert_priority_geometry(&raw, zone, direction, [180.0, 220.0, 200.0]); + assert_eq!(raw.host.frame().unwrap().layout.sections.iter().find(|card| card.section == section("priority-2")).unwrap().outer, third); + let first = raw.content.runtime.layout().layout().section(§ion("priority-0")).unwrap().clone(); + let second = raw.content.runtime.layout().layout().section(§ion("priority-1")).unwrap(); + assert_eq!((first.preferred_extent, second.preferred_extent), (Some(180.0), Some(220.0))); + assert!(first.extent_priority > 0); + assert_eq!(first.extent_priority, second.extent_priority); + assert_eq!(raw.content.runtime.layout().layout().section(§ion("priority-2")).unwrap().preferred_extent, Some(200.0)); + assert_eq!(raw.content.runtime.layout().layout().section(§ion("priority-2")).unwrap().extent_priority, 0); + raw_priority_pair_edit(&mut raw, 1, 2, zone, direction, 190.0); + assert_priority_geometry(&raw, zone, direction, [180.0, 190.0, 230.0]); + let model = raw.content.runtime.layout().layout(); + let a = model.section(§ion("priority-0")).unwrap(); + let b = model.section(§ion("priority-1")).unwrap(); + let c = model.section(§ion("priority-2")).unwrap(); + assert_eq!((a.preferred_extent, a.extent_priority), (first.preferred_extent, first.extent_priority)); + assert_eq!((b.preferred_extent, c.preferred_extent), (Some(190.0), Some(230.0))); + assert!(b.extent_priority > a.extent_priority); + assert_eq!(b.extent_priority, c.extent_priority); + let saved = model.clone(); + let last = raw.host.frame().unwrap().layout.sections.iter().find(|card| card.section == section("priority-2")).unwrap().outer; + let gap = if zone != Zone::Bottom { + Point { x: last.origin.x + 16.0, y: last.origin.y + last.size.height + 16.0 } + } else if direction == Direction::Ltr { + Point { x: last.origin.x + last.size.width + 16.0, y: last.origin.y + 16.0 } + } else { + Point { x: last.origin.x - 16.0, y: last.origin.y + 16.0 } + }; + let used = if zone != Zone::Bottom { + last.origin.y + last.size.height - raw.capacity.origin.y + } else if direction == Direction::Ltr { + last.origin.x + last.size.width - raw.capacity.origin.x + } else { + raw.capacity.origin.x + raw.capacity.size.width - last.origin.x + }; + assert_priority_number(priority_axis(raw.capacity.size, zone) - used, 392.0); + assert!(raw.host.frame().unwrap().layout.usable.contains_rect(LogicalRect { origin: gap, size: Size { width: 4.0, height: 4.0 } })); + assert!(!raw.host.frame().unwrap().layout.input.iter().any(|bounds| bounds.contains(gap))); + if zone == Zone::Bottom { + raw.capacity.size.width = 400.0; + } else { + raw.capacity.size.height = 400.0; + } + raw.frame(Vec::new(), false); + assert_priority_geometry(&raw, zone, direction, [120.0, 120.0 + 112.0 / 9.0, 120.0 + 176.0 / 9.0]); + assert_eq!(raw.content.runtime.layout().layout(), &saved, "compression never rewrites authored intent"); + if zone == Zone::Bottom { + raw.capacity.size.width = 1000.0; + } else { + raw.capacity.size.height = 1000.0; + } + raw.frame(Vec::new(), false); + assert_priority_geometry(&raw, zone, direction, [180.0, 190.0, 230.0]); + assert_eq!(raw.content.runtime.layout().layout(), &saved); + assert_eq!(trace.borrow().factories, factories); + } + } + } +} + +#[test] +fn raw_compressed_common_tier_pair_reaches_minimum_and_overlapping_edit_preserves_third() { + for scale in [1.0, 2.0] { + for direction in [Direction::Ltr, Direction::Rtl] { + for zone in [Zone::Left, Zone::Bottom] { + let (mut raw, trace) = priority_raw_stack(scale, direction, zone, 400.0); + let factories = trace.borrow().factories.clone(); + assert_priority_geometry(&raw, zone, direction, [392.0 / 3.0; 3]); + let third = raw.host.frame().unwrap().layout.sections.iter().find(|card| card.section == section("priority-2")).unwrap().outer; + raw_priority_pair_edit(&mut raw, 0, 1, zone, direction, 120.0); + assert_priority_geometry(&raw, zone, direction, [120.0, 424.0 / 3.0, 392.0 / 3.0]); + let third_after = raw.host.frame().unwrap().layout.sections.iter().find(|card| card.section == section("priority-2")).unwrap().outer; + assert_priority_number(priority_axis(third_after.size, zone), priority_axis(third.size, zone)); + assert_priority_number( + if zone == Zone::Bottom { third_after.origin.x } else { third_after.origin.y }, + if zone == Zone::Bottom { third.origin.x } else { third.origin.y }, + ); + let first = raw.content.runtime.layout().layout().section(§ion("priority-0")).unwrap().clone(); + assert_eq!(first.preferred_extent, Some(120.0)); + assert!(first.extent_priority > 0); + let b = raw.content.runtime.layout().layout().section(§ion("priority-1")).unwrap(); + assert_priority_number(b.preferred_extent.unwrap(), 424.0 / 3.0); + assert_eq!(b.extent_priority, first.extent_priority); + raw_priority_pair_edit(&mut raw, 1, 2, zone, direction, 132.0); + assert_priority_geometry(&raw, zone, direction, [120.0, 132.0, 140.0]); + let saved = raw.content.runtime.layout().layout().clone(); + assert_eq!((saved.sections[0].preferred_extent, saved.sections[0].extent_priority), (Some(120.0), first.extent_priority)); + assert_priority_number(saved.sections[1].preferred_extent.unwrap(), 132.0); + assert_priority_number(saved.sections[2].preferred_extent.unwrap(), 140.0); + assert!(saved.sections[1].extent_priority > first.extent_priority); + assert_eq!(saved.sections[1].extent_priority, saved.sections[2].extent_priority); + if zone == Zone::Bottom { + raw.capacity.size.width = 390.0; + } else { + raw.capacity.size.height = 390.0; + } + raw.frame(Vec::new(), false); + assert_priority_geometry(&raw, zone, direction, [120.0, 128.25, 133.75]); + assert_eq!(raw.content.runtime.layout().layout(), &saved); + assert_eq!(trace.borrow().factories, factories); + } + } + } +} + +fn priority_bottom_raw( + scale: f32, + direction: Direction, + count: usize, + authored_width: bool, + unequal_height: bool, + capacity_height: f32, +) -> (RawPanelHost, ReviewTrace) { + let (mut h, trace) = review_cohort_host(|spec| { + spec.min_size = Size { width: 120.0, height: 32.0 }; + spec.default_size = Size { width: 280.0, height: 64.0 }; + spec.max_size = Size { width: MAX_LOGICAL, height: 300.0 }; + }); + h.dispatch( + (0..count) + .map(|index| fixture_open("fixture.log", &format!("bottom-{index}"), &format!("bottom-{index}"), Zone::Bottom, index).unwrap()) + .collect(), + ) + .unwrap(); + let mut layout = h.runtime.layout().layout().clone(); + let allocated_width = (1000.0 - 4.0 * (count - 1) as f32) / count as f32; + for (index, section) in layout.sections.iter_mut().enumerate() { + section.size = Size { width: 280.0, height: if unequal_height && index == 1 { 180.0 } else { 64.0 } }; + section.preferred_extent = authored_width.then_some(allocated_width); + section.extent_priority = if authored_width { 7 } else { 0 }; + section.weight = 1.0; + } + for (index, instance) in layout.instances.iter_mut().enumerate() { + instance.memory.size = layout.sections[index].size; + instance.memory.preferred_extent = layout.sections[index].preferred_extent; + instance.memory.extent_priority = layout.sections[index].extent_priority; + instance.memory.weight = 1.0; + } + h.apply_layout(layout, None).unwrap(); + let mut environment = h.runtime.environment().clone(); + environment.direction = direction; + h.runtime.set_environment(environment, &mut h.local).unwrap(); + let mut raw = RawPanelHost::new(h, scale); + raw.host = WorkspacePanelHost::new(priority_host_options()).unwrap(); + raw.capacity.size = Size { width: 1000.0, height: capacity_height }; + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + (raw, trace) +} + +#[test] +fn raw_bottom_only_exact_64_row_has_no_separator_and_passes_exact_capacity_admission() { + for scale in [1.0, 2.0] { + for direction in [Direction::Ltr, Direction::Rtl] { + for unavailable_side in [false, true] { + let (mut raw, trace) = priority_bottom_raw(scale, direction, 1, false, false, 64.0); + if unavailable_side { + raw.content.dispatch(vec![fixture_open("fixture.log", "unavailable-side", "unavailable-side", Zone::Left, 1).unwrap()]).unwrap(); + trace.borrow_mut().unavailable.insert(ControllerKey { + instance: id("unavailable-side"), + owner: ContentOwner::Workspace(raw.content.runtime.environment().workspace.clone()), + }); + raw.frame(Vec::new(), false); + } + let host = &raw.host.frame().unwrap().layout; + assert_eq!(host.sections.len(), 1); + let card = &host.sections[0]; + assert_eq!(card.outer, LogicalRect { origin: Point { x: 0.0, y: 0.0 }, size: Size { width: 1000.0, height: 64.0 } }); + assert!(card.inline && card.body.is_none() && card.footer.is_none()); + assert_eq!(card.header, card.outer); + assert_eq!(host.extent.height, 64.0); + assert_eq!(host.viewport, Some(raw.capacity)); + let before = raw.content.runtime.layout().inspect(); + let action = transaction(vec![Mutation::SetBottomHeight { section: section("bottom-0"), height: 64.0 }]); + let _candidate = raw + .content + .runtime + .prepare_host_proposal(host.clone(), action, &raw.content.models) + .expect("exact Bottom capacity admits without a phantom separator"); + assert_eq!(raw.content.runtime.layout().inspect(), before); + } + } + } +} + +#[test] +fn raw_bottom_thickness_drag_preserves_saved_width_preference_rank_and_shared_row() { + for scale in [1.0, 2.0] { + for direction in [Direction::Ltr, Direction::Rtl] { + for count in [1, 2] { + for authored_width in [false, true] { + for unequal_height in [false, true].into_iter().filter(|unequal| count == 2 || !*unequal) { + let (mut raw, trace) = priority_bottom_raw(scale, direction, count, authored_width, unequal_height, 800.0); + let before = raw.content.runtime.layout().layout().clone(); + let factories = trace.borrow().factories.clone(); + let old_geometry = raw.host.frame().unwrap().layout.clone(); + let old_height = if unequal_height { 180.0 } else { 64.0 }; + for card in &old_geometry.sections { + assert_eq!(card.outer.size.height, old_height); + assert_eq!(card.inline, !unequal_height, "64-point row is inline; a saved 180-point row is expanded"); + } + let target = + HostControlTarget::Pointer(HostPointerTarget::Resize { section: section("bottom-0"), edge: HostResizeEdge::Top }); + let at = raw.at(target); + raw.pointer(at, true, false); + let end = at + egui::vec2(0.0, old_height - 100.0); + let preview = raw.frame(vec![egui::Event::PointerMoved(end)], false).0.preview.expect("actual top-edge drag has a candidate"); + assert!(preview.rejection.is_none(), "{preview:?}"); + assert!( + matches!(one_mutation(preview.action.as_ref().unwrap()), Mutation::SetBottomHeight { section: id, height } if *id == section("bottom-0") && *height == 100.0) + ); + let shown = preview.projected.unwrap(); + for card in &shown.sections { + let previous = old_geometry.sections.iter().find(|old| old.section == card.section).unwrap(); + assert_eq!(card.outer.size, Size { width: if count == 1 { 1000.0 } else { 498.0 }, height: 100.0 }); + assert_eq!(card.outer.origin.y, 700.0); + assert_eq!(card.outer.origin.x, previous.outer.origin.x); + } + let release = raw.pointer(end, false, false); + assert_eq!(release.events.iter().filter(|event| matches!(event, HostEvent::PreparedCommitted { .. })).count(), 1); + raw.frame(Vec::new(), false); + let actual = &raw.host.frame().unwrap().layout; + assert_eq!(actual.render_domain, old_geometry.render_domain); + assert_eq!(actual.viewport, old_geometry.viewport); + assert_eq!(actual.extent, old_geometry.extent); + for card in &actual.sections { + let previous = old_geometry.sections.iter().find(|old| old.section == card.section).unwrap(); + assert_eq!(card.outer.origin, Point { x: previous.outer.origin.x, y: 700.0 }); + assert_eq!(card.outer.size, Size { width: if count == 1 { 1000.0 } else { 498.0 }, height: 100.0 }); + assert!(!card.inline && card.body.is_some(), "crossing 88 uses the expanded composition"); + } + let model = raw.content.runtime.layout().layout(); + for section in &model.sections { + let prior = before.section(§ion.id).unwrap(); + assert_eq!( + (section.size.width, section.preferred_extent, section.extent_priority, section.weight), + (prior.size.width, prior.preferred_extent, prior.extent_priority, prior.weight) + ); + assert_eq!(section.size.width, 280.0); + assert_eq!(section.size.height, 100.0); + } + for instance in &model.instances { + let prior = before.instance(&instance.id).unwrap(); + assert_eq!( + ( + instance.memory.size.width, + instance.memory.preferred_extent, + instance.memory.extent_priority, + instance.memory.weight + ), + (prior.memory.size.width, prior.memory.preferred_extent, prior.memory.extent_priority, prior.memory.weight) + ); + assert_eq!(instance.memory.size.height, 100.0); + } + assert_eq!(trace.borrow().factories, factories); + } + } + } + } + } +} + +#[test] +fn raw_bottom_thickness_release_without_move_cannot_commit_an_unseen_landing() { + for scale in [1.0, 2.0] { + for direction in [Direction::Ltr, Direction::Rtl] { + let (mut raw, _) = priority_bottom_raw(scale, direction, 1, false, false, 800.0); + let before = raw.content.runtime.layout().inspect(); + let commits = raw.content.native.commits; + let at = raw.at(HostControlTarget::Pointer(HostPointerTarget::Resize { section: section("bottom-0"), edge: HostResizeEdge::Top })); + raw.pointer(at, true, false); + raw.frame(vec![button_event(at - egui::vec2(0.0, 36.0), false)], false); + assert_eq!(raw.content.runtime.layout().inspect(), before); + assert_eq!(raw.content.native.commits, commits); + assert!(!raw.host.interaction().is_captured()); + assert!(raw.host.frame().unwrap().preview.is_none()); + } + } +} + +#[test] +fn atomic_overlapping_explicit_pair_commands_keep_composed_tiers_and_one_cohort() { + for direction in [Direction::Ltr, Direction::Rtl] { + let (mut raw, trace) = priority_raw_stack(1.0, direction, Zone::Left, 1000.0); + let factories = trace.borrow().factories.clone(); + let commits = raw.content.native.commits; + let registry = raw.content.runtime.layout().registry().clone(); + let h = &mut raw.content; + { + let mut services = ContentServices { models: &h.models, commands: &mut h.commands, local: &mut h.local }; + let mut live = RuntimeActionSink { runtime: &mut h.runtime, native: &mut h.native, services: &mut services }; + let mut sink = super::app::AdmittedActionSink { live: &mut live, host: Some(&mut raw.host), proposal: std::cell::RefCell::new(None) }; + commands::execute_batch( + &[ + serde_json::json!({"command":"panel.resize_pair","params":{"first":"priority-0","second":"priority-1", + "first_size":{"width":280,"height":180},"second_size":{"width":280,"height":220}}}), + serde_json::json!({"command":"panel.resize_pair","params":{"first":"priority-1","second":"priority-2", + "first_size":{"width":280,"height":190},"second_size":{"width":280,"height":230}}}), + ], + &mut commands::PanelCommandContext { sink: &mut sink, registry: ®istry, catalogue: &mut h.catalogue, web: false }, + ) + .unwrap(); + } + raw.frame(Vec::new(), false); + assert_priority_geometry(&raw, Zone::Left, direction, [180.0, 190.0, 230.0]); + let model = raw.content.runtime.layout().layout(); + assert!(model.sections[0].extent_priority > 0); + assert!(model.sections[1].extent_priority > model.sections[0].extent_priority); + assert_eq!(model.sections[1].extent_priority, model.sections[2].extent_priority); + assert_eq!(raw.content.native.commits, commits + 1); + assert_eq!(trace.borrow().factories, factories); + } +} + +#[test] +fn deferred_outgoing_unavailable_actions_use_captured_retained_or_staged_owner_availability() { + use commands::LayoutCatalogue; + for staged in [false, true] { + for operation in ["open", "focus", "move"] { + for available in [false, true] { + let (mut h, trace) = review_cohort_host_with_layout( + |_| {}, + |service| { + apply_fixture(service, vec![fixture_open("fixture.log", "deferred", "deferred", Zone::Left, 0).unwrap()]); + if operation == "open" { + apply_fixture(service, vec![Mutation::Close { instance: id("deferred") }]); + } + service + .set_availability([(id("deferred"), Availability::Unavailable { reason: "outgoing owner unavailable".into() })].into()) + .unwrap(); + }, + ); + let key = ControllerKey { instance: id("deferred"), owner: ContentOwner::Workspace(h.runtime.environment().workspace.clone()) }; + if !staged { + trace.borrow_mut().unavailable.insert(key.clone()); + h.tick().unwrap(); + } + if available { + trace.borrow_mut().unavailable.remove(&key); + } else { + trace.borrow_mut().unavailable.insert(key.clone()); + } + let mut host = WorkspacePanelHost::new(priority_host_options()).unwrap(); + host.capture_metrics(&h.runtime, &h.models).unwrap(); + host.capture_reservations(&h.runtime, &h.catalogue).unwrap(); + host.prepare(&h.runtime, capacity()).unwrap(); + assert_ne!(h.runtime.layout().availability(&id("deferred")), Availability::Available); + let before = h.runtime.layout().inspect(); + let controllers = h.runtime.controller_count(); + let catalogue = h.catalogue.state().clone(); + let commits = h.native.commits; + let factories = trace.borrow().factories.len(); + let measures = trace.borrow().measures.len(); + let reads = trace.borrow().availability_reads; + let mutation = match operation { + "open" => Mutation::Open { kind: PanelKind::new("fixture.log").unwrap(), instance: id("deferred"), destination: None }, + "focus" => Mutation::Focus { instance: id("deferred") }, + "move" => Mutation::Move { + instance: id("deferred"), + destination: Destination::NewSection { + section: section("deferred"), + index: 0, + location: SectionLocation::Dock { zone: Zone::Right }, + size: Size { width: 280.0, height: 240.0 }, + }, + }, + other => panic!("unknown deferred operation fixture: {other}"), + }; + let action = LayoutAction::Apply { expected_revision: Some(before.revision), mutations: vec![mutation] }; + let registry = h.runtime.layout().registry().clone(); + { + let mut services = ContentServices { models: &h.models, commands: &mut h.commands, local: &mut h.local }; + let mut live = RuntimeActionSink { runtime: &mut h.runtime, native: &mut h.native, services: &mut services }; + let mut sink = super::app::AdmittedActionSink { live: &mut live, host: Some(&mut host), proposal: std::cell::RefCell::new(None) }; + if available { + let projected = sink.project(action.clone()).expect("deferred projection must reach the fresh proposed owner"); + assert_eq!(sink.project(action.clone()).unwrap(), projected); + assert_eq!(sink.inspect(), before, "projection cannot publish captured availability or layout"); + assert_eq!(sink.live.runtime.controller_count(), controllers, "staged controllers remain private before dispatch"); + assert_eq!(trace.borrow().factories.len(), factories + usize::from(staged)); + assert_eq!(trace.borrow().measures.len(), measures + 1, "one immutable provider captured for this proposal"); + commands::execute_layout_action( + action, + &mut commands::PanelCommandContext { sink: &mut sink, registry: ®istry, catalogue: &mut h.catalogue, web: false }, + ) + .unwrap(); + } else { + assert_eq!(sink.project(action).unwrap_err().rule, Rule::Availability); + assert!(sink.proposal.borrow().is_none()); + } + } + assert!(trace.borrow().availability_reads > reads, "the proposed-owner capture runs before final availability refusal"); + assert_eq!(trace.borrow().factories.len(), factories + usize::from(staged), "no factory replay between projection and dispatch"); + if available { + assert_eq!(h.runtime.layout().availability(&id("deferred")), Availability::Available); + assert!(h.runtime.layout().layout().instance(&id("deferred")).unwrap().requested_open); + assert_eq!(h.runtime.controller_count(), controllers + usize::from(staged)); + assert_eq!(h.native.commits, commits + 1); + if operation == "move" { + assert_eq!(h.runtime.layout().layout().containing(&id("deferred")).unwrap().location.zone(), Zone::Right); + } + if operation == "focus" { + assert_eq!(h.runtime.layout().interaction().focused, Some(id("deferred"))); + } + } else { + assert_eq!(h.runtime.layout().inspect(), before); + assert_eq!(h.runtime.controller_count(), controllers); + assert_eq!(h.catalogue.state(), &catalogue); + assert_eq!(h.native.commits, commits); + if staged { + assert!(h.probe.state(&key).is_err(), "unavailable staged controller was never published"); + } + } + assert_eq!(h.commands.calls, 0); + } + } + } +} + +#[test] +fn raw_bottom_tab_header_top_edge_resize_owns_label_grip_and_close_overlaps() { + for scale in [1.0, 2.0] { + for direction in [Direction::Ltr, Direction::Rtl] { + let (mut content, trace) = review_cohort_host(|_| {}); + content + .dispatch(vec![ + fixture_open("fixture.editor", "editor", "bottom-tabs", Zone::Bottom, 0).unwrap(), + Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("inactive"), + destination: Some(Destination::JoinTab { section: section("bottom-tabs"), index: 1 }), + }, + Mutation::Activate { instance: id("editor") }, + ]) + .unwrap(); + let mut environment = content.runtime.environment().clone(); + environment.direction = direction; + content.runtime.set_environment(environment.clone(), &mut content.local).unwrap(); + let key = editor_key(&content); + content.probe.edit(&key, |state| state.draft = "resize retains this document draft".into()).unwrap(); + let PanelMountHarness { runtime, probe, catalogue, .. } = content; + let mut session = solidcraft_engine::Session::default(); + session.document_id = "fixture.document".into(); + let mut app = crate::SolveApp::new(session, Default::default()); + app.enable_panel_runtime(runtime, Box::new(FakeAppPanelServices { models: FakeModels { editable: true }, ..Default::default() })) + .unwrap(); + let native = std::rc::Rc::new(std::cell::RefCell::new(FakeNativeAdapter::new(false))); + app.panel_runtime_mut().unwrap().set_command_adapters(Box::new(catalogue), Box::new(SharedNative(native.clone()))).unwrap(); + app.enable_universal_panel_host(priority_host_options()).unwrap(); + let ctx = crate::fonts::test_context(); + ctx.enable_accesskit(); + ctx.set_pixels_per_point(scale); + let capacity = rect(0.0, 0.0, 800.0, 800.0); + let mut time = 0.0; + let mut frame = |app: &mut crate::SolveApp, events: Vec| { + time += 1.0 / 60.0; + app.panel_runtime.as_mut().unwrap().prepare_host(&app.session, capacity).unwrap(); + let mut output = ctx.run_ui( + egui::RawInput { screen_rect: Some(egui_rect(capacity)), events, time: Some(time), focused: true, ..Default::default() }, + |ui| { + app.panel_runtime.as_mut().unwrap().show_host(&app.session, ui).unwrap(); + }, + ); + output.textures_delta.clear(); + app.universal_panel_frame().unwrap().clone() + }; + frame(&mut app, Vec::new()); + let initial = frame(&mut app, Vec::new()); + assert_eq!(initial.layout.sections[0].outer, rect(0.0, 560.0, 800.0, 240.0)); + assert_eq!(initial.layout.sections[0].header.size.height, 24.0); + let factories = trace.borrow().factories.clone(); + let retained = probe.state(&key).unwrap(); + let doc = app.session.doc.clone(); + let model = app.session.model.state(); + let camera = app.cam; + let revision = app.session.revision; + let undo = app.session.undo.len(); + let redo = app.session.redo.len(); + let dirty = app.session.is_dirty(); + // Reuse the same card for three gestures; no duplicate tab-centre + // click/drag matrix. Those existing cases continue to cover tabs. + for underlay in ["inactive-tab", "grip", "close"] { + let before = app.panel_runtime().unwrap().layout().inspect(); + let commits = native.borrow().commits; + let actual = app.universal_panel_frame().unwrap().layout.clone(); + let card = &actual.sections[0]; + let bounds = match underlay { + "inactive-tab" => card.tabs.iter().find(|tab| tab.instance == id("inactive")).unwrap().bounds, + "grip" => card.title.unwrap(), + _ => card.close.unwrap(), + }; + let start = egui::pos2(middle(bounds).x, card.header.origin.y + 2.0); + assert!(bounds.contains(Point { x: start.x, y: start.y })); + let resize = HostPointerTarget::Resize { section: section("bottom-tabs"), edge: HostResizeEdge::Top }; + assert_eq!(actual.hit_test(Point { x: start.x, y: start.y }), Some(resize.clone())); + let resize_id = app_control(&app, HostControlTarget::Pointer(resize)).id; + frame(&mut app, vec![egui::Event::PointerMoved(start)]); + frame(&mut app, vec![button_event(start, true)]); + assert!(ctx.read_response(resize_id).unwrap().is_pointer_button_down_on(), "the actual sash owns {underlay}/{direction:?}/{scale}"); + assert!(app.panel_runtime.as_ref().unwrap().host().unwrap().interaction().is_captured()); + let end = start - egui::vec2(0.0, 40.0); + let shown = frame(&mut app, vec![egui::Event::PointerMoved(end)]).preview.expect("top-edge resize starts above header controls"); + assert!(shown.rejection.is_none(), "{shown:?}"); + assert!(matches!(one_mutation(shown.action.as_ref().unwrap()), Mutation::SetBottomHeight { height, .. } + if *height == card.outer.size.height + 40.0)); + let projected = shown.projected.unwrap(); + assert_eq!(projected.sections[0].outer, rect(0.0, card.outer.origin.y - 40.0, 800.0, card.outer.size.height + 40.0)); + assert_eq!(app.panel_runtime().unwrap().layout().inspect(), before, "preview cannot mutate layout or select the covered tab"); + assert_eq!(app.universal_panel_frame().unwrap().layout.sections, actual.sections); + let release = frame(&mut app, vec![button_event(end, false)]); + assert_eq!(release.events.iter().filter(|event| matches!(event, HostEvent::PreparedCommitted { .. })).count(), 1); + assert_eq!(native.borrow().commits, commits + 1); + let landed = frame(&mut app, Vec::new()); + assert_host_landing(&landed.layout, &projected); + let after = app.panel_runtime().unwrap().layout().inspect(); + assert_eq!(after.revision, before.revision + 1); + assert_eq!(after.layout.sections[0].tabs, before.layout.sections[0].tabs); + assert_eq!(after.layout.sections[0].active, id("editor")); + let repeated = frame(&mut app, vec![button_event(end, false)]); + assert!(!repeated.events.iter().any(|event| matches!(event, HostEvent::PreparedCommitted { .. }))); + assert_eq!(app.panel_runtime().unwrap().layout().inspect(), after); + assert_eq!(native.borrow().commits, commits + 1); + assert!(repeated.menu_bounds.is_none()); + assert_eq!(app.panel_runtime().unwrap().controller_count(), 2); + assert_eq!(trace.borrow().factories, factories); + assert!(trace.borrow().actions.is_empty()); + let state = probe.state(&key).unwrap(); + assert_eq!(state.draft, retained.draft); + assert_eq!( + (state.cancels, state.reparents, state.reopens, state.destroys), + (retained.cancels, retained.reparents, retained.reopens, retained.destroys) + ); + assert_eq!(app.panel_runtime().unwrap().environment(), &environment); + assert!(std::sync::Arc::ptr_eq(&app.session.doc, &doc)); + assert!(std::sync::Arc::ptr_eq(&app.session.model.state(), &model)); + assert_eq!(app.cam, camera); + assert_eq!(app.session.revision, revision); + assert_eq!(app.session.is_dirty(), dirty); + assert_eq!(app.session.undo.len(), undo); + assert_eq!(app.session.redo.len(), redo); + } + } + } +} + +#[test] +fn raw_bottom_two_tab_expanded_120_drag_down_88_reaches_inline_32_without_changing_width_intent() { + for scale in [1.0, 2.0] { + for direction in [Direction::Ltr, Direction::Rtl] { + let (mut h, trace) = review_cohort_host(|spec| { + spec.min_size = Size { width: 120.0, height: 24.0 }; + spec.default_size = Size { width: 280.0, height: 120.0 }; + spec.max_size = Size { width: MAX_LOGICAL, height: 300.0 }; + }); + h.dispatch(vec![ + fixture_open("fixture.log", "bottom-active", "bottom-tabs", Zone::Bottom, 0).unwrap(), + Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("bottom-inactive"), + destination: Some(Destination::JoinTab { section: section("bottom-tabs"), index: 1 }), + }, + Mutation::Activate { instance: id("bottom-active") }, + ]) + .unwrap(); + let mut layout = h.runtime.layout().layout().clone(); + layout.sections[0].size = Size { width: 280.0, height: 120.0 }; + layout.sections[0].preferred_extent = Some(1000.0); + layout.sections[0].extent_priority = 7; + layout.sections[0].weight = 0.75; + for instance in &mut layout.instances { + instance.memory.size = layout.sections[0].size; + instance.memory.preferred_extent = Some(1000.0); + instance.memory.extent_priority = 7; + instance.memory.weight = 0.75; + } + h.apply_layout(layout, None).unwrap(); + let mut environment = h.runtime.environment().clone(); + environment.direction = direction; + h.runtime.set_environment(environment, &mut h.local).unwrap(); + let mut options = priority_host_options(); + options.metrics.footer_height = 16.0; + let mut raw = RawPanelHost::new(h, scale); + raw.host = WorkspacePanelHost::new(options).unwrap(); + raw.capacity.size = Size { width: 1000.0, height: 800.0 }; + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + let before = raw.content.runtime.layout().inspect(); + let factories = trace.borrow().factories.clone(); + let old = raw.host.frame().unwrap().layout.sections[0].clone(); + assert_eq!(old.outer, LogicalRect { origin: Point { x: 0.0, y: 680.0 }, size: Size { width: 1000.0, height: 120.0 } }); + assert!(!old.inline); + assert_eq!(old.header.size.height, 24.0); + assert_eq!(old.tabs.len(), 2); + assert!(old.tabs.iter().all(|tab| tab.bounds.size.height == old.header.size.height)); + assert_eq!(old.footer.unwrap().size.height, 16.0); + assert!(old.body.is_some()); + let start = raw.at(HostControlTarget::Pointer(HostPointerTarget::Resize { section: section("bottom-tabs"), edge: HostResizeEdge::Top })); + raw.pointer(start, true, false); + let end = start + egui::vec2(0.0, 88.0); + let shown = + raw.frame(vec![egui::Event::PointerMoved(end)], false).0.preview.expect("actual top-edge drag must cross composition boundary"); + assert!(shown.rejection.is_none(), "{shown:?}"); + assert!(matches!(one_mutation(shown.action.as_ref().unwrap()), Mutation::SetBottomHeight { height, .. } if *height == 32.0)); + let candidate = &shown.projected.as_ref().unwrap().sections[0]; + assert_eq!(candidate.outer, LogicalRect { origin: Point { x: 0.0, y: 768.0 }, size: Size { width: 1000.0, height: 32.0 } }); + assert!(candidate.inline && candidate.body.is_none() && candidate.footer.is_none()); + assert_eq!(candidate.header, candidate.outer); + assert_eq!(raw.content.runtime.layout().inspect(), before, "preview is observational"); + let release = raw.pointer(end, false, false); + assert_eq!(release.events.iter().filter(|event| matches!(event, HostEvent::PreparedCommitted { .. })).count(), 1); + raw.frame(Vec::new(), false); + let card = &raw.host.frame().unwrap().layout.sections[0]; + assert_eq!(card.outer.origin.y, 768.0); + assert_eq!(card.outer.size, Size { width: 1000.0, height: 32.0 }); + assert!(card.inline && card.inline_content.is_some() && card.body.is_none() && card.footer.is_none()); + let after = raw.content.runtime.layout().layout(); + let saved = &before.layout.sections[0]; + let section = &after.sections[0]; + assert_eq!( + (section.size.width, section.preferred_extent, section.extent_priority, section.weight), + (saved.size.width, saved.preferred_extent, saved.extent_priority, saved.weight) + ); + assert_eq!(section.tabs, saved.tabs); + assert_eq!(section.active, saved.active); + assert_eq!(section.size.height, 32.0); + for instance in &after.instances { + let old = &before.layout.instance(&instance.id).unwrap().memory; + assert_eq!( + (instance.memory.size.width, instance.memory.preferred_extent, instance.memory.extent_priority, instance.memory.weight), + (old.size.width, old.preferred_extent, old.extent_priority, old.weight) + ); + assert_eq!(instance.memory.size.height, 32.0); + } + assert_eq!(trace.borrow().factories, factories); + assert_eq!(raw.content.commands.calls, 0); + // The additive registered request follows the same C/context route + // back across the boundary. Its valid ignored width must not author + // a Bottom width preference or a new extent tier. + run_context_pair_batch( + &mut raw, + &[serde_json::json!({"command":"panel.resize","params":{ + "target":{"type":"section","id":"bottom-tabs"},"size":{"width":1000,"height":120},"thickness_only":true}})], + ) + .unwrap(); + raw.frame(Vec::new(), false); + let restored = &raw.host.frame().unwrap().layout.sections[0]; + assert!(!restored.inline && restored.body.is_some()); + assert_eq!(restored.outer.origin.y, 680.0); + assert_eq!(restored.outer.size.height, 120.0); + let saved = &raw.content.runtime.layout().layout().sections[0]; + assert_eq!((saved.size.width, saved.preferred_extent, saved.extent_priority, saved.weight), (280.0, Some(1000.0), 7, 0.75)); + assert_eq!(trace.borrow().factories, factories); + } + } +} + +fn context_batch_raw(scale: f32, direction: Direction, c_open_floating: bool, captured_available: bool) -> (RawPanelHost, ReviewTrace) { + let (mut h, trace) = review_cohort_host_with_layout( + |spec| { + spec.min_size = Size { width: 120.0, height: 120.0 }; + spec.default_size = Size { width: 280.0, height: 240.0 }; + spec.max_size = Size { width: MAX_LOGICAL, height: MAX_LOGICAL }; + }, + |service| { + apply_fixture( + service, + vec![ + fixture_open("fixture.log", "pair-a", "pair-a", Zone::Left, 0).unwrap(), + fixture_open("fixture.log", "pair-b", "pair-b", Zone::Left, 1).unwrap(), + Mutation::Open { + kind: PanelKind::new("fixture.application").unwrap(), + instance: id("pair-c"), + destination: Some(Destination::NewSection { + section: section("pair-c"), + index: 2, + location: SectionLocation::Floating { origin: Point { x: 600.0, y: 100.0 } }, + size: Size { width: 280.0, height: 240.0 }, + }), + }, + ], + ); + if !c_open_floating { + apply_fixture(service, vec![Mutation::Close { instance: id("pair-c") }]); + } + }, + ); + let mut environment = h.runtime.environment().clone(); + environment.direction = direction; + h.runtime.set_environment(environment, &mut h.local).unwrap(); + let mut raw = RawPanelHost::new(h, scale); + raw.host = WorkspacePanelHost::new(priority_host_options()).unwrap(); + raw.capacity.size = Size { width: 1000.0, height: 800.0 }; + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + assert_ne!(raw.content.runtime.layout().availability(&id("pair-c")), Availability::Available); + assert_eq!(raw.content.runtime.controller_count(), 2, "C is honestly unbound in outgoing presentation"); + let binding = fixture_controller_binding(&raw.content.probe, false, Ownership::Workspace); + let create = binding.create; + let capture_trace = trace.clone(); + raw.content + .runtime + .register( + PanelKind::new("fixture.application").unwrap(), + ControllerBinding { + ownership: Ownership::Workspace, + create: Box::new(move |instance, owner| { + let key = ControllerKey { instance: instance.id.clone(), owner: owner.clone() }; + let serial = capture_trace.borrow().factories.len() + 1; + let inner = create(instance, owner)?; + capture_trace.borrow_mut().factories.push((key.clone(), serial)); + Ok(Box::new(ReviewController { inner, key, serial, trace: capture_trace.clone(), draft: "staged batch draft".into() })) + }), + }, + ) + .unwrap(); + if !captured_available { + trace + .borrow_mut() + .unavailable + .insert(ControllerKey { instance: id("pair-c"), owner: ContentOwner::Workspace(raw.content.runtime.environment().workspace.clone()) }); + } + // No tick after binding: capture must obtain C's new answer through its one + // private incoming object, while the real outgoing service stays unavailable. + (raw, trace) +} +fn context_pair_step(first: f32, second: f32) -> serde_json::Value { + serde_json::json!({"command":"panel.resize_pair","params":{"first":"pair-a","second":"pair-b", + "first_size":{"width":280,"height":first},"second_size":{"width":280,"height":second}}}) +} +fn context_c_step(open: bool, floating: bool) -> serde_json::Value { + let location = + if floating { serde_json::json!({"type":"floating","origin":{"x":600,"y":100}}) } else { serde_json::json!({"type":"dock","zone":"left"}) }; + let destination = serde_json::json!({"type":"new_section","section":"pair-c","index":2,"location":location,"size":{"width":280,"height":240}}); + if open { + serde_json::json!({"command":"panel.open","params":{"kind":"fixture.application","instance":"pair-c","destination":destination}}) + } else { + serde_json::json!({"command":"panel.move","params":{"target":{"type":"instance","id":"pair-c"},"destination":destination}}) + } +} +fn run_context_pair_batch(raw: &mut RawPanelHost, steps: &[serde_json::Value]) -> PanelResult { + let h = &mut raw.content; + let registry = h.runtime.layout().registry().clone(); + let mut services = ContentServices { models: &h.models, commands: &mut h.commands, local: &mut h.local }; + let mut live = RuntimeActionSink { runtime: &mut h.runtime, native: &mut h.native, services: &mut services }; + let mut sink = super::app::AdmittedActionSink { live: &mut live, host: Some(&mut raw.host), proposal: std::cell::RefCell::new(None) }; + commands::execute_batch( + steps, + &mut commands::PanelCommandContext { sink: &mut sink, registry: ®istry, catalogue: &mut h.catalogue, web: false }, + ) +} +fn assert_context_batch_identity(raw: &RawPanelHost, trace: &ReviewTrace, before_factories: usize, before_providers: usize) { + let trace = trace.borrow(); + assert_eq!(trace.factories.len(), before_factories + 1, "one staged C factory across every composed prefix"); + let serial = trace.factories.iter().find(|(key, _)| key.instance == id("pair-c")).unwrap().1; + assert_eq!(trace.factories.iter().filter(|(key, _)| key.instance == id("pair-c")).count(), 1); + assert_eq!(trace.providers.iter().filter(|(measured, _)| *measured == serial).count(), 1, "same C provider is retained while the batch grows"); + assert_eq!(trace.providers.len(), before_providers + 3, "one proposed provider for A, B and C across all prefixes"); + assert!(trace.lifecycle.iter().any(|(identity, event)| *identity == serial && matches!(event, LifecycleEvent::State(_)))); + assert_eq!(raw.content.runtime.controller_count(), 3); + assert_eq!(raw.content.commands.calls, 0); +} + +#[test] +fn raw_pair_batch_and_closed_outgoing_unavailable_floating_open_share_one_captured_cohort_in_either_order() { + use commands::LayoutCatalogue; + for scale in [1.0, 2.0] { + for direction in [Direction::Ltr, Direction::Rtl] { + for open_first in [false, true] { + for available in [false, true] { + let (mut raw, trace) = context_batch_raw(scale, direction, false, available); + let before = raw.content.runtime.layout().inspect(); + let catalogue = raw.content.catalogue.state().clone(); + let commits = raw.content.native.commits; + let factories = trace.borrow().factories.len(); + let providers = trace.borrow().providers.len(); + let original = raw.host.frame().unwrap().layout.clone(); + assert_eq!(original.sections.iter().map(|card| card.outer.size.height).collect::>(), vec![398.0, 398.0]); + let pair = context_pair_step(180.0, 616.0); + let open = context_c_step(true, true); + let steps = if open_first { vec![open, pair] } else { vec![pair, open] }; + let result = run_context_pair_batch(&mut raw, &steps); + if !available { + assert_eq!(result.unwrap_err().rule, Rule::Availability); + assert_eq!(raw.content.runtime.layout().inspect(), before); + assert_eq!(raw.content.catalogue.state(), &catalogue); + assert_eq!(raw.content.runtime.controller_count(), 2); + assert_eq!(raw.content.native.commits, commits); + assert_eq!(trace.borrow().factories.len(), factories + 1); + continue; + } + result.unwrap(); + assert_context_batch_identity(&raw, &trace, factories, providers); + assert_eq!(raw.content.native.commits, commits + 1); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + let reference = raw.host.frame().unwrap().layout.clone(); + let a = reference.sections.iter().find(|card| card.instance == id("pair-a")).unwrap(); + let b = reference.sections.iter().find(|card| card.instance == id("pair-b")).unwrap(); + let c = reference.sections.iter().find(|card| card.instance == id("pair-c")).unwrap(); + assert_priority_number(a.outer.origin.y, 0.0); + assert_priority_number(a.outer.size.height, 180.0); + assert_eq!(a.outer.size.width, 280.0); + assert_priority_number(b.outer.origin.y, 184.0); + assert_priority_number(b.outer.size.height, 616.0); + assert_eq!(b.outer.size.width, 280.0); + assert_eq!(c.outer, LogicalRect { origin: Point { x: 600.0, y: 100.0 }, size: Size { width: 280.0, height: 240.0 } }); + assert_eq!(reference.extent, original.extent); + assert_eq!(reference.render_domain, original.render_domain); + assert_eq!(raw.content.runtime.layout().availability(&id("pair-c")), Availability::Available); + raw.frame(Vec::new(), false); + raw.frame(Vec::new(), false); + assert!( + raw.host.frame().unwrap().layout.sections.iter().any(|card| card.instance == id("pair-c")), + "actual new floating Area is eventually presented" + ); + } + } + } + } +} + +#[test] +fn raw_open_or_move_into_stack_before_pair_uses_captured_prefix_geometry_and_true_unavailable_refuses() { + use commands::LayoutCatalogue; + for scale in [1.0, 2.0] { + for direction in [Direction::Ltr, Direction::Rtl] { + for moving in [false, true] { + for available in [false, true] { + let (mut raw, trace) = context_batch_raw(scale, direction, moving, available); + let before = raw.content.runtime.layout().inspect(); + let catalogue = raw.content.catalogue.state().clone(); + let factories = trace.borrow().factories.len(); + let providers = trace.borrow().providers.len(); + let commits = raw.content.native.commits; + let result = run_context_pair_batch(&mut raw, &[context_c_step(!moving, false), context_pair_step(120.0, 408.0)]); + if !available { + assert_eq!(result.unwrap_err().rule, Rule::Availability); + assert_eq!(raw.content.runtime.layout().inspect(), before); + assert_eq!(raw.content.catalogue.state(), &catalogue); + assert_eq!(raw.content.runtime.controller_count(), 2); + assert_eq!(raw.content.native.commits, commits); + assert_eq!(trace.borrow().factories.len(), factories + 1); + continue; + } + result.unwrap(); + assert_context_batch_identity(&raw, &trace, factories, providers); + raw.frame(Vec::new(), false); + let frame = raw.host.frame().unwrap().layout.clone(); + for (instance, y, height) in [("pair-a", 0.0, 120.0), ("pair-b", 124.0, 408.0), ("pair-c", 536.0, 264.0)] { + let card = frame.sections.iter().find(|card| card.instance == id(instance)).unwrap(); + assert_priority_number(card.outer.origin.y, y); + assert_priority_number(card.outer.size.height, height); + assert_eq!(card.outer.size.width, 280.0); + } + assert_eq!(frame.extent, raw.capacity.size); + assert_eq!(raw.content.native.commits, commits + 1); + raw.frame(Vec::new(), false); + assert_eq!(raw.host.frame().unwrap().layout.sections.len(), 3); + } + } + } + } +} + +#[test] +fn admitted_candidate_rejects_supplied_context_changes_without_replaying_cohort_or_reducer() { + for change in ["sections", "columns", "priority", "stored_priority", "completeness", "replacement_ownership", "replacement_owner"] { + let (mut raw, trace) = priority_raw_stack(1.0, Direction::Ltr, Zone::Left, 1000.0); + let reference = raw.host.command_reference(&raw.content.runtime).unwrap(); + let context = reference.geometry_policy.identity_reservations.preparation_context().unwrap(); + assert!(context.extent_priorities.complete); + let mut changed = context.clone(); + match change { + "sections" => { + changed.sections.insert(section("extra-reserved")); + } + "columns" => { + changed.columns.insert(ColumnId::new("extra-reserved-column").unwrap()); + } + "priority" => { + changed.extent_priorities.records[0].priority += 1; + } + "stored_priority" => { + changed.extent_priorities.records[0].stored_priority += 1; + } + "completeness" => { + changed.extent_priorities.complete = false; + } + "replacement_ownership" => { + changed.replacement_ownership = None; + } + "replacement_owner" => { + changed.replacement_ownership.as_mut().unwrap().sections.get_mut(§ion("priority-0")).unwrap().insert(id("other-owner")); + } + other => panic!("unknown recovery context fixture: {other}"), + } + let action = transaction(vec![Mutation::SetSize { section: section("priority-0"), size: Size { width: 280.0, height: 180.0 } }]); + let before = raw.content.runtime.layout().inspect(); + let commits = raw.content.native.commits; + let h = &mut raw.content; + let mut services = ContentServices { models: &h.models, commands: &mut h.commands, local: &mut h.local }; + let mut live = RuntimeActionSink { runtime: &mut h.runtime, native: &mut h.native, services: &mut services }; + let mut sink = super::app::AdmittedActionSink { live: &mut live, host: Some(&mut raw.host), proposal: std::cell::RefCell::new(None) }; + let projected = sink.project_in_context(action.clone(), &context).unwrap(); + assert_eq!(sink.project_in_context(action.clone(), &context).unwrap(), projected); + let factories = trace.borrow().factories.clone(); + let measures = trace.borrow().measures.clone(); + assert_eq!(sink.dispatch_in_context(action, &changed).unwrap_err().rule, Rule::Revision); + assert!(sink.proposal.borrow().is_none()); + assert_eq!(sink.inspect(), before); + assert_eq!(trace.borrow().factories, factories); + assert_eq!(trace.borrow().measures, measures); + assert!(!sink.live.native.capabilities().native_windows); + drop(sink); + assert_eq!(raw.content.native.commits, commits); + } +} + +fn context_envelope_with_dormant_priority(layout: Layout) -> LayoutEnvelope { + let mut dormant = layout.instances[0].clone(); + dormant.id = id("recovery-priority"); + dormant.kind = PanelKind::new("extension.priority").unwrap(); + dormant.requested_open = false; + dormant.memory.section = section("recovery-priority-section"); + dormant.memory.section_index = layout.sections.len(); + dormant.memory.tab_index = 0; + dormant.memory.preferred_extent = Some(200.0); + dormant.memory.extent_priority = 17; + let mut envelope = LayoutEnvelope::new(layout); + envelope.quarantine.push(QuarantinedPanel { + instance: dormant.id.clone(), + kind: dormant.kind.clone(), + instance_data: serde_json::to_value(dormant).unwrap(), + section: None, + }); + envelope +} +struct ContextDriftCatalogue { + inner: commands::InMemoryCatalogue, + incoming_source: commands::CatalogueState, + drift: bool, + source_changed: bool, + prepared: std::rc::Rc>, + published: std::rc::Rc>, + durable: std::rc::Rc>, +} +impl commands::LayoutCatalogue for ContextDriftCatalogue { + fn state(&self) -> &commands::CatalogueState { + if self.source_changed { &self.incoming_source } else { commands::LayoutCatalogue::state(&self.inner) } + } + fn prepare(&mut self, next: commands::CatalogueState) -> PanelResult { + self.prepared.set(self.prepared.get() + 1); + let staged = commands::LayoutCatalogue::prepare(&mut self.inner, next)?; + // Inject a newer opaque recovery-priority context at the REAL storage + // boundary. IDs, typed live layout, availability and metric sources stay + // equal. This external source change is distinct from action publication. + self.source_changed = self.drift; + Ok(staged) + } + fn publish(&mut self, prepared: commands::PreparedCatalogue) { + self.published.set(self.published.get() + 1); + commands::LayoutCatalogue::publish(&mut self.inner, prepared); + *self.durable.borrow_mut() = commands::LayoutCatalogue::state(&self.inner).clone(); + } +} + +#[test] +fn actual_catalogue_prepare_context_only_drift_refuses_command_widget_and_owned_pointer_atomically() { + use commands::LayoutCatalogue; + for route in ["command", "widget", "pointer"] { + for drift in [false, true] { + let (mut h, probe, observations) = boundary_app(); + h.app + .dispatch_panel_layout(transaction(vec![fixture_open("fixture.log", "context-peer", "context-peer", Zone::Left, 1).unwrap()])) + .unwrap(); + h.frames(3); + let registry = h.app.panel_runtime().unwrap().layout().registry().clone(); + let envelope = context_envelope_with_dormant_priority(h.app.panel_runtime().unwrap().layout().layout().clone()); + let mut incoming = envelope.clone(); + let context = preparation_context(&envelope).unwrap(); + let mut recovery = context + .extent_priorities + .records + .iter() + .find(|record| record.target == ExtentPriorityTarget::Memory(id("recovery-priority"))) + .unwrap() + .clone(); + recovery.priority += 1; + incoming.extent_priority_overrides.push(recovery); + let changed = preparation_context(&incoming).unwrap(); + assert_eq!(changed.sections, context.sections); + assert_eq!(changed.columns, context.columns); + assert_eq!(changed.extent_priorities.complete, context.extent_priorities.complete); + assert_eq!(incoming.layout, envelope.layout); + assert_eq!(incoming.quarantine, envelope.quarantine); + assert_ne!(changed.extent_priorities, context.extent_priorities, "only effective recovery context changes"); + let mut catalogue = fixture_command_catalogue(®istry).unwrap(); + catalogue.remember(&envelope, None, ®istry).unwrap(); + let mut source = fixture_command_catalogue(®istry).unwrap(); + source.remember(&incoming, None, ®istry).unwrap(); + let catalogue_before = catalogue.state().clone(); + let durable = std::rc::Rc::new(std::cell::RefCell::new(catalogue_before.clone())); + let prepared = std::rc::Rc::new(std::cell::Cell::new(0)); + let published = std::rc::Rc::new(std::cell::Cell::new(0)); + let native = std::rc::Rc::new(std::cell::RefCell::new(FakeNativeAdapter::new(true))); + h.app + .panel_runtime_mut() + .unwrap() + .set_command_adapters( + Box::new(ContextDriftCatalogue { + inner: catalogue, + incoming_source: source.state().clone(), + drift, + source_changed: false, + prepared: prepared.clone(), + published: published.clone(), + durable: durable.clone(), + }), + Box::new(SharedNative(native.clone())), + ) + .unwrap(); + h.frames(3); + let before = h.app.panel_runtime().unwrap().layout().inspect(); + let key = app_editor_key(&h.app); + probe.edit(&key, |state| state.draft = "context refusal retains this live draft".into()).unwrap(); + let retained = probe.state(&key).unwrap(); + let controllers = h.app.panel_runtime().unwrap().controller_count(); + let factories = observations.borrow().factory_keys.clone(); + let doc = h.app.session.doc.clone(); + let model = h.app.session.model.state(); + let revision = h.app.session.revision; + let undo = h.app.session.undo.len(); + let dirty = h.app.session.is_dirty(); + let camera = h.app.cam; + if route == "command" { + let result = + h.app.run_panel_command("panel.collapse", &serde_json::json!({"target":{"type":"instance","id":"editor"},"collapsed":true})); + if drift { + assert_eq!(result.unwrap_err().rule, Rule::Revision); + } else { + result.unwrap(); + } + } else { + let target = if route == "widget" { + HostPointerTarget::Collapse { instance: id("editor") } + } else { + HostPointerTarget::Sash { first: section("editor-section"), second: section("context-peer") } + }; + let control = h + .app + .universal_panel_frame() + .unwrap() + .controls + .iter() + .find(|control| control.target == HostControlTarget::Pointer(target.clone())) + .unwrap(); + let at = egui_rect(control.bounds).center(); + h.frame_with(vec![egui::Event::PointerMoved(at), button_event(at, true)]); + let end = if route == "pointer" { at + egui::vec2(0.0, 24.0) } else { at }; + if route == "pointer" { + h.frame_with(vec![egui::Event::PointerMoved(end)]); + let shown = h.app.universal_panel_frame().unwrap().preview.as_ref().expect("exact candidate is shown before storage drift"); + assert!(shown.rejection.is_none()); + assert!(shown.projected.is_some()); + assert_eq!(h.app.panel_runtime().unwrap().layout().inspect(), before); + } + h.frame_with(vec![button_event(end, false)]); + if drift { + assert!( + h.app + .universal_panel_frame() + .unwrap() + .events + .iter() + .any(|event| matches!(event, HostEvent::Rejected { error, .. } if error.rule == Rule::Revision)) + ); + } + } + assert_eq!(prepared.get(), 1, "injected catalogue.prepare, not a manual host recapture, changed the context"); + if drift { + assert_eq!(h.app.panel_runtime().unwrap().layout().inspect(), before); + assert_eq!(*durable.borrow(), catalogue_before, "the action never publishes its staged catalogue over the external source"); + assert_eq!(published.get(), 0); + assert_eq!(native.borrow().commits, 0); + assert!(native.borrow().hosts.is_empty()); + let after = probe.state(&key).unwrap(); + assert_eq!(after.draft, retained.draft); + assert_eq!(after.transaction_live, retained.transaction_live); + assert_eq!( + (after.cancels, after.reopens, after.reparents, after.destroys), + (retained.cancels, retained.reopens, retained.reparents, retained.destroys) + ); + } else { + assert_eq!(published.get(), 1); + assert_eq!(native.borrow().commits, 1); + assert_eq!(h.app.panel_runtime().unwrap().layout().inspect().revision, before.revision + 1); + } + assert_eq!(h.app.panel_runtime().unwrap().controller_count(), controllers); + assert_eq!(observations.borrow().factory_keys, factories); + assert!(std::sync::Arc::ptr_eq(&h.app.session.doc, &doc)); + assert!(std::sync::Arc::ptr_eq(&h.app.session.model.state(), &model)); + assert_eq!(h.app.session.revision, revision); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(h.app.session.is_dirty(), dirty); + assert_eq!(h.app.cam, camera); + } + } +} + +#[test] +fn runtime_sink_without_shared_host_forwards_full_recovery_context_and_retains_native_lifecycle() { + let mut h = PanelMountHarness::new(true).unwrap(); + open_editor(&mut h); + h.tick().unwrap(); + let key = editor_key(&h); + h.probe.edit(&key, |state| state.draft = "headless retained transaction".into()).unwrap(); + let envelope = context_envelope_with_dormant_priority(h.runtime.layout().layout().clone()); + h.catalogue.remember(&envelope, None, h.runtime.layout().registry()).unwrap(); + let context = preparation_context(&envelope).unwrap(); + assert!(context.extent_priorities.complete); + let controllers = h.runtime.controller_count(); + let commits = h.native.commits; + let before = h.runtime.layout().inspect(); + let action = transaction(vec![Mutation::SetSize { section: section("editor-section"), size: Size { width: 280.0, height: 260.0 } }]); + let registry = h.runtime.layout().registry().clone(); + { + let mut services = ContentServices { models: &h.models, commands: &mut h.commands, local: &mut h.local }; + let mut sink = RuntimeActionSink { runtime: &mut h.runtime, native: &mut h.native, services: &mut services }; + let projected = sink.project_in_context(action.clone(), &context).unwrap(); + assert!(projected.sections[0].extent_priority > 17); + assert_eq!(sink.inspect(), before); + commands::execute_layout_action( + action, + &mut commands::PanelCommandContext { sink: &mut sink, registry: ®istry, catalogue: &mut h.catalogue, web: false }, + ) + .unwrap(); + } + assert!(h.runtime.layout().layout().sections[0].extent_priority > 17); + assert_eq!(h.runtime.controller_count(), controllers); + assert_eq!(h.native.commits, commits + 1); + h.command("panel.popout", &panel_command_native_move()).unwrap(); + assert_eq!(h.native.hosts.len(), 1); + assert!(h.probe.state(&key).unwrap().reparents > 0); + h.command("panel.native_close", &serde_json::json!({"target":{"type":"native_host","id":"native-host"}})).unwrap(); + assert!(h.native.hosts.is_empty()); + assert_eq!(h.probe.state(&key).unwrap().draft, "headless retained transaction"); + assert!(h.probe.state(&key).unwrap().transaction_live); + assert_eq!(h.probe.state(&key).unwrap().cancels, 0); + assert_eq!(h.commands.calls, 0); + let current = commands::current_envelope_snapshot(&h.catalogue, &h.runtime.layout().inspect(), ®istry).unwrap(); + assert_eq!(current.quarantine, envelope.quarantine, "full context forwarding does not materialize a dormant controller/body"); +} + +#[test] +fn bare_host_context_is_incomplete_and_only_full_envelope_capture_admits_authored_priority() { + let mut service = allocation_service(|_| {}); + apply_fixture(&mut service, vec![fixture_open("fixture.log", "context-panel", "context-panel", Zone::Left, 0).unwrap()]); + let defaults = HostIdentityReservations::default(); + assert!(!defaults.extent_priorities.complete); + let mut bare = fixture_metric_policy(&service); + bare.identity_reservations = defaults; + // Bare allocation remains honest and useful; it is not full-envelope authority + // for a subsequent authored preference. No provider/factory callback is needed. + let bounds = LogicalRect { origin: Point { x: 0.0, y: 0.0 }, size: Size { width: 1000.0, height: 800.0 } }; + let host = resolve_host_layout(&service, bounds, Direction::Ltr, HostMetrics::default(), &bare).unwrap(); + let action = transaction(vec![Mutation::SetSize { section: section("context-panel"), size: Size { width: 280.0, height: 200.0 } }]); + let before = service.inspect(); + assert_eq!(prepare_host_layout(&service, &fixture_scope(&service), &host, action.clone()).unwrap_err().rule, Rule::Capability); + assert_eq!(service.inspect(), before); + let captured = fixture_metric_policy(&service); + assert!(captured.identity_reservations.extent_priorities.complete); + let host = resolve_host_layout(&service, bounds, Direction::Ltr, HostMetrics::default(), &captured).unwrap(); + let proposal = prepare_host_layout(&service, &fixture_scope(&service), &host, action).unwrap(); + assert_eq!(proposal.prepared().layout().sections[0].preferred_extent, Some(200.0)); + assert!(proposal.prepared().layout().sections[0].extent_priority > 0); + assert_eq!(service.inspect(), before); +} + +#[test] +fn app_atomic_workspace_replacements_accept_distinct_incoming_contexts_and_match_headless_commit() { + use commands::LayoutCatalogue; + let mut outcomes = Vec::new(); + for admitted in [false, true] { + let (mut h, trace) = review_cohort_host_with_layout( + |_| {}, + |service| { + *service = LayoutService::new( + service.registry().clone(), + service.layout().clone(), + HostCapabilities { native_windows: true, max_native_hosts: 8, persistence: true }, + ) + .unwrap(); + apply_fixture( + service, + vec![ + fixture_open("fixture.log", "log", "log-section", Zone::Right, 0).unwrap(), + fixture_open("fixture.editor", "editor", "editor-section", Zone::Left, 1).unwrap(), + ], + ); + }, + ); + h.native = FakeNativeAdapter::new(true); + h.tick().unwrap(); + let key = editor_key(&h); + h.probe + .edit(&key, |state| { + state.draft = "replacement batch retains this transaction".into(); + state.transaction_live = true; + }) + .unwrap(); + let retained = h.probe.state(&key).unwrap(); + let before = h.runtime.layout().inspect(); + let registry = h.runtime.layout().registry().clone(); + let mut catalogue = fixture_command_catalogue(®istry).unwrap(); + catalogue + .register_workspace(commands::WorkspaceDescriptor { + id: WorkspaceId::new("review.final").unwrap(), + title_key: "ui.panel".into(), + default_preset: "Fixture default".into(), + }) + .unwrap(); + let mut contexts = Vec::new(); + for (workspace, reserved_section, reserved_column, rank, native) in [ + ("fixture.other", "incoming-a-reserved", "incoming-a-column", 31, false), + ("review.final", "incoming-b-reserved", "incoming-b-column", 47, true), + ] { + let mut layout = before.layout.clone(); + layout.workspace = WorkspaceId::new(workspace).unwrap(); + if native { + let mut service = LayoutService::new(registry.clone(), layout, before.capabilities.clone()).unwrap(); + apply_fixture( + &mut service, + vec![Mutation::Move { + instance: id("editor"), + destination: serde_json::from_value(panel_command_native_move()["destination"].clone()).unwrap(), + }], + ); + layout = service.layout().clone(); + } + let mut envelope = context_envelope_with_dormant_priority(layout); + let memory = &mut envelope.quarantine[0].instance_data["memory"]; + memory["section"] = serde_json::json!(reserved_section); + memory["column"] = serde_json::json!(reserved_column); + memory["column_width"] = serde_json::json!(280.0); + let mut recovery = preparation_context(&envelope) + .unwrap() + .extent_priorities + .records + .into_iter() + .find(|record| record.target == ExtentPriorityTarget::Memory(id("recovery-priority"))) + .unwrap(); + recovery.priority = rank; + envelope.extent_priority_overrides.push(recovery); + let context = preparation_context(&envelope).unwrap(); + assert!(context.sections.contains(§ion(reserved_section))); + assert!(context.columns.contains(&ColumnId::new(reserved_column).unwrap())); + contexts.push(context); + catalogue.remember(&envelope, None, ®istry).unwrap(); + } + assert_ne!(contexts[0].sections, contexts[1].sections); + assert_ne!(contexts[0].columns, contexts[1].columns); + assert_ne!(contexts[0].extent_priorities, contexts[1].extent_priorities); + let durable = std::rc::Rc::new(std::cell::RefCell::new(catalogue.state().clone())); + let prepared = std::rc::Rc::new(std::cell::Cell::new(0)); + let published = std::rc::Rc::new(std::cell::Cell::new(0)); + let mut counted = ContextDriftCatalogue { + incoming_source: catalogue.state().clone(), + inner: catalogue, + drift: false, + source_changed: false, + prepared: prepared.clone(), + published: published.clone(), + durable: durable.clone(), + }; + let steps = [ + serde_json::json!({"command":"layout.workspace.select","params":{"workspace":"fixture.other"}}), + serde_json::json!({"command":"layout.workspace.select","params":{"workspace":"review.final"}}), + serde_json::json!({"command":"layout.get"}), + ]; + let factories = trace.borrow().factories.len(); + let (reply, state, count, hosts, commits) = if admitted { + let native = std::rc::Rc::new(std::cell::RefCell::new(FakeNativeAdapter::new(true))); + let mut session = solidcraft_engine::Session::default(); + session.document_id = "fixture.document".into(); + let mut app = crate::SolveApp::new(session, Default::default()); + let doc = app.session.doc.clone(); + let model = app.session.model.state(); + let camera = app.cam; + let revision = app.session.revision; + let undo = app.session.undo.len(); + let dirty = app.session.is_dirty(); + app.enable_panel_runtime(h.runtime, Box::new(FakeAppPanelServices { models: FakeModels { editable: true }, ..Default::default() })) + .unwrap(); + app.panel_runtime_mut().unwrap().set_command_adapters(Box::new(counted), Box::new(SharedCommandNative(native.clone()))).unwrap(); + prepare_app_commands(&mut app); + let reply = app.run_panel_batch(&steps).unwrap(); + assert!(std::sync::Arc::ptr_eq(&app.session.doc, &doc)); + assert!(std::sync::Arc::ptr_eq(&app.session.model.state(), &model)); + assert_eq!(app.cam, camera); + assert_eq!(app.session.revision, revision); + assert_eq!(app.session.undo.len(), undo); + assert_eq!(app.session.is_dirty(), dirty); + let runtime = app.panel_runtime().unwrap(); + let adapter = native.borrow(); + (reply, runtime.layout().inspect(), runtime.controller_count(), adapter.hosts.clone(), adapter.commits) + } else { + let mut services = ContentServices { models: &h.models, commands: &mut h.commands, local: &mut h.local }; + let mut sink = RuntimeActionSink { runtime: &mut h.runtime, native: &mut h.native, services: &mut services }; + let reply = commands::execute_batch( + &steps, + &mut commands::PanelCommandContext { sink: &mut sink, registry: ®istry, catalogue: &mut counted, web: false }, + ) + .unwrap(); + (reply, h.runtime.layout().inspect(), h.runtime.controller_count(), h.native.hosts.clone(), h.native.commits) + }; + assert_eq!(reply["completed"], 3); + assert_eq!(state.revision, before.revision + 1); + assert_eq!(state.layout.workspace.0, "review.final"); + assert_eq!(prepared.get(), 1); + assert_eq!(published.get(), 1); + assert_eq!(commits, 1); + let saved = durable.borrow().remembered(&state.layout.workspace).unwrap().project_envelope(®istry, &state.layout.workspace).unwrap(); + let saved_context = preparation_context(&saved).unwrap(); + assert!(saved_context.sections.contains(§ion("incoming-b-reserved"))); + assert!(saved_context.columns.contains(&ColumnId::new("incoming-b-column").unwrap())); + assert_eq!( + saved_context + .extent_priorities + .records + .iter() + .find(|record| record.target == ExtentPriorityTarget::Memory(id("recovery-priority"))) + .unwrap() + .priority, + 47 + ); + assert_eq!(hosts.get(&HostId::new("native-host").unwrap()), Some(§ion("native"))); + assert_eq!(count, 3, "retain outgoing owners and publish only the final incoming workspace controller"); + assert_eq!(trace.borrow().factories.len(), factories + if admitted { 2 } else { 1 }); + for workspace in ["fixture.other", "review.final"] { + let owner = ControllerKey { instance: id("log"), owner: ContentOwner::Workspace(WorkspaceId::new(workspace).unwrap()) }; + let serials: Vec<_> = trace.borrow().factories.iter().filter(|(key, _)| *key == owner).map(|(_, serial)| *serial).collect(); + if workspace == "fixture.other" && !admitted { + assert!(serials.is_empty(), "headless planning creates only the final cohort"); + continue; + } + assert_eq!(serials.len(), 1, "each proposed owner is created once"); + let serial = serials[0]; + assert_eq!( + trace.borrow().measures.iter().filter(|measured| **measured == serial).count(), + 1, + "repeated projection/final dispatch reuse the staged provider" + ); + if workspace == "fixture.other" { + assert!(h.probe.state(&owner).is_err(), "intermediate owner never publishes"); + assert!(!trace.borrow().lifecycle.iter().any(|(identity, _)| *identity == serial)); + } else { + assert!(h.probe.state(&owner).unwrap().last_state.is_some()); + } + } + let after = h.probe.state(&key).unwrap(); + assert_eq!(after.draft, retained.draft); + assert!(after.transaction_live); + assert_eq!(after.reparents, retained.reparents + 1); + assert_eq!((after.cancels, after.reopens, after.destroys), (retained.cancels, retained.reopens, retained.destroys)); + outcomes.push((reply, state, durable.borrow().clone(), hosts)); + } + assert_eq!(outcomes[0], outcomes[1], "app admission and headless planning publish the same final envelope and native placement"); +} + +#[test] +fn captured_renderer_alpha_reaches_new_sections_and_alpha_only_drift_invalidates_owned_geometry() { + for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let (mut h, _, _) = boundary_app(); + h.app.ui.layout = mode; + h.frames(2); + let painted = h.app.universal_panel_frame().unwrap().layout.clone(); + let alpha = HostSurfaceAlpha { + docked: crate::ui_kit::panel_host_frame(&h.ctx, false).fill.a(), + floating: crate::ui_kit::panel_host_frame(&h.ctx, true).fill.a(), + }; + assert_eq!(painted.geometry_policy.surface_alpha, Some(alpha), "the actual app captures the shared renderer policy before allocation"); + assert!(painted.sections.iter().all(|card| card.paint_alpha == Some(alpha.docked))); + let gap = crate::ui_kit::Container::for_layout(mode, crate::ui_kit::Surface::Panel).gap(); + assert_eq!(gap, if mode == crate::shell::LayoutMode::Floating { 7.0 } else { 0.0 }); + assert_eq!(painted.metrics.gap, gap); + assert_eq!(painted.allocation_environment.gap, gap); + let domain = egui_rect(painted.render_domain); + let capacity = egui_rect(painted.capacity); + assert_eq!(h.app.shell.content, Some(domain)); + assert_eq!(painted.viewport, Some(painted.render_domain)); + assert_eq!(capacity.left(), domain.left() + gap); + assert_eq!(capacity.right(), domain.right() - gap); + assert_eq!(capacity.top(), h.app.shell.cards[1].bottom() + gap); + assert_eq!(capacity.bottom(), h.app.shell.status_bar.map_or(domain.bottom(), |bar| bar.top()) - gap); + + let before = h.app.panel_runtime().unwrap().layout().inspect(); + let doc = h.app.session.doc.clone(); + let model = h.app.session.model.state(); + let camera = h.app.cam; + let revision = h.app.session.revision; + let undo = h.app.session.undo.len(); + let dirty = h.app.session.is_dirty(); + let runtime = h.app.panel_runtime().unwrap(); + let service = runtime.layout(); + let environment = runtime.environment(); + let scope = + LocalScope { workspace: environment.workspace.clone(), document: environment.document.clone(), viewport: environment.viewport.clone() }; + // Reuse the analytic metrics fixture for not-yet-created content. The + // alpha and shell geometry above come from the real app preparation. + let mut policy = fixture_metric_policy(service); + policy.surface_alpha = painted.geometry_policy.surface_alpha; + let resolve = |policy: &HostGeometryPolicy| { + resolve_host_layout_in_domain( + service, + painted.render_domain, + painted.capacity, + &painted.chrome_obstacles, + painted.direction, + painted.metrics, + policy, + ) + .unwrap() + }; + let reference = resolve(&policy); + let action = transaction(vec![ + fixture_open("fixture.log", "alpha-dock", "alpha-dock", Zone::Right, 1).unwrap(), + Mutation::Open { + kind: PanelKind::new("fixture.log").unwrap(), + instance: id("alpha-float"), + destination: Some(Destination::NewSection { + section: section("alpha-float"), + index: 2, + location: SectionLocation::Floating { + origin: Point { x: painted.capacity.origin.x + 400.0, y: painted.capacity.origin.y + 80.0 }, + }, + size: Size { width: 280.0, height: 240.0 }, + }), + }, + ]); + let candidate = prepare_host_layout(service, &scope, &reference, action.clone()).unwrap(); + candidate.validate_current(service, &scope, &reference).unwrap(); + for (instance, expected) in [("alpha-dock", alpha.docked), ("alpha-float", alpha.floating)] { + assert!(reference.sections.iter().all(|card| card.instance != id(instance))); + assert_eq!(candidate.layout().sections.iter().find(|card| card.instance == id(instance)).unwrap().paint_alpha, Some(expected)); + } + let changed_alpha = HostSurfaceAlpha { docked: alpha.docked.wrapping_add(1), floating: alpha.floating.wrapping_add(2) }; + policy.surface_alpha = Some(changed_alpha); + let changed = resolve(&policy); + assert_eq!(candidate.validate_current(service, &scope, &changed).unwrap_err().rule, Rule::Revision); + assert_eq!(changed.controls, reference.controls, "alpha drift preserves widget identities and bounds"); + let mut restored = changed.clone(); + restored.geometry_policy.surface_alpha = Some(alpha); + for card in &mut restored.sections { + card.paint_alpha = Some(alpha.docked); + } + assert_eq!(restored, reference, "only captured fill alpha changed, including its section annotation"); + let revised = prepare_host_layout(service, &scope, &changed, action.clone()).unwrap(); + for (instance, expected) in [("alpha-dock", changed_alpha.docked), ("alpha-float", changed_alpha.floating)] { + let card = revised.layout().sections.iter().find(|card| card.instance == id(instance)).unwrap(); + let original = candidate.layout().sections.iter().find(|card| card.instance == id(instance)).unwrap(); + assert_eq!(card.paint_alpha, Some(expected)); + assert_eq!(card.surface, original.surface, "paint alpha does not rewrite surface intent"); + } + assert_eq!(HostGeometryPolicy::default().surface_alpha, None); + policy.surface_alpha = None; + let unknown = prepare_host_layout(service, &scope, &resolve(&policy), action).unwrap(); + assert!(unknown.layout().sections.iter().all(|card| card.paint_alpha.is_none()), "a renderer-free policy cannot claim a known alpha"); + assert_eq!(service.inspect(), before); + assert!(std::sync::Arc::ptr_eq(&h.app.session.doc, &doc)); + assert!(std::sync::Arc::ptr_eq(&h.app.session.model.state(), &model)); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.revision, revision); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(h.app.session.is_dirty(), dirty); + } +} diff --git a/crates/ui-egui/src/panel_runtime/workspace.rs b/crates/ui-egui/src/panel_runtime/workspace.rs new file mode 100644 index 000000000..011eeecb3 --- /dev/null +++ b/crates/ui-egui/src/panel_runtime/workspace.rs @@ -0,0 +1,2594 @@ +//! Shared opt-in workspace renderer. The only mutation path is the retained +//! runtime action sink; resolved geometry and drag previews are observational. +use std::collections::BTreeMap; + +use solidcraft_engine::panels::*; + +use super::runtime::{RuntimeHostProposal, standalone_header_action}; +use super::*; +use crate::ui_kit::{self, HostChrome}; + +// Raw input plus per-control focus, gesture and command outcomes, with room for +// pass diagnostics. Repeated passes replace a snapshot rather than growing it. +const MAX_HOST_FRAME_OUTCOMES: usize = 4096 + 3 * (MAX_INSTANCES + MAX_SECTIONS * (MAX_HEADER_ACTIONS + 8)) + 2; + +/// The command executor stages the injected catalogue before dispatch takes +/// this exact proposal. No reducer, allocator or controller factory runs here. +fn commit_catalogued_proposal( + runtime: &mut PanelRuntime, + proposal: RuntimeHostProposal, + native: &mut dyn NativeHostAdapter, + services: &mut ContentServices<'_>, + catalogue: &mut dyn commands::LayoutCatalogue, +) -> PanelResult { + let action = proposal.action().clone(); + let registry = runtime.layout().registry().clone(); + let mut sink = RetainedCandidateSink { runtime, native, services, proposal: Some(proposal) }; + commands::execute_layout_action( + action, + &mut commands::PanelCommandContext { sink: &mut sink, registry: ®istry, catalogue, web: cfg!(target_arch = "wasm32") }, + ) +} +fn commit_registered_action( + runtime: &mut PanelRuntime, + action: LayoutAction, + native: &mut dyn NativeHostAdapter, + services: &mut ContentServices<'_>, + catalogue: &mut dyn commands::LayoutCatalogue, +) -> PanelResult { + let registry = runtime.layout().registry().clone(); + let mut sink = RuntimeActionSink { runtime, native, services }; + // The shared executor dispatches this standalone owner action before any + // catalogue access. Its runtime sink still validates the owning binding. + commands::execute_layout_action( + action, + &mut commands::PanelCommandContext { sink: &mut sink, registry: ®istry, catalogue, web: cfg!(target_arch = "wasm32") }, + ) +} +struct RetainedCandidateSink<'a, 'services> { + runtime: &'a mut PanelRuntime, + native: &'a mut dyn NativeHostAdapter, + services: &'a mut ContentServices<'services>, + proposal: Option, +} +impl ActionSink for RetainedCandidateSink<'_, '_> { + fn project_in_context(&self, action: LayoutAction, context: &LayoutPreparationContext) -> PanelResult { + self.proposal.as_ref().ok_or_else(|| error(Rule::Revision, "host proposal already consumed"))?.validate_preparation_context(context)?; + self.project(action) + } + fn dispatch_in_context(&mut self, action: LayoutAction, context: &LayoutPreparationContext) -> PanelResult { + self.project_in_context(action.clone(), context)?; + self.dispatch(action) + } + fn inspect(&self) -> LayoutReply { + super::runtime::normalize_native_reply(self.runtime.layout().inspect(), &self.native.capabilities()) + } + fn project(&self, action: LayoutAction) -> PanelResult { + let proposal = self.proposal.as_ref().ok_or_else(|| error(Rule::Revision, "host proposal already consumed"))?; + if proposal.action() != &action { + return Err(error(Rule::Revision, "host proposal intent changed")); + } + proposal.validate_captured(self.runtime, self.services.models)?; + Ok(proposal.layout().clone()) + } + fn dispatch(&mut self, action: LayoutAction) -> PanelResult { + self.project(action)?; + let proposal = self.proposal.take().ok_or_else(|| error(Rule::Revision, "host proposal already consumed"))?; + let reply = self.runtime.commit_host_proposal(proposal, self.native, self.services)?; + Ok(super::runtime::normalize_native_reply(reply, &self.native.capabilities())) + } +} + +#[derive(Clone, Debug)] +pub struct HostOptions { + pub metrics: HostMetrics, + pub geometry: HostGeometryPolicy, + /// Content toolbar space, separate from the shared title and tabs. The + /// content/body split may fit transiently within the bounded outer host. + pub content_header_height: f32, +} +impl Default for HostOptions { + fn default() -> Self { + Self { + metrics: HostMetrics { inline_max_height: crate::theme::PANEL_INLINE_MAX_HEIGHT, ..HostMetrics::default() }, + geometry: HostGeometryPolicy::default(), + content_header_height: crate::theme::Tokens::get().control_height, + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum HostSharedAction { + Focus, + Close, + Collapse, + Move(Zone), + Join(SectionId), + Popout, +} +impl std::hash::Hash for HostSharedAction { + fn hash(&self, state: &mut H) { + std::mem::discriminant(self).hash(state); + match self { + Self::Move(zone) => (*zone as u8).hash(state), + Self::Join(section) => section.hash(state), + _ => {} + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum HostControlTarget { + Pointer(HostPointerTarget), + Shared { instance: InstanceId, action: HostSharedAction }, + Content { instance: InstanceId, action: ControlId }, + PanelMenu { instance: InstanceId }, + Scroll { horizontal: bool }, +} + +#[derive(Clone, Debug)] +pub struct HostFrameControl { + pub id: egui::Id, + pub target: HostControlTarget, + pub bounds: LogicalRect, + pub role: InputRole, + pub accessible_name: String, + pub enabled: bool, +} + +#[derive(Clone, Debug)] +pub enum HostEvent { + Regions { + scope: LocalScope, + revision: u64, + painted: Vec, + input: Vec, + occlusion: Vec, + reservations: Vec, + }, + Committed { + action: LayoutAction, + reply: LayoutReply, + }, + PreparedCommitted { + reply: LayoutReply, + }, + Rejected { + action: Option, + error: PanelError, + }, + ContentAction { + instance: InstanceId, + action: ControlId, + result: PanelResult<()>, + }, + Focus { + target: HostControlTarget, + }, +} + +/// `layout`/controls describe what was actually painted in this pass. `reply` +/// always describes the authoritative post-dispatch state. A successful change +/// also exposes `next_layout`; repaint is requested immediately, without drawing +/// content twice or inventing widgets at unpainted coordinates. +#[derive(Clone, Debug)] +pub struct HostFrame { + pub layout: HostLayout, + pub controls: Vec, + pub events: Vec, + pub preview: Option, + pub reply: LayoutReply, + pub next_layout: Option, + pub menu_bounds: Option, + pub owned_overlays: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +enum HostMenu { + Panel(InstanceId), + Tabs(SectionId), +} + +enum HostCommand { + Layout(LayoutAction), + Prepared(Box), + Scroll { horizontal: bool, offset: f32, source: egui::Id }, + WidgetLayout(LayoutAction, egui::Id), + Content(InstanceId, ControlId, egui::Id), + OpenMenu { menu: HostMenu, anchor: LogicalRect, source: egui::Id, secondary: bool }, +} + +struct PendingHostCommands { + scope: LocalScope, + window: HostId, + frame_number: u64, + allow_actions: bool, + commands: Vec, + pointer_events: Vec<(egui::Id, HostPointerEvent)>, + mount: PanelResult<()>, +} + +#[derive(Clone)] +struct RegisteredOverlay { + region: InputRegion, + layer: Option, +} + +pub struct WorkspacePanelHost { + options: HostOptions, + native_capabilities: HostCapabilities, + interaction: HostInteraction, + frame: Option, + // Executed outcomes survive geometry invalidation only within this egui + // frame. Regions and provisional candidates never enter the journal. + outcome_frame: Option, + outcomes: Vec, + scope: Option<(LocalScope, HostId)>, + menu: Option, + menu_anchor: Option, + last_input_frame: Option, + last_mount_frame: Option, + last_mount_revision: Option, + preview_started: Option, + pending_escape: bool, + last_rejection: Option, + overlays: BTreeMap>, + observed_focus: Option, + focus_request: Option, + egui_context: Option, + owned_focus: Option, + pending: Option, + last_capacity: Option, + last_domain: Option, + last_chrome: Vec, +} + +impl WorkspacePanelHost { + pub(crate) fn set_gap(&mut self, gap: f32) -> PanelResult<()> { + let metrics = HostMetrics { gap, ..self.options.metrics }; + metrics.validate()?; + if metrics != self.options.metrics { + self.invalidate_geometry(); + self.options.metrics = metrics; + } + Ok(()) + } + + pub fn new(options: HostOptions) -> PanelResult { + options.metrics.validate()?; + if !options.content_header_height.is_finite() || options.content_header_height < 0.0 || options.content_header_height > 256.0 { + return Err(error(Rule::Bounds, "invalid content header extent")); + } + if options.geometry.effective_surfaces.len() > MAX_SECTIONS { + return Err(error(Rule::CollectionLimit, "effective surface policy bound")); + } + for section in options.geometry.effective_surfaces.keys() { + valid_id(§ion.0)?; + } + // Declarative transparency/contrast policy belongs to the surface peer. + // Appearance follows the existing adaptive Container, including its fill + // alpha; this guard does not force an opaque paint override. + if !options.geometry.default_opaque || options.geometry.effective_surfaces.values().any(|surface| *surface == PanelSurface::Translucent) { + return Err(error(Rule::Capability, "translucent host requires the surface renderer")); + } + Ok(Self { + options, + native_capabilities: HostCapabilities::default(), + interaction: HostInteraction::default(), + frame: None, + outcome_frame: None, + outcomes: Vec::new(), + scope: None, + menu: None, + menu_anchor: None, + last_input_frame: None, + last_mount_frame: None, + last_mount_revision: None, + preview_started: None, + pending_escape: false, + last_rejection: None, + overlays: BTreeMap::new(), + observed_focus: None, + focus_request: None, + egui_context: None, + owned_focus: None, + pending: None, + last_capacity: None, + last_domain: None, + last_chrome: Vec::new(), + }) + } + pub fn frame(&self) -> Option<&HostFrame> { + self.frame.as_ref() + } + // A pass copies this snapshot without consuming it. The next frame (or + // context teardown) expires it even if no HostFrame geometry remains. + fn renew_outcomes(&mut self, frame_number: u64) { + if self.outcome_frame != Some(frame_number) { + self.outcomes.clear(); + self.outcome_frame = Some(frame_number); + } + } + pub(crate) fn note_native_capabilities(&mut self, capabilities: HostCapabilities) { + self.native_capabilities = capabilities; + } + pub(crate) fn capture_metrics(&mut self, runtime: &PanelRuntime, models: &dyn PanelModels) -> PanelResult<()> { + let metrics = runtime.capture_metrics(models)?; + if self.options.geometry.measure.as_ref().is_some_and(|old| old.revision() == metrics.revision()) { + return Ok(()); + } + if self.options.geometry.measure.as_ref().is_some_and(|old| old.revision() != metrics.revision()) { + self.invalidate_geometry(); + } + self.options.geometry.content_revision = metrics.revision(); + self.options.geometry.measure = Some(metrics); + self.options.geometry.content.clear(); + Ok(()) + } + /// Programmatic changes use the exact allocator and admission of gestures. + /// No host or captured environment means no structural admission. + pub(crate) fn command_reference(&self, runtime: &PanelRuntime) -> PanelResult { + let (domain, capacity, chrome) = if let Some(frame) = &self.frame { + (frame.layout.render_domain, frame.layout.capacity, frame.layout.chrome_obstacles.as_slice()) + } else { + ( + self.last_domain.ok_or_else(|| error(Rule::Availability, "panel host environment is not prepared"))?, + self.last_capacity.ok_or_else(|| error(Rule::Availability, "panel host environment is not prepared"))?, + self.last_chrome.as_slice(), + ) + }; + resolve_frame_layout(runtime, domain, capacity, chrome, &self.options) + } + /// Capture the injected catalogue's full envelope, including opaque/dormant + /// reservations, before either widget or pointer identity generation. + pub(crate) fn capture_reservations(&mut self, runtime: &PanelRuntime, catalogue: &dyn commands::LayoutCatalogue) -> PanelResult<()> { + let service = runtime.layout(); + let envelope = commands::current_envelope_snapshot(catalogue, &service.inspect(), service.registry())?; + let mut reservations = host_identity_reservations(&envelope)?; + reservations.include_layout(service.layout())?; + if self.options.geometry.identity_reservations != reservations { + self.invalidate_geometry(); + self.options.geometry.identity_reservations = reservations; + } + Ok(()) + } + pub(crate) fn cancel_gesture(&mut self) { + if self.interaction.move_source().is_some() + && let Some(ctx) = &self.egui_context + { + ctx.request_repaint(); + } + self.interaction.cancel(); + self.pending = None; + if let Some(frame) = &mut self.frame { + frame.preview = None; + } + } + pub fn interaction(&self) -> &HostInteraction { + &self.interaction + } + pub(crate) fn has_pending(&self) -> bool { + self.pending.is_some() + } + pub(crate) fn prepared_geometry(&self) -> Option<(LogicalRect, LogicalRect, Vec)> { + Some((self.last_domain?, self.last_capacity?, self.last_chrome.clone())) + } + pub(crate) fn wants_escape(&self, runtime: &PanelRuntime) -> bool { + let _ = runtime; + self.interaction.is_captured() || self.menu.is_some() + } + pub(crate) fn request_escape(&mut self) { + self.pending_escape = true; + } + /// Discard geometry and provisional input without tearing down an eligible + /// editor's keyboard focus or retained egui caret/selection state. + pub(crate) fn invalidate_geometry(&mut self) { + if self.interaction.move_source().is_some() + && let Some(ctx) = &self.egui_context + { + ctx.request_repaint(); + } + self.interaction.cancel(); + self.pending = None; + self.frame = None; + self.menu = None; + self.menu_anchor = None; + self.overlays.clear(); + self.preview_started = None; + self.pending_escape = false; + self.focus_request = None; + self.last_mount_frame = None; + self.last_mount_revision = None; + } + /// Owner/scope loss and application hiding also release owned keyboard input. + pub(crate) fn invalidate_context(&mut self) { + self.invalidate_geometry(); + self.outcomes.clear(); + self.outcome_frame = None; + if let (Some(ctx), Some(focused)) = (&self.egui_context, self.owned_focus.take()) { + ctx.memory_mut(|memory| memory.surrender_focus(focused)); + } + } + pub(crate) fn reconcile_scope(&mut self, runtime: &PanelRuntime) { + let identity = (runtime_scope(runtime), runtime.environment().window.clone()); + if self.scope.as_ref() != Some(&identity) { + let replacing_owner = self.scope.is_some(); + self.invalidate_context(); + self.last_rejection = None; + if replacing_owner { + self.observed_focus = runtime.layout().interaction().focused.clone(); + } + self.scope = Some(identity); + } + } + pub(crate) fn note_reply(&mut self, reply: &LayoutReply) { + for effect in &reply.effects { + if let HostEffect::Focus { instance } = effect { + self.focus_request = Some(instance.clone()); + } + } + } + /// App ticks/programmatic forwarding use the same overlay ledger as render + /// and pointer dispatch, so background cleanup cannot leave stale input. + pub(crate) fn with_local_services( + &mut self, + scope: &LocalScope, + services: &mut ContentServices<'_>, + use_services: impl FnOnce(&mut ContentServices<'_>) -> R, + ) -> R { + let capacity = self + .frame + .as_ref() + .map_or(LogicalRect { origin: Point { x: 0.0, y: 0.0 }, size: Size { width: 0.0, height: 0.0 } }, |frame| frame.layout.capacity); + with_local_tracking(services, scope, capacity, &mut self.overlays, use_services) + } + pub(crate) fn with_command_services( + &mut self, + scope: &LocalScope, + services: &mut ContentServices<'_>, + use_services: impl FnOnce(&mut Self, &mut ContentServices<'_>) -> R, + ) -> R { + let capacity = self + .frame + .as_ref() + .map_or(LogicalRect { origin: Point { x: 0.0, y: 0.0 }, size: Size { width: 0.0, height: 0.0 } }, |frame| frame.layout.capacity); + let mut overlays = std::mem::take(&mut self.overlays); + let result = with_local_tracking(services, scope, capacity, &mut overlays, |services| use_services(self, services)); + self.overlays = overlays; + result + } + pub fn prepare(&mut self, runtime: &PanelRuntime, capacity: LogicalRect) -> PanelResult<()> { + self.prepare_in_domain(runtime, capacity, capacity, &[]) + } + + pub(crate) fn note_egui_context(&mut self, ctx: &egui::Context) { + self.egui_context = Some(ctx.clone()); + let surface_alpha = + Some(HostSurfaceAlpha { docked: ui_kit::panel_host_frame(ctx, false).fill.a(), floating: ui_kit::panel_host_frame(ctx, true).fill.a() }); + if self.options.geometry.surface_alpha != surface_alpha { + self.invalidate_geometry(); + self.options.geometry.surface_alpha = surface_alpha; + } + } + + pub fn prepare_in_domain( + &mut self, + runtime: &PanelRuntime, + render_domain: LogicalRect, + capacity: LogicalRect, + chrome: &[LogicalRect], + ) -> PanelResult<()> { + self.reconcile_scope(runtime); + if let Some(frame_number) = self.egui_context.as_ref().map(egui::Context::cumulative_frame_nr) { + self.renew_outcomes(frame_number); + } + let mut layout = match resolve_frame_layout(runtime, render_domain, capacity, chrome, &self.options) { + Ok(layout) => layout, + Err(reason) => { + if self.interaction.move_source().is_some() + && let Some(ctx) = &self.egui_context + { + ctx.request_repaint(); + } + self.last_capacity = None; + self.last_domain = None; + self.last_chrome.clear(); + self.frame = None; + self.interaction.cancel(); + self.menu = None; + self.menu_anchor = None; + self.overlays.clear(); + return Err(reason); + } + }; + let mut unmeasured_instances = Vec::new(); + // Predict only the kit's forced invisible Area measurement pass before + // scene navigation runs. Retain intended sections/resolved mount geometry. + for section in &layout.sections { + if !(section.peek || section.zone == Zone::Floating) { + continue; + } + let area = section_surface_id(&runtime_scope(runtime), &runtime.environment().window, §ion.section).with("area"); + let measured = + self.egui_context.as_ref().is_some_and(|ctx| egui::containers::AreaState::load(ctx, area).is_some_and(|state| state.size.is_some())); + if !measured { + unmeasured_instances.push(section.instance.clone()); + layout.controls.retain(|control| match &control.target { + HostPointerTarget::Header { instance } + | HostPointerTarget::Surface { instance } + | HostPointerTarget::Menu { instance } + | HostPointerTarget::Collapse { instance } + | HostPointerTarget::Close { instance } + | HostPointerTarget::HeaderAction { instance, .. } => *instance != section.instance, + HostPointerTarget::Tab { instance } => !section.tabs.iter().any(|tab| tab.instance == *instance), + HostPointerTarget::Resize { section: id, .. } | HostPointerTarget::TabOverflow { section: id } => *id != section.section, + _ => true, + }); + let clipped = logical_rect(egui_rect(section.outer).intersect(egui_rect(capacity))); + for regions in [&mut layout.painted, &mut layout.input, &mut layout.occlusion] { + if let Some(index) = regions.iter().position(|rect| *rect == clipped) { + regions.remove(index); + } + } + } + } + layout.reservations = layout.painted.clone(); + let obstacles: Vec<_> = layout.chrome_obstacles.iter().chain(&layout.painted).copied().collect(); + layout.usable = resolve_usable_region(layout.render_domain, &obstacles)?; + self.overlays.retain(|instance, _| layout.resolved.panels.iter().any(|panel| panel.instance == *instance)); + self.last_capacity = Some(capacity); + self.last_domain = Some(render_domain); + self.last_chrome = chrome.to_vec(); + let preview = self.frame.as_ref().and_then(|frame| frame.preview.clone()); + self.frame = Some(HostFrame { + layout, + controls: Vec::new(), + events: self.outcomes.clone(), + preview, + reply: super::runtime::normalize_native_reply(runtime.layout().inspect(), &self.native_capabilities), + next_layout: None, + menu_bounds: None, + owned_overlays: overlay_regions(&self.overlays, self.egui_context.as_ref(), &unmeasured_instances), + }); + Ok(()) + } + + /// Mount the complete in-app set, including an empty set. Repeated egui + /// passes at the same revision repaint without another reconciliation. A + /// new committed revision must reconcile before painting its new content. + pub fn show( + &mut self, + ui: &mut egui::Ui, + runtime: &mut PanelRuntime, + native: &mut dyn NativeHostAdapter, + services: &mut ContentServices<'_>, + catalogue: &mut dyn commands::LayoutCatalogue, + ) -> PanelResult<()> { + let painted = self.show_deferred(ui, runtime, native, services); + let finished = self.finish(ui, runtime, native, services, catalogue); + painted.and(finished) + } + + /// Paint/mount now; the embedding app calls finish AFTER its other windows + /// and modals have registered their actual layers and widget responses. + pub fn show_deferred( + &mut self, + ui: &mut egui::Ui, + runtime: &mut PanelRuntime, + native: &mut dyn NativeHostAdapter, + services: &mut ContentServices<'_>, + ) -> PanelResult<()> { + if !ui.is_visible() || ui.is_sizing_pass() { + self.invalidate_context(); + return runtime.mount_in_app(&ResolvedLayout::default(), &mut EmptyPanelHost, services); + } + self.note_native_capabilities(native.capabilities()); + let frame_number = ui.ctx().cumulative_frame_nr(); + self.renew_outcomes(frame_number); + let Some(mut frame) = self.frame.take() else { + return Err(error(Rule::Lifecycle, "prepare host geometry before painting")); + }; + frame.reply.capabilities = runtime.layout().inspect().capabilities; + frame.reply = super::runtime::normalize_native_reply(frame.reply, &self.native_capabilities); + self.egui_context = Some(ui.ctx().clone()); + let allow_actions = self.last_input_frame != Some(frame_number) && ui.is_enabled(); + frame.events.clone_from(&self.outcomes); + frame.controls.clear(); + frame.menu_bounds = None; + // Resolve each pass, including the pass after an invisible Area sizing + // pass. Actual paint/input arrays below may have omitted sizing areas; + // intended geometry must be restored before the next attempt to paint. + if frame.layout.revision != runtime.layout().inspect().revision { + frame.reply = super::runtime::normalize_native_reply(runtime.layout().inspect(), &self.native_capabilities); + } + frame.layout = + resolve_frame_layout(runtime, frame.layout.render_domain, frame.layout.capacity, &frame.layout.chrome_obstacles, &self.options)?; + let scope = runtime_scope(runtime); + let window = runtime.environment().window.clone(); + let locale = crate::i18n::Locale::for_language(crate::i18n::language()); + let _resolved_labels = crate::i18n::resolved_labels(); + let mut metadata = BTreeMap::new(); + let mut owners = BTreeMap::new(); + let mut header_icons = BTreeMap::new(); + for instance in &runtime.layout().layout().instances { + if let Ok(value) = runtime.instance_presentation(&instance.id) { + metadata.insert(instance.id.clone(), value); + } + if let Ok(owner) = runtime.instance_owner(&instance.id) { + owners.insert(instance.id.clone(), owner); + } + for action in &runtime.layout().registry().get(&instance.kind)?.header_actions { + header_icons.insert((instance.id.clone(), action.id.clone()), action.icon.clone()); + } + } + for control in &frame.layout.controls { + let target = HostControlTarget::Pointer(control.target.clone()); + let instance = pointer_instance(&control.target); + let name = if matches!(&control.target, HostPointerTarget::Collapse { instance } + if runtime.layout().layout().containing(instance).is_ok_and(|section| section.collapsed)) + { + locale.text("ui.panel_host.expand").to_owned() + } else { + chrome_label(&control.target, &control.accessible_name, &metadata, locale) + }; + let binding_enabled = match &control.target { + HostPointerTarget::HeaderAction { instance, action } => metadata + .get(instance) + .is_some_and(|presentation| presentation.actions.iter().any(|binding| binding.id == *action && binding.enabled)), + HostPointerTarget::Close { instance } => runtime + .layout() + .layout() + .instance(instance) + .and_then(|panel| runtime.layout().registry().get(&panel.kind)) + .is_ok_and(|spec| spec.features.closable), + HostPointerTarget::Collapse { instance } => runtime.layout().layout().containing(instance).is_ok_and(|section| { + section.tabs.iter().all(|id| { + runtime + .layout() + .layout() + .instance(id) + .and_then(|panel| runtime.layout().registry().get(&panel.kind)) + .is_ok_and(|spec| spec.features.collapsible) + }) + }), + _ => true, + }; + let enabled = ui.is_enabled() + && binding_enabled + && (instance.is_none_or(|id| runtime.layout().availability(id) == Availability::Available) + || matches!(&control.target, HostPointerTarget::Menu { .. })); + frame.controls.push(HostFrameControl { + id: control_id(runtime, &owners, &target), + target, + bounds: control.bounds, + role: control.role, + accessible_name: name, + enabled, + }); + } + let focused = runtime.layout().interaction().focused.clone(); + if focused != self.observed_focus { + self.focus_request = focused.clone(); + self.observed_focus = focused; + } + let mut commands = Vec::new(); + let mut pointer_events = Vec::new(); + let mut unpainted = Vec::new(); + let mut renderer = WorkspaceContentHost { + ui, + layout: &frame.layout, + move_source: self.interaction.move_source(), + controls: &mut frame.controls, + metadata: &metadata, + header_icons: &header_icons, + scope: &scope, + window: &window, + owned_focus: &mut self.owned_focus, + commands: &mut commands, + allow_actions, + unpainted: &mut unpainted, + }; + let mut overlays = std::mem::take(&mut self.overlays); + let reconcile = self.last_mount_frame != Some(frame_number) || self.last_mount_revision != Some(frame.layout.revision); + if reconcile { + self.last_mount_frame = Some(frame_number); + self.last_mount_revision = Some(frame.layout.revision); + } + let mount = with_local_tracking(services, &scope, frame.layout.capacity, &mut overlays, |services| { + if reconcile { + runtime.mount_in_app(&frame.layout.resolved, &mut renderer, services) + } else { + runtime.repaint_in_app(&frame.layout.resolved, &mut renderer, services) + } + }); + // An Area's first sizing pass is invisible and non-interactable. Keep + // the intended resolved geometry, but never publish it as actual paint + // or an input/occlusion shield, even if no further egui pass is allowed. + let mut unpainted_instances = Vec::new(); + for (layer, bounds) in &unpainted { + let hidden_sections: Vec<_> = frame + .layout + .sections + .iter() + .filter(|section| section_surface_id(&scope, &window, §ion.section).with("area") == layer.id) + .collect(); + let hidden_instances: Vec<_> = hidden_sections + .iter() + .flat_map(|section| std::iter::once(section.instance.clone()).chain(section.tabs.iter().map(|tab| tab.instance.clone()))) + .collect(); + unpainted_instances.extend(hidden_instances.iter().cloned()); + let clipped = logical_rect(egui_rect(*bounds).intersect(egui_rect(frame.layout.capacity))); + // Remove one occurrence: a visible card can occupy the same rect. + for regions in [&mut frame.layout.painted, &mut frame.layout.input, &mut frame.layout.occlusion] { + if let Some(index) = regions.iter().position(|rect| *rect == clipped) { + regions.remove(index); + } + } + let hidden: Vec<_> = frame + .controls + .iter() + .filter(|control| { + let owned = match &control.target { + HostControlTarget::Pointer(pointer) => { + pointer_instance(pointer).is_some_and(|instance| hidden_instances.contains(instance)) + || matches!(pointer, HostPointerTarget::Resize { section, .. } | HostPointerTarget::TabOverflow { section } + if hidden_sections.iter().any(|hidden| hidden.section == *section)) + } + _ => false, + }; + owned || ui.ctx().read_response(control.id).is_some_and(|response| response.layer_id == *layer) + }) + .map(|control| control.target.clone()) + .collect(); + for target in &hidden { + if let HostControlTarget::Pointer(HostPointerTarget::Surface { instance }) = target { + unpainted_instances.push(instance.clone()); + } + } + frame.layout.controls.retain(|control| !hidden.contains(&HostControlTarget::Pointer(control.target.clone()))); + frame.controls.retain(|control| !hidden.contains(&control.target)); + } + if !unpainted_instances.is_empty() { + let mut actual = frame.layout.resolved.clone(); + actual.panels.retain(|panel| !unpainted_instances.contains(&panel.instance)); + with_local_tracking(services, &scope, frame.layout.capacity, &mut overlays, |services| { + runtime.reconcile_in_app_presentation(&actual, services.local); + }); + } + frame.owned_overlays = overlay_regions(&overlays, Some(ui.ctx()), &unpainted_instances); + self.paint_scrollbars(ui, &scope, &window, &mut frame, &mut commands, allow_actions); + // Usable space follows this pass's actual card/chrome footprints. Popup + // input remains separate and never becomes a camera framing target. + let obstacles: Vec<_> = frame.layout.chrome_obstacles.iter().chain(&frame.layout.painted).copied().collect(); + frame.layout.reservations = frame.layout.painted.clone(); + frame.layout.usable = resolve_usable_region(frame.layout.render_domain, &obstacles)?; + // Rails, dock sashes and overflow exist even with no mounted content. + // Section resize widgets are painted on their card's own layer. + self.paint_remaining(ui, runtime, &metadata, &mut frame, &mut commands, &mut pointer_events, allow_actions, locale); + if let Some(instance) = self.focus_request.as_ref().filter(|_| ui.is_enabled() && !ui_kit::Container::modal_input_blocked(ui.ctx())) { + if runtime.layout().layout().containing(instance).is_ok_and(|section| section.location.zone() == Zone::Window) { + self.focus_request = None; + } else { + // A first Area sizing pass has no actual enabled Header. Keep + // the typed request until its visible widget exists; animation + // opacity never delays this focus transfer. + let actual = + |control: &&HostFrameControl| control.enabled && ui.ctx().read_response(control.id).is_some_and(|response| response.enabled()); + let target = frame.controls.iter().filter(actual).find(|control| matches!(&control.target, HostControlTarget::Pointer(HostPointerTarget::Header { instance: id }) if id == instance)) + .or_else(|| frame.controls.iter().filter(actual).find(|control| matches!(&control.target, HostControlTarget::Pointer(HostPointerTarget::Tab { instance: id }) if id == instance))) + .or_else(|| frame.controls.iter().filter(actual).find(|control| control.target == HostControlTarget::Pointer(HostPointerTarget::OverflowAll))); + if let Some(control) = target { + ui.memory_mut(|memory| memory.request_focus(control.id)); + self.focus_request = None; + } + } + } + self.paint_menu(ui, runtime, native.capabilities(), &metadata, &owners, &mut frame, &mut commands, allow_actions, locale); + self.pending = Some(PendingHostCommands { scope, window, frame_number, allow_actions, commands, pointer_events, mount: mount.clone() }); + self.overlays = overlays; + self.frame = Some(frame); + mount + } + + pub fn finish( + &mut self, + ui: &mut egui::Ui, + runtime: &mut PanelRuntime, + native: &mut dyn NativeHostAdapter, + services: &mut ContentServices<'_>, + catalogue: &mut dyn commands::LayoutCatalogue, + ) -> PanelResult<()> { + self.note_native_capabilities(native.capabilities()); + let Some(pending) = self.pending.take() else { + return Ok(()); + }; + // Chrome has already painted this pass. Threshold/cancellation changes + // need another paint even when there is no admitted landing to animate. + let painted_move_source = self.interaction.move_source().cloned(); + if pending.scope != runtime_scope(runtime) + || pending.window != runtime.environment().window + || pending.frame_number != ui.ctx().cumulative_frame_nr() + { + self.invalidate_context(); + ui.ctx().request_repaint(); + return Err(error(Rule::Placement, "host context changed after paint")); + } + self.capture_metrics(runtime, services.models)?; + self.capture_reservations(runtime, catalogue)?; + let PendingHostCommands { scope, frame_number, allow_actions, mut commands, mut pointer_events, mount, .. } = pending; + let Some(mut frame) = self.frame.take() else { + ui.ctx().request_repaint(); + return Ok(()); + }; + frame.reply.capabilities = runtime.layout().inspect().capabilities; + frame.reply = super::runtime::normalize_native_reply(frame.reply, &self.native_capabilities); + let stale = frame.layout.revision != runtime.layout().inspect().revision; + if stale { + self.interaction.cancel(); + commands.clear(); + pointer_events.clear(); + frame.preview = None; + frame.reply = super::runtime::normalize_native_reply(runtime.layout().inspect(), &self.native_capabilities); + frame.next_layout = + resolve_frame_layout(runtime, frame.layout.render_domain, frame.layout.capacity, &frame.layout.chrome_obstacles, &self.options).ok(); + let reason = error(Rule::Revision, "host layout changed after paint"); + if !frame.events.iter().any(|event| matches!(event, HostEvent::Rejected { action: None, error } if error == &reason)) { + frame.events.push(HostEvent::Rejected { action: None, error: reason }); + } + ui.ctx().request_repaint(); + } + let hard_modal = ui_kit::Container::modal_input_blocked(ui.ctx()); + if hard_modal { + // Modal backdrops own the entire input context, including points + // outside the card and releases from an earlier host capture. + // This is not a content lifecycle or layout/peek mutation. + self.interaction.cancel(); + frame.preview = None; + commands.clear(); + pointer_events.clear(); + self.menu = None; + self.menu_anchor = None; + self.pending_escape = false; + self.preview_started = None; + self.focus_request = None; + self.last_input_frame = Some(frame_number); + let owned = self.owned_focus.take(); + ui.memory_mut(|memory| { + if let Some(focused) = memory.focused() + && (owned == Some(focused) || frame.controls.iter().any(|control| control.id == focused)) + { + memory.surrender_focus(focused); + } + }); + // Report what this pass painted; remove private menu/preview state + // on the next paint without changing viewport reservations. + ui.ctx().request_repaint(); + } + let allow_actions = + allow_actions && !stale && mount.is_ok() && ui.is_enabled() && ui.is_visible() && ui.input(|input| input.focused) && !hard_modal; + let dismiss_menu = self.pending_escape || ui.input(|input| input.key_pressed(egui::Key::Escape)); + if mount.is_err() { + commands.clear(); + self.interaction.cancel(); + frame.preview = None; + } + if allow_actions { + self.last_input_frame = Some(frame_number); + if self.scroll_from_wheel(ui, &frame) { + self.interaction.cancel(); + frame.preview = None; + commands.clear(); + pointer_events.clear(); + ui.ctx().request_repaint(); + } + if commands.iter().any(|command| { + matches!( + command, + HostCommand::Layout(_) | HostCommand::WidgetLayout(_, _) | HostCommand::Content(_, _, _) | HostCommand::Scroll { .. } + ) + }) { + self.interaction.cancel(); + frame.preview = None; + pointer_events.clear(); + } + self.pointer_input(ui, runtime, &scope, &mut frame, &mut commands, pointer_events); + for control in &frame.controls { + if ui.ctx().read_response(control.id).is_some_and(|response| response.has_focus() && response.gained_focus()) { + self.owned_focus = Some(control.id); + frame.events.push(HostEvent::Focus { target: control.target.clone() }); + } + } + } else if !ui.is_enabled() || !ui.is_visible() || !ui.input(|input| input.focused) { + self.interaction.cancel(); + frame.preview = None; + } + if let Some(preview) = &frame.preview + && preview.rejection.is_none() + && preview.projected.is_some() + { + let now = ui.input(|input| input.time); + let started = *self.preview_started.get_or_insert(now); + let duration = if runtime.environment().motion == Motion::Reduced || ui.style().animation_time <= 0.0 { + 0.0 + } else { + ui.style().animation_time.clamp(0.12, 0.16) + }; + let progress = if duration <= 0.0 { 1.0 } else { ((now - started) as f32 / duration).clamp(0.0, 1.0) }; + let opacity = 1.0 - (1.0 - progress).powi(3); + if let Some(projected) = &preview.projected { + for section in &projected.sections { + if section.outer != preview.bounds + && frame + .layout + .sections + .iter() + .find(|before| before.section == section.section) + .is_none_or(|before| before.outer != section.outer) + { + ui_kit::panel_host_neighbour_preview(ui, egui_rect(section.outer), false, opacity); + } + } + for section in &frame.layout.sections { + if !projected.sections.iter().any(|after| after.section == section.section) { + ui_kit::panel_host_neighbour_preview(ui, egui_rect(section.outer), true, opacity); + } + } + } + ui_kit::panel_host_preview(ui, egui_rect(preview.bounds), true, None, opacity); + if let Some(marker) = preview.tab_marker { + ui_kit::panel_host_tab_insertion(ui, egui_rect(marker), opacity); + } + if progress < 1.0 { + ui.ctx().request_repaint(); + } + } else { + self.preview_started = None; + } + if let Err(reason) = &mount + && !frame.events.iter().any(|event| matches!(event, HostEvent::Rejected { action: None, error } if error == reason)) + { + frame.events.push(HostEvent::Rejected { action: None, error: reason.clone() }); + } + // Dispatch AFTER painting, with the same provider/native adapter that + // created the retained runtime. No content is recreated for this borrow. + let mut overlays = std::mem::take(&mut self.overlays); + let mut accepted = Vec::new(); + let mut dismiss_popup_peek = false; + for command in commands { + let (command, source) = match command { + HostCommand::WidgetLayout(action, source) => { + if !owns_widget_action(ui.ctx(), source) { + continue; + } + (HostCommand::Layout(action), Some(source)) + } + HostCommand::Content(instance, action, source) => { + if !owns_widget_action(ui.ctx(), source) { + continue; + } + (HostCommand::Content(instance, action, source), Some(source)) + } + HostCommand::Scroll { horizontal, offset, source } => { + if !owns_widget_action(ui.ctx(), source) + && !ui.ctx().read_response(source).is_some_and(|response| response.enabled() && response.dragged()) + && !owns_focused_action(ui.ctx(), source) + { + continue; + } + (HostCommand::Scroll { horizontal, offset, source }, Some(source)) + } + HostCommand::OpenMenu { menu, anchor, source, secondary } => { + if !allow_actions || dismiss_menu || !owns_menu_action(ui.ctx(), source, secondary) { + continue; + } + (HostCommand::OpenMenu { menu, anchor, source, secondary }, Some(source)) + } + other => (other, None), + }; + dismiss_popup_peek |= source.is_some_and(|source| self.popup_action_dismisses_peek(runtime, &frame, ui.ctx(), source)); + accepted.push(command); + } + if dismiss_popup_peek + && !accepted.iter().any(|command| { + matches!(command, + HostCommand::Layout(action) if standalone_header_action(action)) + }) + { + // Preserve an unrelated popup through press so its actual row can + // complete its click. Dismiss on the accepted activation, atomically + // with the first structural Apply; never merge unrelated actions. + if let Some(mutations) = accepted.iter_mut().find_map(|command| match command { + HostCommand::Layout(LayoutAction::Apply { mutations, .. }) => Some(mutations), + _ => None, + }) { + if !mutations.contains(&Mutation::DismissPeek) { + mutations.insert(0, Mutation::DismissPeek); + } + } else { + accepted.insert(0, HostCommand::Layout(apply_action(frame.layout.revision, vec![Mutation::DismissPeek]))); + } + } + let mut sent_layout = false; + for command in accepted { + match command { + HostCommand::Scroll { horizontal, offset, .. } => { + if horizontal { + self.options.geometry.scroll.x = offset; + } else { + self.options.geometry.scroll.y = offset; + } + self.interaction.cancel(); + frame.preview = None; + ui.ctx().request_repaint(); + } + HostCommand::Prepared(candidate) if !sent_layout => { + sent_layout = true; + let result = with_local_tracking(services, &scope, frame.layout.capacity, &mut overlays, |services| { + let proposal = runtime.retain_host_candidate(*candidate, frame.layout.clone(), services.models)?; + commit_catalogued_proposal(runtime, proposal, native, services, catalogue) + }); + match result { + Ok(reply) => { + let reply = super::runtime::normalize_native_reply(reply, &self.native_capabilities); + self.note_reply(&reply); + frame.events.push(HostEvent::PreparedCommitted { reply: reply.clone() }); + frame.reply = reply; + self.last_rejection = None; + self.menu = None; + self.menu_anchor = None; + frame.next_layout = resolve_frame_layout( + runtime, + frame.layout.render_domain, + frame.layout.capacity, + &frame.layout.chrome_obstacles, + &self.options, + ) + .ok(); + ui.ctx().request_repaint(); + } + Err(reason) => { + self.last_rejection = Some(reason.clone()); + frame.events.push(HostEvent::Rejected { action: None, error: reason }); + } + } + self.interaction.cancel(); + frame.preview = None; + } + HostCommand::Layout(action) if !sent_layout => { + sent_layout = true; + let result: PanelResult = with_local_tracking(services, &scope, frame.layout.capacity, &mut overlays, |services| { + let reply = if standalone_header_action(&action) { + commit_registered_action(runtime, action.clone(), native, services, catalogue)? + } else { + let proposal = runtime.prepare_host_proposal(frame.layout.clone(), action.clone(), services.models)?; + commit_catalogued_proposal(runtime, proposal, native, services, catalogue)? + }; + Ok(super::runtime::normalize_native_reply(reply, &self.native_capabilities)) + }); + match result { + Ok(reply) => { + self.last_rejection = None; + for effect in &reply.effects { + if let HostEffect::Focus { instance } = effect { + self.focus_request = Some(instance.clone()); + } + } + frame.events.push(HostEvent::Committed { action, reply: reply.clone() }); + frame.reply = reply; + self.menu = None; + self.menu_anchor = None; + self.interaction.cancel(); + frame.preview = None; + frame.next_layout = resolve_frame_layout( + runtime, + frame.layout.render_domain, + frame.layout.capacity, + &frame.layout.chrome_obstacles, + &self.options, + ) + .ok(); + ui.ctx().request_repaint(); + } + Err(reason) => { + self.last_rejection = Some(reason.clone()); + if let Some(preview) = &mut frame.preview { + preview.rejection = Some(reason.clone()); + preview.action = None; + } + frame.events.push(HostEvent::Rejected { action: Some(action), error: reason }); + frame.reply = super::runtime::normalize_native_reply(runtime.layout().inspect(), &self.native_capabilities); + self.interaction.cancel(); + } + } + } + HostCommand::Content(instance, action, _) => { + let result = with_local_tracking(services, &scope, frame.layout.capacity, &mut overlays, |services| { + runtime.content_action(&instance, &action, services) + }); + if let Err(reason) = &result { + self.last_rejection = Some(reason.clone()); + } + frame.events.push(HostEvent::ContentAction { instance, action, result }); + } + HostCommand::OpenMenu { menu, anchor, source, secondary } => { + if allow_actions && !dismiss_menu && owns_menu_action(ui.ctx(), source, secondary) { + self.menu = Some(menu); + self.menu_anchor = Some(anchor); + // This pass still reports only the menu actually painted. + ui.ctx().request_repaint(); + } + } + HostCommand::Layout(_) | HostCommand::WidgetLayout(_, _) | HostCommand::Prepared(_) => {} + } + } + if painted_move_source.as_ref() != self.interaction.move_source() { + ui.ctx().request_repaint(); + } + if let (Some(instance), Some(at)) = (self.interaction.move_source(), self.interaction.move_position()) + && let Ok(presentation) = runtime.instance_presentation(instance) + { + ui_kit::panel_host_drag_title( + ui, + &presentation.title, + egui::pos2(at.x, at.y), + egui_rect(frame.layout.render_domain), + frame.layout.direction == Direction::Rtl, + ); + } + let input = self.input_rects(&frame); + let occlusion = self.occlusion_rects(&frame); + frame.events.retain(|event| !matches!(event, HostEvent::Regions { .. })); + frame.events.truncate(MAX_HOST_FRAME_OUTCOMES); + // Replace the complete frame outcome snapshot; never append the copy + // restored by show_deferred. Publish only this pass's Regions below. + self.outcomes.clone_from(&frame.events); + frame.events.insert( + 0, + HostEvent::Regions { + scope, + revision: frame.layout.revision, + painted: frame + .layout + .painted + .iter() + .copied() + .chain(frame.menu_bounds) + .chain(frame.owned_overlays.iter().map(|region| region.bounds)) + .collect(), + input, + occlusion, + reservations: frame.layout.reservations.clone(), + }, + ); + self.overlays = overlays; + self.frame = Some(frame); + mount + } + + fn input_rects(&self, frame: &HostFrame) -> Vec { + frame.layout.input.iter().copied().chain(frame.menu_bounds).chain(frame.owned_overlays.iter().map(|region| region.bounds)).collect() + } + + fn popup_action_dismisses_peek(&self, runtime: &PanelRuntime, frame: &HostFrame, ctx: &egui::Context, source: egui::Id) -> bool { + let Some(peek) = runtime.layout().interaction().peek.as_ref() else { + return false; + }; + let Ok(peek_section) = runtime.layout().layout().containing(peek) else { + return false; + }; + let protects = match self.menu.as_ref() { + Some(HostMenu::Panel(instance)) => runtime.layout().layout().containing(instance).is_ok_and(|section| section.id == peek_section.id), + Some(HostMenu::Tabs(section)) => *section == peek_section.id, + None => return false, + }; + if protects { + return false; + } + let Some(control) = frame.controls.iter().find(|control| control.id == source) else { + return false; + }; + if !frame.menu_bounds.is_some_and(|bounds| bounds.contains_rect(control.bounds)) { + return false; + } + let at = ctx + .read_response(source) + .and_then(|response| { + (response.clicked_by(egui::PointerButton::Primary) || response.secondary_clicked()).then(|| response.interact_pointer_pos()).flatten() + }) + .map_or_else(|| center(control.bounds), point); + !frame.layout.sections.iter().any(|section| section.peek && section.instance == *peek && section.outer.contains(at)) + && !frame.layout.rails.iter().any(|rail| rail.bounds.contains(at)) + } + fn occlusion_rects(&self, frame: &HostFrame) -> Vec { + frame.layout.occlusion.iter().copied().chain(frame.menu_bounds).chain(frame.owned_overlays.iter().map(|region| region.bounds)).collect() + } + + #[allow(clippy::too_many_arguments)] + fn scroll_from_wheel(&mut self, ui: &egui::Ui, frame: &HostFrame) -> bool { + if self.menu.is_some() { + return false; + } + let maximum = egui::vec2( + (frame.layout.extent.width - frame.layout.capacity.size.width).max(0.0), + (frame.layout.extent.height - frame.layout.capacity.size.height).max(0.0), + ); + if maximum == egui::Vec2::ZERO { + return false; + } + let hovered = ui.input(|input| input.pointer.hover_pos()).is_some_and(|position| { + frame.controls.iter().filter(|control| matches!(&control.target, HostControlTarget::Pointer(HostPointerTarget::Surface { .. }))).any( + |control| { + control.enabled + && egui_rect(control.bounds).contains(position) + && ui.ctx().read_response(control.id).is_some_and(|response| { + response.enabled() + && response.interact_rect.contains(position) + && owns_current_layer_at(ui.ctx(), response.layer_id, position) + }) + }, + ) + }); + if !hovered { + return false; + } + let previous = self.options.geometry.scroll; + let next = crate::navigation::panel_scroll_offset(ui.ctx(), egui::vec2(previous.x, previous.y), maximum); + self.options.geometry.scroll = Point { x: next.x, y: next.y }; + previous != self.options.geometry.scroll + } + + fn paint_scrollbars( + &self, + ui: &mut egui::Ui, + scope: &LocalScope, + window: &HostId, + frame: &mut HostFrame, + commands: &mut Vec, + allow_actions: bool, + ) { + for (horizontal, bounds) in scroll_tracks(&frame.layout) { + let target = HostControlTarget::Scroll { horizontal }; + let id = scoped_id(scope, window, None, &target); + let label = crate::i18n::tr(if horizontal { "ui.panel_host.scroll_horizontal" } else { "ui.panel_host.scroll_vertical" }); + let (visible, total, offset) = if horizontal { + (frame.layout.capacity.size.width, frame.layout.extent.width, frame.layout.allocation_environment.scroll.x) + } else { + (frame.layout.capacity.size.height, frame.layout.extent.height, frame.layout.allocation_environment.scroll.y) + }; + let (response, next) = ui_kit::panel_host_scrollbar(ui, id, egui_rect(bounds), horizontal, visible, total, offset, label); + record_control(frame, &response, target, label, true, ui.clip_rect()); + if allow_actions && let Some(offset) = next { + commands.push(HostCommand::Scroll { horizontal, offset, source: response.id }); + } + } + } + + fn paint_remaining( + &self, + ui: &mut egui::Ui, + _runtime: &PanelRuntime, + _metadata: &BTreeMap, + frame: &mut HostFrame, + _commands: &mut Vec, + pointer_events: &mut Vec<(egui::Id, HostPointerEvent)>, + allow_actions: bool, + _locale: crate::i18n::Locale, + ) { + for control in &frame.controls { + let HostControlTarget::Pointer(target @ HostPointerTarget::Sash { .. }) = &control.target else { + continue; + }; + let response = ui_kit::panel_host_sash(ui, control.id, egui_rect(control.bounds), &control.accessible_name); + if allow_actions && response.double_clicked() { + pointer_events.push((response.id, HostPointerEvent::DoubleClick { target: target.clone() })); + } + if allow_actions && response.has_focus() && !response.dragged() { + let horizontal = control.bounds.size.height > control.bounds.size.width; + let delta = ui.input_mut(|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.consume_key(egui::Modifiers::NONE, forward)) as f32 + - u8::from(input.consume_key(egui::Modifiers::NONE, back)) as f32 + }); + if delta != 0.0 { + let at = center(control.bounds); + let step = crate::theme::Tokens::get().space_8.max(HOST_DRAG_THRESHOLD); + let end = Point { x: at.x + if horizontal { delta * step } else { 0.0 }, y: at.y + if horizontal { 0.0 } else { delta * step } }; + for event in [ + HostPointerEvent::Press { at, target: Some(target.clone()) }, + HostPointerEvent::Move { at: end }, + HostPointerEvent::Release { at: end }, + ] { + pointer_events.push((response.id, event)); + } + } + } + } + } + fn pointer_input( + &mut self, + ui: &egui::Ui, + runtime: &PanelRuntime, + scope: &LocalScope, + frame: &mut HostFrame, + commands: &mut Vec, + extra: Vec<(egui::Id, HostPointerEvent)>, + ) { + let raw = ui.input(|input| input.events.iter().take(4097).cloned().collect::>()); + if raw.len() > 4096 { + self.interaction.cancel(); + frame.preview = None; + commands.clear(); + frame.events.push(HostEvent::Rejected { action: None, error: error(Rule::CollectionLimit, "host input event limit") }); + return; + } + let mut events = Vec::new(); + // egui reports end-of-frame button state. Recover the state before the + // first raw button transition so a real release frame can still commit. + // PointerGone itself preserves egui's held buttons. + let mut primary_down = raw + .iter() + .find_map(|event| match event { + egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed, .. } => Some(!*pressed), + _ => None, + }) + .unwrap_or_else(|| ui.input(|input| input.pointer.primary_down())); + if self.interaction.is_captured() && !primary_down { + events.push(HostPointerEvent::Cancel); + } + let reserved_escape = std::mem::take(&mut self.pending_escape); + if reserved_escape { + if !self.interaction.is_captured() && self.menu.is_some() { + self.menu = None; + self.menu_anchor = None; + } else { + events.push(HostPointerEvent::Escape); + } + } + for event in raw.into_iter().take(4096) { + match event { + egui::Event::Key { key: egui::Key::Escape, pressed: true, .. } => { + if reserved_escape { + continue; + } + if !self.interaction.is_captured() && self.menu.is_some() { + self.menu = None; + self.menu_anchor = None; + } else { + events.push(HostPointerEvent::Escape); + } + } + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, .. } => { + primary_down = pressed; + let at = point(pos); + if pressed { + let in_menu = frame.menu_bounds.is_some_and(|bounds| bounds.contains(at)); + let in_owned_overlay = + runtime.layout().interaction().peek.as_ref().and_then(|peek| self.overlays.get(peek)).is_some_and(|regions| { + regions.iter().any(|entry| frame.owned_overlays.contains(&entry.region) && entry.region.bounds.contains(at)) + }); + let other_overlay_press = !ui_kit::Container::modal_input_blocked(ui.ctx()) + && self.overlays.iter().any(|(instance, entries)| { + runtime.layout().interaction().peek.as_ref() != Some(instance) + && entries.iter().any(|entry| { + entry.region.bounds.contains(at) + && frame.owned_overlays.contains(&entry.region) + && entry.layer.is_some_and(|layer| { + current_area_contains(ui.ctx(), layer, pos) && owns_current_layer_at(ui.ctx(), layer, pos) + }) + }) + }); + let geometric_target = frame.layout.hit_test(at); + let target = geometric_target.as_ref().and_then(|target| { + frame + .controls + .iter() + .find(|control| control.enabled && control.target == HostControlTarget::Pointer(target.clone())) + .filter(|control| owns_primary_press(ui.ctx(), control.id, pos)) + .map(|_| target.clone()) + }); + // A body leaf (e.g. TextEdit) owns its press instead of + // the enclosing Surface response. Its actual card layer + // still owns outside-dismissal, without becoming a drag + // source or consuming/retargeting the leaf's input. + let body_press = matches!(&geometric_target, Some(HostPointerTarget::Surface { .. })) + && geometric_target.as_ref().is_some_and(|pointer| { + frame.controls.iter().any(|control| { + control.enabled + && control.target == HostControlTarget::Pointer(pointer.clone()) + && ui.ctx().read_response(control.id).is_some_and(|response| { + response.enabled() + && response.interact_rect.contains(pos) + && owns_current_layer_at(ui.ctx(), response.layer_id, pos) + }) + }) + }); + let content_control = frame.controls.iter().rev().any(|control| { + control.enabled + && control.bounds.contains(at) + && matches!(&control.target, HostControlTarget::Content { .. }) + && owns_primary_press(ui.ctx(), control.id, pos) + }); + if in_owned_overlay { + events.push(HostPointerEvent::OutsidePress { at, inside_owned_overlay: true }); + } else if !in_menu || other_overlay_press { + // A foreign widget/window owns covered geometry. It + // must not begin a drag or dismiss peek underneath. + if geometric_target.is_some() && target.is_none() && !content_control && !body_press && !other_overlay_press { + continue; + } + if target.is_none() + && !body_press + && !content_control + && !other_overlay_press + && !owns_current_layer_at(ui.ctx(), ui.layer_id(), pos) + { + continue; + } + if self.menu.is_some() { + self.menu = None; + self.menu_anchor = None; + } + if body_press || content_control || other_overlay_press { + events.push(HostPointerEvent::OutsidePress { at, inside_owned_overlay: false }); + } else if target.is_some() { + events.push(HostPointerEvent::Press { at, target }); + } else { + events.push(HostPointerEvent::OutsidePress { at, inside_owned_overlay: false }); + } + } + } else { + events.push(HostPointerEvent::Release { at }); + } + } + egui::Event::PointerMoved(pos) => events.push(HostPointerEvent::Move { at: point(pos) }), + egui::Event::PointerGone => events.push(if primary_down { HostPointerEvent::Leave } else { HostPointerEvent::Cancel }), + egui::Event::WindowFocused(false) => events.push(HostPointerEvent::Cancel), + _ => {} + } + } + // Validate a captured scope/revision/source even when the pointer stands + // still. Pointer cancellation must never depend on receiving another drag. + if events.is_empty() && self.interaction.is_captured() { + events.push(HostPointerEvent::Reconcile); + } + // Widget-derived gestures are provisional until all later windows have + // painted, just like menu and content actions. Existing raw captures + // retain their independent Move/Release routing above. + events.extend( + extra + .into_iter() + .filter(|(source, _)| owns_widget_action(ui.ctx(), *source) || owns_focused_action(ui.ctx(), *source)) + .map(|(_, event)| event), + ); + for event in events { + let update = self.interaction.update(runtime.layout(), scope, &frame.layout, event); + frame.preview = update.preview; + if let Some(candidate) = update.candidate { + commands.push(HostCommand::Prepared(Box::new(candidate))); + } + if let Some(error) = update.rejection { + frame.events.push(HostEvent::Rejected { action: None, error }); + } + } + } +} + +pub(crate) fn runtime_scope(runtime: &PanelRuntime) -> LocalScope { + let environment = runtime.environment(); + LocalScope { workspace: environment.workspace.clone(), document: environment.document.clone(), viewport: environment.viewport.clone() } +} + +fn overlay_regions(overlays: &BTreeMap>, ctx: Option<&egui::Context>, hidden: &[InstanceId]) -> Vec { + overlays + .iter() + .filter(|(instance, _)| !hidden.contains(instance)) + .flat_map(|(_, entries)| entries.iter()) + .filter(|entry| { + entry.layer.is_none_or(|layer| { + ctx.is_some_and(|ctx| { + let bounds = egui_rect(entry.region.bounds); + current_area_contains(ctx, layer, bounds.center()) + && egui::containers::AreaState::load(ctx, layer.id).is_some_and(|state| { + ctx.layer_transform_to_global(layer).map_or(state.rect(), |transform| transform * state.rect()).contains_rect(bounds) + }) + }) + }) + }) + .map(|entry| entry.region.clone()) + .collect() +} + +/// Observe accepted local overlay requests while forwarding to the exact same +/// injected local provider. This is routing metadata, never a second service or +/// a guess based on popup titles/egui IDs. Lifecycle release clears the record. +struct HostLocalBridge<'a> { + inner: &'a mut dyn PanelLocalServices, + scope: &'a LocalScope, + capacity: LogicalRect, + overlays: &'a mut BTreeMap>, +} + +impl HostLocalBridge<'_> { + fn prepare_overlay( + &self, + scope: &LocalScope, + instance: &InstanceId, + region: &InputRegion, + layer: Option, + ) -> PanelResult> { + LocalRequest::Overlay { instance: instance.clone(), region: region.clone() }.validate()?; + if scope != self.scope { + return Ok(None); + } + if !self.capacity.contains_rect(region.bounds) { + return Err(error(Rule::Bounds, "panel overlay outside workspace")); + } + let entries = self.overlays.get(instance); + if entries.is_none() && self.overlays.len() >= MAX_INSTANCES { + return Err(error(Rule::CollectionLimit, "panel overlay owner limit")); + } + if entries.is_some_and(|entries| entries.len() >= MAX_TABS && !entries.iter().any(|entry| entry.region.control == region.control)) { + return Err(error(Rule::CollectionLimit, "panel overlay limit")); + } + Ok(Some(RegisteredOverlay { region: region.clone(), layer })) + } + + fn record_overlay(&mut self, instance: &InstanceId, overlay: RegisteredOverlay) { + let entries = self.overlays.entry(instance.clone()).or_default(); + if let Some(entry) = entries.iter_mut().find(|entry| entry.region.control == overlay.region.control) { + *entry = overlay; + } else { + entries.push(overlay); + } + } +} + +impl PanelLocalServices for HostLocalBridge<'_> { + fn request(&mut self, scope: &LocalScope, request: LocalRequest) -> PanelResult<()> { + request.validate()?; + let overlay = if let LocalRequest::Overlay { instance, region } = &request { + self.prepare_overlay(scope, instance, region, None)?.map(|overlay| (instance.clone(), overlay)) + } else { + None + }; + let clear = if let LocalRequest::ClearOverlays { instance } = &request { Some(instance.clone()) } else { None }; + self.inner.request(scope, request)?; + if scope == self.scope { + if let Some(instance) = clear { + self.overlays.remove(&instance); + } + if let Some((instance, overlay)) = overlay { + self.record_overlay(&instance, overlay); + } + } + Ok(()) + } + fn request_overlay_layer(&mut self, scope: &LocalScope, instance: &InstanceId, region: InputRegion, layer: egui::LayerId) -> PanelResult<()> { + let overlay = self.prepare_overlay(scope, instance, ®ion, Some(layer))?; + self.inner.request_overlay_layer(scope, instance, region, layer)?; + if let Some(overlay) = overlay { + self.record_overlay(instance, overlay); + } + Ok(()) + } + fn release(&mut self, scope: &LocalScope, instance: &InstanceId) { + self.inner.release(scope, instance); + if scope == self.scope { + self.overlays.remove(instance); + } + } +} + +fn with_local_tracking( + services: &mut ContentServices<'_>, + scope: &LocalScope, + capacity: LogicalRect, + overlays: &mut BTreeMap>, + use_services: impl FnOnce(&mut ContentServices<'_>) -> R, +) -> R { + let mut local = HostLocalBridge { inner: &mut *services.local, scope, capacity, overlays }; + let mut adapted = ContentServices { models: services.models, commands: &mut *services.commands, local: &mut local }; + use_services(&mut adapted) +} + +fn pointer_instance(target: &HostPointerTarget) -> Option<&InstanceId> { + match target { + HostPointerTarget::Header { instance } + | HostPointerTarget::Tab { instance } + | HostPointerTarget::Rail { instance } + | HostPointerTarget::Surface { instance } + | HostPointerTarget::Collapse { instance } + | HostPointerTarget::Close { instance } + | HostPointerTarget::HeaderAction { instance, .. } + | HostPointerTarget::Menu { instance } => Some(instance), + _ => None, + } +} + +fn chrome_label( + target: &HostPointerTarget, + fallback: &str, + metadata: &BTreeMap, + locale: crate::i18n::Locale, +) -> String { + match target { + HostPointerTarget::Menu { .. } => locale.text("ui.panel_host.menu").to_owned(), + HostPointerTarget::Collapse { .. } => locale.text(fallback).to_owned(), + HostPointerTarget::Close { .. } => locale.text("ui.panel_host.close").to_owned(), + HostPointerTarget::HeaderAction { instance, action } => metadata + .get(instance) + .and_then(|presentation| presentation.actions.iter().find(|binding| binding.id == *action)) + .map_or_else(|| locale.text(fallback).to_owned(), |binding| binding.label.clone()), + HostPointerTarget::TabOverflow { .. } => locale.text("ui.panel_host.tabs").to_owned(), + _ => pointer_instance(target) + .and_then(|instance| metadata.get(instance)) + .map_or_else(|| locale.text(fallback).to_owned(), |presentation| presentation.title.clone()), + } +} + +/// Geometry selects a candidate, but egui decides who actually owns a press. +/// Release/Move for an existing host capture intentionally do not use this gate. +fn owns_current_layer_at(ctx: &egui::Context, source: egui::LayerId, at: egui::Pos2) -> bool { + let Some(raised) = ui_kit::Container::current_layer_raises(ctx) else { + return false; + }; + // egui stable-sorts (Order, was-raised) at end_pass. A returning Area raises + // itself; explicit application raises go through the shared Container seam. + // Two raised layers retain their previous relative order, not call order. + let (source_returning, source_rank, candidates) = ctx.memory(|memory| { + let source_rank = memory.layer_ids().position(|layer| layer == source); + ( + !memory.areas().visible_last_frame(&source), + source_rank, + memory + .layer_ids() + .enumerate() + .filter_map(|(rank, layer)| { + (layer != source && layer.order >= source.order).then_some((layer, rank, !memory.areas().visible_last_frame(&layer))) + }) + .collect::>(), + ) + }); + let source_raised = raised.contains(&source) || source_returning && current_area_contains(ctx, source, at); + !candidates.into_iter().any(|(layer, rank, returning)| { + // A stale prior-frame Area, a noninteractive overlay or an invisible + // sizing pass cannot shield input. Bounds include the layer transform. + if !current_area_contains(ctx, layer, at) { + return false; + } + if layer.order > source.order { + return true; + } + let candidate_raised = raised.contains(&layer) || returning; + match (candidate_raised, source_raised) { + (true, false) => true, + (false, true) => false, + // Read stored pair order directly. A stale third Area can mask + // both candidates in layer_id_at, but cannot change their ranks. + _ => source_rank.is_none_or(|source_rank| rank > source_rank), + } + }) +} + +fn current_area_contains(ctx: &egui::Context, layer: egui::LayerId, at: egui::Pos2) -> bool { + if !ctx.graphics(|graphics| { + graphics.get(layer).is_some_and(|paint| { + paint.all_entries().any(|entry| { + // Native backing reserves a Noop before deciding whether its Area is shown. + let bounds = (entry.transform_after_tessellation * entry.shape.visual_bounding_rect()).intersect(entry.clip_rect); + bounds.is_positive() && bounds.is_finite() + }) + }) + }) { + return false; + } + egui::containers::AreaState::load(ctx, layer.id).is_some_and(|state| { + let bounds = ctx.layer_transform_to_global(layer).map_or(state.rect(), |transform| transform * state.rect()); + state.interactable && bounds.contains(at) + }) +} + +fn owns_primary_press(ctx: &egui::Context, id: egui::Id, at: egui::Pos2) -> bool { + ctx.read_response(id).is_some_and(|response| { + response.enabled() + && response.interact_rect.contains(at) + && owns_current_layer_at(ctx, response.layer_id, at) + && (response.is_pointer_button_down_on() + || response.clicked_by(egui::PointerButton::Primary) + || response.drag_started_by(egui::PointerButton::Primary) + || response.dragged_by(egui::PointerButton::Primary) + || response.drag_stopped_by(egui::PointerButton::Primary)) + }) +} + +fn owns_widget_action(ctx: &egui::Context, id: egui::Id) -> bool { + ctx.read_response(id).is_some_and(|response| { + if !response.enabled() { + return false; + } + if !response.clicked_by(egui::PointerButton::Primary) { + return response.clicked() && ctx.memory(|memory| memory.focused()) == Some(id); + } + response + .interact_pointer_pos() + .or_else(|| ctx.input(|input| input.pointer.interact_pos())) + .is_some_and(|at| owns_current_layer_at(ctx, response.layer_id, at)) + }) +} + +fn owns_focused_action(ctx: &egui::Context, id: egui::Id) -> bool { + ctx.memory(|memory| memory.focused()) == Some(id) + && ctx.read_response(id).is_some_and(|response| response.enabled() && response.interact_rect.is_positive()) +} + +fn owns_menu_action(ctx: &egui::Context, id: egui::Id, secondary: bool) -> bool { + if !secondary { + return owns_widget_action(ctx, id); + } + ctx.read_response(id).is_some_and(|response| { + response.enabled() + && response.secondary_clicked() + && response + .interact_pointer_pos() + .or_else(|| ctx.input(|input| input.pointer.interact_pos())) + .is_some_and(|at| response.interact_rect.contains(at) && owns_current_layer_at(ctx, response.layer_id, at)) + }) +} + +fn section_surface_id(scope: &LocalScope, window: &HostId, section: &SectionId) -> egui::Id { + egui::Id::unique(("universal_panel_section", &scope.workspace, &scope.document, &scope.viewport, window, section)) +} + +fn scoped_id(scope: &LocalScope, window: &HostId, owner: Option<&ContentOwner>, target: &HostControlTarget) -> egui::Id { + egui::Id::unique(("universal_panel_host", &scope.workspace, &scope.document, &scope.viewport, window, owner, target)) +} +fn control_id(runtime: &PanelRuntime, owners: &BTreeMap, target: &HostControlTarget) -> egui::Id { + let instance = match target { + HostControlTarget::Pointer(pointer) => pointer_instance(pointer), + HostControlTarget::Shared { instance, .. } | HostControlTarget::Content { instance, .. } | HostControlTarget::PanelMenu { instance } => { + Some(instance) + } + HostControlTarget::Scroll { .. } => None, + }; + scoped_id(&runtime_scope(runtime), &runtime.environment().window, instance.and_then(|id| owners.get(id)), target) +} +pub(crate) fn egui_rect(rect: LogicalRect) -> egui::Rect { + egui::Rect::from_min_size(egui::pos2(rect.origin.x, rect.origin.y), egui::vec2(rect.size.width, rect.size.height)) +} +pub(crate) fn logical_rect(rect: egui::Rect) -> LogicalRect { + LogicalRect { origin: point(rect.min), size: Size { width: rect.width(), height: rect.height() } } +} +fn point(at: egui::Pos2) -> Point { + Point { x: at.x, y: at.y } +} +fn center(rect: LogicalRect) -> Point { + Point { x: rect.origin.x + rect.size.width / 2.0, y: rect.origin.y + rect.size.height / 2.0 } +} + +pub(crate) struct EmptyPanelHost; +impl PanelHost for EmptyPanelHost { + fn mount( + &mut self, + _geometry: &ResolvedPanel, + _presentation: &PanelPresentation, + _context: &PanelContext, + _content: &mut dyn PanelController, + _services: &mut ContentServices<'_>, + ) -> PanelResult<()> { + Err(error(Rule::Placement, "empty host cannot mount content")) + } +} + +fn rule_key(rule: Rule) -> &'static str { + match rule { + Rule::Availability => "ui.panel_host.rule.availability", + Rule::Bounds => "ui.panel_host.rule.bounds", + Rule::NoSpace => "ui.panel_host.rule.no_space", + Rule::Capability => "ui.panel_host.rule.capability", + Rule::CollectionLimit => "ui.panel_host.rule.collection_limit", + Rule::DuplicateId => "ui.panel_host.rule.duplicate_id", + Rule::ExactlyOnce => "ui.panel_host.rule.exactly_once", + Rule::FeatureDisabled => "ui.panel_host.rule.feature_disabled", + Rule::Id => "ui.panel_host.rule.id", + Rule::IncompatibleTabs => "ui.panel_host.rule.incompatible_tabs", + Rule::Lifecycle => "ui.panel_host.rule.lifecycle", + Rule::MissingTarget => "ui.panel_host.rule.missing_target", + Rule::PinConflict => "ui.panel_host.rule.pin_conflict", + Rule::PinOrder => "ui.panel_host.rule.pin_order", + Rule::Placement => "ui.panel_host.rule.placement", + Rule::Revision => "ui.panel_host.rule.revision", + Rule::Schema => "ui.panel_host.rule.schema", + Rule::Version => "ui.panel_host.rule.version", + } +} + +struct WorkspaceContentHost<'a> { + ui: &'a mut egui::Ui, + layout: &'a HostLayout, + move_source: Option<&'a InstanceId>, + controls: &'a mut Vec, + metadata: &'a BTreeMap, + header_icons: &'a BTreeMap<(InstanceId, ControlId), String>, + scope: &'a LocalScope, + window: &'a HostId, + owned_focus: &'a mut Option, + commands: &'a mut Vec, + allow_actions: bool, + unpainted: &'a mut Vec<(egui::LayerId, LogicalRect)>, +} + +impl PanelHost for WorkspaceContentHost<'_> { + fn mount( + &mut self, + geometry: &ResolvedPanel, + presentation: &PanelPresentation, + context: &PanelContext, + content: &mut dyn PanelController, + services: &mut ContentServices<'_>, + ) -> PanelResult<()> { + geometry.validate()?; + presentation.validate()?; + context.validate()?; + if geometry.instance != context.instance || geometry.outer != context.outer || geometry.body != context.usable_body { + return Err(error(Rule::Placement, "content context differs from resolved host")); + } + if geometry.painted.is_empty() { + return Ok(()); + } + let section = self + .layout + .sections + .iter() + .find(|section| section.instance == geometry.instance) + .ok_or_else(|| error(Rule::MissingTarget, "resolved section metadata missing"))?; + let surface_target = HostControlTarget::Pointer(HostPointerTarget::Surface { instance: geometry.instance.clone() }); + let surface_id = scoped_id(self.scope, self.window, Some(&context.owner), &surface_target); + let mut failure = None; + ui_kit::panel_host_surface( + self.ui, + section_surface_id(self.scope, self.window, §ion.section), + egui_rect(section.outer), + section.peek || section.zone == Zone::Floating, + |ui, content_clip| { + if (section.peek || section.zone == Zone::Floating) && (!ui.is_visible() || ui.is_sizing_pass()) { + self.unpainted.push((ui.layer_id(), section.outer)); + return; + } + // A surface response provides semantic focus and owns only the actual + // painted card; child controls retain their own accessible responses. + let response = ui.interact(egui_rect(section.outer), surface_id, egui::Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Unknown, ui.is_enabled(), &presentation.title)); + for control in self.controls.iter() { + let HostControlTarget::Pointer(target) = &control.target else { + continue; + }; + let belongs = match target { + HostPointerTarget::Header { instance } + | HostPointerTarget::Menu { instance } + | HostPointerTarget::Collapse { instance } + | HostPointerTarget::Close { instance } + | HostPointerTarget::HeaderAction { instance, .. } => *instance == section.instance, + HostPointerTarget::Tab { instance } => section.tabs.iter().any(|tab| tab.instance == *instance), + HostPointerTarget::TabOverflow { section: id } => *id == section.section, + _ => false, + }; + if !belongs { + continue; + } + let data = pointer_instance(target).and_then(|instance| self.metadata.get(instance)); + let label = &control.accessible_name; + let response = if matches!(target, HostPointerTarget::Collapse { .. }) { + ui_kit::panel_host_disclosure(ui, control.id, egui_rect(control.bounds), label, control.enabled, section.collapsed) + } else { + ui_kit::panel_host_control_label_opacity( + ui, + control.id, + egui_rect(control.bounds), + HostChrome { + label, + icon: if matches!(target, HostPointerTarget::Menu { .. }) { + Some("dots") + } else if matches!(target, HostPointerTarget::TabOverflow { .. }) { + Some("chevron") + } else if matches!(target, HostPointerTarget::Close { .. }) { + Some("close") + } else if let HostPointerTarget::HeaderAction { instance, action } = target { + self.header_icons.get(&(instance.clone(), action.clone())).map(String::as_str) + } else { + None + }, + icon_only: matches!( + target, + HostPointerTarget::Menu { .. } + | HostPointerTarget::TabOverflow { .. } + | HostPointerTarget::Close { .. } + | HostPointerTarget::HeaderAction { .. } + ), + attention: data.is_some_and(|value| value.attention), + selected: matches!(target, HostPointerTarget::Tab { instance } if *instance == section.instance), + enabled: control.enabled, + drag: matches!(target, HostPointerTarget::Header { .. } | HostPointerTarget::Tab { .. }), + title: matches!(target, HostPointerTarget::Header { .. }), + grip_only: matches!(target, HostPointerTarget::Header { .. }) && section.tabs.len() + section.hidden_tabs.len() > 1, + rtl: self.layout.direction == Direction::Rtl, + }, + if matches!(target, HostPointerTarget::Header { instance } | HostPointerTarget::Tab { instance } + if self.move_source == Some(instance)) + { + 0.5 + } else { + 1.0 + }, + ) + }; + let clicked = response.clicked(); + let secondary = response.secondary_clicked(); + if let Some(status) = data.and_then(|value| value.status.as_deref()) { + response.clone().on_hover_text(status); + } + if let HostPointerTarget::HeaderAction { action, .. } = target + && let Some(reason) = data + .and_then(|presentation| presentation.actions.iter().find(|binding| binding.id == *action)) + .and_then(|binding| binding.disabled_reason.as_deref()) + { + response.clone().on_disabled_hover_text(reason); + } + if self.allow_actions && (clicked || secondary) { + match target { + HostPointerTarget::Collapse { .. } if clicked => self.commands.push(HostCommand::WidgetLayout( + apply_action( + self.layout.revision, + vec![Mutation::Collapse { section: section.section.clone(), collapsed: !section.collapsed }], + ), + control.id, + )), + HostPointerTarget::Close { instance } if clicked => self.commands.push(HostCommand::WidgetLayout( + apply_action(self.layout.revision, vec![Mutation::Close { instance: instance.clone() }]), + control.id, + )), + HostPointerTarget::HeaderAction { instance, action } if clicked => self.commands.push(HostCommand::WidgetLayout( + apply_action( + self.layout.revision, + vec![Mutation::HeaderAction { instance: instance.clone(), action: action.clone() }], + ), + control.id, + )), + HostPointerTarget::Menu { instance } => self.commands.push(HostCommand::OpenMenu { + menu: HostMenu::Panel(instance.clone()), + anchor: control.bounds, + source: response.id, + secondary, + }), + HostPointerTarget::TabOverflow { section } => self.commands.push(HostCommand::OpenMenu { + menu: HostMenu::Tabs(section.clone()), + anchor: control.bounds, + source: response.id, + secondary, + }), + HostPointerTarget::Header { instance } | HostPointerTarget::Tab { instance } if secondary => { + self.commands.push(HostCommand::OpenMenu { + menu: HostMenu::Panel(instance.clone()), + anchor: control.bounds, + source: response.id, + secondary: true, + }); + } + HostPointerTarget::Tab { instance } if !ui.input(|input| input.pointer.primary_released()) => { + self.commands.push(HostCommand::WidgetLayout( + apply_action(self.layout.revision, vec![Mutation::Activate { instance: instance.clone() }]), + control.id, + )); + } + _ => {} + } + } + } + let t = crate::theme::Tokens::get(); + // The title and its controls share the card background. One + // kit separator spans the header, rather than per-control tiles. + if !section.collapsed && !section.inline { + let header = egui_rect(section.header); + t.secondary_hline(ui.painter(), header.x_range(), header.bottom(), t.dialog_rule); + } + // Content scrolls only where it chooses. Each slot is an isolated + // bounded child, so malicious/minimum-size content cannot enlarge + // the outer host or cover the shared menu and tab strip. Keep + // content fills inside the frame's rounded corners as well. + let mut content_ui = ui.new_child(egui::UiBuilder::new().id_salt("content_clip").max_rect(egui_rect(section.outer))); + content_ui.set_clip_rect(content_clip); + let content_ui = &mut content_ui; + if !section.collapsed && section.inline { + if let Some(body) = section.inline_content { + render_slot(content_ui, ContentSlot::Inline, body, context, content, services, &mut failure); + } + } else if !section.collapsed { + if let Some(header) = content_header_bounds(section) { + render_slot(content_ui, ContentSlot::Header, header, context, content, services, &mut failure); + } + if let Some(body) = section.body { + render_slot(content_ui, ContentSlot::Body, body, context, content, services, &mut failure); + } + if let Some(footer) = section.footer { + let has_footer_actions = presentation.actions.iter().any(|action| !section.actions.iter().any(|(id, _)| *id == action.id)); + let row_height = if has_footer_actions { self.layout.metrics.control_extent.min(footer.size.height) } else { 0.0 }; + if row_height > 0.0 && egui_rect(footer).intersect(content_ui.clip_rect()).is_positive() { + let inset = crate::theme::Tokens::get().space_4.min(footer.size.width / 2.0); + let row = LogicalRect { + origin: Point { x: footer.origin.x + inset, y: footer.origin.y }, + size: Size { width: footer.size.width - 2.0 * inset, height: row_height }, + }; + let actions_id = egui::Id::unique(("panel-actions", &context.instance, &context.owner)); + let mut actions = content_ui.new_child(egui::UiBuilder::new().scope_id(actions_id).max_rect(egui_rect(row))); + actions.set_clip_rect(egui_rect(row).intersect(content_ui.clip_rect())); + egui::ScrollArea::horizontal().id_salt("scroll").max_height(row_height).show(&mut actions, |ui| { + ui.horizontal(|ui| { + for action in presentation.actions.iter().filter(|action| !section.actions.iter().any(|(id, _)| *id == action.id)) + { + let target = HostControlTarget::Content { instance: context.instance.clone(), action: action.id.clone() }; + let id = scoped_id(self.scope, self.window, Some(&context.owner), &target); + let response = ui + .push_id(id, |ui| { + ui.add_enabled_ui(action.enabled, |ui| { + ui_kit::button(ui, action.label.as_str(), ui_kit::Button::Small) + }) + .inner + }) + .inner; + let visible = response.rect.intersect(ui.clip_rect()).intersect(egui_rect(row)); + if visible.is_positive() { + self.controls.push(HostFrameControl { + id: response.id, + target, + bounds: logical_rect(visible), + role: InputRole::Action, + accessible_name: action.label.clone(), + enabled: action.enabled && response.enabled(), + }); + } + if self.allow_actions && response.clicked() { + self.commands.push(HostCommand::Content(context.instance.clone(), action.id.clone(), response.id)); + } + if let Some(reason) = &action.disabled_reason { + response.on_disabled_hover_text(reason); + } + } + }); + }); + } + let remaining = footer.size.height - row_height; + render_slot( + content_ui, + ContentSlot::Footer, + LogicalRect { + origin: Point { x: footer.origin.x, y: footer.origin.y + row_height }, + size: Size { width: footer.size.width, height: remaining }, + }, + context, + content, + services, + &mut failure, + ); + } + } + // Resize must be above content on the card's actual UI/layer. Its + // published bounds and scoped ID remain the layout authority's. + for control in self.controls.iter() { + if matches!(&control.target, HostControlTarget::Pointer(HostPointerTarget::Resize { section: id, .. }) if *id == section.section) + { + ui_kit::panel_host_sash(ui, control.id, egui_rect(control.bounds), &control.accessible_name); + } + } + if let Some(focused) = ui.memory(|memory| memory.focused()) + && ui.ctx().read_response(focused).is_some_and(|response| { + response.layer_id == ui.layer_id() + && response.interact_rect.is_positive() + && egui_rect(section.outer).contains_rect(response.interact_rect) + }) + { + *self.owned_focus = Some(focused); + } + }, + ); + if let Some(reason) = failure { Err(reason) } else { Ok(()) } + } +} + +fn render_slot( + ui: &mut egui::Ui, + slot: ContentSlot, + bounds: LogicalRect, + context: &PanelContext, + content: &mut dyn PanelController, + services: &mut ContentServices<'_>, + failure: &mut Option, +) { + if failure.is_some() || bounds.size.width <= 0.0 || bounds.size.height <= 0.0 { + return; + } + let bounds = egui_rect(bounds); + let t = crate::theme::Tokens::get(); + let inset = bounds.shrink2(egui::vec2(t.space_4.min(bounds.width().max(0.0) / 2.0), t.space_2.min(bounds.height().max(0.0) / 2.0))); + let clip = ui.clip_rect().intersect(inset); + if !clip.is_positive() { + return; + } + let identity_slot = if slot == ContentSlot::Inline { ContentSlot::Body } else { slot }; + let identity = egui::Id::unique(("panel-content", &context.instance, &context.owner, identity_slot as u8)); + // Explicit UI identity survives a different section/column/native parent. + // Each owner/instance mounts only once in its complete presentation cohort. + let mut child = ui.new_child(egui::UiBuilder::new().scope_id(identity).max_rect(inset)); + child.set_clip_rect(clip); + let result = if slot == ContentSlot::Inline { + content.render_inline(&mut child, context, services) + } else { + content.render(slot, &mut child, context, services) + }; + if let Err(reason) = result { + *failure = Some(reason); + } +} + +fn content_header_bounds(section: &HostSection) -> Option { + let body = section.body?; + let y = section.header.origin.y + section.header.size.height; + let height = body.origin.y - y; + if height <= 0.0 { + return None; + } + Some(LogicalRect { origin: Point { x: body.origin.x, y }, size: Size { width: body.size.width, height } }) +} + +fn resolve_frame_layout( + runtime: &PanelRuntime, + render_domain: LogicalRect, + capacity: LogicalRect, + chrome: &[LogicalRect], + options: &HostOptions, +) -> PanelResult { + let mut metrics = options.metrics; + metrics.content_header_height = options.content_header_height; + let mut layout = resolve_host_layout_in_domain( + runtime.layout(), + render_domain, + capacity, + chrome, + runtime.environment().direction, + metrics, + &options.geometry, + )?; + for (_, bounds) in scroll_tracks(&layout) { + layout.painted.push(bounds); + layout.input.push(bounds); + layout.occlusion.push(bounds); + layout.reservations.push(bounds); + } + let obstacles: Vec<_> = layout.chrome_obstacles.iter().chain(&layout.painted).copied().collect(); + layout.usable = resolve_usable_region(layout.render_domain, &obstacles)?; + layout.validate()?; + Ok(layout) +} + +fn scroll_tracks(layout: &HostLayout) -> Vec<(bool, LogicalRect)> { + let capacity = egui_rect(layout.capacity); + if !capacity.is_positive() { + return Vec::new(); + } + let thickness = crate::theme::Tokens::get().space_8.min(capacity.width()).min(capacity.height()); + let horizontal = layout.extent.width > layout.capacity.size.width; + let vertical = layout.extent.height > layout.capacity.size.height; + let mut tracks = Vec::new(); + if horizontal { + let bounds = egui::Rect::from_min_max( + egui::pos2(capacity.left(), capacity.bottom() - thickness), + egui::pos2(capacity.right() - if vertical { thickness } else { 0.0 }, capacity.bottom()), + ); + if bounds.is_positive() { + tracks.push((true, logical_rect(bounds))); + } + } + if vertical { + let bounds = egui::Rect::from_min_max( + egui::pos2(capacity.right() - thickness, capacity.top()), + egui::pos2(capacity.right(), capacity.bottom() - if horizontal { thickness } else { 0.0 }), + ); + if bounds.is_positive() { + tracks.push((false, logical_rect(bounds))); + } + } + tracks +} + +fn apply_action(revision: u64, mutations: Vec) -> LayoutAction { + LayoutAction::Apply { expected_revision: Some(revision), mutations } +} + +impl WorkspacePanelHost { + #[allow(clippy::too_many_arguments)] + fn paint_menu( + &mut self, + ui: &mut egui::Ui, + runtime: &PanelRuntime, + native: HostCapabilities, + metadata: &BTreeMap, + owners: &BTreeMap, + frame: &mut HostFrame, + commands: &mut Vec, + allow_actions: bool, + locale: crate::i18n::Locale, + ) { + let (Some(menu), Some(anchor)) = (self.menu.clone(), self.menu_anchor) else { + return; + }; + let Some(bounds) = menu_geometry(frame.layout.capacity, anchor) else { + self.menu = None; + return; + }; + let id = egui::Id::unique(( + "universal_panel_menu", + &runtime.environment().workspace, + &runtime.environment().document, + &runtime.environment().window, + &runtime.environment().viewport, + )); + // Distinct menus retain their own scroll position. A long overflow + // list must not start its shorter nested panel menu at the old offset. + let scroll_id = match &menu { + HostMenu::Panel(instance) => egui::Id::unique(("panel", instance)), + HostMenu::Tabs(section) => egui::Id::unique(("tabs", section)), + }; + ui_kit::panel_host_popup(ui, id, bounds, |ui| { + if !ui.is_visible() || ui.is_sizing_pass() { + return; + } + frame.menu_bounds = Some(logical_rect(bounds)); + egui::ScrollArea::vertical().id_salt(("items", scroll_id)).max_height(ui.available_height()).show(ui, |ui| { + ui.set_min_width(ui.available_width()); + if let Some(reason) = &self.last_rejection { + ui.colored_label(crate::theme::Tokens::get().form_error, locale.text(rule_key(reason.rule))); + } + match &menu { + HostMenu::Panel(instance) => { + if let Some(presentation) = metadata.get(instance) { + ui.label(&presentation.title); + if let Some(status) = &presentation.status { + ui.label(status); + } + } + let mut actions = vec![HostSharedAction::Focus, HostSharedAction::Collapse]; + actions.extend([Zone::Left, Zone::Right, Zone::Bottom, Zone::Floating].into_iter().map(HostSharedAction::Move)); + actions.extend( + runtime + .layout() + .layout() + .sections + .iter() + .filter(|section| !section.tabs.contains(instance)) + .map(|section| HostSharedAction::Join(section.id.clone())), + ); + actions.extend([HostSharedAction::Popout, HostSharedAction::Close]); + for shared in actions { + let target = HostControlTarget::Shared { instance: instance.clone(), action: shared.clone() }; + let label = shared_label(&shared, instance, runtime, metadata, locale); + let action = shared_action( + runtime, + instance, + &shared, + &native, + frame.layout.capacity, + &frame.layout.geometry_policy.identity_reservations, + ) + .and_then(|action| { + prepare_host_layout(runtime.layout(), &runtime_scope(runtime), &frame.layout, action.clone())?; + Ok(action) + }); + let reason = action.as_ref().err().map(|reason| locale.text(rule_key(reason.rule)).to_owned()); + let response = menu_row(ui, control_id(runtime, owners, &target), &label, action.is_ok()); + record_control(frame, &response, target, &label, action.is_ok(), bounds.intersect(ui.clip_rect())); + if allow_actions + && response.clicked() + && let Ok(action) = action + { + commands.push(HostCommand::WidgetLayout(action, response.id)); + } + if let Some(reason) = reason { + response.on_disabled_hover_text(reason); + } + } + if let Some(presentation) = metadata.get(instance) { + for action in &presentation.actions { + let target = HostControlTarget::Content { instance: instance.clone(), action: action.id.clone() }; + let response = menu_row(ui, control_id(runtime, owners, &target), &action.label, action.enabled); + record_control(frame, &response, target, &action.label, action.enabled, bounds.intersect(ui.clip_rect())); + if allow_actions && response.clicked() { + let registered = runtime + .layout() + .layout() + .instance(instance) + .and_then(|panel| runtime.layout().registry().get(&panel.kind)) + .is_ok_and(|spec| spec.header_actions.iter().any(|entry| entry.id == action.id)); + if registered { + commands.push(HostCommand::WidgetLayout( + apply_action( + frame.layout.revision, + vec![Mutation::HeaderAction { instance: instance.clone(), action: action.id.clone() }], + ), + response.id, + )); + } else { + commands.push(HostCommand::Content(instance.clone(), action.id.clone(), response.id)); + } + } + if let Some(reason) = &action.disabled_reason { + response.on_disabled_hover_text(reason); + } + } + } + // Collapsed and inline groups have one total header. + // Retain access to inactive identities through the same + // bounded shared menu, after the selected panel's actions. + if let Ok(section) = runtime.layout().layout().containing(instance) { + for tab in section.tabs.iter().filter(|tab| *tab != instance) { + menu_instance(ui, runtime, owners, metadata, frame, commands, tab, bounds, allow_actions, locale); + } + } + } + HostMenu::Tabs(section) => { + if let Ok(section) = runtime.layout().layout().section(section) { + for instance in §ion.tabs { + menu_instance(ui, runtime, owners, metadata, frame, commands, instance, bounds, allow_actions, locale); + } + } + } + } + }); + }); + } +} + +fn menu_geometry(capacity: LogicalRect, anchor: LogicalRect) -> Option { + let capacity = egui_rect(capacity); + if !capacity.is_positive() || !capacity.is_finite() { + return None; + } + let t = crate::theme::Tokens::get(); + if capacity.width() <= t.space_6 * 2.0 || capacity.height() <= t.space_6 * 2.0 { + return None; + } + let width = t.form_card_width.min(capacity.width()); + let height = (t.control_height * 12.0 + t.space_12).min(capacity.height()); + let left = anchor.origin.x.min(capacity.right() - width).max(capacity.left()); + let top = (anchor.origin.y + anchor.size.height).min(capacity.bottom() - height).max(capacity.top()); + Some(egui::Rect::from_min_size(egui::pos2(left, top), egui::vec2(width, height))) +} + +fn menu_row(ui: &mut egui::Ui, id: egui::Id, label: &str, enabled: bool) -> egui::Response { + ui.push_id(id.with("menu"), |ui| ui.add_enabled_ui(enabled, |ui| ui_kit::button(ui, label, ui_kit::Button::Small)).inner) + .inner + .on_hover_text(label) +} + +fn record_control(frame: &mut HostFrame, response: &egui::Response, target: HostControlTarget, name: &str, enabled: bool, clip: egui::Rect) { + let bounds = response.rect.intersect(clip); + if bounds.is_positive() && bounds.is_finite() { + frame.controls.push(HostFrameControl { + id: response.id, + target, + bounds: logical_rect(bounds), + role: InputRole::Action, + accessible_name: name.to_owned(), + enabled: enabled && response.enabled(), + }); + } +} + +#[allow(clippy::too_many_arguments)] +fn menu_instance( + ui: &mut egui::Ui, + runtime: &PanelRuntime, + owners: &BTreeMap, + metadata: &BTreeMap, + frame: &mut HostFrame, + commands: &mut Vec, + instance: &InstanceId, + clip: egui::Rect, + allow_actions: bool, + locale: crate::i18n::Locale, +) { + let label = metadata.get(instance).map_or_else(|| locale.text("ui.panel_host.tab").to_owned(), |value| value.title.clone()); + ui.label(&label); + if metadata.get(instance).is_some_and(|presentation| presentation.attention) { + ui.label(locale.text("ui.panel_host.attention")); + } + ui.horizontal(|ui| { + let target = HostControlTarget::Shared { instance: instance.clone(), action: HostSharedAction::Focus }; + let action = apply_action(runtime.layout().inspect().revision, vec![Mutation::Focus { instance: instance.clone() }]); + let check = runtime.layout().prepare(action.clone()); + let response = menu_row(ui, control_id(runtime, owners, &target), locale.text("ui.panel_host.focus"), check.is_ok()); + let accessible = locale.format("ui.panel_host.focus_target", &[("title", &label)]); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, check.is_ok(), &accessible)); + record_control(frame, &response, target, &accessible, check.is_ok(), clip.intersect(ui.clip_rect())); + if allow_actions && response.clicked() { + commands.push(HostCommand::WidgetLayout(action, response.id)); + } + if let Err(reason) = check { + response.on_disabled_hover_text(locale.text(rule_key(reason.rule))); + } + let target = HostControlTarget::PanelMenu { instance: instance.clone() }; + let response = menu_row(ui, control_id(runtime, owners, &target), locale.text("ui.panel_host.menu"), true); + record_control(frame, &response, target, locale.text("ui.panel_host.menu"), true, clip.intersect(ui.clip_rect())); + if allow_actions && response.clicked() { + commands.push(HostCommand::OpenMenu { + menu: HostMenu::Panel(instance.clone()), + anchor: logical_rect(response.rect), + source: response.id, + secondary: false, + }); + } + }); +} + +fn shared_label( + action: &HostSharedAction, + instance: &InstanceId, + runtime: &PanelRuntime, + metadata: &BTreeMap, + locale: crate::i18n::Locale, +) -> String { + if *action == HostSharedAction::Collapse && runtime.layout().layout().containing(instance).is_ok_and(|section| section.collapsed) { + return locale.text("ui.panel_host.expand").to_owned(); + } + if let HostSharedAction::Join(section) = action { + let title = runtime + .layout() + .layout() + .section(section) + .ok() + .and_then(|section| metadata.get(§ion.active)) + .map(|presentation| presentation.title.as_str()) + .unwrap_or_else(|| locale.text("ui.panel_host.tab")); + return locale.format("ui.panel_host.join_target", &[("title", title)]); + } + locale + .text(match action { + HostSharedAction::Focus => "ui.panel_host.focus", + HostSharedAction::Close => "ui.panel_host.close", + HostSharedAction::Collapse => "ui.panel_host.collapse", + HostSharedAction::Move(Zone::Left) => "ui.panel_host.left", + HostSharedAction::Move(Zone::Right) => "ui.panel_host.right", + HostSharedAction::Move(Zone::Bottom) => "ui.panel_host.bottom", + HostSharedAction::Move(Zone::Floating) => "ui.panel_host.floating", + HostSharedAction::Move(Zone::Window) | HostSharedAction::Popout => "ui.panel_host.popout", + HostSharedAction::Join(_) => "ui.panel_host.join", + }) + .to_owned() +} + +fn shared_action( + runtime: &PanelRuntime, + instance: &InstanceId, + action: &HostSharedAction, + native: &HostCapabilities, + capacity: LogicalRect, + reservations: &HostIdentityReservations, +) -> PanelResult { + let service = runtime.layout(); + let panel = service.layout().instance(instance)?; + let section = service.layout().containing(instance)?; + let spec = service.registry().get(&panel.kind)?; + let mutations = match action { + HostSharedAction::Focus => vec![Mutation::Focus { instance: instance.clone() }], + HostSharedAction::Close => vec![Mutation::Close { instance: instance.clone() }], + HostSharedAction::Collapse => vec![Mutation::Collapse { section: section.id.clone(), collapsed: !section.collapsed }], + HostSharedAction::Join(target) => { + let target_section = service.layout().section(target)?; + vec![Mutation::Move { + instance: instance.clone(), + destination: Destination::JoinTab { section: target.clone(), index: target_section.tabs.len() }, + }] + } + HostSharedAction::Move(zone) => { + let (id, mut index) = new_section_identity(service, instance, reservations)?; + if zone.docked() && spec.edge_rule == EdgeRule::PinOuter { + index = service + .layout() + .sections + .iter() + .filter(|candidate| !(candidate.id == section.id && section.tabs.len() == 1)) + .position(|candidate| candidate.location.zone() == *zone) + .unwrap_or(index); + } + let location = if zone.docked() { + SectionLocation::Dock { zone: *zone } + } else if *zone == Zone::Floating { + SectionLocation::Floating { origin: capacity.origin } + } else { + return Err(error(Rule::Capability, "window movement needs native pop-out")); + }; + let size = section.size; + vec![ + Mutation::Move { instance: instance.clone(), destination: Destination::NewSection { section: id, index, location, size } }, + Mutation::Focus { instance: instance.clone() }, + ] + } + HostSharedAction::Popout => { + if !spec.features.popout { + return Err(error(Rule::FeatureDisabled, "panel cannot pop out")); + } + if cfg!(target_arch = "wasm32") { + return shared_action(runtime, instance, &HostSharedAction::Move(Zone::Floating), native, capacity, reservations); + } + if !native.native_windows || !service.capabilities().native_windows { + return Err(error(Rule::Capability, "native panel windows unavailable")); + } + let (id, index) = new_section_identity(service, instance, reservations)?; + let mut number = 0; + let host = loop { + let candidate = HostId::new(format!("host.window.{number}"))?; + if !service + .layout() + .sections + .iter() + .any(|section| matches!(§ion.location, SectionLocation::Window { host, .. } if *host == candidate)) + { + break candidate; + } + number += 1; + if number > MAX_SECTIONS { + return Err(error(Rule::CollectionLimit, "native host identity capacity")); + } + }; + let zone = if section.location.zone().docked() { section.location.zone() } else { spec.default_zone }; + let zone = if zone.docked() { zone } else { Zone::Left }; + let return_index = service.layout().sections.iter().position(|entry| entry.id == section.id).unwrap_or(0); + let join = if section.tabs.len() > 1 { + Some(ReturnTab { section: section.id.clone(), index: section.tabs.iter().position(|entry| entry == instance).unwrap_or(0) }) + } else { + None + }; + let location = SectionLocation::Window { + host, + origin: capacity.origin, + return_to: DockReturn { + zone, + index: return_index, + size: section.size, + collapsed: section.collapsed, + join, + section: Some(section.id.clone()), + column: section.column.clone(), + column_index: service + .layout() + .columns + .iter() + .filter(|column| column.zone == zone) + .position(|column| Some(&column.id) == section.column.as_ref()) + .unwrap_or(0), + column_width: section + .column + .as_ref() + .and_then(|id| service.layout().columns.iter().find(|column| column.id == *id).map(|column| column.width)), + weight: section.weight, + preferred_extent: section.preferred_extent, + extent_priority: section.extent_priority, + }, + }; + vec![Mutation::Move { + instance: instance.clone(), + destination: Destination::NewSection { section: id, index, location, size: section.size }, + }] + } + }; + let action = apply_action(service.inspect().revision, mutations); + service.prepare(action.clone())?; + Ok(action) +} + +fn new_section_identity(service: &LayoutService, instance: &InstanceId, reservations: &HostIdentityReservations) -> PanelResult<(SectionId, usize)> { + let source = service.layout().containing(instance)?; + let index = service.layout().sections.len().saturating_sub(usize::from(source.tabs.len() == 1)); + if source.tabs.len() == 1 { + return Ok((source.id.clone(), index)); + } + Ok((next_host_section_id(service.layout(), reservations)?, index)) +} diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index fc4331a7c..6a76269e7 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -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, /// The appearance last asked of the native window ([`sync_window_theme`]). window_theme: Option, + /// Last observed OS tone, independent of the selected theme's tone. + system_theme_dark: Option, + /// 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 0, - "dark" => 1, - "system" => 2, - _ => 3, - }); - let mut tile_action: Option<(&str, String)> = None; - let mut action_theme: Option = None; - let mut chosen: Option = 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::(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) { 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 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); diff --git a/crates/ui-egui/src/prefs/sketch.rs b/crates/ui-egui/src/prefs/sketch.rs index e29936b05..ee2a232e2 100644 --- a/crates/ui-egui/src/prefs/sketch.rs +++ b/crates/ui-egui/src/prefs/sketch.rs @@ -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, diff --git a/crates/ui-egui/src/prefs/theme_picker.rs b/crates/ui-egui/src/prefs/theme_picker.rs new file mode 100644 index 000000000..f97dc2b61 --- /dev/null +++ b/crates/ui-egui/src/prefs/theme_picker.rs @@ -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, + pub high: Option, + 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 { + 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::(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::(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); +} diff --git a/crates/ui-egui/src/prefs/tools.rs b/crates/ui-egui/src/prefs/tools.rs index 24ab1196f..e573f97f3 100644 --- a/crates/ui-egui/src/prefs/tools.rs +++ b/crates/ui-egui/src/prefs/tools.rs @@ -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)); diff --git a/crates/ui-egui/src/prefs_search.rs b/crates/ui-egui/src/prefs_search.rs index 359cf5f77..1932a16c0 100644 --- a/crates/ui-egui/src/prefs_search.rs +++ b/crates/ui-egui/src/prefs_search.rs @@ -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::>() + ); + 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"] { diff --git a/crates/ui-egui/src/render_ui/mod.rs b/crates/ui-egui/src/render_ui/mod.rs index 649d76eb7..d9e11ee0b 100644 --- a/crates/ui-egui/src/render_ui/mod.rs +++ b/crates/ui-egui/src/render_ui/mod.rs @@ -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 }; diff --git a/crates/ui-egui/src/render_workspace.rs b/crates/ui-egui/src/render_workspace.rs index 5c74f926e..5d6a5f9b7 100644 --- a/crates/ui-egui/src/render_workspace.rs +++ b/crates/ui-egui/src/render_workspace.rs @@ -146,6 +146,9 @@ pub struct State { pub upload_error: crate::gpu::UploadError, pub image_host: Option, 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, } @@ -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 { + 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 { + 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 { + 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) -> 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(); diff --git a/crates/ui-egui/src/render_workspace_compare.rs b/crates/ui-egui/src/render_workspace_compare.rs index ed28ed33b..ed2be08e0 100644 --- a/crates/ui-egui/src/render_workspace_compare.rs +++ b/crates/ui-egui/src/render_workspace_compare.rs @@ -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) -> 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 }); }); diff --git a/crates/ui-egui/src/render_workspace_tests.rs b/crates/ui-egui/src/render_workspace_tests.rs index cecac02d5..f709d984e 100644 --- a/crates/ui-egui/src/render_workspace_tests.rs +++ b/crates/ui-egui/src/render_workspace_tests.rs @@ -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::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::>() + }); + 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)); + } + } +} diff --git a/crates/ui-egui/src/revolve_edit_tests.rs b/crates/ui-egui/src/revolve_edit_tests.rs index 81c0f3d9c..64b78f05e 100644 --- a/crates/ui-egui/src/revolve_edit_tests.rs +++ b/crates/ui-egui/src/revolve_edit_tests.rs @@ -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, 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::>())); + 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())) +} diff --git a/crates/ui-egui/src/scenario.rs b/crates/ui-egui/src/scenario.rs index 4328e5457..e96c4d0ec 100644 --- a/crates/ui-egui/src/scenario.rs +++ b/crates/ui-egui/src/scenario.rs @@ -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) { { diff --git a/crates/ui-egui/src/settings_profiles.rs b/crates/ui-egui/src/settings_profiles.rs index 2d38cde5b..b3326b1be 100644 --- a/crates/ui-egui/src/settings_profiles.rs +++ b/crates/ui-egui/src/settings_profiles.rs @@ -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", diff --git a/crates/ui-egui/src/settings_profiles_tests.rs b/crates/ui-egui/src/settings_profiles_tests.rs index 067994ab6..e9da4684c 100644 --- a/crates/ui-egui/src/settings_profiles_tests.rs +++ b/crates/ui-egui/src/settings_profiles_tests.rs @@ -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(); diff --git a/crates/ui-egui/src/shell.rs b/crates/ui-egui/src/shell.rs index e59681d5c..8113f2640 100644 --- a/crates/ui-egui/src/shell.rs +++ b/crates/ui-egui/src/shell.rs @@ -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 { - 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 { - occluding_rects(app, true) + occluding_rects(app, true, false, true) } -fn occluding_rects(app: &SolveApp, fitting: bool) -> Vec { +/// 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 { + 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 { 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; diff --git a/crates/ui-egui/src/shell_tests.rs b/crates/ui-egui/src/shell_tests.rs index 3ab417e93..5ef309fc1 100644 --- a/crates/ui-egui/src/shell_tests.rs +++ b/crates/ui-egui/src/shell_tests.rs @@ -1,6 +1,1247 @@ use super::*; use crate::scenario::{Harness, rect_of}; use serde_json::json; +use solidcraft_engine::panels::ActionSink as _; + +/// Inspect existing caches; never warm/evaluate geometry as part of an assertion. +fn assert_panel_host_preserves_design(h: &mut Harness, exercise: impl FnOnce(&mut Harness)) { + let document = h.app.session.doc.clone(); + let model = h.app.session.model.state(); + let cache = h.app.session.model.cache.clone(); + let meshes = model.bodies.iter().map(|body| body.cached_mesh()).collect::>(); + let revision = h.app.session.revision; + let undo = h.app.session.undo.len(); + let dirty = h.app.session.is_dirty(); + let recomputed = h.app.session.model.recomputed; + let camera = h.app.cam; + let render_domain = h.app.viewport.rect; + let sample_points = [solidcore_record::Vec3::ZERO, solidcore_record::Vec3::new(1.0, 2.0, 3.0)]; + let screen_points = render_domain.map(|domain| sample_points.map(|point| crate::viewport::projection(&h.app, domain).to_screen(point))); + let preferences = serde_json::to_value(&h.app.preferences).unwrap(); + exercise(h); + assert!(std::sync::Arc::ptr_eq(&document, &h.app.session.doc), "panel chrome must retain document identity"); + let after = h.app.session.model.state(); + assert!(std::sync::Arc::ptr_eq(&model, &after), "panel chrome must retain model identity"); + assert!(std::sync::Arc::ptr_eq(&cache, &h.app.session.model.cache), "panel chrome must retain evaluation cache identity"); + assert_eq!(h.app.session.revision, revision); + assert_eq!(h.app.session.undo.len(), undo); + assert_eq!(h.app.session.is_dirty(), dirty); + assert_eq!(h.app.session.model.recomputed, recomputed); + assert_eq!(h.app.cam, camera); + if render_domain.is_some() { + assert_eq!(h.app.viewport.rect, render_domain, "ordinary panel work preserves the full render projection"); + assert_eq!( + h.app.viewport.rect.map(|domain| sample_points.map(|point| crate::viewport::projection(&h.app, domain).to_screen(point))), + screen_points, + "panel layout never changes the model's screen position or framing offset" + ); + } + assert_eq!(serde_json::to_value(&h.app.preferences).unwrap(), preferences); + for (body, mesh) in after.bodies.iter().zip(meshes) { + match (mesh, body.cached_mesh()) { + (Some(before), Some(after)) => assert!(std::sync::Arc::ptr_eq(&before, &after), "panel chrome must retain cached mesh identity"), + (None, None) => {} + _ => panic!("panel chrome changed mesh cache population"), + } + } +} + +#[test] +fn universal_panel_host_is_opt_in_and_each_specimen_preserves_design_and_preferences() { + for preset in ["docks", "tabs", "collapsed", "floating", "overflow", "pinned"] { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.run("solid.box", json!({"length":40,"width":30,"height":20})).unwrap(); + h.settle(); + assert!(h.app.panel_runtime().is_none()); + assert!(h.app.universal_panel_frame().is_none()); + let legacy_browser = rect_of("browser:card"); + assert!(legacy_browser.is_some(), "default still mounts legacy Browser"); + assert_panel_host_preserves_design(&mut h, |h| { + crate::panel_runtime::enable_host_specimen(&mut h.app, preset).unwrap(); + h.frames(4); + assert!(h.app.universal_panel_frame().is_some(), "actual workspace host: {preset}"); + let runtime = h.app.panel_runtime().unwrap(); + for spec in runtime.layout().registry().specs() { + assert!(!spec.header_actions.iter().any(|action| action.id.0 == "pulse"), "native specimens have no debug action"); + } + assert!(!h.app.universal_panel_frame().unwrap().controls.iter().any(|control| matches!(&control.target, + crate::panel_runtime::HostControlTarget::Pointer(crate::panel_runtime::HostPointerTarget::HeaderAction { action, .. }) if action.0 == "pulse"))); + assert!(rect_of("browser:card").is_none(), "legacy placement must be suppressed: {preset}"); + h.app.disable_universal_panel_host().unwrap(); + h.frames(3); + assert!(h.app.universal_panel_frame().is_none()); + assert!(rect_of("browser:card").is_some(), "legacy placement returns when opt-in ends"); + }); + } +} + +#[test] +fn specimen_rejects_unknown_presets_and_cannot_take_over_an_existing_runtime() { + let mut h = Harness::new(); + h.app.home.open = false; + assert_panel_host_preserves_design(&mut h, |h| { + assert!(crate::panel_runtime::enable_host_specimen(&mut h.app, "unbounded-user-input").is_err()); + assert!(h.app.panel_runtime().is_none()); + assert!(h.app.universal_panel_frame().is_none()); + crate::panel_runtime::enable_host_specimen(&mut h.app, "tabs").unwrap(); + h.frames(3); + let before = h.app.panel_runtime().unwrap().layout().inspect(); + let controllers = h.app.panel_runtime().unwrap().controller_count(); + assert!(crate::panel_runtime::enable_host_specimen(&mut h.app, "docks").is_err()); + assert_eq!(h.app.panel_runtime().unwrap().layout().inspect(), before); + assert_eq!(h.app.panel_runtime().unwrap().controller_count(), controllers); + h.frames(2); + assert_eq!(h.app.panel_runtime().unwrap().layout().inspect(), before); + }); +} + +fn assert_host_legacy_window(h: &Harness, bounds: egui::Rect) { + use crate::panel_runtime::logical_rect; + assert_eq!(h.app.viewport.host_windows.as_deref(), Some([bounds].as_slice()), "only the actual legacy window reserves space"); + let usable = crate::shell::host_usable(&h.app).unwrap(); + assert!(usable.obstacles.contains(&logical_rect(bounds))); + let controls = h.app.viewport.layout.as_ref().unwrap(); + assert!(controls.usable.as_ref().unwrap().obstacles.contains(&logical_rect(bounds))); + for control in [controls.navigation, controls.axis_view] { + if control.is_positive() { + assert!(!control.intersect(bounds).is_positive(), "same-pass controls avoid the real editor"); + } + } +} + +fn assert_host_legacy_windows_closed(h: &Harness) { + assert_eq!(h.app.viewport.host_windows.as_deref(), Some([].as_slice())); + assert!(rect_of("dialog:window").is_none() && rect_of("dialog:outer").is_none()); + assert_eq!(crate::shell::host_usable(&h.app).unwrap(), h.app.universal_panel_frame().unwrap().layout.usable); +} + +#[test] +fn host_retains_one_legacy_move_editor_and_the_pending_capture_question() { + let (mut h, _, occurrence) = crate::test_support::component_box(); + h.app.home.open = false; + h.app.preferences.language = "en".into(); + h.app.run("occurrence.move", json!({"occurrence":occurrence,"translate":[10,0,0],"capture":false})).unwrap(); + h.settle(); + let pending = h.app.session.pending_moves.clone(); + h.app.tree.occurrence_move = Some(crate::browser::OccMove::new(occurrence)); + h.frames(3); + let baseline = h.app.tree.occurrence_move.as_ref().unwrap().baseline; + assert!(baseline.is_some()); + assert_panel_host_preserves_design(&mut h, |h| { + crate::panel_runtime::enable_host_specimen(&mut h.app, "tabs").unwrap(); + h.frames(4); + let draft = h.app.tree.occurrence_move.as_ref().unwrap(); + assert_eq!(draft.baseline, baseline); + assert!(draft.had_pending); + assert_eq!(draft.translate, [0.0; 3]); + assert_eq!(crate::scenario::handles("occurrence-move:distance:0").len(), 1); + assert_host_legacy_window(h, rect_of("dialog:window").unwrap()); + assert_eq!(h.app.session.pending_moves, pending); + }); + // Cancel must restore the opening baseline, including the earlier pending move. + h.step(&json!({"click":{"handle":"dialog:cancel"}})).unwrap(); + h.frames(2); + assert!(h.app.tree.occurrence_move.is_none()); + assert_eq!(h.app.session.pending_moves, pending); + assert_host_legacy_windows_closed(&h); + assert_panel_host_preserves_design(&mut h, |h| { + h.app.start("sketch.create"); + h.frames(3); + assert_eq!(h.app.tree.capture_prompt.as_deref(), Some("sketch.create")); + assert!(h.app.dialog.is_none(), "the guarded command still waits for its existing question"); + assert!(h.widget("Capture Position").is_some() && h.widget("Revert").is_some()); + assert_host_legacy_window(h, rect_of("dialog:window").unwrap()); + h.step(&json!({"click":{"handle":"dialog:cancel"}})).unwrap(); + h.frames(2); + assert!(h.app.tree.capture_prompt.is_none() && h.app.dialog.is_none()); + assert_eq!(h.app.session.pending_moves, pending); + assert_host_legacy_windows_closed(h); + }); +} + +#[test] +fn host_keeps_legacy_canvas_cloud_and_attachment_drafts_with_only_visible_footprints() { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.preferences.language = "en".into(); + let mut png = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR".to_vec(); + png.extend(400u32.to_be_bytes()); + png.extend(200u32.to_be_bytes()); + png.extend([8, 6, 0, 0, 0, 0, 0, 0, 0]); + let data = solidcraft_engine::doc::canvas::base64_encode(&png); + let canvas = h.app.run("canvas.insert", json!({"data":data,"plane":"XY","width":80})).unwrap()["canvas"].as_u64().unwrap(); + let path = h.dir.join("legacy-editor.xyz"); + std::fs::write(&path, "0 0 0 255 0 0\n1 0 0 0 255 0\n").unwrap(); + let cloud = h.app.run("pointcloud.insert", json!({"path":path.to_string_lossy()})).unwrap()["cloud"].as_u64().unwrap(); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + let sketch = h.app.session.active_sketch.unwrap(); + h.app.run("sketch.finish", json!({})).unwrap(); + h.settle(); + crate::panel_runtime::enable_host_specimen(&mut h.app, "tabs").unwrap(); + h.frames(4); + h.ctx.options_mut(|options| options.max_passes = 1.try_into().unwrap()); + for editor in ["canvas", "cloud", "attachment"] { + assert_panel_host_preserves_design(&mut h, |h| { + match editor { + "canvas" => { + let mut draft = crate::browser::CanvasPanel::new(&h.app, canvas, true); + draft.a = [3.0, 4.0]; + draft.distance = 73.0; + h.app.tree.canvas_panel = Some(draft); + } + "cloud" => h.app.tree.cloud_panel = Some(crate::browser::CloudPanel::new(&h.app, cloud)), + _ => { + h.app.tree.redefine = Some(sketch); + let mut draft = crate::sketch_attachment_ui::Draft::new(&h.app, sketch); + draft.label = "retained plane draft".into(); + draft.error = Some("retained draft error".into()); + h.app.tree.redefine_draft = Some(draft); + } + } + h.frame(); + assert_eq!(h.app.viewport.host_windows.as_deref(), Some([].as_slice()), "{editor}: invisible sizing cannot reserve a window"); + h.frames(3); + let name = if editor == "attachment" { "dialog:outer" } else { "dialog:window" }; + assert_eq!(crate::scenario::rects(name).iter().filter(|(key, _)| key == name).count(), 1, "{editor}: one legacy producer"); + assert_host_legacy_window(h, rect_of(name).unwrap()); + match editor { + "canvas" => { + let draft = h.app.tree.canvas_panel.as_ref().unwrap(); + assert_eq!((draft.a, draft.distance), ([3.0, 4.0], 73.0)); + } + "cloud" => assert_eq!(h.app.tree.cloud_panel.as_ref().unwrap().cloud, cloud), + _ => { + let draft = h.app.tree.redefine_draft.as_ref().unwrap(); + assert_eq!(draft.label, "retained plane draft"); + assert_eq!(draft.error.as_deref(), Some("retained draft error")); + } + } + h.step(&json!({"click":{"handle":"dialog:cancel"}})).unwrap(); + h.frames(2); + assert!(h.app.tree.canvas_panel.is_none() && h.app.tree.cloud_panel.is_none() && h.app.tree.redefine_draft.is_none()); + assert_host_legacy_windows_closed(h); + }); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn host_clears_suppressed_assistant_geometry_without_losing_chat_or_tool_width() { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.ui.layout = LayoutMode::Floating; + h.call("ui.agent_chat", json!({"open":true,"side":"right","width":440,"picker":false})); + h.frames(3); + h.app.agent_chat.input = "retained unsent draft".into(); + h.app.agent_chat.items.push(crate::agent_chat::Item::Agent { thought: false, text: "retained conversation".into() }); + let items = crate::agent_chat::status(&h.app)["items"].clone(); + let stale = h.app.agent_chat.panel_rect.unwrap(); + let viewport = h.app.viewport.rect.unwrap(); + assert!(crate::agent_chat::tool_space(&h.app, viewport).width() < viewport.width()); + assert_panel_host_preserves_design(&mut h, |h| { + crate::panel_runtime::enable_host_specimen(&mut h.app, "tabs").unwrap(); + h.frame(); + assert!(h.app.agent_chat.panel_rect.is_none() && h.app.agent_chat.drop_rect.is_none() && h.app.agent_chat.dock_space.is_none()); + assert!(rect_of("agent_chat:panel").is_none()); + let domain = h.app.viewport.rect.unwrap(); + assert_eq!(crate::agent_chat::tool_space(&h.app, domain), domain); + assert_eq!(crate::shell::tool_drag_rect(&h.app, domain).x_range(), domain.x_range()); + assert!(!crate::shell::host_usable(&h.app).unwrap().obstacles.contains(&crate::panel_runtime::logical_rect(stale))); + assert!(h.app.agent_chat.open); + assert_eq!(h.app.agent_chat.input, "retained unsent draft"); + assert_eq!(crate::agent_chat::status(&h.app)["items"], items); + h.app.disable_universal_panel_host().unwrap(); + h.frames(3); + assert!(h.app.agent_chat.panel_rect.is_some() && h.app.agent_chat.drop_rect.is_some()); + assert_eq!(h.app.agent_chat.input, "retained unsent draft"); + assert_eq!(crate::agent_chat::status(&h.app)["items"], items); + }); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn host_retains_the_existing_popped_assistant_window_path() { + // Harness uses egui's embedded native-window fallback; this is not OS-window evidence. + let mut h = Harness::new(); + h.app.home.open = false; + let saved_place = Some([120.0, 80.0, 520.0, 700.0]); + h.app.preferences.agent_chat_window = saved_place; + h.call("ui.agent_chat", json!({"open":true,"popped":true,"picker":false})); + h.frames(3); + assert!(rect_of("agent_chat:window").is_some() && h.app.agent_chat.window_placed); + h.app.agent_chat.input = "native window draft".into(); + assert_panel_host_preserves_design(&mut h, |h| { + crate::panel_runtime::enable_host_specimen(&mut h.app, "tabs").unwrap(); + h.frames(4); + assert!(rect_of("agent_chat:window").is_some(), "host enablement must still invoke the existing native-window producer"); + assert!(rect_of("agent_chat:panel").is_none()); + assert!(h.app.agent_chat.window_placed && h.app.agent_chat.open && h.app.preferences.agent_chat_popped); + assert_eq!(h.app.agent_chat.input, "native window draft"); + let domain = h.app.viewport.rect.unwrap(); + assert_eq!(crate::agent_chat::tool_space(&h.app, domain), domain); + h.step(&json!({"click":{"handle":"agent_chat:dock"}})).unwrap(); + h.frames(2); + assert!(!h.app.preferences.agent_chat_popped && !h.app.agent_chat.window_placed); + assert!(rect_of("agent_chat:window").is_none()); + assert!(h.app.agent_chat.panel_rect.is_none() && h.app.agent_chat.drop_rect.is_none() && h.app.agent_chat.dock_space.is_none()); + assert_eq!(h.app.preferences.agent_chat_window, saved_place, "Dock retains the saved opening position and size"); + assert!(h.app.agent_chat.open); + assert_eq!(h.app.agent_chat.input, "native window draft"); + h.call("ui.agent_chat", json!({"popped":true})); + h.frames(3); + assert!(rect_of("agent_chat:window").is_some() && h.app.agent_chat.window_placed); + assert_eq!(h.app.preferences.agent_chat_window, saved_place); + + h.app.agent_chat.items.push(crate::agent_chat::Item::Agent { thought: false, text: "Retained transcript before New Chat".into() }); + h.app.agent_chat.pending.push(crate::agent_chat::Pending { + text: "Retained queued message".into(), + image: false, + context: Default::default(), + files: Vec::new(), + }); + h.frames(2); + let pending = h.app.agent_chat.pending.clone(); + let transcript = rect_of("agent_chat:msg:0").expect("the real transcript publishes its message footprint").center(); + assert!(h.app.agent_chat.panel_rect.unwrap().contains(transcript)); + let composer = egui::Id::unique("sc_agent_chat_input"); + h.ctx.memory_mut(|memory| memory.surrender_focus(composer)); + assert!(!h.ctx.memory(|memory| memory.has_focus(composer))); + assert!(crate::agent_chat::new_chat_needs_confirm(&h.app)); + assert!(!h.app.agent_chat.confirm_new); + // Existing New Chat is Command/Ctrl+Shift+L, including transcript hover. + h.frame_with(vec![ + egui::Event::PointerMoved(transcript), + egui::Event::Key { + key: egui::Key::L, + physical_key: Some(egui::Key::L), + pressed: true, + repeat: false, + modifiers: egui::Modifiers::COMMAND.plus(egui::Modifiers::SHIFT), + }, + ]); + assert!(h.app.agent_chat.confirm_new, "hover routes New Chat without composer focus"); + assert_eq!(h.app.agent_chat.pending, pending, "the existing guard keeps queued work until confirmation"); + assert!( + matches!(h.app.agent_chat.items.as_slice(), [crate::agent_chat::Item::Agent { text, .. }] if text == "Retained transcript before New Chat") + ); + assert_eq!(h.app.agent_chat.input, "native window draft"); + h.frame_with(vec![egui::Event::Key { + key: egui::Key::L, + physical_key: Some(egui::Key::L), + pressed: false, + repeat: false, + modifiers: egui::Modifiers::COMMAND.plus(egui::Modifiers::SHIFT), + }]); + h.step(&json!({"click":{"handle":"agent_chat:new_confirm"}})).unwrap(); + h.frames(2); + assert!(!h.app.agent_chat.confirm_new && !crate::agent_chat::new_chat_needs_confirm(&h.app)); + assert!(h.app.agent_chat.items.is_empty() && h.app.agent_chat.pending.is_empty()); + assert_eq!(h.app.agent_chat.input, "native window draft", "existing New Chat leaves the unsent composer draft intact"); + h.app.disable_universal_panel_host().unwrap(); + h.frames(3); + assert!(rect_of("agent_chat:window").is_some() && h.app.agent_chat.window_placed); + assert_eq!(h.app.agent_chat.input, "native window draft"); + }); +} + +fn panel_host_point(h: &Harness, target: crate::panel_runtime::HostPointerTarget) -> egui::Pos2 { + let bounds = + h.app.universal_panel_frame().unwrap().layout.control(&target).unwrap_or_else(|| panic!("missing actual host control {target:?}")).bounds; + egui::pos2(bounds.origin.x + bounds.size.width * 0.5, bounds.origin.y + bounds.size.height * 0.5) +} + +fn panel_host_drop_point( + h: &Harness, + instance: &solidcraft_engine::panels::InstanceId, + target: &crate::panel_runtime::HostDropTargetId, +) -> egui::Pos2 { + let frame = h.app.universal_panel_frame().unwrap(); + let targets = crate::panel_runtime::host_drop_targets(h.app.panel_runtime().unwrap().layout(), &frame.layout, instance).unwrap(); + let bounds = + targets.iter().rev().find(|candidate| candidate.id == *target).unwrap_or_else(|| panic!("missing explicit landing {target:?}")).bounds; + egui::pos2(bounds.origin.x + bounds.size.width / 2.0, bounds.origin.y + bounds.size.height / 2.0) +} + +fn panel_host_pointer(h: &mut Harness, at: egui::Pos2, pressed: bool) { + h.frame_with(vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, + ]); +} + +fn panel_host_click(h: &mut Harness, at: egui::Pos2) { + h.frame_with(vec![egui::Event::PointerMoved(at)]); + panel_host_pointer(h, at, true); + panel_host_pointer(h, at, false); +} + +fn panel_host_key(h: &mut Harness, key: egui::Key) { + h.frame_with(vec![egui::Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }]); + h.frame_with(vec![egui::Event::Key { key, physical_key: Some(key), pressed: false, repeat: false, modifiers: egui::Modifiers::NONE }]); +} + +fn panel_host_semantic_click(h: &mut Harness, target: crate::panel_runtime::HostControlTarget) { + let bounds = h + .app + .universal_panel_frame() + .unwrap() + .controls + .iter() + .find(|control| control.target == target) + .unwrap_or_else(|| panic!("missing actual action {target:?}")) + .bounds; + panel_host_click(h, egui::pos2(bounds.origin.x + bounds.size.width / 2.0, bounds.origin.y + bounds.size.height / 2.0)); + h.frames(2); +} + +fn assert_panel_host_landing(h: &Harness, shown: &crate::panel_runtime::HostLayout) { + let committed = &h.app.universal_panel_frame().unwrap().layout; + assert_eq!(committed.sections, shown.sections, "paint the exact admitted slots and neighbours"); + assert_eq!(committed.resolved.panels, shown.resolved.panels); + assert_eq!(committed.extent, shown.extent); + assert_eq!(committed.allocation_environment.scroll, shown.allocation_environment.scroll); + assert_eq!(committed.render_domain, shown.render_domain); +} + +fn warm_empty_universal_canvas_before_cold_cards(h: &mut Harness) { + use solidcraft_engine::panels::{Layout, LayoutAction}; + if h.app.universal_panel_frame().is_none() { + let capacity = crate::panel_runtime::logical_rect(h.ctx.content_rect()); + let app = &mut h.app; + app.panel_runtime.as_mut().unwrap().prepare_host(&app.session, capacity).unwrap(); + } + let saved = h.app.panel_runtime().unwrap().layout().layout().clone(); + h.app.dispatch_panel_layout(LayoutAction::Replace { expected_revision: None, layout: Layout::empty(saved.workspace.clone()) }).unwrap(); + // The universal canvas has a distinct egui identity. Establish its actual + // hit rectangle without creating floating Area sizing state. + h.frames(2); + let empty = h.app.universal_panel_frame().unwrap(); + assert!(empty.layout.sections.is_empty()); + assert!(empty.layout.painted.is_empty() && empty.layout.input.is_empty()); + assert!(h.app.viewport.rect.is_some()); + h.app.dispatch_panel_layout(LayoutAction::Replace { expected_revision: None, layout: saved }).unwrap(); +} + +#[test] +fn actual_tabs_preset_raw_widget_drag_retains_the_inactive_editor_identity_and_draft() { + use crate::panel_runtime::{HostControlTarget, HostEvent, HostPointerTarget, enable_host_specimen, inspect_host_specimen}; + use solidcraft_engine::panels::{Destination, InstanceId, Point, SectionId}; + fn editor_probe(observation: &serde_json::Value) -> &serde_json::Value { + observation["runtime"]["probe"]["controllers"].as_array().unwrap().iter().find(|controller| controller["instance"] == "specimen-0").unwrap() + } + fn assert_inactive_editor_has_not_rendered(h: &mut Harness, before: &serde_json::Value) { + let observation = inspect_host_specimen(&mut h.app).unwrap(); + let editor = editor_probe(&observation); + assert_eq!(editor["state"]["presented"], false); + assert_eq!(editor["renders"], before["renders"], "press, preview and cancellation cannot render the inactive editor"); + } + for scale in [1.0, 2.0] { + let mut h = Harness::new(); + h.app.home.open = false; + h.ctx.set_pixels_per_point(scale); + enable_host_specimen(&mut h.app, "tabs").unwrap(); + h.frames(3); + let editor = InstanceId::new("specimen-0").unwrap(); + let source_id = SectionId::new("specimen-section-0").unwrap(); + let destination_id = SectionId::new("specimen-section-1").unwrap(); + let body = h.app.universal_panel_frame().unwrap().layout.sections.iter().find(|section| section.instance == editor).unwrap().body.unwrap(); + let draft_label = h.app.tr("ui.panel_fixture.draft").to_string(); + let mut edit_at = None; + for _ in 0..8 { + let nodes = &h.output.accesskit_update.as_ref().unwrap().nodes; + edit_at = nodes + .iter() + .filter(|(_, node)| { + node.role() == egui::accesskit::Role::MultilineTextInput + && nodes.iter().any(|(id, label)| { + node.labelled_by().contains(id) + && label.role() == egui::accesskit::Role::Label + && label.value() == Some(draft_label.as_str()) + }) + }) + .find_map(|(_, node)| { + let bounds = node.bounds()?; + let at = Point { x: ((bounds.x0 + bounds.x1) / 2.0) as f32, y: ((bounds.y0 + bounds.y1) / 2.0) as f32 }; + body.contains(at).then_some(egui::pos2(at.x, at.y)) + }); + if edit_at.is_some() { + break; + } + let at = egui::pos2(body.origin.x + body.size.width / 2.0, body.origin.y + body.size.height / 2.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, -64.0), + modifiers: egui::Modifiers::NONE, + phase: egui::TouchPhase::Move, + }, + ]); + h.frames(8); + } + let edit_at = edit_at.expect("the actual specimen editor has a reachable accessible text input inside its body"); + panel_host_click(&mut h, edit_at); + h.frame_with(vec![egui::Event::Text("Draft entered through the specimen text field".into())]); + panel_host_semantic_click(&mut h, HostControlTarget::Pointer(HostPointerTarget::Tab { instance: InstanceId::new("specimen-2").unwrap() })); + let observation = inspect_host_specimen(&mut h.app).unwrap(); + let before_editor = editor_probe(&observation).clone(); + assert_eq!(before_editor["draft"], "Draft entered through the specimen text field"); + assert_eq!(before_editor["state"]["presented"], false); + + assert_panel_host_preserves_design(&mut h, |h| { + let before = h.app.panel_runtime().unwrap().layout().inspect(); + let target = HostControlTarget::Pointer(HostPointerTarget::Tab { instance: editor.clone() }); + let control = h.app.universal_panel_frame().unwrap().controls.iter().find(|control| control.target == target).unwrap(); + assert!( + h.output + .accesskit_update + .as_ref() + .unwrap() + .nodes + .iter() + .any(|(_, node)| node.role() == egui::accesskit::Role::Button && node.label() == Some(control.accessible_name.as_str())), + "use an actual accessible Tab widget, not a reducer-only target" + ); + let bounds = control.bounds; + let card = h.app.universal_panel_frame().unwrap().layout.sections.iter().find(|card| card.section == source_id).unwrap(); + assert_eq!(bounds.origin.y, card.header.origin.y); + assert_eq!(bounds.size.height, card.header.size.height); + assert!(!crate::panel_runtime::egui_rect(card.title.unwrap()).intersect(crate::panel_runtime::egui_rect(bounds)).is_positive()); + let start = egui::pos2(bounds.origin.x + bounds.size.width / 2.0, bounds.origin.y + bounds.size.height / 2.0); + h.frame_with(vec![egui::Event::PointerMoved(start)]); + panel_host_pointer(h, start, true); + assert_inactive_editor_has_not_rendered(h, &before_editor); + h.frame_with(vec![egui::Event::PointerMoved(start + egui::vec2(5.99, 0.0))]); + assert!(h.app.universal_panel_frame().unwrap().preview.is_none()); + assert_eq!(h.app.panel_runtime().unwrap().layout().inspect(), before); + assert_inactive_editor_has_not_rendered(h, &before_editor); + h.frame_with(vec![egui::Event::PointerMoved(start + egui::vec2(6.0, 0.0))]); + assert!(h.app.universal_panel_frame().unwrap().preview.is_some()); + assert_eq!(h.app.panel_runtime().unwrap().layout().inspect(), before); + assert_inactive_editor_has_not_rendered(h, &before_editor); + let end = + panel_host_drop_point(h, &editor, &crate::panel_runtime::HostDropTargetId::Tab { section: destination_id.clone(), before: None }); + h.frame_with(vec![egui::Event::PointerMoved(end)]); + let preview = h.app.universal_panel_frame().unwrap().preview.as_ref().unwrap(); + assert_eq!(preview.destination, Some(Destination::JoinTab { section: destination_id.clone(), index: 2 })); + assert!(preview.rejection.is_none()); + let candidate = preview.projected.clone().expect("the preview includes the exact landing and affected neighbours"); + assert!(preview.tab_marker.is_some()); + assert_eq!(h.app.panel_runtime().unwrap().layout().inspect(), before); + assert_inactive_editor_has_not_rendered(h, &before_editor); + panel_host_key(h, egui::Key::Escape); + panel_host_pointer(h, start + egui::vec2(6.0, 0.0), false); + h.frames(2); + assert_eq!( + h.app.panel_runtime().unwrap().layout().inspect(), + before, + "Escape and the eventual real Tab release cannot activate the inactive editor" + ); + assert!(h.app.universal_panel_frame().unwrap().preview.is_none()); + assert!(!h.app.panel_runtime_mut().unwrap().host().unwrap().interaction().is_captured()); + assert_inactive_editor_has_not_rendered(h, &before_editor); + + // A fresh accepted drag activates the retained editor only as part + // of the same Move+Activate transaction that makes its landing visible. + let start = panel_host_point(h, HostPointerTarget::Tab { instance: editor.clone() }); + panel_host_pointer(h, start, true); + h.frame_with(vec![egui::Event::PointerMoved(end)]); + let preview = h.app.universal_panel_frame().unwrap().preview.as_ref().unwrap(); + assert_eq!(preview.destination, Some(Destination::JoinTab { section: destination_id.clone(), index: 2 })); + assert!(preview.rejection.is_none() && preview.tab_marker.is_some()); + assert_eq!(preview.projected.as_ref(), Some(&candidate)); + let projected = preview.projected.clone().unwrap(); + assert_inactive_editor_has_not_rendered(h, &before_editor); + panel_host_pointer(h, end, false); + let release = h.app.universal_panel_frame().unwrap(); + let commits = release + .events + .iter() + .filter_map(|event| match event { + HostEvent::PreparedCommitted { reply } => Some(reply), + _ => None, + }) + .collect::>(); + assert_eq!(commits.len(), 1, "consume the shown candidate exactly once"); + assert_eq!(commits[0].revision, before.revision + 1); + h.frames(2); + let layout = h.app.panel_runtime().unwrap().layout().layout(); + assert_eq!(layout.section(&source_id).unwrap().tabs, vec![InstanceId::new("specimen-2").unwrap()]); + assert_eq!(layout.section(&source_id).unwrap().active, InstanceId::new("specimen-2").unwrap()); + let destination = layout.section(&destination_id).unwrap(); + assert_eq!(destination.tabs, vec![InstanceId::new("specimen-1").unwrap(), InstanceId::new("specimen-3").unwrap(), editor.clone()]); + assert_eq!(destination.active, editor.clone(), "the dragged retained editor is the visible landing tab"); + assert_eq!(layout.sections.len(), 2); + assert_eq!(h.app.panel_runtime().unwrap().layout().inspect().revision, before.revision + 1); + assert_panel_host_landing(h, &projected); + }); + let after = inspect_host_specimen(&mut h.app).unwrap(); + let retained = editor_probe(&after); + for field in ["controller_identity", "draft", "transaction_live", "applies", "cancels", "finishes", "reopens", "destroys"] { + assert_eq!(retained[field], before_editor[field], "retained editor state survives its actual Tab drag: {field}"); + } + assert_eq!(retained["state"]["presented"], true); + assert!( + retained["renders"].as_u64().unwrap() > before_editor["renders"].as_u64().unwrap(), + "the accepted active landing must actually render the editor" + ); + assert_eq!(retained["reparents"].as_u64().unwrap(), before_editor["reparents"].as_u64().unwrap() + 1); + assert!(retained["updates"].as_u64().unwrap() > before_editor["updates"].as_u64().unwrap()); + assert_eq!(after["runtime"]["controller_count"], observation["runtime"]["controller_count"]); + assert_eq!(after["runtime"]["probe"]["content_command_calls"], 0); + } +} + +#[test] +fn actual_clamped_floating_resize_preserves_session_provider_controller_and_camera_invariants() { + use crate::panel_runtime::{HostEvent, HostPointerTarget, HostResizeEdge, enable_host_specimen, inspect_host_specimen}; + use solidcraft_engine::panels::{LayoutAction, Mutation, Point, SectionId, Size}; + for scale in [1.0, 2.0] { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.run("solid.box", json!({"length":40,"width":30,"height":20})).unwrap(); + h.settle(); + h.call("ui.resize", json!({"width":800,"height":800})); + h.ctx.set_pixels_per_point(scale); + enable_host_specimen(&mut h.app, "floating").unwrap(); + h.frames(3); + let section_id = SectionId::new("specimen-section-0").unwrap(); + h.app + .dispatch_panel_layout(LayoutAction::Apply { + expected_revision: None, + mutations: vec![Mutation::SetFloatingRect { + section: section_id.clone(), + origin: Point { x: 1000.0, y: 0.0 }, + size: Size { width: 280.0, height: 240.0 }, + }], + }) + .unwrap(); + h.frames(3); + let observations = inspect_host_specimen(&mut h.app).unwrap(); + assert_panel_host_preserves_design(&mut h, |h| { + let before = h.app.panel_runtime().unwrap().layout().inspect(); + let layout = &h.app.universal_panel_frame().unwrap().layout; + let gap = crate::ui_kit::Container::new(&h.ctx, crate::ui_kit::Surface::Panel).gap(); + assert_eq!(layout.capacity.size.width, layout.render_domain.size.width - 2.0 * gap); + let outer = layout.sections.iter().find(|section| section.section == section_id).unwrap().outer; + assert_eq!(outer.origin.x, layout.capacity.origin.x + layout.capacity.size.width - 280.0 - layout.allocation_environment.scroll.x); + assert_eq!(outer.size, Size { width: 280.0, height: 240.0 }); + let expected = solidcraft_engine::panels::LogicalRect { origin: outer.origin, size: Size { width: 250.0, height: 240.0 } }; + let start = panel_host_point(h, HostPointerTarget::Resize { section: section_id.clone(), edge: HostResizeEdge::BottomRight }); + h.frame_with(vec![egui::Event::PointerMoved(start)]); + panel_host_pointer(h, start, true); + let end = start - egui::vec2(30.0, 0.0); + h.frame_with(vec![egui::Event::PointerMoved(end)]); + let preview = h.app.universal_panel_frame().unwrap().preview.as_ref().unwrap().clone(); + assert_eq!(preview.bounds, expected); + assert!(preview.rejection.is_none()); + assert_eq!(h.app.panel_runtime().unwrap().layout().inspect(), before); + panel_host_pointer(h, end, false); + let actions = h + .app + .universal_panel_frame() + .unwrap() + .events + .iter() + .filter_map(|event| if let HostEvent::PreparedCommitted { reply } = event { Some(reply) } else { None }) + .collect::>(); + assert_eq!(actions.len(), 1); + assert_eq!(actions[0].revision, before.revision + 1); + h.frames(2); + assert_eq!( + h.app.universal_panel_frame().unwrap().layout.sections.iter().find(|section| section.section == section_id).unwrap().outer, + expected + ); + assert_eq!(h.app.panel_runtime().unwrap().layout().inspect().revision, before.revision + 1); + }); + let after = inspect_host_specimen(&mut h.app).unwrap(); + assert_eq!(after["runtime"]["controller_count"], observations["runtime"]["controller_count"]); + assert_eq!(after["runtime"]["probe"]["content_command_calls"], 0); + for before in observations["runtime"]["probe"]["controllers"].as_array().unwrap() { + let retained = after["runtime"]["probe"]["controllers"] + .as_array() + .unwrap() + .iter() + .find(|controller| controller["instance"] == before["instance"] && controller["owner"] == before["owner"]) + .unwrap(); + for field in ["controller_identity", "draft", "transaction_live", "reparents", "applies", "cancels", "finishes", "destroys"] { + assert_eq!(retained[field], before[field], "rect-only application resize must retain its controller/provider state: {field}"); + } + } + } +} + +#[test] +fn actual_host_raw_pointer_threshold_preview_escape_and_drop_preserve_the_design_at_both_scales() { + use crate::panel_runtime::HostPointerTarget; + use solidcraft_engine::panels::{InstanceId, Zone}; + for scale in [1.0, 2.0] { + for zone in [Zone::Left, Zone::Right, Zone::Bottom] { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.run("solid.box", json!({"length":40,"width":30,"height":20})).unwrap(); + h.call("ui.resize", json!({"width":1280,"height":800})); + h.ctx.set_pixels_per_point(scale); + crate::panel_runtime::enable_host_specimen(&mut h.app, "docks").unwrap(); + h.frames(4); + assert_panel_host_preserves_design(&mut h, |h| { + let before = h.app.panel_runtime().unwrap().layout().inspect(); + let projection = h.app.viewport.rect; + let target = HostPointerTarget::Header { instance: InstanceId::new("specimen-0").unwrap() }; + let start = panel_host_point(h, target.clone()); + panel_host_pointer(h, start, true); + h.frame_with(vec![egui::Event::PointerMoved(start + egui::vec2(5.99, 0.0))]); + assert!(h.app.universal_panel_frame().unwrap().preview.is_none()); + h.frame_with(vec![egui::Event::PointerMoved(start + egui::vec2(6.0, 0.0))]); + assert!(h.app.universal_panel_frame().unwrap().preview.is_some(), "six logical points, including 12 physical pixels at 200%"); + assert_eq!(h.app.panel_runtime().unwrap().layout().inspect(), before); + assert_eq!(h.app.viewport.rect, projection, "preview must not move camera projection"); + panel_host_key(h, egui::Key::Escape); + panel_host_pointer(h, start, false); + assert_eq!(h.app.panel_runtime().unwrap().layout().inspect(), before); + assert!(h.app.universal_panel_frame().unwrap().preview.is_none()); + let capacity = h.app.universal_panel_frame().unwrap().layout.capacity; + let x0 = capacity.origin.x; + let y0 = capacity.origin.y; + let w = capacity.size.width; + let height = capacity.size.height; + let drop = match zone { + Zone::Left => egui::pos2(x0 + 1.0, y0 + height * 0.5), + Zone::Right => egui::pos2(x0 + w - 1.0, y0 + height * 0.5), + Zone::Bottom => egui::pos2(x0 + w * 0.5, y0 + height - 1.0), + _ => egui::pos2(x0 + w * 0.5, y0 + height * 0.5), + }; + let start = panel_host_point(h, target); + panel_host_pointer(h, start, true); + h.frame_with(vec![egui::Event::PointerMoved(start + egui::vec2(8.0, 0.0))]); + h.frame_with(vec![egui::Event::PointerMoved(drop)]); + let landing = h.app.universal_panel_frame().unwrap().preview.as_ref().unwrap(); + assert!(landing.rejection.is_none()); + let projected = landing.projected.clone().expect("explicit target resolves final affected geometry"); + assert_eq!(h.app.panel_runtime().unwrap().layout().inspect(), before); + panel_host_pointer(h, drop, false); + h.frames(3); + let reply = h.app.panel_runtime().unwrap().layout().inspect(); + assert_eq!(reply.revision, before.revision + 1, "one release commits once at scale {scale}: {zone:?}"); + assert_eq!(reply.layout.containing(&InstanceId::new("specimen-0").unwrap()).unwrap().location.zone(), zone); + assert_eq!(h.app.universal_panel_frame().unwrap().reply, reply, "published frame must describe committed state"); + assert_panel_host_landing(h, &projected); + }); + } + } +} + +#[test] +fn host_full_canvas_and_same_pass_controls_follow_actual_sizing_footprints_without_moving_the_model() { + use crate::panel_runtime::{enable_host_specimen, logical_rect}; + use solidcraft_engine::panels::{LayoutAction, Mutation, Point, Size}; + for scale in [1.0, 2.0] { + for mode in [LayoutMode::Docked, LayoutMode::Floating] { + for preset in ["docks", "floating", "collapsed"] { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.ui.layout = mode; + h.call("ui.resize", json!({"width":1400,"height":1000})); + h.app.run("solid.box", json!({"length":40,"width":30,"height":20})).unwrap(); + h.settle(); + h.ctx.set_pixels_per_point(scale); + h.ctx.options_mut(|options| options.max_passes = 1.try_into().unwrap()); + h.app.preferences.navigation_bar.position = match preset { + "docks" => crate::navigation_bar::Position::Centre, + "floating" => crate::navigation_bar::Position::Left, + _ => crate::navigation_bar::Position::Right, + }; + let camera = h.app.cam; + enable_host_specimen(&mut h.app, preset).unwrap(); + warm_empty_universal_canvas_before_cold_cards(&mut h); + if preset == "floating" { + let sections = + h.app.panel_runtime().unwrap().layout().layout().sections.iter().map(|section| section.id.clone()).collect::>(); + let origins = + [Point { x: 500.0, y: 300.0 }, Point { x: 40.0, y: 220.0 }, Point { x: 40.0, y: 560.0 }, Point { x: 400.0, y: 650.0 }]; + h.app + .dispatch_panel_layout(LayoutAction::Apply { + expected_revision: None, + mutations: sections + .into_iter() + .zip(origins) + .map(|(section, origin)| Mutation::SetFloatingRect { section, origin, size: Size { width: 280.0, height: 240.0 } }) + .collect(), + }) + .unwrap(); + } + let pointer = egui::pos2(640.0, 420.0); + let mut first_projection = None; + for visible_pass in [false, true] { + h.frame_with(vec![egui::Event::PointerMoved(pointer)]); + let frame = h.app.universal_panel_frame().unwrap(); + let domain = h.app.viewport.rect.unwrap(); + assert_eq!(domain, egui::Rect::from_min_max(egui::pos2(0.0, toolbar::APP_BAR_HEIGHT), h.ctx.content_rect().max)); + assert_eq!(frame.layout.render_domain, logical_rect(domain)); + assert_eq!(frame.layout.viewport, Some(logical_rect(domain))); + assert_eq!(h.app.cam, camera); + let model_points = [solidcore_record::Vec3::ZERO, solidcore_record::Vec3::new(40.0, 30.0, 20.0)] + .map(|point| crate::viewport::projection(&h.app, domain).to_screen(point)); + if let Some(first) = first_projection { + assert_eq!(model_points, first, "the newly visible panel cannot shift model pixels or framing"); + } else { + first_projection = Some(model_points); + } + let controls = h.app.viewport.layout.as_ref().unwrap(); + assert_eq!(controls.viewport, domain); + for (name, bounds) in [("nav:outer", controls.navigation), ("axis_view:outer", controls.axis_view)] { + if bounds.is_positive() { + assert_eq!(rect_of(name), Some(bounds), "the published control and final same-pass metadata agree"); + assert!(frame.layout.usable.contains_rect(logical_rect(bounds))); + assert!(frame.layout.usable.obstacles.iter().all(|obstacle| { + !bounds + .expand(crate::theme::Tokens::get().space_4) + .intersect(crate::panel_runtime::egui_rect(*obstacle)) + .is_positive() + })); + } else { + assert!(rect_of(name).is_none()); + } + } + assert!(controls.navigation.is_positive(), "the measured navbar remains accessible in ample usable space"); + assert!(!controls.navigation.intersect(controls.axis_view).is_positive()); + if preset == "floating" { + let inside = Point { x: pointer.x, y: pointer.y }; + assert_eq!(frame.layout.consumes_pointer(inside), visible_pass); + assert_eq!( + h.app.viewport.mouse, + if visible_pass { None } else { Some(pointer) }, + "first invisible sizing reaches navigation; the next actual card shields it" + ); + } + } + } + } + } +} + +#[test] +fn first_invisible_host_sizing_pass_allows_real_wheel_navigation_and_the_visible_card_blocks_it() { + use solidcraft_engine::panels::{LayoutAction, Mutation, Point, Size}; + for scale in [1.0, 2.0] { + for mode in [LayoutMode::Docked, LayoutMode::Floating] { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.ui.layout = mode; + h.call("ui.resize", json!({"width":1400,"height":1000})); + h.app.run("solid.box", json!({"length":40,"width":30,"height":20})).unwrap(); + h.settle(); + h.ctx.set_pixels_per_point(scale); + h.ctx.options_mut(|options| options.max_passes = 1.try_into().unwrap()); + crate::panel_runtime::enable_host_specimen(&mut h.app, "floating").unwrap(); + warm_empty_universal_canvas_before_cold_cards(&mut h); + let sections = h.app.panel_runtime().unwrap().layout().layout().sections.iter().map(|section| section.id.clone()).collect::>(); + let origins = [Point { x: 500.0, y: 300.0 }, Point { x: 40.0, y: 220.0 }, Point { x: 40.0, y: 560.0 }, Point { x: 400.0, y: 650.0 }]; + h.app + .dispatch_panel_layout(LayoutAction::Apply { + expected_revision: None, + mutations: sections + .into_iter() + .zip(origins) + .map(|(section, origin)| Mutation::SetFloatingRect { section, origin, size: Size { width: 280.0, height: 240.0 } }) + .collect(), + }) + .unwrap(); + let at = egui::pos2(640.0, 420.0); + let wheel = || { + 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, + }, + ] + }; + let before = h.app.cam; + h.frame_with(wheel()); + assert!(!h.app.universal_panel_frame().unwrap().layout.consumes_pointer(Point { x: at.x, y: at.y })); + assert_eq!(h.app.viewport.mouse, Some(at)); + assert_ne!(h.app.cam.distance.to_bits(), before.distance.to_bits(), "the real first-pass wheel reaches the existing navigation path"); + let navigated = h.app.cam; + h.frame_with(wheel()); + assert!(h.app.universal_panel_frame().unwrap().layout.consumes_pointer(Point { x: at.x, y: at.y })); + assert!(h.app.viewport.mouse.is_none()); + assert_eq!(h.app.cam, navigated, "an actual visible card shields the next wheel without moving projection"); + h.frames(3); + assert_eq!(h.app.cam, navigated, "blocked input cannot leave delayed navigation behind"); + } + } +} + +#[test] +fn actual_host_fit_and_centring_respect_the_measured_sketch_palette_at_both_scales() { + use crate::panel_runtime::{HostControlTarget, HostPointerTarget, egui_rect, enable_host_specimen, logical_rect}; + use solidcore_record::Vec3; + use solidcraft_engine::geom::{Aabb3, Vec3Geom as _}; + use solidcraft_engine::panels::{InstanceId, LayoutAction, Mutation}; + fn projected_extent(h: &Harness, bounds: Aabb3) -> egui::Rect { + let domain = h.app.viewport.rect.unwrap(); + let projection = crate::viewport::projection(&h.app, domain); + let mut extent = egui::Rect::NOTHING; + for x in [bounds.min.x, bounds.max.x] { + for y in [bounds.min.y, bounds.max.y] { + for z in [bounds.min.z, bounds.max.z] { + extent.extend_with(projection.to_screen(Vec3::new(x, y, z)).expect("every actual sketch-bound corner must project")); + } + } + } + extent + } + fn assert_palette_and_controls(h: &Harness, palette: egui::Rect) { + let frame = h.app.universal_panel_frame().unwrap(); + let layout = h.app.viewport.layout.as_ref().unwrap(); + let usable = layout.usable.as_ref().unwrap(); + let effective = crate::shell::host_usable(&h.app).unwrap(); + assert_eq!(rect_of("sketch_palette:outer"), Some(palette)); + assert!(crate::shell::fit_rects(&h.app).contains(&palette), "the palette must be an actual persistent footprint"); + assert!(usable.obstacles.contains(&logical_rect(palette))); + assert!(usable.free.iter().all(|piece| !egui_rect(*piece).intersect(palette).is_positive())); + for (name, control) in [("nav:outer", layout.navigation), ("axis_view:outer", layout.axis_view)] { + if control.is_positive() { + assert_eq!(rect_of(name), Some(control), "published controls must match the actual same-pass footprint"); + assert!(!control.expand(crate::theme::Tokens::get().space_4).intersect(palette).is_positive()); + assert!(effective.contains_rect(logical_rect(control))); + assert!(frame.layout.usable.obstacles.iter().all(|obstacle| !control.intersect(egui_rect(*obstacle)).is_positive())); + } else { + assert!(rect_of(name).is_none()); + } + } + } + for scale in [1.0, 2.0] { + for mode in [LayoutMode::Docked, LayoutMode::Floating] { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.ui.layout = mode; + h.app.preferences.look_at_anim = false; + h.app.preferences.navigator_fit = false; + h.app.preferences.home_fit_size = 1.0; + h.call("ui.resize", json!({"width":1400,"height":1000})); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.app.run("sketch.line", json!({"points":[[0,0],[100,0]],"infer":false,"connect":false})).unwrap(); + h.settle(); + h.ctx.set_pixels_per_point(scale); + enable_host_specimen(&mut h.app, "docks").unwrap(); + h.frames(4); + let sketch = h.app.session.active_sketch.expect("the real sketch palette requires an active sketch"); + let palette = h.app.viewport.palette_rect.expect("the actual sketch palette must paint beside the host"); + let domain = h.app.viewport.rect.unwrap(); + assert_eq!(domain, egui::Rect::from_min_max(egui::pos2(0.0, toolbar::APP_BAR_HEIGHT), h.ctx.content_rect().max)); + assert!(domain.contains_rect(palette)); + assert!( + h.app.universal_panel_frame().unwrap().layout.usable.free.iter().any(|piece| egui_rect(*piece).intersect(palette).is_positive()), + "the palette must cover space beyond host-only footprints, so this exercises the missing union" + ); + assert_palette_and_controls(&h, palette); + let bounds = crate::viewport::view_bounds(&h.app); + assert!((bounds.max.x - bounds.min.x - 100.0).abs() < 1e-8); + h.app.fit_view(); + h.settle(); + assert_eq!(h.app.viewport.rect, Some(domain), "explicit fitting preserves the full render domain"); + let footprint = projected_extent(&h, bounds); + let padded = footprint.expand(crate::theme::Tokens::get().space_8 - 0.01); + assert!( + h.app.viewport.layout.as_ref().unwrap().usable.as_ref().unwrap().contains_rect(logical_rect(padded)), + "{scale}x {mode:?}: the full 100 mm line and its clearance must avoid the palette, host and controls: {padded:?}" + ); + for endpoint in [Vec3::ZERO, Vec3::new(100.0, 0.0, 0.0)] { + let point = crate::viewport::projection(&h.app, domain).to_screen(endpoint).unwrap(); + assert!(domain.contains(point) && !palette.contains(point)); + } + let fitted = h.app.cam; + let contour = h.app.viewport.layout.as_ref().unwrap().usable.clone(); + let editor = InstanceId::new("specimen-0").unwrap(); + panel_host_semantic_click(&mut h, HostControlTarget::Pointer(HostPointerTarget::Menu { instance: editor.clone() })); + assert!(h.app.universal_panel_frame().unwrap().menu_bounds.is_some()); + assert_eq!(h.app.viewport.layout.as_ref().unwrap().usable, contour, "transient host menus cannot change the fitting/control contour"); + h.app.fit_view(); + h.settle(); + assert_eq!(h.app.cam, fitted); + panel_host_key(&mut h, egui::Key::Escape); + + h.app.cam.distance = 2.0; + h.app.cam.yaw = 1.0; + h.app.cam.pitch = 0.2; + let distance = h.app.cam.distance.to_bits(); + let lens = h.app.cam.fov.to_bits(); + let look_at = crate::scenario::handle_at("sketch_palette:look_at").unwrap(); + assert!(palette.contains(look_at)); + panel_host_click(&mut h, look_at); + h.settle(); + assert_eq!(h.app.cam.distance.to_bits(), distance, "explicit palette Look At must not zoom out to fit an oversized line"); + assert_eq!(h.app.cam.fov.to_bits(), lens); + assert!(h.app.cam.back().dist(Vec3::Z) < 1e-6); + let focus = crate::viewport::projection(&h.app, domain).to_screen(Vec3::new(50.0, 0.0, 0.0)).unwrap(); + assert!(h.app.viewport.layout.as_ref().unwrap().usable.as_ref().unwrap().free.iter().any(|piece| egui_rect(*piece).contains(focus))); + h.app.run("select.set", json!({"items":[{"type":"plane","name":"XY"}]})).unwrap(); + let selection = h.app.session.selection.clone(); + h.app.start("view.normal_to"); + h.settle(); + assert_eq!(h.app.cam.distance.to_bits(), distance); + assert_eq!(h.app.cam.fov.to_bits(), lens); + assert!(h.app.cam.back().dist(-Vec3::Z) < 1e-6, "normal-to retains its existing second-invocation flip semantics"); + assert_eq!(h.app.session.selection, selection); + assert_eq!(h.app.viewport.rect, Some(domain)); + let focus = crate::viewport::projection(&h.app, domain).to_screen(Vec3::ZERO).unwrap(); + assert!(h.app.viewport.layout.as_ref().unwrap().usable.as_ref().unwrap().free.iter().any(|piece| egui_rect(*piece).contains(focus))); + assert_panel_host_preserves_design(&mut h, |h| { + let section = h.app.panel_runtime().unwrap().layout().layout().containing(&editor).unwrap().id.clone(); + h.app + .dispatch_panel_layout(LayoutAction::Apply { + expected_revision: None, + mutations: vec![Mutation::Collapse { section, collapsed: true }], + }) + .unwrap(); + h.frames(3); + assert_eq!(h.app.session.active_sketch, Some(sketch)); + }); + assert_palette_and_controls(&h, h.app.viewport.palette_rect.unwrap()); + h.app.run("sketch.finish", json!({})).unwrap(); + h.settle(); + assert!(h.app.viewport.palette_rect.is_none()); + assert!(rect_of("sketch_palette:outer").is_none()); + assert!( + !h.app.viewport.layout.as_ref().unwrap().usable.as_ref().unwrap().obstacles.contains(&logical_rect(palette)), + "a closed palette cannot leave a phantom reservation" + ); + } + } +} + +#[test] +fn actual_host_full_header_restore_preserves_weights_and_leaves_gaps_for_navigation() { + use crate::panel_runtime::HostPointerTarget; + use solidcraft_engine::panels::{InstanceId, Point}; + for scale in [1.0, 2.0] { + let mut h = Harness::new(); + h.app.home.open = false; + h.ctx.set_pixels_per_point(scale); + crate::panel_runtime::enable_host_specimen(&mut h.app, "collapsed").unwrap(); + h.frames(4); + let desired = h.app.panel_runtime().unwrap().layout().layout().clone(); + let camera = serde_json::to_value(&h.app.cam).unwrap(); + for index in [0, 1] { + let instance = InstanceId::new(format!("specimen-{index}")).unwrap(); + let at = panel_host_point(&h, HostPointerTarget::Collapse { instance: instance.clone() }); + panel_host_click(&mut h, at); + h.frames(2); + assert!(!h.app.panel_runtime().unwrap().layout().layout().containing(&instance).unwrap().collapsed); + assert!( + h.app.universal_panel_frame().unwrap().layout.sections.iter().find(|section| section.instance == instance).unwrap().body.is_some() + ); + assert!(h.app.universal_panel_frame().unwrap().layout.resolved.rails.is_empty()); + let at = panel_host_point(&h, HostPointerTarget::Collapse { instance }); + panel_host_click(&mut h, at); + h.frames(2); + } + assert_eq!(h.app.panel_runtime().unwrap().layout().layout(), &desired); + assert_eq!(serde_json::to_value(&h.app.cam).unwrap(), camera); + let frame = h.app.universal_panel_frame().unwrap(); + let left = frame.layout.sections.iter().find(|section| section.instance.0 == "specimen-0").unwrap(); + let outside = egui::pos2(left.outer.origin.x + left.outer.size.width * 0.5, frame.layout.capacity.origin.y + 160.0); + assert!(!frame.layout.consumes_pointer(Point { x: outside.x, y: outside.y })); + h.frame_with(vec![egui::Event::PointerMoved(outside)]); + assert_eq!(h.app.viewport.mouse, Some(outside), "uncovered gaps reach the existing navigation path"); + assert_eq!(serde_json::to_value(&h.app.cam).unwrap(), camera); + } +} +#[test] +fn actual_host_document_switch_and_lost_pointer_cancel_pending_drag() { + use crate::panel_runtime::HostPointerTarget; + use solidcraft_engine::panels::InstanceId; + for switch_document in [false, true] { + let mut h = Harness::new(); + h.app.home.open = false; + crate::panel_runtime::enable_host_specimen(&mut h.app, "docks").unwrap(); + h.frames(3); + let before = h.app.panel_runtime().unwrap().layout().layout().clone(); + let start = panel_host_point(&h, HostPointerTarget::Header { instance: InstanceId::new("specimen-0").unwrap() }); + panel_host_pointer(&mut h, start, true); + let drop = start + egui::vec2(500.0, 200.0); + h.frame_with(vec![egui::Event::PointerMoved(drop)]); + assert!(h.app.universal_panel_frame().unwrap().preview.is_some()); + if switch_document { + crate::documents::open_tab(&mut h.app, solidcraft_engine::Session::default()).unwrap(); + h.app.home.open = false; + h.frames(2); + } else { + h.frame_with(vec![egui::Event::PointerGone]); + } + panel_host_pointer(&mut h, drop, false); + h.frames(2); + assert!(h.app.universal_panel_frame().unwrap().preview.is_none()); + assert_eq!(h.app.panel_runtime().unwrap().layout().layout(), &before); + } +} + +#[derive(Default)] +struct ShellPanelServices { + commands: crate::panel_runtime::FakeContentCommands, + local: crate::panel_runtime::FakeLocalServices, + models: crate::panel_runtime::FakeModels, +} +impl crate::panel_runtime::AppPanelServices for ShellPanelServices { + fn refresh_read_only(&mut self, _: &solidcraft_engine::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 } + } +} + +#[test] +fn enabling_generic_runtime_alone_keeps_legacy_workspace_placement_until_host_enablement() { + use crate::panel_runtime::*; + use solidcraft_engine::panels::*; + let mut h = Harness::new(); + h.app.home.open = false; + h.frames(3); + let legacy_browser = rect_of("browser:card").unwrap(); + assert_panel_host_preserves_design(&mut h, |h| { + let mut fixture = PanelMountHarness::new(false).unwrap(); + fixture.dispatch(vec![fixture_open("fixture.log", "log", "log", Zone::Left, 0).unwrap()]).unwrap(); + h.app.enable_panel_runtime(fixture.runtime, Box::::default()).unwrap(); + h.frames(3); + assert!(!h.app.universal_panel_host_enabled()); + assert!(h.app.universal_panel_frame().is_none()); + assert_eq!(rect_of("browser:card"), Some(legacy_browser)); + let before = h.app.panel_runtime().unwrap().layout().inspect(); + let count = h.app.panel_runtime().unwrap().controller_count(); + let mut invalid = HostOptions::default(); + invalid.metrics.header_height = f32::NAN; + assert!(h.app.enable_universal_panel_host(invalid).is_err()); + assert_eq!(h.app.panel_runtime().unwrap().layout().inspect(), before); + assert_eq!(h.app.panel_runtime().unwrap().controller_count(), count); + assert!(!h.app.universal_panel_host_enabled()); + h.app.enable_universal_panel_host(HostOptions::default()).unwrap(); + h.frames(3); + assert!(rect_of("browser:card").is_none()); + h.app.disable_universal_panel_host().unwrap(); + h.frames(3); + assert_eq!(rect_of("browser:card"), Some(legacy_browser)); + assert_eq!(h.app.panel_runtime().unwrap().controller_count(), count, "host lifetime does not recreate controllers"); + }); +} + +#[test] +fn universal_host_scenarios_drive_real_shared_actions_and_leave_the_fixture_disabled() { + for (name, source) in [ + ("shared actions", include_str!("../tests/scenarios/universal_panel_host_shared_actions.json")), + ("collapsed", include_str!("../tests/scenarios/universal_panel_host_collapsed.json")), + ("columns and inline", include_str!("../tests/scenarios/universal_panel_host_columns_inline.json")), + ("overflow and scale", include_str!("../tests/scenarios/universal_panel_host_overflow_scale.json")), + ] { + let mut h = Harness::new(); + h.app.home.open = false; + let before = h.app.session.doc.clone(); + let steps: serde_json::Value = serde_json::from_str(source).unwrap(); + for (index, step) in steps.as_array().unwrap().iter().enumerate() { + let action_before = + (step["params"]["command"] == "panel.action").then(|| crate::panel_runtime::inspect_host_specimen(&mut h.app).unwrap()); + h.step(step).unwrap_or_else(|reason| panic!("{name}: step {index}: {reason}")); + if let Some(action_before) = action_before { + let after = crate::panel_runtime::inspect_host_specimen(&mut h.app).unwrap(); + let applies = |value: &serde_json::Value| { + value["runtime"]["probe"]["controllers"] + .as_array() + .unwrap() + .iter() + .find(|controller| controller["instance"] == "specimen-0") + .unwrap()["applies"] + .as_u64() + .unwrap() + }; + assert_eq!(applies(&after), applies(&action_before) + 1, "the scenario must invoke the editor's Apply binding"); + assert_eq!(after["session"], action_before["session"], "synthetic Apply leaves the Session unchanged"); + } + } + assert!(h.app.panel_runtime().is_none()); + assert!(!h.app.universal_panel_host_enabled()); + assert!(std::sync::Arc::ptr_eq(&before, &h.app.session.doc)); + assert_eq!(h.app.session.undo.len(), 0); + assert!(rect_of("browser:card").is_some()); + } +} + +#[test] +fn actual_host_resize_reset_header_collapse_restore_and_tab_join_preserve_document_cache_and_camera() { + use crate::panel_runtime::{HostControlTarget, HostPointerTarget, HostSharedAction}; + use solidcraft_engine::panels::InstanceId; + let mut h = Harness::new(); + h.app.home.open = false; + h.app.run("solid.box", json!({"length":40,"width":30,"height":20})).unwrap(); + h.settle(); + crate::panel_runtime::enable_host_specimen(&mut h.app, "docks").unwrap(); + h.frames(3); + assert_panel_host_preserves_design(&mut h, |h| { + let sash = h + .app + .universal_panel_frame() + .unwrap() + .layout + .controls + .iter() + .find(|control| matches!(control.target, HostPointerTarget::Sash { .. })) + .unwrap() + .target + .clone(); + let start = panel_host_point(h, sash.clone()); + panel_host_pointer(h, start, true); + h.frame_with(vec![egui::Event::PointerMoved(start + egui::vec2(0.0, 30.0))]); + panel_host_pointer(h, start + egui::vec2(0.0, 30.0), false); + h.frames(2); + let at = panel_host_point(h, sash); + panel_host_click(h, at); + panel_host_click(h, at); + h.frames(2); + let editor = InstanceId::new("specimen-0").unwrap(); + panel_host_semantic_click(h, HostControlTarget::Pointer(HostPointerTarget::Menu { instance: editor.clone() })); + panel_host_semantic_click(h, HostControlTarget::Shared { instance: editor.clone(), action: HostSharedAction::Collapse }); + panel_host_semantic_click(h, HostControlTarget::Pointer(HostPointerTarget::Collapse { instance: editor.clone() })); + assert!(h.app.panel_runtime().unwrap().layout().interaction().peek.is_none()); + assert!(!h.app.panel_runtime().unwrap().layout().layout().containing(&editor).unwrap().collapsed); + let start = panel_host_point(h, HostPointerTarget::Header { instance: editor.clone() }); + let destination = h.app.panel_runtime().unwrap().layout().layout().containing(&InstanceId::new("specimen-1").unwrap()).unwrap(); + let destination_id = destination.id.clone(); + let insertion = destination.tabs.len(); + let end = panel_host_drop_point(h, &editor, &crate::panel_runtime::HostDropTargetId::Tab { section: destination_id.clone(), before: None }); + panel_host_pointer(h, start, true); + h.frame_with(vec![egui::Event::PointerMoved(end)]); + let shown = h.app.universal_panel_frame().unwrap().preview.as_ref().unwrap(); + assert!(shown.rejection.is_none()); + let Some(solidcraft_engine::panels::LayoutAction::Apply { mutations, .. }) = shown.action.as_ref() else { + panic!("the actual tab append must show a prepared atomic landing"); + }; + assert_eq!( + mutations, + &vec![ + solidcraft_engine::panels::Mutation::Move { + instance: editor.clone(), + destination: solidcraft_engine::panels::Destination::JoinTab { section: destination_id.clone(), index: insertion }, + }, + solidcraft_engine::panels::Mutation::Activate { instance: editor.clone() }, + ] + ); + let projected = shown.projected.clone().unwrap(); + panel_host_pointer(h, end, false); + h.frames(2); + let joined = h.app.panel_runtime().unwrap().layout().layout().containing(&editor).unwrap(); + assert_eq!(joined.tabs.len(), 2); + assert_eq!(joined.id, destination_id); + assert_eq!(joined.tabs[insertion], editor); + assert_eq!(joined.active, editor); + assert_panel_host_landing(h, &projected); + }); +} #[test] fn modes_are_transient_and_available_to_control_and_scenarios() { diff --git a/crates/ui-egui/src/sketch_attachment_ui.rs b/crates/ui-egui/src/sketch_attachment_ui.rs index a21ef2dee..71d791d7e 100644 --- a/crates/ui-egui/src/sketch_attachment_ui.rs +++ b/crates/ui-egui/src/sketch_attachment_ui.rs @@ -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); diff --git a/crates/ui-egui/src/sketch_attachment_ui_tests.rs b/crates/ui-egui/src/sketch_attachment_ui_tests.rs index 600c234f7..f415eaac1 100644 --- a/crates/ui-egui/src/sketch_attachment_ui_tests.rs +++ b/crates/ui-egui/src/sketch_attachment_ui_tests.rs @@ -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; diff --git a/crates/ui-egui/src/sketch_guidance_ui_tests.rs b/crates/ui-egui/src/sketch_guidance_ui_tests.rs index 45404e476..f6a6e0e3e 100644 --- a/crates/ui-egui/src/sketch_guidance_ui_tests.rs +++ b/crates/ui-egui/src/sketch_guidance_ui_tests.rs @@ -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]]})), diff --git a/crates/ui-egui/src/sketch_modify_ui_tests.rs b/crates/ui-egui/src/sketch_modify_ui_tests.rs index ced008fbf..903e1c423 100644 --- a/crates/ui-egui/src/sketch_modify_ui_tests.rs +++ b/crates/ui-egui/src/sketch_modify_ui_tests.rs @@ -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(); diff --git a/crates/ui-egui/src/sketch_palette.rs b/crates/ui-egui/src/sketch_palette.rs index e36a5fa13..91b87fa19 100644 --- a/crates/ui-egui/src/sketch_palette.rs +++ b/crates/ui-egui/src/sketch_palette.rs @@ -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 { diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index f359a4ca7..da074b27f 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -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. diff --git a/crates/ui-egui/src/ui_kit/container.rs b/crates/ui-egui/src/ui_kit/container.rs index b34d7eb73..af2876e34 100644 --- a/crates/ui-egui/src/ui_kit/container.rs +++ b/crates/ui-egui/src/ui_kit/container.rs @@ -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, + 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(self, ctx: &Context, content: impl FnOnce(&mut egui::Ui) -> T) -> egui::ModalResponse { + 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::(escape_key); + data.remove::(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, } 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(self, ctx: &Context, body: impl FnOnce(&mut egui::Ui) -> R) -> Option>> { @@ -264,11 +351,38 @@ impl<'a> FeatureWindow<'a> { background: Option, body: impl FnOnce(&mut egui::Ui) -> R, ) -> Option>> { - 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) { + 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::(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> { + let stamp = (ctx.cumulative_frame_nr(), ctx.cumulative_pass_nr()); + let key = host_windows_key(ctx); + match ctx.data(|data| data.get_temp::(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::(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> { + 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::(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::(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 { diff --git a/crates/ui-egui/src/ui_kit/fields.rs b/crates/ui-egui/src/ui_kit/fields.rs index 6da9a4e4a..d75c1bf76 100644 --- a/crates/ui-egui/src/ui_kit/fields.rs +++ b/crates/ui-egui/src/ui_kit/fields.rs @@ -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 }); diff --git a/crates/ui-egui/src/ui_kit/gallery.rs b/crates/ui-egui/src/ui_kit/gallery.rs index 03025a09e..5ec93f8c8 100644 --- a/crates/ui-egui/src/ui_kit/gallery.rs +++ b/crates/ui-egui/src/ui_kit/gallery.rs @@ -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] { diff --git a/crates/ui-egui/src/ui_kit/layout_tests.rs b/crates/ui-egui/src/ui_kit/layout_tests.rs index 86d17fd1c..5c4f2f138 100644 --- a/crates/ui-egui/src/ui_kit/layout_tests.rs +++ b/crates/ui-egui/src/ui_kit/layout_tests.rs @@ -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 { (0..count).filter(|i| scenario::rect_of(&format!("page:item:{i}")).is_some()).collect() }; - let draw = |events: Vec| { - 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::>()); - click("prefs.carousel_previous"); - assert_eq!(shown(), (0..page).collect::>(), "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::>(), "width {width}: next shows the cards that were hidden"); - for _ in 0..count { - click("prefs.carousel_next"); - } - let last: Vec = (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::>(), "width {width}: previous shows the cards before"); - for _ in 0..count { - click("prefs.carousel_previous"); - } - assert_eq!(shown(), (0..page).collect::>(), "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(); diff --git a/crates/ui-egui/src/ui_kit/mod.rs b/crates/ui-egui/src/ui_kit/mod.rs index b5b8ad519..ee0889e18 100644 --- a/crates/ui-egui/src/ui_kit/mod.rs +++ b/crates/ui-egui/src/ui_kit/mod.rs @@ -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::*; diff --git a/crates/ui-egui/src/ui_kit/panel_host.rs b/crates/ui-egui/src/ui_kit/panel_host.rs new file mode 100644 index 000000000..a65790e4c --- /dev/null +++ b/crates/ui-egui/src/ui_kit/panel_host.rs @@ -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( + 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) { + 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::(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::(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(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 +} diff --git a/crates/ui-egui/src/ui_kit/panel_tests.rs b/crates/ui-egui/src/ui_kit/panel_tests.rs index c5a23fea0..1507bfcbb 100644 --- a/crates/ui-egui/src/ui_kit/panel_tests.rs +++ b/crates/ui-egui/src/ui_kit/panel_tests.rs @@ -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, + 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 { + 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] diff --git a/crates/ui-egui/src/ui_kit/preferences.rs b/crates/ui-egui/src/ui_kit/preferences.rs index 4f13cd053..85663f15b 100644 --- a/crates/ui-egui/src/ui_kit/preferences.rs +++ b/crates/ui-egui/src/ui_kit/preferences.rs @@ -566,15 +566,18 @@ fn settings_section_count_spaced( pub(crate) fn settings_card(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> egui::InnerResponse { 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(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(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]) { diff --git a/crates/ui-egui/src/ui_kit/preferences_cards.rs b/crates/ui-egui/src/ui_kit/preferences_cards.rs index 54fbf9d02..149370951 100644 --- a/crates/ui-egui/src/ui_kit/preferences_cards.rs +++ b/crates/ui-egui/src/ui_kit/preferences_cards.rs @@ -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::(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, diff --git a/crates/ui-egui/src/ui_kit/preferences_figure_ops.rs b/crates/ui-egui/src/ui_kit/preferences_figure_ops.rs index 8f5a8728c..aa809b622 100644 --- a/crates/ui-egui/src/ui_kit/preferences_figure_ops.rs +++ b/crates/ui-egui/src/ui_kit/preferences_figure_ops.rs @@ -298,6 +298,23 @@ pub(super) fn paint(p: &Painter, rect: Rect, figure: &Figure, sample: Option<&Th paint_with_tokens(p, rect, figure, sample, clip, &Tokens::get(), Palette::Figure); } +/// Clip every miniature-window operation, including its top bar, to its rounded outline. +/// Rectangular scissoring alone leaves the bar's square corners outside the rounded ground. +pub(super) fn paint_rounded(p: &Painter, rect: Rect, figure: &Figure, sample: &ThemeSample, radius: f32) { + let size = rect.size(); + if !rect.is_finite() || !size.is_finite() || size.min_elem() < 1.0 || size.max_elem() > MAX_SIDE || !radius.is_finite() { + return; + } + let [fw, fh] = figure.size; + if !(fw > 0.0 && fh > 0.0) { + return; + } + let scale = (size.x / fw).min(size.y / fh); + let outline: Vec<_> = + rounded(Rect::from_min_size(Pos2::ZERO, vec2(fw, fh)), radius.max(0.0) / scale).into_iter().map(|point| [point.x, point.y]).collect(); + paint(p, rect, figure, Some(sample), Some(&outline)); +} + /// Reuse the six canonical figures with the semantic palette being previewed, without global state. pub(super) fn paint_colour_vision(p: &Painter, rect: Rect, index: usize, t: &Tokens) { use super::preferences_figure_data as figures; diff --git a/crates/ui-egui/src/ui_kit/preferences_figures.rs b/crates/ui-egui/src/ui_kit/preferences_figures.rs index 94267f0d1..c63ce27be 100644 --- a/crates/ui-egui/src/ui_kit/preferences_figures.rs +++ b/crates/ui-egui/src/ui_kit/preferences_figures.rs @@ -295,14 +295,10 @@ pub(crate) fn paint_theme_thumbnail(p: &Painter, rect: Rect, sample: &ThemeSampl paint(p, rect, &super::preferences_figure_data::THEME_THUMBNAIL, Some(sample), None); } -#[allow(dead_code, reason = "painted by the Preferences pages of #9875 to #9883")] -/// The "System" theme card: `light` with `dark` over a slanted band of it (the board clips the dark -/// half to the polygon 56 %,0 / 100 %,0 / 100 %,100 % / 40 %,100 %). -pub(crate) fn paint_theme_system(p: &Painter, rect: Rect, light: &ThemeSample, dark: &ThemeSample) { - const BAND: [[f32; 2]; 4] = [[69.44, 0.0], [124.0, 0.0], [124.0, 76.0], [49.6, 76.0]]; - let figure = &super::preferences_figure_data::THEME_THUMBNAIL; - paint(p, rect, figure, Some(light), None); - paint(p, rect, figure, Some(dark), Some(&BAND)); +/// The theme picker's thumbnails have an inner radius matching their card's border. +/// Keep other thumbnail callers' existing sizing and painting unchanged. +pub(crate) fn paint_theme_thumbnail_rounded(p: &Painter, rect: Rect, sample: &ThemeSample, radius: f32) { + super::preferences_figure_ops::paint_rounded(p, rect, &super::preferences_figure_data::THEME_THUMBNAIL, sample, radius); } #[cfg(test)] @@ -364,7 +360,7 @@ mod tests { } } - use super::{ThemeSample, paint_theme_system, paint_theme_thumbnail}; + use super::{ThemeSample, paint_theme_thumbnail, paint_theme_thumbnail_rounded}; use crate::theme::Tokens; use crate::ui_kit::preferences_figure_data::FIGURES; use egui::{Pos2, Rect, vec2}; @@ -397,6 +393,34 @@ mod tests { ] } + #[test] + fn theme_thumbnail_operations_stay_inside_the_rounded_inner_border() { + let rect = Rect::from_min_size(Pos2::new(20.0, 20.0), vec2(124.0, 76.0)); + for dark in [false, true] { + let sample = ThemeSample::from_tokens(&if dark { Tokens::dark() } else { Tokens::light() }); + for border in [1.0, 2.0] { + let radius = f32::from(Tokens::get().radius_lg) - border; + let centre_rect = rect.shrink(radius); + let mut vertices = 0; + for clipped in shapes(rect, |p, r| paint_theme_thumbnail_rounded(p, r, &sample, radius)) { + crate::test_support::each_shape(&clipped.shape, &mut |shape| { + if let egui::Shape::Mesh(mesh) = shape { + for vertex in &mesh.vertices { + let nearest = Pos2::new( + vertex.pos.x.clamp(centre_rect.left(), centre_rect.right()), + vertex.pos.y.clamp(centre_rect.top(), centre_rect.bottom()), + ); + assert!(vertex.pos.distance(nearest) <= radius + 0.05, "thumbnail fill leaks outside rounded clip: {:?}", vertex.pos); + vertices += 1; + } + } + }); + } + assert!(vertices > 20, "check the actual background and top-bar geometry"); + } + } + } + /// Every figure, in both themes, paints at size zero, tiny, normal, huge and non-finite without /// panicking, and at a normal size stays inside its rectangle with a bounded number of shapes. #[test] @@ -444,18 +468,16 @@ mod tests { } #[test] - fn theme_thumbnails_paint_with_the_sample_colours_and_a_slanted_system_band() { + fn theme_thumbnails_paint_with_the_sample_colours() { let (light, dark) = (ThemeSample::from_tokens(&Tokens::light()), ThemeSample::from_tokens(&Tokens::dark())); assert_ne!(light, dark); let rect = Rect::from_min_size(Pos2::new(4.0, 4.0), vec2(124.0, 76.0)); for rect in rects().into_iter().chain([rect]) { let _ = shapes(rect, |p, r| paint_theme_thumbnail(p, r, &light)); - let _ = shapes(rect, |p, r| paint_theme_system(p, r, &light, &dark)); } - let single = shapes(rect, |p, r| paint_theme_thumbnail(p, r, &light)).len(); - let system = shapes(rect, |p, r| paint_theme_system(p, r, &light, &dark)).len(); - assert!(system > single, "the dark band adds shapes over the light card"); - for shape in shapes(rect, |p, r| paint_theme_system(p, r, &light, &dark)) { + let single = shapes(rect, |p, r| paint_theme_thumbnail(p, r, &light)); + assert!(!single.is_empty()); + for shape in single { let bounds = shape.shape.visual_bounding_rect().intersect(shape.clip_rect); assert!(!bounds.is_positive() || rect.expand(1.0).contains_rect(bounds), "{bounds:?}"); } diff --git a/crates/ui-egui/src/ui_kit/theme_picker.rs b/crates/ui-egui/src/ui_kit/theme_picker.rs new file mode 100644 index 000000000..9f3ad9ddd --- /dev/null +++ b/crates/ui-egui/src/ui_kit/theme_picker.rs @@ -0,0 +1,549 @@ +//! Shared theme browser vocabulary: toggle segments, slots, marked cards and scroll viewport. +use super::*; +use crate::{scenario, theme::Tokens}; +use egui::{Align2, Color32, FontId, Painter, Rect, Response, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; + +#[derive(Clone, Copy, PartialEq)] +pub(crate) enum ThemeGlyph { + None, + Sun, + Moon, + Contrast, + Monitor, + Carousel, + Grid, + Check, + Import, + Previous, + Next, +} + +fn glyph(p: &Painter, r: Rect, kind: ThemeGlyph, ink: Color32) { + if !r.is_finite() || !r.is_positive() { + return; + } + let scale = r.width().min(r.height()) / 24.0; + let origin = r.center() - egui::Vec2::splat(Tokens::get().space_12) * scale; + let at = |x, y| origin + vec2(x, y) * scale; + let line = |points: &[[f32; 2]], width| { + p.add(egui::Shape::line(points.iter().map(|[x, y]| at(*x, *y)).collect(), Stroke::new(width * scale, ink))); + }; + let stroke = Stroke::new(2.0 * scale, ink); + match kind { + ThemeGlyph::None => {} + ThemeGlyph::Sun => { + p.circle_stroke(at(12.0, 12.0), 4.0 * scale, stroke); + for points in [ + [[12.0, 2.0], [12.0, 5.0]], + [[12.0, 19.0], [12.0, 22.0]], + [[2.0, 12.0], [5.0, 12.0]], + [[19.0, 12.0], [22.0, 12.0]], + [[5.0, 5.0], [7.0, 7.0]], + [[17.0, 17.0], [19.0, 19.0]], + [[19.0, 5.0], [17.0, 7.0]], + [[7.0, 17.0], [5.0, 19.0]], + ] { + line(&points, 2.0); + } + } + ThemeGlyph::Moon => { + // SVG A8 8 0 1 1 10 4: the large clockwise arc from (20,14). + let centre = vec2(15.0 - 7.0_f32.sqrt(), 9.0 + 7.0_f32.sqrt()); + let start = (14.0 - centre.y).atan2(20.0 - centre.x); + let end = (4.0 - centre.y).atan2(10.0 - centre.x) + std::f32::consts::TAU; + let points: Vec<_> = (0..=32) + .map(|i| { + let a = start + (end - start) * i as f32 / 32.0; + let point = centre + vec2(a.cos(), a.sin()) * 8.0; + at(point.x, point.y) + }) + .chain((0..=32).map(|i| { + // SVG scales the second radius (6.5) to half the chord, sqrt(50). + let a = -3.0 * std::f32::consts::FRAC_PI_4 - std::f32::consts::PI * i as f32 / 32.0; + at(15.0 + a.cos() * 50.0_f32.sqrt(), 9.0 + a.sin() * 50.0_f32.sqrt()) + })) + .collect(); + p.add(egui::Shape::closed_line(points, stroke)); + } + ThemeGlyph::Contrast => { + p.circle_stroke(at(12.0, 12.0), 9.0 * scale, stroke); + line(&[[12.0, 3.0], [12.0, 21.0]], 2.0); + let points = (0..=32) + .map(|i| { + let a = -std::f32::consts::FRAC_PI_2 + i as f32 / 32.0 * std::f32::consts::PI; + at(12.0 + a.cos() * 9.0, 12.0 + a.sin() * 9.0) + }) + .collect(); + p.add(egui::Shape::convex_polygon(points, ink, Stroke::NONE)); + } + ThemeGlyph::Monitor => { + p.rect_stroke(Rect::from_min_max(at(3.0, 4.0), at(21.0, 16.0)), 2.0 * scale, stroke, StrokeKind::Middle); + line(&[[8.0, 20.0], [16.0, 20.0]], 2.0); + line(&[[12.0, 16.0], [12.0, 20.0]], 2.0); + } + ThemeGlyph::Carousel => { + for (x, y, w, h, radius, opacity) in + [(2.0, 6.0, 5.0, 12.0, 1.2, 0.55), (9.0, 4.0, 6.0, 16.0, 1.5, 1.0), (17.0, 6.0, 5.0, 12.0, 1.2, 0.55)] + { + p.rect_filled(Rect::from_min_size(at(x, y), vec2(w, h) * scale), radius * scale, ink.gamma_multiply(opacity)); + } + } + ThemeGlyph::Grid => { + for x in [3.0, 13.0] { + for y in [3.0, 13.0] { + p.rect_filled(Rect::from_min_size(at(x, y), egui::Vec2::splat(Tokens::get().space_8) * scale), 1.5 * scale, ink); + } + } + } + ThemeGlyph::Check => { + line(&[[5.0, 12.0], [10.0, 17.0], [19.0, 7.0]], 3.2); + } + ThemeGlyph::Import => { + line(&[[12.0, 4.0], [12.0, 15.0]], 2.0); + line(&[[7.0, 10.0], [12.0, 15.0], [17.0, 10.0]], 2.0); + line(&[[5.0, 20.0], [19.0, 20.0]], 2.0); + } + ThemeGlyph::Previous => line(&[[15.0, 5.0], [8.0, 12.0], [15.0, 19.0]], 2.4), + ThemeGlyph::Next => line(&[[9.0, 5.0], [16.0, 12.0], [9.0, 19.0]], 2.4), + } +} + +pub(crate) struct ThemeSegment<'a> { + label: &'a str, + icon: ThemeGlyph, + count: Option, +} +impl<'a> ThemeSegment<'a> { + pub(crate) fn new(label: &'a str, icon: ThemeGlyph, count: Option) -> Self { + Self { label, icon, count } + } +} + +pub(crate) fn theme_segments(ui: &mut Ui, key: &str, options: &[ThemeSegment<'_>], selected: Option, icon_only: bool) -> Option { + let labels: Vec<_> = options.iter().map(|o| o.label).collect(); + crate::prefs_search::note_unlabelled(ui, &labels); + if crate::prefs_search::querying(ui) && !crate::prefs_search::visible(ui, &labels) { + return None; + } + let t = Tokens::get(); + let mut clicked = None; + let icon_size = if key == "tone" || key == "contrast" { t.space_12 } else { t.space_14 }; + let widths: Vec<_> = options + .iter() + .map(|option| { + let text = option.count.map(|n| format!("{} {n}", option.label)).unwrap_or_else(|| option.label.to_owned()); + let icon_width = if option.icon == ThemeGlyph::None { 0.0 } else { icon_size + t.space_6 }; + if icon_only { t.space_24 + t.space_10 } else { ContentWidth::name(ui, &text) + t.space_16 + icon_width } + }) + .collect(); + // Reserve just the group's natural width. A nested horizontal Ui would reserve the + // remaining row too, pushing the right-hand toolbar controls beyond the page. + let (group, _) = ui.allocate_exact_size(vec2(widths.iter().sum(), t.control_height), Sense::hover()); + let mut x = group.left(); + for (index, option) in options.iter().enumerate() { + let text = option.count.map(|n| format!("{} {n}", option.label)).unwrap_or_else(|| option.label.to_owned()); + let icon_size = if key == "tone" || key == "contrast" { t.space_12 } else { t.space_14 }; + let icon_width = if option.icon == ThemeGlyph::None { 0.0 } else { icon_size + t.space_6 }; + let width = widths.get(index).copied().unwrap_or_default(); + let r = Rect::from_min_size(pos2(x, group.top()), vec2(width, t.control_height)); + x += width; + let response = ui.interact(r, ui.make_persistent_id((key, index)), Sense::click()); + let on = selected == Some(index); + let rounding = egui::CornerRadius { + nw: if index == 0 { t.radius_md } else { 0 }, + sw: if index == 0 { t.radius_md } else { 0 }, + ne: if index + 1 == options.len() { t.radius_md } else { 0 }, + se: if index + 1 == options.len() { t.radius_md } else { 0 }, + }; + let rounding = if options.len() == 1 { egui::CornerRadius::same((t.control_height / 2.0) as u8) } else { rounding }; + ui.painter().rect( + r, + rounding, + if on { + t.selected_bg + } else if response.hovered() { + t.hover + } else { + t.control_fill + }, + Stroke::new(1.0, if on { t.form_primary } else { t.control_border }), + StrokeKind::Inside, + ); + let ink = if on { t.selected_ink } else { t.form_ink }; + let icon = Rect::from_center_size( + if icon_only { r.center() } else { pos2(r.left() + t.space_8 + icon_size / 2.0, r.center().y) }, + vec2(icon_size, icon_size), + ); + glyph(ui.painter(), icon, option.icon, ink); + if !icon_only { + ui.painter().text( + pos2(r.left() + t.space_8 + icon_width, r.center().y), + Align2::LEFT_CENTER, + &text, + FontId::proportional(t.font_label), + ink, + ); + } + if response.has_focus() { + ui.painter().rect_stroke(r.expand(t.space_2), rounding, Stroke::new(t.space_2, t.form_primary), StrokeKind::Outside); + } + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, ui.is_enabled(), on, option.label)); + crate::prefs_search::remember(ui, option.label, r); + crate::prefs_search::follow(ui, option.label, r); + let visible = r.intersect(ui.clip_rect()); + if visible.is_positive() { + scenario::publish_target(&format!("prefs:theme_{key}:{index}"), visible); + } + if response.clicked() { + clicked = Some(index); + } + response.backing_on_hover_text(option.label).on_hover_cursor(egui::CursorIcon::PointingHand); + } + clicked +} + +/// Reserve the trailing control first; the leading groups wrap within the space left. +/// Only the mode/import row supplies a nonzero stacking threshold (about 460 pt). +pub(crate) fn theme_toolbar( + ui: &mut Ui, + key: &str, + trailing_width: f32, + stack_below: f32, + leading: impl FnOnce(&mut Ui) -> L, + trailing: impl FnOnce(&mut Ui) -> R, +) -> (L, R) { + let t = Tokens::get(); + let width = bounded_width(ui); + let gap = t.space_10; + let stacked = width < stack_below; + let right_width = trailing_width.min(width); + let left_width = if stacked { width } else { (width - right_width - gap).max(0.0) }; + let start = ui.next_widget_position(); + let mut left = ui.new_child( + egui::UiBuilder::new() + .id_salt((key, "leading")) + .max_rect(Rect::from_min_size(start, vec2(left_width, t.control_height))) + .layout(egui::Layout::left_to_right(egui::Align::Center).with_main_wrap(true)), + ); + left.set_clip_rect(left.clip_rect().intersect(Rect::from_x_y_ranges(start.x..=start.x + left_width, f32::NEG_INFINITY..=f32::INFINITY))); + left.spacing_mut().item_spacing.x = t.space_8; + let a = leading(&mut left); + let left_height = left.min_size().y.max(t.control_height); + let right_start = pos2(start.x + width - right_width, start.y + if stacked { left_height + gap } else { 0.0 }); + let mut right = ui.new_child( + egui::UiBuilder::new() + .id_salt((key, "trailing")) + .max_rect(Rect::from_min_size(right_start, vec2(right_width, t.control_height))) + .layout(egui::Layout::left_to_right(egui::Align::Center)), + ); + let b = trailing(&mut right); + let height = if stacked { left_height + gap + right.min_size().y } else { left_height.max(right.min_size().y) }; + let (rect, _) = ui.allocate_exact_size(vec2(width, height), Sense::hover()); + scenario::publish_rect(&format!("prefs:theme_toolbar:{key}"), rect); + (a, b) +} + +fn bounded_width(ui: &Ui) -> f32 { + let available = super::metrics::dimension(ui.available_width()); + if ui.is_visible() { available.min((ui.clip_rect().right() - ui.next_widget_position().x).max(0.0)) } else { available } +} + +pub(crate) fn theme_import_button(ui: &mut Ui, label: &str) -> Response { + crate::prefs_search::note_unlabelled(ui, &[label]); + if crate::prefs_search::querying(ui) && !crate::prefs_search::visible(ui, &[label]) { + return crate::prefs_search::hidden_response(ui); + } + let t = Tokens::get(); + let width = ContentWidth::name(ui, label) + t.space_14 + t.space_6 + t.space_10 * 2.0; + let (r, response) = ui.allocate_exact_size(vec2(width, t.control_height), Sense::click()); + ui.painter().rect( + r, + t.radius_md, + if response.hovered() { t.hover } else { t.control_fill }, + Stroke::new(1.0, t.control_border), + StrokeKind::Inside, + ); + let icon = Rect::from_center_size(pos2(r.left() + t.space_10 + t.space_14 / 2.0, r.center().y), vec2(t.space_14, t.space_14)); + glyph(ui.painter(), icon, ThemeGlyph::Import, t.form_ink); + ui.painter().text(pos2(icon.right() + t.space_6, r.center().y), Align2::LEFT_CENTER, label, FontId::proportional(t.font_label), t.form_ink); + if response.has_focus() { + ui.painter().rect_stroke(r.expand(t.space_2), t.radius_md, Stroke::new(t.space_2, t.form_primary), StrokeKind::Outside); + } + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), label)); + crate::prefs_search::remember(ui, label, r); + crate::prefs_search::follow(ui, label, r); + response.on_hover_cursor(egui::CursorIcon::PointingHand) +} + +pub(crate) struct ThemeSlot<'a> { + pub title: &'a str, + pub name: &'a str, + pub hint: &'a str, + pub aimed: bool, + pub night: bool, + pub width: f32, + pub sample: ThemeSample, +} +pub(crate) fn theme_slot(ui: &mut Ui, slot: &ThemeSlot<'_>) -> Response { + let t = Tokens::get(); + crate::prefs_search::note_unlabelled(ui, &[slot.title, slot.name, slot.hint]); + if crate::prefs_search::querying(ui) && !crate::prefs_search::visible(ui, &[slot.title, slot.name, slot.hint]) { + return crate::prefs_search::hidden_response(ui); + } + let (r, response) = ui.allocate_exact_size(vec2(slot.width.max(0.0), t.space_24 * 2.0 + t.space_16), Sense::click()); + ui.painter().rect( + r, + t.radius_lg, + if slot.aimed { t.selected_bg } else { t.control_fill }, + Stroke::new(if slot.aimed { 2.0 } else { 1.0 }, if slot.aimed { t.form_primary } else { t.dialog_border }), + StrokeKind::Inside, + ); + let thumbnail = Rect::from_min_size(r.min + vec2(t.space_10, t.space_10), vec2(t.space_24 * 2.0 + t.space_16, t.space_24 * 2.0 - t.space_8)); + paint_theme_thumbnail_rounded(ui.painter(), thumbnail, &slot.sample, (f32::from(t.radius_lg) - if slot.aimed { 2.0 } else { 1.0 }).max(0.0)); + let x = thumbnail.right() + t.space_10; + let icon = Rect::from_min_size(pos2(x, r.top() + t.space_10), vec2(t.space_12, t.space_12)); + glyph(ui.painter(), icon, if slot.night { ThemeGlyph::Moon } else { ThemeGlyph::Sun }, t.form_dim); + let p = ui.painter().with_clip_rect(r.shrink(t.space_8).intersect(ui.clip_rect())); + p.text(pos2(icon.right() + t.space_4, icon.center().y), Align2::LEFT_CENTER, slot.title, FontId::proportional(t.font_small), t.form_dim); + p.text(pos2(x, r.bottom() - t.space_16 - t.space_4), Align2::LEFT_CENTER, slot.name, crate::fonts::semibold(t.font_label), t.form_ink); + p.text(pos2(r.right() - t.space_10, r.center().y), Align2::RIGHT_CENTER, slot.hint, FontId::proportional(t.font_small), t.form_dim); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, ui.is_enabled(), slot.aimed, slot.title)); + crate::prefs_search::remember(ui, slot.title, r); + crate::prefs_search::follow(ui, slot.title, r); + response.on_hover_cursor(egui::CursorIcon::PointingHand) +} + +pub(crate) struct ThemeCard<'a> { + pub name: &'a str, + pub note: &'a str, + pub options: Option<&'a str>, + pub sample: ThemeSample, + pub selected: bool, + pub dark: bool, + pub high: bool, + pub day: bool, + pub night: bool, +} +pub(crate) fn theme_card(ui: &mut Ui, card: &ThemeCard<'_>, width: f32) -> Response { + let t = Tokens::get(); + let inner_radius = (f32::from(t.radius_lg) - if card.selected { 2.0 } else { 1.0 }).max(0.0); + let response = picture_card( + ui, + &Card { + label: card.name, + sub: Some(card.note), + selected: card.selected, + enabled: true, + options: None, + check: false, + aspect: 124.0 / 76.0, + figure: &|p, r| paint_theme_thumbnail_rounded(p, r, &card.sample, inner_radius), + }, + width, + ); + if !response.rect.is_positive() { + return response; + } + let r = response.rect; + let size = t.space_16 + t.space_2; + let badge_width = if card.high { t.space_10 * 2.0 + t.space_2 + t.space_4 * 2.0 } else { size }; + let badge = Rect::from_min_size(r.min + vec2(t.space_8, t.space_8), vec2(badge_width, size)); + let dark = Tokens::dark(); + ui.painter().rect_filled(badge, size / 2.0, dark.panel.gamma_multiply(0.85)); + let tone = Rect::from_center_size(pos2(badge.left() + t.space_4 + t.space_10 / 2.0, badge.center().y), vec2(t.space_10, t.space_10)); + glyph(ui.painter(), tone, if card.dark { ThemeGlyph::Moon } else { ThemeGlyph::Sun }, dark.text); + if card.high { + glyph(ui.painter(), tone.translate(vec2(t.space_12, 0.0)), ThemeGlyph::Contrast, dark.text); + } + let mut x = r.right() - t.space_8 - size / 2.0; + for kind in [ + card.night.then_some(ThemeGlyph::Moon), + card.day.then_some(ThemeGlyph::Sun), + (card.selected && !card.day && !card.night).then_some(ThemeGlyph::Check), + ] + .into_iter() + .flatten() + { + let centre = pos2(x, badge.center().y); + ui.painter().circle_filled(centre, size / 2.0, t.form_primary); + glyph(ui.painter(), Rect::from_center_size(centre, vec2(t.space_10 + 1.0, t.space_10 + 1.0)), kind, t.on_accent); + x -= size + t.space_2; + } + if let Some(help) = card.options { + let centre = pos2(r.right() - t.space_8 - size / 2.0, r.top() + t.space_4 + (width - t.space_8) * 76.0 / 124.0 - size / 2.0); + ui.painter().circle_filled(centre, size / 2.0, t.form_primary); + crate::icons::paint_ink(ui.painter(), Rect::from_center_size(centre, vec2(t.space_12, t.space_12)), "settings", t.on_accent); + return response.backing_on_hover_text(help); + } + response +} + +fn browser_frame(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> egui::InnerResponse { + let container = Container::new(ui.ctx(), Surface::Navigation); + let frame = super::preferences::settings_card_frame(ui).inner_margin(0); + let border = frame.stroke.width; + let width = bounded_width(ui); + container.show_frame(ui, frame, ui.max_rect(), |ui| { + ui.set_width((width - border * 2.0).max(0.0)); + add(ui) + }) +} + +pub(crate) fn theme_empty(ui: &mut Ui, message: &str, clear: &str, reset: impl FnOnce()) { + browser_frame(ui, |ui| { + ui.set_min_width(ui.available_width()); + ui.set_min_height(Tokens::get().space_24 * 5.0); + ui.vertical_centered(|ui| { + ui.add_space(Tokens::get().space_24); + ui.label(message); + if ui.link(clear).clicked() { + reset(); + } + }); + scenario::publish_rect("prefs:theme_empty", ui.min_rect()); + }); +} + +/// A clipped row with overlaid fades, or five equal columns with vertical scrolling. +pub(crate) fn theme_browser(ui: &mut Ui, id: &str, count: usize, grid: bool, reveal: Option, mut item: impl FnMut(&mut Ui, usize, f32)) { + let t = Tokens::get(); + let fill = super::preferences::settings_card_frame(ui).fill; + browser_frame(ui, |ui| { + let width = bounded_width(ui); + let gap = t.space_8; + let card_width = if grid { ((width - t.space_10 * 2.0 - gap * 4.0) / 5.0).max(1.0) } else { t.space_24 * 5.0 - t.space_2 }; + let card_height = (card_width - t.space_8) * 76.0 / 124.0 + t.space_16 + t.space_14 + t.space_8 + t.space_6; + if grid { + egui::ScrollArea::vertical() + .id_salt((id, "grid")) + .auto_shrink([false, false]) + .max_width(width) + .max_height((card_height + gap) * 2.5) + .show(ui, |ui| { + let card_width = ((ui.available_width() - t.space_10 * 2.0 - gap * 4.0) / 5.0).max(1.0); + ui.add_space(t.space_10); + for row in (0..count).step_by(5) { + ui.horizontal_top(|ui| { + ui.spacing_mut().item_spacing.x = gap; + ui.spacing_mut().item_spacing.y = gap; + ui.allocate_exact_size(vec2((t.space_10 - gap).max(0.0), 0.0), Sense::hover()); + for index in row..(row + 5).min(count) { + ui.allocate_ui_with_layout(vec2(card_width, card_height), egui::Layout::top_down(egui::Align::Min), |ui| { + item(ui, index, card_width); + if reveal == Some(index) { + ui.scroll_to_rect(ui.min_rect(), None); + } + }); + } + }); + } + ui.add_space(t.space_10); + }); + return; + } + let stride = card_width + gap; + let padding = t.space_10; + let content_width = count as f32 * stride - gap + padding * 2.0; + let key = ui.make_persistent_id((id, "offset")); + let mut offset = ui.data(|d| d.get_temp::(key)).unwrap_or_default(); + let max = (content_width - width).max(0.0); + if let Some(index) = reveal { + let start = padding + index as f32 * stride; + if start < offset + padding { + offset = start - padding; + } else if start + card_width + padding > offset + width { + offset = start + card_width + padding - width; + } + } + offset = offset.clamp(0.0, max); + let out = egui::ScrollArea::horizontal() + .id_salt((id, "carousel")) + .auto_shrink([false, true]) + .scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysHidden) + // egui normally maps vertical wheels to a horizontal-only scroll area. + // Handle the horizontal axis below, leaving vertical input for the page. + .scroll_source(egui::scroll_area::ScrollSource { mouse_wheel: false, ..Default::default() }) + .horizontal_scroll_offset(offset) + .max_width(width) + .max_height(card_height + padding * 2.0) + .show(ui, |ui| { + // A single reservation avoids implicit layout spacing below the row. + // The end spacers scroll with the cards, so mid-scroll clipping still + // reaches the box edges while both resting ends have equal padding. + let (content, _) = ui.allocate_exact_size(vec2(content_width, card_height + padding * 2.0), Sense::hover()); + for index in 0..count { + let at = content.min + vec2(padding + index as f32 * stride, padding); + let mut card_ui = ui.new_child( + egui::UiBuilder::new() + .id_salt((id, index)) + .max_rect(Rect::from_min_size(at, vec2(card_width, card_height))) + .layout(egui::Layout::top_down(egui::Align::Min)), + ); + item(&mut card_ui, index, card_width); + } + }); + offset = out.state.clamped_offset().x; + let r = out.inner_rect; + let hovered = ui.rect_contains_pointer(r); + let wheel = if hovered { crate::navigation::take_horizontal_wheel(ui, offset, max) } else { 0.0 }; + let horizontal_wheel = wheel != 0.0; + if horizontal_wheel { + offset = (offset - wheel).clamp(0.0, max); + } + let time_key = key.with("last_scroll"); + let now = ui.input(|i| i.time); + if horizontal_wheel || ui.input(|i| i.pointer.any_down()) { + ui.data_mut(|d| d.insert_temp(time_key, now)); + } else if let Some(last) = ui.data(|d| d.get_temp::(time_key)) { + if now - last > 0.15 { + offset = ((offset / stride).round() * stride).clamp(0.0, max); + ui.data_mut(|d| d.remove::(time_key)); + } else { + ui.ctx().request_repaint(); + } + } + for (left, present) in [(true, offset > 0.5), (false, offset < max - 0.5)] { + if !present { + continue; + } + let fade_width = (t.space_24 * 3.0 + t.space_12).min(r.width() / 2.0); + let edge = if left { r.left() } else { r.right() }; + let end = edge + if left { fade_width } else { -fade_width }; + let mut mesh = egui::Mesh::default(); + let clear = fill.gamma_multiply(0.0); + for (x, color) in [(edge, fill), (end, clear)] { + mesh.colored_vertex(pos2(x, r.top()), color); + mesh.colored_vertex(pos2(x, r.bottom()), color); + } + mesh.add_triangle(0, 1, 2); + mesh.add_triangle(1, 3, 2); + ui.painter().with_clip_rect(r).add(egui::Shape::mesh(mesh)); + let size = t.space_24 + t.space_4; + let centre = pos2(edge + if left { t.space_8 + size / 2.0 } else { -t.space_8 - size / 2.0 }, r.center().y); + let arrow = Rect::from_center_size(centre, vec2(size, size)); + let response = ui.interact(arrow, key.with(left), Sense::click()); + let shadow = t.shell_shadow(); + ui.painter().add(shadow.as_shape(arrow, egui::CornerRadius::same((size / 2.0) as u8))); + ui.painter().circle(centre, size / 2.0, if response.hovered() { t.hover } else { t.control_fill }, Stroke::new(1.0, t.dialog_border)); + let icon = Rect::from_center_size(centre, vec2(t.space_14, t.space_14)); + glyph(ui.painter(), icon, if left { ThemeGlyph::Previous } else { ThemeGlyph::Next }, t.form_ink); + if response.has_focus() { + ui.painter().circle_stroke(centre, size / 2.0 + t.space_2, Stroke::new(t.space_2, t.form_primary)); + } + let label = crate::i18n::tr(if left { "prefs.appearance.previous_themes" } else { "prefs.appearance.next_themes" }); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), label)); + scenario::publish_target(if left { "prefs:theme_previous" } else { "prefs:theme_next" }, arrow); + if response.clicked() { + // A screenful: the cards that fit in view, at least one (#11434). + let page = (r.width() / stride).floor().max(1.0) * stride; + offset = (offset + if left { -page } else { page }).clamp(0.0, max); + } + response.backing_on_hover_text(label).on_hover_cursor(egui::CursorIcon::PointingHand); + } + if (offset - out.state.clamped_offset().x).abs() > 0.1 { + ui.ctx().request_repaint(); + } + ui.data_mut(|d| d.insert_temp(key, offset)); + scenario::publish_rect("prefs:theme_viewport", r); + }); +} diff --git a/crates/ui-egui/src/view_confirm.rs b/crates/ui-egui/src/view_confirm.rs index 1e6a96698..4a5af02f9 100644 --- a/crates/ui-egui/src/view_confirm.rs +++ b/crates/ui-egui/src/view_confirm.rs @@ -64,6 +64,10 @@ struct Choice { /// (`ViewportState::corner`), which acts on it as on its own OK and Cancel; a sketch's runs at /// once, the way the ribbon's Finish Sketch and Cancel do (a refusal shows as their errors do). pub(crate) fn show(app: &mut SolveApp, ctx: &egui::Context) { + let host = app.universal_panel_host_enabled(); + if host { + app.viewport.host_confirm = Some(Rect::NOTHING); + } let (Some(answers), Some(rect)) = (answers(app), rect(app)) else { return }; let choices = match answers { Answers::Dialog => { @@ -96,7 +100,9 @@ pub(crate) fn show(app: &mut SolveApp, ctx: &egui::Context) { let container = Container::new(ctx, Surface::Navigation); let frame = container.frame(ctx, t.overlay, crate::frame::Side::Right); let mut clicked = None; + let mut painted = false; container.area(egui::Id::unique("sc_view_confirm")).order(egui::Order::Middle).fixed_pos(rect.min).fade_in(false).show(ctx, |ui| { + painted = ui.is_visible() && !ui.is_sizing_pass(); let (outer, _) = ui.allocate_exact_size(rect.size(), Sense::hover()); Container::paint_frame(ui.painter(), frame, outer.shrink(frame.stroke.width)); // The check, then the cross in the very corner, where a close sits on a title bar. @@ -110,13 +116,20 @@ pub(crate) fn show(app: &mut SolveApp, ctx: &egui::Context) { crate::icons::paint_icon(ui.painter(), at.shrink(t.space_6), choice.icon, if choice.enabled { 1.0 } else { 0.35 }); let label = crate::i18n::tr_label(choice.label); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, choice.enabled, label)); - crate::scenario::publish_target(choice.key, at); + if !host || painted { + crate::scenario::publish_target(choice.key, at); + } if response.backing_on_hover_text(label).clicked() && choice.enabled { clicked = Some(choice.action); } } }); - crate::scenario::publish_rect("view:confirm", rect); + if host { + app.viewport.host_confirm = Some(if painted { rect } else { Rect::NOTHING }); + } + if !host || painted { + crate::scenario::publish_rect("view:confirm", rect); + } crate::scenario::publish_count("view:confirm:ok:enabled", f64::from(choices.first().is_some_and(|choice| choice.enabled))); match (answers, clicked) { (Answers::Dialog, Some(action)) => app.viewport.corner = Some(action), diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index e7ac2d9bd..fae816cf3 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -133,6 +133,12 @@ pub struct ViewportState { pub rect: Option, pub(crate) layout: Option, pub(crate) palette_rect: Option, + /// None before the host's early confirmation paint; Some(NOTHING) means + /// no visible pair this pass. Late controls retain the already drawn rect. + pub(crate) host_confirm: Option, + /// Snapshot of this host pass's shared persistent Window paint. None is a + /// bounded-ledger failure; the usable seam then refuses placement/framing. + pub(crate) host_windows: Option>, pub(crate) dialog_rect: Option, /// OK or Cancel clicked in the view's corner for the open dialog (#6709), which /// `dialogs::show` acts on in the same frame as its own buttons. @@ -5631,9 +5637,11 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { crate::design_properties::overlay(app, &painter, &proj); crate::sketch_dims::show(app, ui, &proj); crate::select_other::show(app, ui.ctx()); - axis_view(app, ui, rect); - crate::view_angles::show(app, ui, rect); - crate::navigation_bar_view::show(app, ui, rect); + if !app.universal_panel_host_enabled() { + axis_view(app, ui, rect); + crate::view_angles::show(app, ui, rect); + crate::navigation_bar_view::show(app, ui, rect); + } crate::viewport_status::show(app, ui.ctx(), rect); crate::viewport_status_fixture::show(app, ui.ctx(), rect); // The notices and the agent chip first, so the 3D mouse picture can keep clear of them. @@ -7130,6 +7138,40 @@ pub(crate) fn scene_palette(dark: bool, mode: crate::theme::ColorVision) -> soli pub(crate) fn refresh_layout(app: &mut SolveApp, ctx: &egui::Context) { if let Some(rect) = app.viewport.rect { + if app.universal_panel_frame().is_some() { + let Ok(usable) = crate::shell::host_usable(app) else { + // Refuse new control placement without inventing an occupied + // viewport. An early pair already painted remains authoritative. + app.viewport.layout = Some(crate::viewport_layout::Layout { + viewport: rect, + content: rect, + drawable: Rect::NOTHING, + middle: Rect::NOTHING, + navigation: Rect::NOTHING, + axis_view: Rect::NOTHING, + confirm: app.viewport.host_confirm.unwrap_or(Rect::NOTHING), + usable: None, + }); + return; + }; + let navigation = if app.ui.show_navigation_bar { crate::navigation_bar_view::measured(app, ctx, rect).rect } else { Rect::NOTHING }; + let orbit = crate::navigation_bar::canvas_caps(app).orbit; + app.viewport.layout = Some(if let Some(confirm) = app.viewport.host_confirm { + crate::viewport_layout::Layout::host_with_retained_confirm(rect, &usable, app.preferences.navigator_style, confirm, navigation, orbit) + } else if orbit { + crate::viewport_layout::Layout::host(rect, &usable, app.preferences.navigator_style, crate::view_confirm::size(app), navigation) + } else { + crate::viewport_layout::Layout::host_with_axis( + rect, + &usable, + app.preferences.navigator_style, + crate::view_confirm::size(app), + navigation, + false, + ) + }); + return; + } let docks = crate::shell::fit_rects(app); let mut content = crate::shell::content_rect(app, rect); if crate::render_ui::focused(app) { @@ -7172,6 +7214,19 @@ pub(crate) fn refresh_layout(app: &mut SolveApp, ctx: &egui::Context) { } } +/// The opt-in host paints its existing controls after resolving actual Area +/// visibility. This does not render the scene or call navigation::handle again. +pub(crate) fn show_host_controls(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect) { + refresh_layout(app, ui.ctx()); + if crate::navigation_bar::canvas_caps(app).orbit { + axis_view(app, ui, rect); + if !crate::render_workspace::active(app) { + crate::view_angles::show(app, ui, rect); + } + } + crate::navigation_bar_view::show(app, ui, rect); +} + /// Orientation controls share the layout reservation used by model fitting. fn axis_center(app: &SolveApp, rect: Rect) -> Pos2 { let c = axis_rect(app, rect).center(); diff --git a/crates/ui-egui/src/viewport_layout.rs b/crates/ui-egui/src/viewport_layout.rs index 9d3e9f8c9..bfe877be1 100644 --- a/crates/ui-egui/src/viewport_layout.rs +++ b/crates/ui-egui/src/viewport_layout.rs @@ -18,6 +18,9 @@ pub(crate) struct Layout { pub navigation: Rect, /// OK and Cancel in the view's corner (#6709), or nothing while they are not shown. pub confirm: Rect, + /// Full bounded contour for the opt-in host. Legacy layouts keep their + /// existing rectangle policy; rendering always uses `viewport`. + pub usable: Option, } /// How far the OK and Cancel pair sits in from the content's top right corner, and the space @@ -32,7 +35,15 @@ pub(crate) fn free_rect(view: Rect, obstacles: &[Rect]) -> Rect { } let mut xs = vec![view.left(), view.right()]; let mut ys = vec![view.top(), view.bottom()]; - let obstacles: Vec<_> = obstacles.iter().take(16).map(|r| r.intersect(view)).filter(|r| r.is_positive() && r.is_finite()).collect(); + let obstacles: Vec<_> = obstacles.iter().map(|r| r.intersect(view)).filter(|r| r.is_positive() && r.is_finite()).collect(); + if obstacles.len() > 16 { + let obstacles: Vec<_> = obstacles.iter().copied().map(crate::panel_runtime::logical_rect).collect(); + return crate::panel_runtime::resolve_usable_region(crate::panel_runtime::logical_rect(view), &obstacles) + .ok() + .and_then(|region| region.free.into_iter().max_by(|a, b| (a.size.width * a.size.height).total_cmp(&(b.size.width * b.size.height)))) + .map(crate::panel_runtime::egui_rect) + .unwrap_or(Rect::NOTHING); + } for r in &obstacles { xs.extend([r.left(), r.right()]); ys.extend([r.top(), r.bottom()]); @@ -56,6 +67,112 @@ pub(crate) fn free_rect(view: Rect, obstacles: &[Rect]) -> Rect { } impl Layout { + /// Place independent controls within the whole contour. No placement step + /// changes camera state or reduces the rendering/picking domain. + pub fn host( + viewport: Rect, + usable: &crate::panel_runtime::HostUsableRegion, + style: crate::prefs::NavigatorStyle, + corner: egui::Vec2, + navigation: Rect, + ) -> Self { + Self::host_with_axis(viewport, usable, style, corner, navigation, true) + } + + pub(crate) fn host_with_axis( + viewport: Rect, + usable: &crate::panel_runtime::HostUsableRegion, + style: crate::prefs::NavigatorStyle, + corner: egui::Vec2, + navigation: Rect, + show_axis: bool, + ) -> Self { + Self::host_impl(viewport, usable, style, corner, navigation, show_axis, None) + } + + pub(crate) fn host_with_retained_confirm( + viewport: Rect, + usable: &crate::panel_runtime::HostUsableRegion, + style: crate::prefs::NavigatorStyle, + confirm: Rect, + navigation: Rect, + show_axis: bool, + ) -> Self { + Self::host_impl(viewport, usable, style, egui::Vec2::ZERO, navigation, show_axis, Some(confirm)) + } + + fn host_impl( + viewport: Rect, + usable: &crate::panel_runtime::HostUsableRegion, + style: crate::prefs::NavigatorStyle, + corner: egui::Vec2, + navigation: Rect, + show_axis: bool, + retained_confirm: Option, + ) -> Self { + use crate::panel_runtime::{egui_rect, logical_rect, resolve_usable_region}; + use solidcraft_engine::panels::{Point, Size}; + let clearance = crate::theme::Tokens::get().space_4; + let mut obstacles = usable.obstacles.clone(); + let navigation = if navigation.is_positive() && navigation.is_finite() && usable.contains_rect(logical_rect(navigation)) { + navigation + } else { + Rect::NOTHING + }; + if navigation.is_positive() { + obstacles.push(logical_rect(navigation)); + } + let with_navigation = resolve_usable_region(usable.domain, &obstacles).ok(); + let confirm = retained_confirm.unwrap_or_else(|| { + with_navigation + .as_ref() + .and_then(|region| { + region.place_footprint( + Size { width: corner.x, height: corner.y }, + Point { x: viewport.right() - CORNER_INSET - corner.x / 2.0, y: viewport.top() + CORNER_INSET + corner.y / 2.0 }, + clearance, + ) + }) + .map(egui_rect) + .unwrap_or(Rect::NOTHING) + }); + if confirm.is_positive() && !obstacles.contains(&logical_rect(confirm)) { + obstacles.push(logical_rect(confirm)); + } + let before_axis = resolve_usable_region(usable.domain, &obstacles).ok(); + let extent = super::viewport::axis_view_size(style); + let axis_view = before_axis + .as_ref() + .filter(|_| show_axis) + .and_then(|region| { + region.place_footprint( + Size { width: extent, height: extent }, + Point { x: viewport.right() - extent / 2.0 - clearance, y: viewport.top() + extent / 2.0 + clearance }, + clearance, + ) + }) + .map(egui_rect) + .unwrap_or(Rect::NOTHING); + if axis_view.is_positive() { + obstacles.push(logical_rect(axis_view)); + } + let region = resolve_usable_region(usable.domain, &obstacles).ok(); + // Compatibility summaries use an existing safe sweep piece. Searching + // all spanning rectangles belongs only to an explicit Fit request. + let largest_piece = |region: &crate::panel_runtime::HostUsableRegion| { + region + .free + .iter() + .max_by(|a, b| (a.size.width * a.size.height).total_cmp(&(b.size.width * b.size.height))) + .copied() + .map(egui_rect) + .unwrap_or(Rect::NOTHING) + }; + let middle = largest_piece(usable); + let drawable = region.as_ref().map(largest_piece).unwrap_or(Rect::NOTHING); + Self { viewport, drawable, middle, content: viewport, axis_view, navigation, confirm, usable: region } + } + /// `corner` is the size of the OK and Cancel pair (#6709; zero while it is not shown): it is /// held in the top right corner of the content, and the axis view moves down below it. /// `navigation` is the measured rectangle of the navigation bar (nothing while it is hidden). @@ -110,7 +227,7 @@ impl Layout { ) -> Self { let fit_in_content = inspector_side.is_some(); let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 }; - let mut obstacles: Vec<_> = docks.iter().take(14).copied().filter(|r| r.is_finite()).map(|r| r.expand(4.0)).collect(); + let mut obstacles: Vec<_> = docks.iter().copied().filter(|r| r.is_finite()).map(|r| r.expand(4.0)).collect(); // Navigation is anchored to the viewport, never to transient dialog space. let available = content; let confirm = if corner.is_finite() @@ -145,8 +262,9 @@ impl Layout { } else { Rect::NOTHING }; + // Preserve legacy control anchors. Product controls retain their existing + // vertical relocation policy; the universal host uses the full contour. if fit_in_content { - // A focus-exit or folded-dock chip may occupy the compass's corner. for _ in 0..obstacles.len() { let bottom = obstacles.iter().filter(|dock| axis_view.intersect(**dock).is_positive()).map(Rect::bottom).max_by(f32::total_cmp); let Some(bottom) = bottom else { break }; @@ -178,10 +296,180 @@ impl Layout { } } let drawable = free_rect(within, &obstacles).shrink(16.0 / scale); - Self { viewport, drawable, middle, content, axis_view, navigation, confirm } + Self { viewport, drawable, middle, content, axis_view, navigation, confirm, usable: None } } } +/// Add independently drawn controls once, retaining the complete persistent +/// contour. Exact deduplication avoids counting the early confirmation twice. +fn framing_region(layout: &Layout, usable: &crate::panel_runtime::HostUsableRegion) -> Option { + use crate::panel_runtime::{MAX_USABLE_OBSTACLES, logical_rect, resolve_usable_region}; + let mut obstacles = usable.obstacles.clone(); + for rect in [layout.navigation, layout.confirm, layout.axis_view] { + if !rect.is_positive() || !rect.is_finite() { + continue; + } + let rect = logical_rect(rect); + if !obstacles.contains(&rect) { + if obstacles.len() >= MAX_USABLE_OBSTACLES { + return None; + } + obstacles.push(rect); + } + } + match &layout.usable { + Some(region) if region.domain == usable.domain && region.obstacles == obstacles => Some(region.clone()), + _ => resolve_usable_region(usable.domain, &obstacles).ok(), + } +} + +/// Reuse the actual host contour in a product-owned projection (for example a +/// Render picture). Controls stay where they painted; only their intersections +/// with the picture can obstruct its camera. This never allocates UI or fits. +pub(crate) fn host_projection_layout(layout: &Layout, usable: &crate::panel_runtime::HostUsableRegion, projection: Rect) -> Option { + use crate::panel_runtime::{egui_rect, logical_rect, resolve_usable_region}; + if !projection.is_finite() || !projection.is_positive() || !layout.viewport.contains_rect(projection) { + return None; + } + let region = framing_region(layout, usable)?; + let obstacles: Vec<_> = region + .obstacles + .iter() + .map(|rect| egui_rect(*rect).intersect(projection)) + .filter(|rect| rect.is_positive() && rect.is_finite()) + .map(logical_rect) + .collect(); + let region = resolve_usable_region(logical_rect(projection), &obstacles).ok()?; + Some(Layout { + viewport: projection, + content: projection, + drawable: layout.drawable.intersect(projection), + middle: layout.middle.intersect(projection), + // These footprints are already included, clipped, in the new contour. + navigation: Rect::NOTHING, + axis_view: Rect::NOTHING, + confirm: Rect::NOTHING, + usable: Some(region), + }) +} + +/// Explicit Fit/centring chooses a safe rectangle for the model's projected +/// aspect within the contour, then uses the existing camera-fitting path and +/// its full-domain projection/corner checks. Panel changes never call this. +pub(crate) fn fit_host_bounds( + cam: Camera, + bounds: &Aabb3, + layout: &Layout, + usable: &crate::panel_runtime::HostUsableRegion, + fov: f64, + share: f64, +) -> Option { + use crate::panel_runtime::egui_rect; + use solidcraft_engine::panels::Point; + if bounds.is_empty() || !bounds.min.is_finite() || !bounds.max.is_finite() || !cam.is_valid() { + return None; + } + let (right, up, _) = cam.basis(); + let extent = bounds.max - bounds.min; + let half = |axis: Vec3| (extent.x * axis.x.abs() + extent.y * axis.y.abs() + extent.z * axis.z.abs()) * 0.5; + let (width, height) = (half(right).max(0.5), half(up).max(0.5)); + if !width.is_finite() || !height.is_finite() { + return None; + } + let aspect = (width / height).clamp(0.0001, 10000.0) as f32; + let region = framing_region(layout, usable)?; + let room = region.fit_rect_with_clearance( + aspect, + Point { x: layout.viewport.center().x, y: layout.viewport.center().y }, + crate::theme::Tokens::get().space_8, + )?; + let room = egui_rect(room); + if !room.is_positive() { + return None; + } + let mut target = layout.clone(); + target.drawable = room; + target.middle = room; + fit_bounds_sized(cam, bounds, &target, fov, share) +} + +/// Reposition an explicitly selected focus at the current zoom. Perspective +/// corners are checked after translation; an oversized selection falls back to +/// centring only its requested focus, never silently changing distance. +pub(crate) fn centre_host_camera( + mut cam: Camera, + bounds: Option<&Aabb3>, + layout: &Layout, + usable: &crate::panel_runtime::HostUsableRegion, + fov: f64, +) -> Option { + use crate::panel_runtime::{egui_rect, logical_rect}; + use solidcraft_engine::panels::{Point, Size}; + if !cam.is_valid() || !layout.viewport.is_positive() || !fov.is_finite() || !(0.0..std::f64::consts::PI).contains(&fov) { + return None; + } + let region = framing_region(layout, usable)?; + let room = egui_rect(region.largest_rect()?); + let original_fov = cam.fov; + cam.fov = fov; + let focus = cam.target; + let (right, up, _) = cam.basis(); + let h = f64::from(layout.viewport.height()); + let w = f64::from(layout.viewport.width()); + let k = 2.0 * cam.half_height() / h; + let translate = |at: egui::Pos2| { + let offset = at - layout.viewport.center(); + let mut result = cam; + result.target = focus - right * (f64::from(offset.x) * k) + up * (f64::from(offset.y) * k); + result + }; + let corners: Vec<_> = bounds + .filter(|bounds| !bounds.is_empty() && bounds.min.is_finite() && bounds.max.is_finite()) + .map(|bounds| { + [bounds.min.x, bounds.max.x] + .into_iter() + .flat_map(|x| { + [bounds.min.y, bounds.max.y] + .into_iter() + .flat_map(move |y| [bounds.min.z, bounds.max.z].into_iter().map(move |z| Vec3::new(x, y, z))) + }) + .collect() + }) + .unwrap_or_default(); + let radius = corners.iter().map(|p| p.dist(focus)).fold(cam.half_height().max(10.0), f64::max) * 2.0; + let project = |camera: Camera, point: Vec3| { + camera.to_screen(point, w, h, radius).and_then(|(x, y, z)| { + (x.is_finite() && y.is_finite() && (0.0..=1.0).contains(&z)) + .then(|| pos2(layout.viewport.left() + x as f32, layout.viewport.top() + y as f32)) + }) + }; + let mut result = translate(room.center()); + if !corners.is_empty() { + let projected: Option> = corners.iter().map(|p| project(cam, *p)).collect(); + if let Some(points) = projected { + let footprint = points.iter().fold(Rect::NOTHING, |rect, p| rect.union(Rect::from_min_max(*p, *p))); + let size = footprint.size().max(vec2(1.0, 1.0)); + if let Some(landing) = region.place_footprint( + Size { width: size.x, height: size.y }, + Point { x: layout.viewport.center().x, y: layout.viewport.center().y }, + crate::theme::Tokens::get().space_8, + ) { + let at = layout.viewport.center() + (egui_rect(landing).center() - footprint.center()); + let candidate = translate(at); + let final_points: Option> = corners.iter().map(|p| project(candidate, *p)).collect(); + if let Some(points) = final_points { + let footprint = points.iter().fold(Rect::NOTHING, |rect, p| rect.union(Rect::from_min_max(*p, *p))); + if region.contains_rect(logical_rect(footprint.expand(crate::theme::Tokens::get().space_4))) { + result = candidate; + } + } + } + } + } + result.fov = original_fov; + result.is_valid().then_some(result) +} + /// Product cameras keep the authored lens while framing the free canvas. pub(crate) fn fit_product_bounds(cam: Camera, bounds: &Aabb3, layout: &Layout) -> Option { fit_bounds(cam, bounds, layout, cam.fov) diff --git a/crates/ui-egui/src/viewport_layout_tests.rs b/crates/ui-egui/src/viewport_layout_tests.rs index f7444107d..0f44ab7ea 100644 --- a/crates/ui-egui/src/viewport_layout_tests.rs +++ b/crates/ui-egui/src/viewport_layout_tests.rs @@ -8,6 +8,256 @@ fn bar_rect(canvas: Rect) -> Rect { crate::navigation_bar_view::measure(canvas, &Default::default(), crate::navigation::NavCaps::MODEL, |_| 0.0).rect } +fn assert_navigator_shared_zoom(app: &crate::SolveApp, camera: Camera) { + let context = format!( + "host={}, measured={}, render={}, fov={}, up={:?}, viewport={:?}, shell_content={:?}", + app.universal_panel_host_enabled(), + app.universal_panel_frame().is_some(), + crate::render_workspace::active(app), + camera.fov, + camera.up, + app.viewport.rect, + app.shell.content, + ); + if crate::render_workspace::active(app) && app.universal_panel_frame().is_some() { + let layout = app.viewport.layout.as_ref().expect(&context); + let usable = crate::shell::host_usable(app).expect(&context); + let picture = crate::render_workspace::host_picture_layout(app, layout, &usable).expect(&context); + let region = picture.usable.as_ref().expect(&context); + assert!( + region + .fit_rect_with_clearance( + 1.0, + solidcraft_engine::panels::Point { x: picture.viewport.center().x, y: picture.viewport.center().y }, + crate::theme::Tokens::get().space_8, + ) + .is_some(), + "the Render fixture must leave clear picture room: {context}; free={:?}", + region.free + ); + } + let bounds = Aabb3 { min: Vec3::new(120.0, -35.0, 5.0), max: Vec3::new(180.0, -5.0, 15.0) }; + let centre = bounds.center(); + let radius = bounds.diagonal() * 0.5; + let offset = Vec3::new(radius, radius, radius); + let sphere = Aabb3 { min: centre - offset, max: centre + offset }; + let mut front = if app.universal_panel_host_enabled() { camera } else { Camera::default() }; + front.set_view(StandardView::Front); + let distance = app.try_fitted_bounds(front, &sphere).expect(&context).distance; + let reference = app.navigator_fitted_bounds(front, &bounds).expect(&context); + let mut directions = Vec::new(); + for view in + [StandardView::Front, StandardView::Back, StandardView::Left, StandardView::Right, StandardView::Top, StandardView::Bottom, StandardView::Iso] + { + let mut requested = camera; + requested.set_view(view); + directions.push(requested); + } + for yaw in [-3.0, -1.0, 1.0, 3.0] { + for pitch in [-1.0, 1.0] { + directions.push(Camera { + yaw: yaw * std::f64::consts::FRAC_PI_4, + pitch: pitch * (1.0_f64 / 3.0_f64.sqrt()).asin(), + roll: 0.17, + ..camera + }); + } + } + for requested in directions { + let fitted = app.navigator_fitted_bounds(requested, &bounds).expect(&context); + assert_eq!(fitted.distance.to_bits(), distance.to_bits(), "every navigator direction uses the Front probe's zoom"); + assert_eq!( + (fitted.yaw, fitted.pitch, fitted.roll, fitted.up, fitted.fov), + (requested.yaw, requested.pitch, requested.roll, requested.up, requested.fov) + ); + if app.universal_panel_frame().is_some() { + let layout = app.viewport.layout.as_ref().unwrap(); + let usable = crate::shell::host_usable(app).unwrap(); + let (projection, fov) = if crate::render_workspace::active(app) { + (crate::render_workspace::host_picture_layout(app, layout, &usable).unwrap(), requested.fov) + } else { + (host_projection_layout(layout, &usable, layout.viewport).unwrap(), app.view_fov()) + }; + assert!((fitted.target - centre).dot(fitted.back()).abs() < 1e-8, "the contour offset must stay in the image plane"); + let viewport = projection.viewport; + let project = |camera| { + let effective = Camera { fov, ..camera }; + let (x, y, _) = effective.to_screen(centre, f64::from(viewport.width()), f64::from(viewport.height()), distance * 4.0).unwrap(); + pos2(viewport.left() + x as f32, viewport.top() + y as f32) + }; + let focus = project(fitted); + let reference_focus = project(reference); + assert!((focus - reference_focus).length() < 1e-3, "every navigator direction keeps one screen centre: {focus:?} vs {reference_focus:?}"); + assert!( + projection.usable.as_ref().unwrap().free.iter().any(|piece| crate::panel_runtime::egui_rect(*piece).contains(focus)), + "the same object centre lands in the usable picture, although its world-space target offset rotates" + ); + } else { + assert_eq!(fitted.target, centre, "Classic and an unmeasured host keep the legacy centre"); + } + } +} + +fn navigator_layout_fixture(host: bool, measured: bool, render: bool) -> Harness { + let mut h = Harness::new(); + h.app.home.open = false; + if render { + crate::render_workspace::enter(&mut h.app, true).unwrap(); + h.app.run("view.render_stage", json!({"stage":"frame"})).unwrap(); + h.app.run("render.output.size", json!({"width":400,"height":1600})).unwrap(); + } + // Start from a coherent Classic composition, including the shell content + // that anchors Render's picture, before optionally enabling the host. + h.frames(4); + if host { + crate::panel_runtime::enable_host_specimen(&mut h.app, "docks").unwrap(); + if measured { + h.frames(4); + if !render { + let viewport = h.app.viewport.rect.unwrap(); + // Design has an asymmetric contour; Render keeps its real docks + // and Frame controls so the authored picture remains available. + h.app.viewport.host_windows = + Some(vec![Rect::from_min_max(pos2(viewport.left() + 550.0, viewport.top()), pos2(viewport.right(), viewport.bottom() - 300.0))]); + } + } + } + assert_eq!(h.app.universal_panel_host_enabled(), host); + assert_eq!(h.app.universal_panel_frame().is_some(), measured); + h +} + +#[test] +fn navigator_front_probe_shares_zoom_in_classic_measured_and_unmeasured_hosts() { + for (host, measured) in [(false, false), (true, false), (true, true)] { + let mut h = navigator_layout_fixture(host, measured, false); + for perspective in [false, true] { + h.app.ui.perspective = perspective; + h.app.ui.auto_ortho_faces = false; + for up in [solidcraft_engine::render::UpAxis::Z, solidcraft_engine::render::UpAxis::Y] { + assert_navigator_shared_zoom(&h.app, Camera { up, fov: 0.95, ..Default::default() }); + } + } + } +} + +#[test] +fn navigator_render_keeps_classic_probe_and_host_authored_lens_and_picture() { + for (host, measured) in [(false, false), (true, false), (true, true)] { + let mut h = navigator_layout_fixture(host, measured, true); + for fov in [0.0, 0.95] { + // Host framing uses the authored lens even when Design preferences disagree. + h.app.ui.perspective = fov == 0.0; + h.app.ui.auto_ortho_faces = false; + assert_ne!(h.app.view_fov(), fov); + let layout = h.app.viewport.layout.as_ref().unwrap(); + let picture = crate::render_workspace::picture_layout(&h.app, layout); + assert!(picture.viewport.width() < layout.viewport.width(), "the portrait frame must exercise a distinct projection"); + for up in [solidcraft_engine::render::UpAxis::Z, solidcraft_engine::render::UpAxis::Y] { + assert_navigator_shared_zoom(&h.app, Camera { up, fov, ..Default::default() }); + } + } + } +} + +#[test] +fn host_picture_projection_clips_real_controls_and_refuses_invalid_domains() { + use crate::panel_runtime::{egui_rect, logical_rect, resolve_usable_region}; + let viewport = Rect::from_min_max(pos2(0.0, 34.0), pos2(1400.0, 950.0)); + let picture = Rect::from_min_max(pos2(420.0, 160.0), pos2(980.0, 860.0)); + let outside = Rect::from_min_size(pos2(0.0, 34.0), vec2(1400.0, 100.0)); + let crossing = Rect::from_min_size(pos2(300.0, 300.0), vec2(220.0, 120.0)); + let usable = resolve_usable_region(logical_rect(viewport), &[logical_rect(outside), logical_rect(crossing)]).unwrap(); + let mut layout = Layout::host_with_axis(viewport, &usable, crate::prefs::NavigatorStyle::Axes, egui::Vec2::ZERO, Rect::NOTHING, false); + layout.navigation = Rect::from_min_size(pos2(900.0, 800.0), vec2(200.0, 40.0)); + let projection = host_projection_layout(&layout, &usable, picture).unwrap(); + let region = projection.usable.as_ref().unwrap(); + assert_eq!(projection.viewport, picture); + assert_eq!(egui_rect(region.domain), picture); + assert_eq!(region.obstacles.len(), 2, "only real intersections remain"); + assert!(region.obstacles.contains(&logical_rect(crossing.intersect(picture)))); + assert!(region.obstacles.contains(&logical_rect(layout.navigation.intersect(picture)))); + assert!(region.obstacles.iter().all(|rect| picture.contains_rect(egui_rect(*rect)))); + assert_eq!(layout.viewport, viewport, "preparing a fit never changes the canvas"); + for invalid in [ + Rect::NOTHING, + Rect::from_min_size(picture.min, vec2(0.0, 1.0)), + viewport.expand(1.0), + Rect::from_min_size(pos2(f32::NAN, 0.0), vec2(10.0, 10.0)), + ] { + assert!(host_projection_layout(&layout, &usable, invalid).is_none()); + } +} + +#[test] +fn host_picture_fit_keeps_product_lens_and_padded_corners_in_the_picture_contour() { + use crate::panel_runtime::{egui_rect, logical_rect, resolve_usable_region}; + let viewport = Rect::from_min_max(pos2(0.0, 34.0), pos2(1400.0, 950.0)); + // A 40 px inset leaves 1320 × 836 px: portrait 1:4 and landscape 12:5 frames. + for size in [vec2(209.0, 836.0), vec2(1320.0, 550.0)] { + let picture = Rect::from_center_size(viewport.center(), size); + let obstacle = Rect::from_min_size(picture.min, picture.size() * 0.25); + 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); + let projection = host_projection_layout(&layout, &usable, picture).unwrap(); + let region = projection.usable.as_ref().unwrap(); + for fov in [0.0, 0.95] { + for bounds in [ + Aabb3 { min: Vec3::new(-60.0, -15.0, -2.0), max: Vec3::new(60.0, 15.0, 2.0) }, + Aabb3 { min: Vec3::ZERO, max: Vec3::new(100.0, 0.0, 0.0) }, + ] { + let camera = Camera { fov, ..Default::default() }; + let fitted = fit_host_bounds(camera, &bounds, &projection, region, camera.fov, 1.0).unwrap(); + assert_eq!(fitted.fov, fov); + let radius = (bounds.diagonal() + bounds.center().dist(fitted.target)).max(fitted.half_height() * 2.0).max(10.0); + let mut footprint = Rect::NOTHING; + for x in [bounds.min.x, bounds.max.x] { + for y in [bounds.min.y, bounds.max.y] { + for z in [bounds.min.z, bounds.max.z] { + let (x, y, depth) = + fitted.to_screen(Vec3::new(x, y, z), f64::from(picture.width()), f64::from(picture.height()), radius).unwrap(); + assert!((0.0..=1.0).contains(&depth)); + footprint.extend_with(pos2(picture.left() + x as f32, picture.top() + y as f32)); + } + } + } + assert!( + region.contains_rect(logical_rect(footprint.expand(crate::theme::Tokens::get().space_4))), + "{footprint:?} in {:?}", + egui_rect(region.domain) + ); + } + } + } +} + +#[test] +fn host_picture_centring_keeps_distance_and_selected_focus_at_the_product_lens() { + use crate::panel_runtime::{logical_rect, resolve_usable_region}; + let viewport = Rect::from_min_max(pos2(0.0, 34.0), pos2(1200.0, 900.0)); + let picture = Rect::from_min_max(pos2(420.0, 180.0), pos2(780.0, 800.0)); + let obstacle = Rect::from_min_size(picture.min, vec2(100.0, 180.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); + let projection = host_projection_layout(&layout, &usable, picture).unwrap(); + let safe = projection.usable.as_ref().unwrap(); + let bounds = Aabb3 { min: Vec3::new(-20.0, -10.0, 0.0), max: Vec3::new(20.0, 10.0, 0.0) }; + for fov in [0.0, 0.95] { + for distance in [2.0, 500.0] { + let camera = Camera { distance, fov, target: bounds.center(), ..Default::default() }; + let centred = centre_host_camera(camera, Some(&bounds), &projection, safe, camera.fov).unwrap(); + assert_eq!(centred.distance.to_bits(), distance.to_bits()); + assert_eq!(centred.fov, fov); + let (x, y, _) = centred.to_screen(camera.target, f64::from(picture.width()), f64::from(picture.height()), 2000.0).unwrap(); + let focus = pos2(picture.left() + x as f32, picture.top() + y as f32); + assert!(picture.contains(focus) && !obstacle.contains(focus)); + } + } + let tiny = Rect::from_min_size(picture.min, vec2(4.0, 4.0)); + let projection = host_projection_layout(&layout, &usable, tiny).unwrap(); + assert!(fit_host_bounds(Camera::default(), &bounds, &projection, projection.usable.as_ref().unwrap(), 0.0, 1.0).is_none()); +} + #[test] fn render_compass_avoids_the_navigation_bar_on_either_inspector_side() { let viewport = Rect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 140.0)); @@ -159,6 +409,249 @@ fn hostile_or_empty_fit_keeps_the_existing_camera_valid() { assert_eq!(app.fitted_bounds(cam, &bounds), cam); } +#[test] +fn host_fit_uses_the_actual_contour_and_model_extent_with_the_full_projection() { + use crate::panel_runtime::{egui_rect, logical_rect, resolve_usable_region}; + let viewport = Rect::from_min_max(pos2(0.0, crate::toolbar::APP_BAR_HEIGHT), pos2(1400.0, 1000.0)); + let obstacles = [ + Rect::from_min_max(viewport.min, pos2(1400.0, 130.0)), + Rect::from_min_size(pos2(0.0, 130.0), vec2(260.0, 170.0)), + Rect::from_min_size(pos2(1180.0, 130.0), vec2(220.0, 300.0)), + Rect::from_min_size(pos2(500.0, 340.0), vec2(220.0, 160.0)), + ]; + let usable = resolve_usable_region(logical_rect(viewport), &obstacles.map(logical_rect)).unwrap(); + assert!(usable.free.iter().any(|piece| egui_rect(*piece).contains(pos2(100.0, 700.0))), "the short-panel gap is part of the retained contour"); + for style in [crate::prefs::NavigatorStyle::Axes, crate::prefs::NavigatorStyle::Cube] { + let navigation = bar_rect(viewport); + let layout = Layout::host(viewport, &usable, style, egui::Vec2::ZERO, navigation); + assert_eq!(layout.viewport, viewport); + assert!(layout.navigation.is_positive() && layout.axis_view.is_positive()); + for control in [layout.navigation, layout.axis_view] { + assert!(usable.contains_rect(logical_rect(control))); + assert!(obstacles.iter().all(|obstacle| !control.intersect(*obstacle).is_positive())); + } + assert!(!layout.axis_view.expand(crate::theme::Tokens::get().space_4).intersect(layout.navigation).is_positive()); + for bounds in [ + Aabb3 { min: Vec3::new(-90.0, -5.0, -2.0), max: Vec3::new(110.0, 5.0, 2.0) }, + Aabb3 { min: Vec3::new(-5.0, -90.0, -2.0), max: Vec3::new(5.0, 110.0, 2.0) }, + ] { + for view in [StandardView::Top, StandardView::Iso] { + for fov in [0.0, 0.6] { + let mut cam = Camera::default(); + cam.set_view(view); + let fitted = fit_host_bounds(cam, &bounds, &layout, &usable, fov, 1.0).unwrap(); + assert_eq!((fitted.yaw, fitted.pitch, fitted.up), (cam.yaw, cam.pitch, cam.up)); + assert_eq!(fit_host_bounds(fitted, &bounds, &layout, &usable, fov, 1.0).unwrap(), fitted); + let mut effective = fitted; + effective.fov = fov; + let radius = (bounds.diagonal() * 0.5 + bounds.center().dist(fitted.target)).max(effective.half_height() * 2.0).max(10.0); + let mut projected = Rect::NOTHING; + for x in [bounds.min.x, bounds.max.x] { + for y in [bounds.min.y, bounds.max.y] { + for z in [bounds.min.z, bounds.max.z] { + let (sx, sy, depth) = effective + .to_screen(Vec3::new(x, y, z), f64::from(viewport.width()), f64::from(viewport.height()), radius) + .unwrap(); + assert!((0.0..=1.0).contains(&depth)); + projected.extend_with(pos2(viewport.left() + sx as f32, viewport.top() + sy as f32)); + } + } + } + assert!(viewport.contains_rect(projected)); + assert!( + obstacles.iter().all(|obstacle| !projected.intersect(*obstacle).is_positive()), + "the entire model footprint must clear short panels and floating holes: {projected:?}" + ); + assert!([layout.navigation, layout.axis_view, layout.confirm].iter().all(|control| !projected.intersect(*control).is_positive())); + } + } + } + } +} + +#[test] +fn host_fit_keeps_thin_and_degenerate_model_footprints_padded_at_both_scales() { + use crate::panel_runtime::{logical_rect, resolve_usable_region}; + for scale in [1.0, 2.0] { + let ctx = crate::fonts::test_context(); + ctx.set_pixels_per_point(scale); + crate::test_support::frame( + &ctx, + egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1400.0, 1000.0))), focused: true, ..Default::default() }, + |ui| { + assert_eq!(ui.ctx().pixels_per_point(), scale); + let viewport = Rect::from_min_max(pos2(0.0, crate::toolbar::APP_BAR_HEIGHT), ui.ctx().content_rect().max); + let obstacles = [ + Rect::from_min_max(viewport.min, pos2(1400.0, 130.0)), + Rect::from_min_size(pos2(0.0, 130.0), vec2(260.0, 170.0)), + Rect::from_min_size(pos2(1180.0, 130.0), vec2(220.0, 300.0)), + Rect::from_min_size(pos2(500.0, 340.0), vec2(220.0, 160.0)), + ]; + let usable = resolve_usable_region(logical_rect(viewport), &obstacles.map(logical_rect)).unwrap(); + let layout = Layout::host(viewport, &usable, crate::prefs::NavigatorStyle::Axes, egui::Vec2::ZERO, bar_rect(viewport)); + let all_obstacles = obstacles + .iter() + .copied() + .chain([layout.navigation, layout.axis_view, layout.confirm].into_iter().filter(|rect| rect.is_positive())) + .map(logical_rect) + .collect::>(); + let safe = resolve_usable_region(logical_rect(viewport), &all_obstacles).unwrap(); + for extent in [Vec3::new(100.0, 0.0, 0.0), Vec3::new(0.0, 100.0, 0.0), Vec3::new(100.0, 1e-9, 0.0), Vec3::new(1e-9, 100.0, 0.0)] { + let bounds = Aabb3 { min: extent * -0.5, max: extent * 0.5 }; + for fov in [0.0, 0.6] { + let mut cam = Camera::default(); + cam.set_view(StandardView::Top); + let fitted = fit_host_bounds(cam, &bounds, &layout, &usable, fov, 1.0) + .expect("a line or near-flat extent must still fit with clearance"); + assert_eq!((fitted.yaw, fitted.pitch, fitted.up, fitted.fov), (cam.yaw, cam.pitch, cam.up, cam.fov)); + let mut effective = fitted; + effective.fov = fov; + let radius = (bounds.diagonal() * 0.5 + bounds.center().dist(fitted.target)).max(effective.half_height() * 2.0).max(10.0); + let mut projected = Rect::NOTHING; + for x in [bounds.min.x, bounds.max.x] { + for y in [bounds.min.y, bounds.max.y] { + for z in [bounds.min.z, bounds.max.z] { + let (sx, sy, depth) = effective + .to_screen(Vec3::new(x, y, z), f64::from(viewport.width()), f64::from(viewport.height()), radius) + .unwrap(); + assert!((0.0..=1.0).contains(&depth)); + projected.extend_with(pos2(viewport.left() + sx as f32, viewport.top() + sy as f32)); + } + } + } + assert!(projected.is_finite()); + let padding = crate::theme::Tokens::get().space_8; + let padded = projected.expand(padding - 0.01); + assert!( + safe.contains_rect(logical_rect(padded)), + "{scale}x thin extent {extent:?} needs its full projected clearance: {padded:?}" + ); + assert!(all_obstacles.iter().all(|obstacle| !padded.intersect(crate::panel_runtime::egui_rect(*obstacle)).is_positive())); + } + } + }, + ); + } +} + +#[test] +fn explicit_host_centring_preserves_zoom_and_only_falls_back_to_the_selected_focus() { + use crate::panel_runtime::{egui_rect, logical_rect, resolve_usable_region}; + let viewport = Rect::from_min_max(pos2(0.0, crate::toolbar::APP_BAR_HEIGHT), pos2(1000.0, 700.0)); + let obstacles = [Rect::from_min_size(pos2(0.0, viewport.top()), vec2(260.0, 220.0)), Rect::from_min_size(pos2(450.0, 300.0), vec2(180.0, 160.0))]; + let usable = resolve_usable_region(logical_rect(viewport), &obstacles.map(logical_rect)).unwrap(); + let layout = Layout::host(viewport, &usable, crate::prefs::NavigatorStyle::Axes, egui::Vec2::ZERO, bar_rect(viewport)); + let safe = layout.usable.as_ref().unwrap(); + let bounds = Aabb3 { min: Vec3::new(0.0, 0.0, 10.0), max: Vec3::new(40.0, 30.0, 10.0) }; + for fov in [0.0, 0.6] { + for distance in [2.0, 500.0] { + let mut camera = Camera::default(); + camera.set_view(StandardView::Top); + camera.target = Vec3::new(20.0, 15.0, 10.0); + camera.distance = distance; + camera.fov = fov; + let focus = camera.target; + let centred = centre_host_camera(camera, Some(&bounds), &layout, &usable, fov).unwrap(); + assert_eq!(centred.distance.to_bits(), camera.distance.to_bits(), "centring must never silently zoom out an oversized selection"); + assert_eq!(centred.fov.to_bits(), camera.fov.to_bits()); + assert_eq!((centred.yaw, centred.pitch, centred.roll, centred.up), (camera.yaw, camera.pitch, camera.roll, camera.up)); + let radius = (bounds.diagonal().max(camera.half_height()).max(10.0)) * 2.0; + let project = |point| { + let (x, y, _) = centred.to_screen(point, f64::from(viewport.width()), f64::from(viewport.height()), radius).unwrap(); + pos2(viewport.left() + x as f32, viewport.top() + y as f32) + }; + let selected = project(focus); + assert!(safe.free.iter().any(|piece| egui_rect(*piece).contains(selected))); + assert!(obstacles.iter().all(|obstacle| !obstacle.contains(selected))); + if distance == 500.0 { + let mut footprint = Rect::NOTHING; + for x in [bounds.min.x, bounds.max.x] { + for y in [bounds.min.y, bounds.max.y] { + footprint.extend_with(project(Vec3::new(x, y, 10.0))); + } + } + assert!(safe.contains_rect(logical_rect(footprint)), "when the current zoom fits, the complete selected footprint lands safely"); + } + } + } +} + +#[test] +fn host_normal_to_keeps_distance_and_selection_while_generic_view_follow_remains_exact() { + for scale in [1.0, 2.0] { + for perspective in [false, true] { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.preferences.look_at_anim = false; + h.call("ui.resize", json!({"width":1400,"height":900})); + h.app.run("solid.box", json!({"length":40,"width":30,"height":10})).unwrap(); + h.settle(); + h.ctx.set_pixels_per_point(scale); + crate::panel_runtime::enable_host_specimen(&mut h.app, "docks").unwrap(); + h.frames(3); + let body = h.app.session.model.state().bodies[0].clone(); + let face = (0..body.body.face_count()).find(|index| body.body.planar_face(*index).is_some_and(|plane| plane.normal().z > 0.99)).unwrap(); + let focus = Vec3::new(20.0, 15.0, 10.0); + h.app.run("select.set", json!({"items":[{"type":"face","body":body.name,"index":face,"point":focus}]})).unwrap(); + let selection = h.app.session.selection.clone(); + h.app.ui.perspective = perspective; + h.app.cam.distance = 2.0; + h.app.cam.fov = if perspective { 0.6 } else { 0.0 }; + h.app.cam.target = Vec3::new(-50.0, -50.0, 0.0); + let distance = h.app.cam.distance.to_bits(); + let lens = h.app.cam.fov.to_bits(); + h.app.start("view.normal_to"); + h.settle(); + assert_eq!(h.app.cam.distance.to_bits(), distance); + assert_eq!(h.app.cam.fov.to_bits(), lens); + assert!(h.app.cam.back().dist(Vec3::Z) < 1e-6); + assert_eq!(h.app.session.selection, selection); + let viewport = h.app.viewport.rect.unwrap(); + let point = crate::viewport::projection(&h.app, viewport).to_screen(focus).unwrap(); + assert!( + h.app + .viewport + .layout + .as_ref() + .unwrap() + .usable + .as_ref() + .unwrap() + .free + .iter() + .any(|piece| crate::panel_runtime::egui_rect(*piece).contains(point)), + "an oversized selection keeps zoom while placing its selected focus safely" + ); + let mut requested = h.app.cam; + requested.target = Vec3::new(123.0, 456.0, 7.0); + requested.distance = 17.0; + h.app.session.camera = Some(requested); + h.app.follow_view_request(false); + h.frames(2); + assert_eq!(h.app.cam, requested, "generic apply/replay must not acquire an implicit centring offset"); + } + } +} + +#[test] +fn legacy_usable_space_does_not_silently_ignore_obstacles_after_sixteen() { + let viewport = Rect::from_min_size(pos2(0.0, 0.0), vec2(1000.0, 600.0)); + let mut obstacles = (0..20).map(|index| Rect::from_min_size(pos2(index as f32 * 40.0, 0.0), vec2(20.0, 20.0))).collect::>(); + let late = Rect::from_min_size(pos2(820.0, 0.0), vec2(180.0, 180.0)); + obstacles.push(late); + let room = free_rect(viewport, &obstacles); + assert!(room.is_positive() && room.area() > 100000.0); + assert!(obstacles.iter().all(|obstacle| !room.intersect(*obstacle).is_positive())); + for scale in [1.0, 2.0] { + let layout = + Layout::with_content(viewport, viewport, &obstacles, scale, crate::prefs::NavigatorStyle::Axes, egui::Vec2::ZERO, bar_rect(viewport)); + assert_eq!(layout.viewport, viewport); + assert!(layout.drawable.is_positive()); + assert!(obstacles.iter().all(|obstacle| !layout.drawable.intersect(*obstacle).is_positive())); + assert_eq!(layout.navigation, bar_rect(viewport), "legacy callers retain their supplied measured navigation policy"); + } +} + #[test] fn fit_home_animation_and_manual_takeover_use_one_layout_solution() { for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { diff --git a/crates/ui-egui/tests/icon_audit.rs b/crates/ui-egui/tests/icon_audit.rs index a04de8d66..a779b91d3 100644 --- a/crates/ui-egui/tests/icon_audit.rs +++ b/crates/ui-egui/tests/icon_audit.rs @@ -49,6 +49,145 @@ fn collect(h: &mut Harness, surface: &str, requested: &mut BTreeMap) { + use solidcraft_engine::panels::{Destination, LayoutAction, Mutation, Point, SectionId, Size}; + use solidcraft_ui_egui::panel_runtime::{HostControlTarget, HostPointerTarget, enable_host_specimen}; + fn click_control(h: &mut Harness, target: &HostControlTarget) { + let control = h + .app + .universal_panel_frame() + .unwrap() + .controls + .iter() + .find(|control| control.target == *target) + .unwrap_or_else(|| panic!("missing actual host control: {target:?}")); + let bounds = control.bounds; + assert!(control.enabled, "the audit must use an available real chrome control: {target:?}"); + let x = bounds.origin.x + bounds.size.width / 2.0; + let y = bounds.origin.y + bounds.size.height / 2.0; + if let HostControlTarget::Pointer(HostPointerTarget::Menu { instance }) = target { + assert!( + h.app + .universal_panel_frame() + .unwrap() + .layout + .sections + .iter() + .filter(|section| section.instance != *instance) + .all(|section| !section.outer.contains(Point { x, y })), + "the real menu source must not be covered by another specimen card" + ); + } + assert_eq!(h.call("ui.move", json!({"x":x,"y":y}))["ok"], true); + assert_eq!(h.call("ui.click", json!({"x":x,"y":y}))["ok"], true); + h.frames(3); + } + let mut opened_menus = 0; + let mut opened_overflow = 0; + for preset in ["docks", "tabs", "collapsed", "floating", "overflow", "pinned", "columns", "stack_tabs", "content_fill", "inline"] { + let mut h = harness(); + h.app.home.open = false; + let (width, height) = if preset == "floating" { (1400, 1000) } else { (800, 600) }; + h.call("ui.resize", json!({"width":width,"height":height})); + enable_host_specimen(&mut h.app, preset).unwrap(); + h.frames(3); + if preset == "overflow" { + let section = SectionId::new("specimen-section-0").unwrap(); + let members = + h.app.panel_runtime().unwrap().layout().layout().instances.iter().skip(1).map(|instance| instance.id.clone()).collect::>(); + h.app + .dispatch_panel_layout(LayoutAction::Apply { + expected_revision: None, + mutations: members + .into_iter() + .enumerate() + .map(|(index, instance)| Mutation::Move { + instance, + destination: Destination::JoinTab { section: section.clone(), index: index + 1 }, + }) + .collect(), + }) + .unwrap(); + h.frames(3); + assert!( + h.app.universal_panel_frame().unwrap().controls.iter().any(|control| { + control.enabled && control.target == HostControlTarget::Pointer(HostPointerTarget::TabOverflow { section: section.clone() }) + }), + "the typed fixture must force a real tab overflow launcher" + ); + } + if preset == "floating" { + // Audit visible menu widgets, rather than clicking a lower card + // whose default clamped header is covered by its floating peers. + let sections = h.app.panel_runtime().unwrap().layout().layout().sections.iter().map(|section| section.id.clone()).collect::>(); + let origins = [Point { x: 40.0, y: 200.0 }, Point { x: 400.0, y: 200.0 }, Point { x: 40.0, y: 500.0 }, Point { x: 400.0, y: 500.0 }]; + h.app + .dispatch_panel_layout(LayoutAction::Apply { + expected_revision: None, + mutations: sections + .into_iter() + .zip(origins) + .map(|(section, origin)| Mutation::SetFloatingRect { section, origin, size: Size { width: 280.0, height: 240.0 } }) + .collect(), + }) + .unwrap(); + } + h.frames(3); + collect(&mut h, &format!("universal host {preset}"), requested); + let targets = h + .app + .universal_panel_frame() + .unwrap() + .controls + .iter() + .filter_map(|control| match &control.target { + HostControlTarget::Pointer( + HostPointerTarget::Menu { .. } + | HostPointerTarget::TabOverflow { .. } + | HostPointerTarget::Overflow { .. } + | HostPointerTarget::OverflowAll, + ) => Some(control.target.clone()), + _ => None, + }) + .collect::>(); + assert!(!targets.is_empty(), "specimen must expose actual shared chrome: {preset}"); + for target in targets { + click_control(&mut h, &target); + assert!(h.app.universal_panel_frame().unwrap().menu_bounds.is_some(), "actual host menu must open for {preset}: {target:?}"); + opened_menus += 1; + collect(&mut h, &format!("universal host {preset} {target:?}"), requested); + if matches!( + target, + HostControlTarget::Pointer( + HostPointerTarget::Overflow { .. } | HostPointerTarget::OverflowAll | HostPointerTarget::TabOverflow { .. } + ) + ) { + opened_overflow += 1; + let nested = h + .app + .universal_panel_frame() + .unwrap() + .controls + .iter() + .find_map(|control| match &control.target { + HostControlTarget::PanelMenu { .. } => Some(control.target.clone()), + _ => None, + }) + .expect("overflow must expose the same per-instance action menu"); + click_control(&mut h, &nested); + assert!(h.app.universal_panel_frame().unwrap().menu_bounds.is_some()); + collect(&mut h, &format!("universal host {preset} overflow actions"), requested); + } + h.step(&json!({"key":"Escape"})).unwrap(); + h.frames(2); + } + } + assert!(opened_menus >= 6, "must traverse actual menus in every bounded preset"); + assert!(opened_overflow > 0, "must traverse an actual overflow menu"); +} + fn menu(h: &mut Harness, target: Value, surface: &str, requested: &mut BTreeMap) { // Open on empty canvas so the picker cannot replace the prepared face/edge/sketch // selection with whatever happens to lie under the menu's anchor. @@ -516,6 +655,7 @@ fn requested_menu_icons_have_artwork_and_match_manifest() { scenario.run(&serde_json::from_str(source).unwrap()).unwrap_or_else(|e| panic!("{name}: {e}")); collect(&mut scenario, name, &mut requested); } + universal_panel_host_menus(&mut requested); icon_svg::audit::stop(); let manifest = requested.iter().map(|(name, placeholder)| format!("{name}\t{placeholder}\n")).collect::(); let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets/icons/ui/design/requested_icons.txt"); diff --git a/crates/ui-egui/tests/scenarios/sketch_mirror_dialog.json b/crates/ui-egui/tests/scenarios/sketch_mirror_dialog.json index ae729b9f1..73505abd7 100644 --- a/crates/ui-egui/tests/scenarios/sketch_mirror_dialog.json +++ b/crates/ui-egui/tests/scenarios/sketch_mirror_dialog.json @@ -1,5 +1,5 @@ [ - {"call":"ui.prefs","params":{"look_at_anim":false}}, + {"call":"ui.prefs","params":{"look_at_anim":false,"sketch_mirror_auto_line":false}}, {"call":"engine.execute","params":{"command":"sketch.create","params":{"plane":"XY"}}}, {"call":"engine.execute","params":{"command":"sketch.line","params":{"points":[[-30,10],[-15,10]]}}}, {"call":"engine.execute","params":{"command":"sketch.line","params":{"points":[[-15,10],[-15,25]]}}}, diff --git a/crates/ui-egui/tests/scenarios/universal_panel_host_collapsed.json b/crates/ui-egui/tests/scenarios/universal_panel_host_collapsed.json new file mode 100644 index 000000000..595f101d3 --- /dev/null +++ b/crates/ui-egui/tests/scenarios/universal_panel_host_collapsed.json @@ -0,0 +1,11 @@ +[ + {"note":"Collapsed specimens keep full-width headers, declared actions and one-click restoration; hidden bodies keep their controllers."}, + {"call":"ui.resize","params":{"width":1400,"height":900}}, + {"panel_fixture":{"enabled":true,"preset":"collapsed"}}, + {"widget":"Expand panel"}, + {"widget":"Collapse panel"}, + {"call":"engine.execute","params":{"command":"panel.action","params":{"target":{"type":"instance","id":"specimen-0"},"action":"apply"}}}, + {"panel_fixture":{}}, + {"expect":{"errors":0,"features":0,"dialog":null,"tool":null}}, + {"panel_fixture":{"enabled":false}} +] diff --git a/crates/ui-egui/tests/scenarios/universal_panel_host_columns_inline.json b/crates/ui-egui/tests/scenarios/universal_panel_host_columns_inline.json new file mode 100644 index 000000000..6320fb9e0 --- /dev/null +++ b/crates/ui-egui/tests/scenarios/universal_panel_host_columns_inline.json @@ -0,0 +1,19 @@ +[ + {"note":"Explicit specimens exercise independent columns, stack/tab grouping, sole Content versus Fill, and the editable one-row inline slot. Production adapters remain unchanged."}, + {"call":"ui.resize","params":{"width":1600,"height":1000}}, + {"panel_fixture":{"preset":"columns"}}, + {"widget":"Collapse panel"}, + {"widget":"Expand panel"}, + {"panel_fixture":{}}, + {"panel_fixture":{"enabled":false}}, + {"panel_fixture":{"preset":"stack_tabs"}}, + {"panel_fixture":{}}, + {"panel_fixture":{"enabled":false}}, + {"panel_fixture":{"preset":"content_fill"}}, + {"panel_fixture":{}}, + {"panel_fixture":{"enabled":false}}, + {"panel_fixture":{"preset":"inline"}}, + {"panel_fixture":{}}, + {"expect":{"errors":0,"features":0,"dialog":null,"tool":null}}, + {"panel_fixture":{"enabled":false}} +] diff --git a/crates/ui-egui/tests/scenarios/universal_panel_host_overflow_scale.json b/crates/ui-egui/tests/scenarios/universal_panel_host_overflow_scale.json new file mode 100644 index 000000000..eb3571769 --- /dev/null +++ b/crates/ui-egui/tests/scenarios/universal_panel_host_overflow_scale.json @@ -0,0 +1,19 @@ +[ + {"note":"24 synthetic instances retain minima in a bounded scroll extent at small sizes and 200% scale. Scroll tracks own only their narrow input regions."}, + {"call":"ui.resize","params":{"width":1280,"height":800}}, + {"panel_fixture":{"enabled":true,"preset":"overflow"}}, + {"call":"ui.resize","params":{"width":800,"height":600}}, + {"widget":"Scroll panel columns"}, + {"widget":"Scroll panel stacks"}, + {"call":"ui.resize","params":{"width":480,"height":320}}, + {"widget":"Scroll panel stacks"}, + {"call":"ui.prefs","params":{"ui_scale":2}}, + {"panel_fixture":{}}, + {"call":"ui.resize","params":{"width":1280,"height":800}}, + {"widget":"Scroll panel columns"}, + {"call":"ui.prefs","params":{"ui_scale":1}}, + {"call":"ui.resize","params":{"width":1600,"height":1000}}, + {"panel_fixture":{}}, + {"expect":{"errors":0,"features":0,"dialog":null,"tool":null}}, + {"panel_fixture":{"enabled":false}} +] diff --git a/crates/ui-egui/tests/scenarios/universal_panel_host_shared_actions.json b/crates/ui-egui/tests/scenarios/universal_panel_host_shared_actions.json new file mode 100644 index 000000000..e702d71e3 --- /dev/null +++ b/crates/ui-egui/tests/scenarios/universal_panel_host_shared_actions.json @@ -0,0 +1,18 @@ +[ + {"note":"The opt-in synthetic panels use the actual workspace host and shared move menu."}, + {"call":"ui.resize","params":{"width":1280,"height":800}}, + {"panel_fixture":{"enabled":true,"preset":"docks"}}, + {"widget":"Panel actions"}, + {"widget":"Floating"}, + {"widget":"Panel actions"}, + {"widget":"Right"}, + {"widget":"Panel actions"}, + {"widget":"Bottom"}, + {"widget":"Panel actions"}, + {"widget":"Left"}, + {"key":"Escape"}, + {"panel_fixture":{}}, + {"expect":{"errors":0,"features":0,"dialog":null,"tool":null}}, + {"panel_fixture":{"enabled":false}}, + {"expect":{"errors":0}} +] diff --git a/docs/book/src/guide/features.md b/docs/book/src/guide/features.md index 38a7ee90a..26dc4556f 100644 --- a/docs/book/src/guide/features.md +++ b/docs/book/src/guide/features.md @@ -89,6 +89,14 @@ start or end offsets or a From Object input, the target also sets the stored dis one-sided direction, so returning to **Distance** keeps that reach. Thin Extrude keeps its existing picks. With the setting off, picks only add profiles. +Dragging Extrude's distance arrow stops at flat faces parallel to the profile that lie over it, +such as the far side of the block a cut goes into: once the arrow's tip comes within a few +screen points of such a face, the distance becomes exactly that face's and the face is +outlined. Elsewhere the distance moves in round steps. Hold Alt or Ctrl for a free drag, which +stops at neither. **Extrude arrow stops at faces** (Preferences › Tools, on by default) turns +the face stops off; the arrow then moves in round steps only, as before. The distance stays a number; to follow the face when the model changes, use +**To Object** or **Through All**. + A positive extrude taper slopes the side walls outward, so the profile grows along the extrusion direction and the far end is larger; a negative taper slopes them inward, making the far end smaller. For example, a 10 × 10 mm square extruded 10 mm with `taper: "5 deg"` diff --git a/docs/book/src/guide/sketching.md b/docs/book/src/guide/sketching.md index a78444f91..3c61f91fe 100644 --- a/docs/book/src/guide/sketching.md +++ b/docs/book/src/guide/sketching.md @@ -546,6 +546,12 @@ it to remove it. Each input has its own Clear button. Source inputs show a count references identify the chosen mirror line, direction, or centre. Box selection also works while the window is open. Sketch modify tools take geometry from the sketch being edited. +If your preselection includes exactly one straight construction line of the active sketch, +opening Mirror uses it as **Mirror line**, keeping your selected entities. Other construction +lines in the sketch do not count unless selected. With none or multiple selected construction +lines, choose the reference manually. You can clear or replace the line. To always choose it +manually, turn off **Preferences > Sketch > Use the preselected construction line for Mirror**. + Proposed sketch geometry appears **green** before confirmation. Change the inputs or values to update the preview, then press **OK**. **Cancel** discards the preview. A circular pattern centre can be an existing point or a position clicked in empty sketch space. diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 63e46f986..68a5712bf 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -42,13 +42,14 @@ Query replies contain no new host effects. | `panel.list` | `{}` → `{state:LayoutReply,kinds:[PanelSpec]}` from the live sink and registry. | | `panel.open` | `{kind,instance,destination?,expected_revision?}`. New instances require a destination; closed instances can reuse remembered placement. | | `panel.close` | `{target:instance,expected_revision?}`. Explicit guarded close retains placement and can refuse cancellation. | -| `panel.move` | `{target:instance,destination,expected_revision?}`. Existing open instances only. | -| `panel.resize` | `{target:section|instance,size:{width,height},expected_revision?}`. Instance must have an open section; all tab bounds intersect. | -| `panel.collapse` | `{target:section|instance,collapsed:bool,expected_revision?}`. Keeps requested dimensions. | +| `panel.move` | `{target:instance,destination,activate?:false,expected_revision?}`. Existing open instances only; explicit activation joins atomically. | +| `panel.resize` | `{target:column\|section\|instance,size:{width,height},thickness_only?:bool,expected_revision?}`. Omitted/false keeps full-size behavior. True changes shared Bottom row height or side column width while preserving stack extent preference/rank/weight; Floating/Window refuse. Both size components must remain finite, positive and bounded. All tab and column bounds intersect. | +| `panel.collapse` | `{target:section\|instance,collapsed:bool,expected_revision?}`. Keeps requested dimensions. | | `panel.float` | Same as move, requiring a `new_section` with `floating` location. | | `panel.popout` | Same as move, requiring a `new_section` with `window` location and return destination. Desktop/headless without native capability refuse; web explicitly lowers to `floating`. | | `panel.focus` | `{target:instance,expected_revision?}`. Reopens retained closed state, activates, expands and requests focus. | | `panel.activate` | `{target:instance,expected_revision?}`. Activates an open tab without expanding or requesting focus. | +| `panel.action` | `{target:instance,action:ControlId,expected_revision?}`. Validates registration, active/open state, availability and owning controller binding, then invokes the real bound action. Returns `LayoutReply`; missing/disabled bindings refuse. | | `panel.peek` | `{target:instance,expected_revision?}`. Temporary presentation of a collapsed tab, without persistence changes to size/collapse. | | `panel.dismiss` | `{expected_revision?}`. Dismisses transient peek. | | `panel.resize_pair` | `{first:SectionId,second:SectionId,first_size:{width,height},second_size:{width,height},expected_revision?}`. Adjacent sections of one dock; conserves split-axis extent and cross-axis dimensions. | @@ -58,13 +59,14 @@ Query replies contain no new host effects. | `layout.apply` | `{name,expected_revision?}`. Applies a named preset to the **current** workspace, rebinding its known layout workspace ID. | | `layout.reset` | `{expected_revision?}`. Applies the selected workspace's registered immutable default. User presets and other workspace histories remain. Missing defaults return a capability error. | | `layout.get` | `{}` → `{state,workspaces:[{id,title_key,default_preset,has_remembered_layout}]}`. Selection is only `state.layout.workspace`. | -| `layout.workspace.select` | `{workspace:WorkspaceId,expected_revision?}` → `{previous_workspace,source:"remembered"|"default_preset"|"unchanged",state}`. Registered descriptors only; no implicit creation. | +| `layout.workspace.select` | `{workspace:WorkspaceId,expected_revision?}` → `{previous_workspace,source:"remembered"\|"default_preset"\|"unchanged",state}`. Registered descriptors only; no implicit creation. | Destinations are distinct foundation operations, not aliases: ```json {"type":"new_section","section":"logs","index":0,"location":{"type":"dock","zone":"left"},"size":{"width":280,"height":240}} {"type":"join_tab","section":"logs","index":1} +{"type":"relative","section":"logs","placement":"after_column","new_section":"new-logs","new_column":"extra-column","size":{"width":280,"height":240}} ``` New-section indices address the global section order after detachment; join indices @@ -75,6 +77,32 @@ activation, collapse and dimensions. Locations are `dock` (left/right/bottom), recursively contains another native host. Pins and placement/size intersections retain the foundation's structured refusal rules. +The host's explicit title/tab drag is a separate UX intent: a tab landing sends +Move and Activate in the same guarded transaction so the dragged tab is visible. +Generic background joins keep the activation semantics above. + +Side sections reference stable columns, ordered outer to inner, and retain saved +stack weights. Relative Before/After column placement is logical; Above/Below +stacks within a target column. Pointer code maps physical edges through dock side +and RTL. App commands and gestures share host allocation and typed `no_space` +admission. Missing host/environment refuses structural app commands. Overflowing +neutral/worsening proposals reject except Close, Collapse (including expansion), +Focus, Activate, or strict extent improvement without growth on the other axis. Independent +commands and refused batches cancel a pending gesture before parsing/preflight. +Standalone `panel.action` validates registration, the available fallback selection, +owner availability, enabled binding and controller preflight. It can execute +without a host environment, during overflow, or when layout storage refuses writes; +it neither allocates placement nor stages layout persistence. It cannot be combined with structural +mutations in one runtime transaction. Published peek/dismiss requests remain +compatibility commands; the amended host exposes no rail/peek/pin-open UI. + +Sole side Content height uses bounded immutable controller metrics at assigned +width, including chrome/body/footer/padding. Fill is declarative registration or +responsive snapshot data. An incoming owner cohort captures its own availability and immutable metric +providers before candidate allocation. Projection and commit retain those same +controllers/providers. Changing metrics cancels previews, pending widget intents, +cached proposals and the old frame, requiring fresh paint for widget admission. No hidden render pass is used. + Preset names trim surrounding whitespace, require 1..64 Unicode scalar values and reject controls anywhere in the supplied name. Raw input is capped at 1024 UTF-8 bytes before trimming; the trimmed name is at most 256 bytes. Names are case-sensitive. @@ -184,7 +212,9 @@ model change earlier in a sequential batch/script is visible to the next panel step without a tick. Queries and failed actions cannot borrow the previous document's context. No content tick, document edit, geometry work or camera tail is added to this boundary. All application GUI and command routes use one stored -native adapter, installed once; redock its native sections before disabling it. +native adapter. Command-adapter installation is once-only and precedes native +placements. Disabling the runtime preflights retained controllers and native +release through that same adapter; refusal leaves it installed. Unsupported atomic intent mixtures are rejected by pure structural preflight before any context/controller publication as well as before layout/native effects. @@ -207,6 +237,119 @@ instances. Integrations with explicit identities can issue typed `panel.move`, `panel.resize` and `panel.collapse` requests for safe placement changes. No command implicitly selects a layout workspace on a document, ribbon, tool or context change. +At the Rust app boundary, `AppPanelRuntime::new(runtime, services)` is fallible and +rejects incoming native placements. `SolveApp::dispatch_panel_layout(action)` uses +the stored native adapter with the shared host enabled or disabled; it accepts no +borrowed adapter. Install a future native adapter with `set_panel_native_adapter` +before native creation/restore, or install it with the catalogue through +`AppPanelRuntime::set_command_adapters`. Once command adapters are installed, +neither injection API can replace them. App command/action/render/mount boundaries reconcile the +actual current Session without another service tick. Runtime inspection remains +read-only. The shared host adds no production command registration beyond the +application-layout commands above. + +For native host evidence, `ui.panel_fixture {enabled?, preset?}` installs bounded +synthetic content in the real `SolveApp` workspace host. The normal connection +authentication applies. It is off by default; no environment switch, preference, +design change, production content registration or native panel window is added. + +| Request | Effect | +| --- | --- | +| `{}` | Read current host/probe/Session observations without ticking services or dispatching actions. | +| `{"enabled":true}` | Enable the `docks` specimen if no runtime exists. | +| `{"preset":"tabs"}` | Enable the named specimen if no runtime exists. | +| `{"enabled":false}` | Preflight and tear down only the specimen runtime; refusal leaves it intact. | + +Presets are `docks` (Left/Right/Bottom, with two Left sections), `tabs` (two groups +of two), `collapsed` (four full-width collapsed headers), `floating` (four in-app floating +sections), `overflow` (24 instances), and `pinned` (an outer pinned Right section +plus ordinary docks), `columns` (three independent Left columns), `stack_tabs`, `content_fill` (sole Content versus Fill), and `inline` (one editable total row). The retired `rails` preset is rejected. Original synthetic content retains editable drafts and +controller state across hiding and moves. Services keep ticking while content is +hidden. Apply/Finish/Cancel are synthetic actions; the Session is never passed to +their command sink. The editor's cancellation guard checkbox can refuse explicit +Close and whole-runtime teardown while its synthetic transaction is live. + +Enabling always rejects an existing runtime, including an already enabled specimen. +To change preset, disable successfully first, then enable the next preset. Enable +stages the runtime, first tick and host before publishing any of them; teardown +preflights every retained controller. Wrong types, unknown parameters/presets and +`enabled:false` combined with `preset` fail before mutation. + +Replies include `enabled`, `runtime` when the specimen runtime exists, `host` +(null before its first rendered frame), and `session`. `runtime` contains the +committed `LayoutReply`, retained controller count and synthetic probe snapshots +(typed instance/owner, process-local controller identity tokens, drafts, +service/render/lifecycle/action counts, transaction and guard state). +`host` reports the last actual host frame: full semantic control IDs/typed target +descriptions, accessible names, enabled flags and logical rectangles; section/body +rectangles, collapse/inline flags, declared surface policy and captured frame +`paint_alpha` (null without a renderer snapshot), resolved unpresented content, +bounded scroll extent/offset, paint/input/occlusion +rectangles, render domain, placement capacity, usable-space geometry, viewport, +exact prepared preview, menu bounds, observed host events and committed frame +reply. The top-level `effective_usable` application contour additionally includes +current persistent windows and independent navigation controls; the host's own +usable geometry describes host footprints. Sections and resolved geometry retain intended layout; +paint/input/occlusion arrays and published controls describe actual paint, excluding +invisible Area sizing passes. `reply`, `committed` and `prepared_committed` events describe authoritative post-dispatch state. +Region events include the menu and owned overlays in effective paint/input/ +occlusion rectangles. Those overlays do not shrink the render domain or become +automatic camera targets. The viewport fills everything below the application +bar, including behind the ribbon and panels; opacity never makes controls +click-through. Ordinary layout commands and gestures preserve camera pose, zoom, +projection and framing offset. Explicit Fit/Centre use safe usable space and the +model extent. The effective contour combines host footprints with current +persistent surfaces outside the host, such as the active sketch palette; hidden +surfaces and transient menus do not create fitting reservations. Fit may change +zoom. Existing Look At/`view.normal_to` centring +preserves zoom/distance, requested orientation and selected focus: it places the +whole footprint at the current zoom when possible, otherwise only the focus at a +stable usable centre. It never silently zooms out, and generic camera apply/replay +does not acquire a centring offset. + +Ordinary title/tab drags accept explicit dock, split and tab targets. A landing +preview describes the exact candidate, affected neighbours and insertion index. +Empty space does not create a floating panel; use `panel.float` or the explicit +menu action. Invalid/no target, cancellation and stale captured geometry +commit nothing. A valid unchanged candidate commits once, consuming its owned prepared state without redispatch. Only its landing, changed neighbours and tab marker are painted. There are no idle target widgets. Full-width collapsed headers retain declared custom actions, menu, chevron and optional quick close; one click expands. Tiny windows retain panels at minima in a bounded scroll extent; narrow scroll tracks do not shield uncovered canvas. + +Public Rust `SolveApp::universal_panel_frame()` also exposes +`HostFrame::next_layout`, the resolved state pending repaint, and +`owned_overlays`. The fixture JSON does not serialize those two as separate +fields. Never infer painted controls from pending layout geometry. Compare the +painted frame's revision with committed replies and runtime revisions. An empty +fixture query neither reconciles context nor ticks: the current Session may have +changed since the retained runtime/frame was reconciled. Compare document scope +as well as revision. Target descriptions are diagnostics, never command addresses +or strings to parse. + +`session` observes actual document ID/UID/revision/dirty/undo/redo, document/model/ +cache Arc identities, recomputed feature counts, existing cached mesh identities +(first 128 bodies, with total count), and camera. Pointer strings are opaque +process-local equality tokens. Inspection uses only already cached meshes; +`evaluation_count` counts live-model evaluations after Session initialization. +It excludes construction, other Sessions and trial evaluations of cloned models; +it does not count all geometry work or tessellation. These values permit +before/after comparisons, not a claim that any invariant or visual result has +already been verified. + +In the real `cad_ui`, host drawing defers input finalization until after all +foreground windows/modal layers. Finalization checks the current Session and the +actual enabled/top-layer egui target before accepting an initial press, then uses +the stored native adapter for dispatch. Exported rectangles alone do not authorize +clicking through another window. The root host and each native-host presentation +use complete separate mount sets; mounting or unmounting one does not deactivate +the others. These are native-adapter seams, not an implementation of OS panel +windows. The specimen/default adapter advertises no native windows, and the +current opaque renderer rejects unsupported translucent policy requests. + +Scenarios accept `{"panel_fixture":{"enabled":true,"preset":"docks"}}`, +`{"panel_fixture":{}}` and `{"panel_fixture":{"enabled":false}}`, using this +same control path and normal `fail:true` handling. Use the returned control +rectangles with existing pointer/key, resize and screenshot requests. Capture real +native `ui.screenshot` output and inspect it for chrome evidence; a model-only +`ui.render` or headless scenario does not show a native panel host. + For UI-kit review, `ui.status_fixture {"preset":"mode"}` shows bounded status specimens in the real viewport. Presets are `off`, `mode`, `result`, `attention`, `row`, `kinds`, `many` and `key`; the reply carries the preset and item count. This @@ -714,6 +857,7 @@ One setting per line, sorted by name. A change that adds a setting adds its own - `dimension_input` (`view` (default): a sketch dimension's value is typed in a box on the dimension; `window`: placing a dimension with the Dimension tool, or double-clicking one, opens a small window at it with the value field (handle `dimwin:value`), arrows that step the value (`dimwin:up`, `dimwin:down`), a check (`dimwin:ok`, also Enter) and a cross (`dimwin:cancel`, also Esc), #7246) - `dimension_step_deg` (default 1, 0.001…180: what the dimension window's arrows, Up/Down and the wheel over its field add to an angle, in degrees) - `dimension_step_mm` (default 1, 0.001…1000: what the window's arrows, Up/Down and the wheel over its field add to a length, in millimetres, written in the unit the value is written in) +- `extrude_arrow_face_stops` (default true: dragging Extrude's distance arrow stops at flat faces parallel to the profile that lie over it, takes their exact distance and outlines them, #2398; false: the drag moves in round steps only, as before) - `extrude_auto_to_object` (default true: in the Extrude dialog, with a profile picked, a face, vertex or parallel plane picked off its plane switches the extent to To Object, unless the Profiles box was clicked into; it applies to Extrude dialogs opened afterwards) - `frame_rate_details` (default false: with the frame rate, a frame-time graph of the frames drawn with the triangles over it, a frame-time histogram and what the GPU drew; clicking the readout switches it) - `graphics_adapter` (exact card name, or empty for Automatic; applies after restart; `WGPU_ADAPTER_NAME` takes precedence) @@ -769,6 +913,7 @@ One setting per line, sorted by name. A change that adds a setting adds its own - `sketch_conflict_colour` (default true: while the open sketch's constraints conflict, the curves and points a failing constraint holds are drawn in the theme's `sketch_conflict` colour too, not only its glyph or dimension; false: only the glyphs and dimensions are red, in `error`, as before, #7244) - `sketch_construction_lines` (default true: show the Construction Line tool family in Sketch CREATE; false restores the earlier menu) - `sketch_exit_view` (`keep` (default: the view stays where it is when a sketch ends), `previous` (back to the view from before the sketch), `unless_rotated` (back unless the sketch view was turned)) +- `sketch_mirror_auto_line` (default true: opening Sketch Mirror uses the only preselected straight construction line of the active sketch as its reference; unselected lines do not count; false keeps manual reference selection) - `sketch_open_look_at` (default true: creating or editing a sketch turns the view to face it; false leaves the view as it is, and Look At faces the sketch when asked) - `sketch_recent_snap` (default false: while drawing, the cursor snaps where the horizontal guide of one recent circle or arc centre or straight-edge midpoint meets the vertical guide of another; a free coordinate, with no constraint and no construction geometry. Off: those guides stay visual and the cursor does not move. The references come from `sketch_tracking_guides`, #8694) - `sketch_state_icons` (default true: a sketch's icon in History and the browser takes the colour of its solve state, `sketch` under constrained, `sketch_fixed` fully constrained, `error` while its constraints conflict, and its tooltip names the state; false: every sketch row's icon and tooltip as before, #7245) diff --git a/docs/design/preferences/pages/appearance.md b/docs/design/preferences/pages/appearance.md index a6f95545c..f2ce7cee3 100644 --- a/docs/design/preferences/pages/appearance.md +++ b/docs/design/preferences/pages/appearance.md @@ -5,16 +5,21 @@ Tag: In profile (hover "Saved in settings profiles"). Reference boards: `Theme_O `Settings_Interface` for Scale and text and Colour vision. Source today: Interface page (`prefs/interface.rs`). -## Theme (6 themes) +## Theme | Label | Control | Edits | Default | Hover | Figure | Notes | |---|---|---|---|---|---|---| -| Theme cards: Light (Built in), Dark (Built in), System (Follows the OS), Gruvbox (Built in), Studio glass (Imported file) | Carousel of picture cards (88 wide) with previous and next arrows ("Previous themes", "Next themes") | `Prefs.theme` (id string); "System" follows the OS (`app.window_theme`) | `"dark"` | "Has options" on the disc of cards that have theme options | `theme-light`, `theme-dark`, `theme-system-light-half` + `theme-system-dark-half`, `theme-gruvbox`, `theme-imported` | The count "6 themes" is the number of cards. Gruvbox and Studio glass carry the "has options" disc. Build the cards from the theme list in `theme_files` (built-ins in `assets/styles/ui/themes`, imported in `Prefs.custom_themes`); only the first five are drawn on the board, the carousel scrolls to the rest. | -| Import... / theme file | Dashed card at the end of the carousel | theme import (`Prefs.custom_themes`) | n/a | none | none | "Import..." with the sub-label "theme file". | +| One theme / Follow system | Segmented mode control, monitor / half-filled circle icons | `Prefs.theme` | One theme, `"dark"` | none | Painter glyphs | Follow system is `"system"`; System is no longer a theme card. Entering One theme selects the theme currently in effect. Entering Follow system assigns the previous theme to the slot matching its tone. | +| Import theme file… | Small import button, always at the right of the mode row | `Prefs.custom_themes` | n/a | Existing import help | Painter glyph | Keeps the file picker, drop target and desktop clipboard context menu. | +| Day theme / Night theme | Two slot cards with thumbnails, sun/moon icons, names and Pick from below / Change | `Prefs.theme_day`, `Prefs.theme_night` | `"light"`, `"dark"` | none | Existing thumbnail painter | Only shown in Follow system. Exactly one is aimed, initially Day. Clicking a slot presets Light/Dark; choosing a card fills only that slot. Unknown ids resolve to the slot's default. Both settings are persistent, command accessible, in Appearance profiles and restored by the page's defaults. | +| Light / Dark; Standard / High contrast; Imported | Independent toggle segments and an Imported chip, with counts | UI state | All clear | Count with the other filters applied | Painter glyphs | Clicking a selected filter clears it. A count ignores its own group. Interim classification in `theme_traits`: tone uses resolved thumbnail background luminance below 0.5; high contrast uses primary text/background contrast at least 20:1. The four maximal-contrast shipped themes measure 21:1; the others are at most 16.006:1. A later change will let themes declare these traits; this picker adds no theme-file fields. | +| Carousel / Grid | Icon-only view switch at the right of the filter row | UI state | Carousel | Accessible names | Painter glyphs | The browser reuses the theme-options panel's fill and stroke. Carousel content has equal 10 pt padding on all four sides at its resting ends; mid-scroll cards clip at the box edges, with 84 pt fades and round 28 pt arrows where there are more cards. Arrows move three cards. Horizontal wheel/trackpad input and dragging scroll and snap; predominantly vertical input passes through to the Preferences page. Grid has five equal columns, a vertical scroller and a height of about 2.5 rows. | +| Theme cards | Existing thumbnails, names, Built in / Imported file and optional · High contrast | `Prefs.theme` or the aimed slot | As above | Has options; context menu Export… and Remove for imported themes | Existing thumbnail painter | The section shows the real theme count excluding System. Tone/contrast badges sit at top left; check or Day/Night marks at top right. Selected and slot-holding cards use accent borders and selected backgrounds. Options keep their badge and panel. No search field or footer within the picker. | +| No theme matches these filters. / Clear filters | Empty well with reset link | All three filters | n/a | none | none | Clear filters leaves mode, aimed slot and view unchanged. | ### Theme options panel ("Studio glass", "6 options", Reset) -Follows `Theme_Options.dc.html`. Shown under the carousel for a theme that has options. "Reset" +Follows `Theme_Options.dc.html`. Shown under the picker for the active theme when it has options. "Reset" restores the theme's own option values (`Prefs.theme_options[]`). Two columns. | Label | Control | Edits | Default | Hover | Notes | @@ -64,4 +69,7 @@ Source: `Settings_Interface.dc.html` (section "Scale and text"). * The dark board's accent `#8CBEF5` has no token (see `tokens.md`). * Only `opacity` has a provider on main (`theme_options.rs`); blur, tab colours and the fade are standard ids without one yet, so the board shows them ahead of the code. -* Only 5 of the 6 theme cards are drawn on the board. +The updated theme states are in `plan/theme-picker/Prefs2_Appearance_Theme.dc.html`; the interactive +behaviour and icon coordinates are in that folder's `SPEC.md` and `ICONS.md`. Filters, view and aimed +slot are window UI state, never saved preferences. Changes a default: no (default Day/Night retain the +previous operating-system Light/Dark resolution). Ctrl F still indexes theme names and picker labels. diff --git a/docs/features.md b/docs/features.md index 3fdd23781..dd3162c94 100644 --- a/docs/features.md +++ b/docs/features.md @@ -623,6 +623,7 @@ SolidCraft's commands by area, generated by `cargo xtask features` from the comm | Command | Id | Toolbar | |---|---|---| +| Run Panel Header Action | `panel.action` | – | | Activate Panel Tab | `panel.activate` | – | | Close Panel | `panel.close` | – | | Collapse Panel Section | `panel.collapse` | – | diff --git a/docs/panel-foundation.md b/docs/panel-foundation.md index ef3d792b1..084ac1e98 100644 --- a/docs/panel-foundation.md +++ b/docs/panel-foundation.md @@ -1,309 +1,291 @@ # Universal panel foundation -The public foundation is `solidcraft_engine::panels` and -`solidcraft_ui_egui::panel_runtime`. It establishes contracts and executable -synthetic fixtures for #11302. The current shell and defaults remain in use. -No panel commands, preferences, content migrations, native windows or docking -gestures are enabled by this change. Classic remains a permanent compatibility -preset. Production adapters land in the separate children of #11218. +The public contracts are `solidcraft_engine::panels` and +`solidcraft_ui_egui::panel_runtime`. The #11305 host is explicitly enabled and +uses synthetic controllers to exercise shared behaviour. Production Browser, +History, Assistant, Render, Sketch, feature forms and BOM adapters are sibling +work. The shipping shell, content, preferences and Classic behaviour retain +their existing defaults. A specimen is not production migration or visual evidence. +The current migration boundary permits only existing docked Browser, History and +Assistant content and their allowed Render counterparts in future sibling work. +Draggable tool windows and the existing native Assistant retain their legacy hosts. -## Ownership and integration boundaries +## Ownership -| Owner | Public contract | Responsibility | -| --- | --- | --- | -| Foundation / engine | `PanelRegistry`, `PanelSpec`, `Layout`, `LayoutService`, `ActionSink` | Stable identities, bounded wire values, constraints, atomic actions and inspection. No egui or Session dependency. | -| Foundation / UI | `PanelRuntime`, `ControllerBinding`, `PanelController`, `RuntimeActionSink` | Retained state, ownership, lifecycle preflight, live availability, independent service ticks. | -| Host child | `PanelHost`, `PanelContext`, `ResolvedLayout`, `EguiPanelHost` | Geometry, host composition and later docking interactions. Existing `ui_kit::Container` remains the outer boundary. | -| Command child | `LayoutAction`, `LayoutReply`, `PanelError`, `LayoutTarget` | Register schemas and route GUI/agent requests to the live runtime sink. Do not construct a second service from a saved snapshot. | -| Persistence child | `LayoutEnvelope`, `LayoutPersistence`, `decode`, `encode` | Workspace preference key, atomic storage, presets and future migrations. Keep unrelated preferences. | -| Native child | `NativeHostAdapter`, `HostEffect`, `HostCapabilities` | Preflight resources, native host realization, focus and redock. No native implementation is included here. | -| Surface/accessibility children | `InputRegion`, `ControlId`, `Direction`, `Motion`, `ContrastOutcome` | Painted/input bounds, semantic roles, keyboard routing, mirrored edges, reduced motion and validated theme surfaces. | -| Content children | `PanelModels`, `ContentCommandSink`, `PanelLocalServices`, content slots | Model access, explicit content commands, controllers, owner-scoped services and independently scrolling content. | +The engine registry owns bounded kind metadata and capabilities. Layout owns +instance, column, section and tab identities, placement memory, widths, saved +weights, collapse, active tabs and native return destinations. Side columns are +ordered outer to inner; each contains a contiguous vertical stack of sections. +Each section contains ordered tabs. Inactive tabs still constrain composite size +limits. Registrations declare allowed zones, PinOuter, Content/Fill height policy, +text-heavy content, surface preference, header actions and independent +`closable`/`hot_closable` flags. No generic host branches on product panel names. +Only future History product registration allows Bottom; synthetic kinds can allow +all zones. Quick close is an affordance, not the close capability itself. -Panel kind, instance, section, workspace, document, viewport, native host and -semantic control IDs are different Rust types. Their wire values are bounded -lowercase identifiers. Registry specs and serializable layout never contain -callbacks, document state, egui state or live editors. Only `allowed_zones`, -`edge_rule` and `surface` express placement exceptions. Normal capabilities -(close, tabs, collapse, popout, multiple instances) are shared feature flags. +Layout is application/workspace preference data. It never enters CAD files, +document undo, evaluation or tessellation. `PanelRuntime` retains controllers by +instance and `ContentOwner`, independent of presentation. Services tick while +controllers are collapsed, inactive, unavailable, closed or on inactive documents. +Owner changes retain the appropriate draft/controller rather than redirecting an +old document's model reads to a new document. Explicit close/destroy/reopen and +reparent have side-effect-free lifecycle preflight before commit. Hidden bodies +are not rendered to measure them or animate collapse. -Layout belongs to the application/workspace; it never enters a design file, -Session revision, dirty flag, undo stack, evaluator or tessellation cache. -`ContentOwner` independently chooses application, workspace, document or window -ownership. A native reparent does not change content ownership. Document switching -retains existing controllers and creates only missing owner/instance bindings. -Complete layout application changes the live workspace without replacing the -runtime or service. Application/document/window controllers keep matching instance -identities; workspace controllers remain under their original workspace owner and -continue ticking while hidden. Switching back reuses those controllers and drafts. -All retained controllers receive service updates even when closed, unavailable, -inactive, collapsed or on another document. Providers must expose models for -retained owners, not redirect old-document reads to the current document. +`PanelModels` reads immutable owner models. Explicit content operations use +`ContentCommandSink`. `PanelLocalServices` owns viewport-local keyboard, focus, +clipboard, picking, drops and overlays. Registered header actions must also have a +retained controller binding and pass availability/enabled checks. `panel.action` +returns a truthful committed `LayoutReply`; it cannot invoke an unregistered +binding. A fallible content action cannot be mixed with structural mutations in +one runtime transaction. Synthetic Apply/Finish/Pulse actions never run Session +commands. Real History playback and Assistant New Chat bindings belong to their +content migrations. -`SolveApp::enable_panel_runtime` accepts a runtime and `AppPanelServices` explicitly. -Its optional field defaults to `None`, remains on the app across document tabs, -and is ticked from `SolveApp::logic` independently of presentation. Refresh receives -only `&Session`. `disable_panel_runtime` preflights cleanup and requires native -sections to be redocked before dropping their adapter. Tick failures remain -inspectable on `AppPanelRuntime::last_error`; they do not inject untranslated UI. -This is an internal adapter seam, not a preference, environment switch or control -method. `dispatch_panel_layout`, `mount_panels`, `panel_content_action` and -`tick_panel_runtime` forward through the same injected provider. Application -command, atomic-batch and GUI dispatch boundaries refresh the read-only provider -and current document environment before inspection/projection. Availability is -refreshed without ticking content, evaluating models or creating geometry; retained -service failures still require a successful real update to recover. Sequential -programmatic model/document changes are therefore visible to the next panel step -without waiting for a frame tick. +## Allocation and presentation -`AppPanelRuntime::set_command_adapters` installs one catalogue and one native -adapter once, before native hosts exist. Both `SolveApp::dispatch_panel_layout(action)` -and command routes use that stored adapter; there is no per-call native argument. -`AppPanelRuntime::dispatch`, content actions and command/batch methods take the current `&Session` -for read-only context refresh. Its runtime is private with a read-only `runtime()` -accessor; service borrowing is internal, so consumers cannot replace the runtime or -dispatch through another adapter through a mutable services callback. Standalone -`PanelRuntime`/`RuntimeActionSink` fixtures retain their explicit fake-adapter seam. -Changing the installed application adapter is refused rather than abandoning its -created hosts. These are integration APIs, not a production native implementation. +The pure engine allocator is authoritative for both commands and gestures. It +intersects every tab's constraints and each column's width constraints, uses +constrained saved weights for stacks, and preserves minimum dimensions when the +window is tiny. Right and Bottom placement share a bounded scroll extent, avoiding +overlapping docked hosts. The viewport domain stays fixed below the application +bar, including behind the ribbon and panels. -## Actions and atomicity +A sole presented side section defaults to Content height. The active tab supplies +bounded preferred outer height at the assigned width, including shared header, +body, content toolbar, footer, padding and spacing. Fill consumes available height +within the same composite limits. Multiple sections use their saved stack weights; +entering/leaving the sole-section state does not rewrite them. Collapse reserves +only the full-width header and leaves genuine uncovered canvas below short or +all-collapsed stacks. -`ActionSink::dispatch` accepts `Inspect`, `Apply { expected_revision, mutations }` -or `Replace { expected_revision, layout }`. -GUI, keyboard and agent adapters share this reducer. `RuntimeActionSink` adds -controller/native lifecycle guards around the same engine service. Runtime users -receive immutable layout inspection; there is no mutable bare-service escape. -Replies describe committed layout, revision, availability, interaction, capabilities -and host effects. Layout revision is independent of document revision. +Expanded dock sizing can declare `preferred_extent` on the stack axis. An +omitted preference remains None; saved legacy size does not imply a new override. +After reserving every presented minimum, allocation processes `extent_priority` +tiers highest-first, compressing requested surplus proportionally within a tier +when necessary. Older/common preferences use rank 0; nonexplicit members receive +the weighted remainder. SetSize authors a new highest tier. Ordinary weighted +pair resize/reset clears the pair's overrides/ranks; when weights cannot represent +a feasible actual split, the pair's exact requested extents receive one new tied +highest tier. Repeated overlapping edits therefore favor the latest authored pair +under later compression while preserving older preferences. Unrelated neighbours +keep their rectangles, even when their normalized weights need a common scale; +zero saved surplus remains valid. Sole side Content/Fill ignores latent extent +and rank during presentation and retains them for returning to a stack. -`Replace` validates a complete preset/saved layout and atomically changes the -workspace on the same authoritative service/revision. It stages availability, -controller factories and native create/rebind/release effects before committing. -Omitted entries and entries marked closed are noncanceling hides: their retained -controllers keep drafts, conversations and service updates, with no collapsed rail -unless the snapshot actually requests one. Restoring the snapshot restores those -controllers. Instance IDs cannot change kind across workspace switches; the service -retains a bounded identity catalogue until explicit Destroy releases an identity -and all of its retained owners. Unknown kinds fail atomically; persistence -adapters first decode/quarantine unknown data and apply the known layout portion. -Registered kinds with missing bindings or unavailable context remain dormant. -After successful replacement, old local input/overlay ownership is released; -failure leaves environment, revision, controllers and local/native hosts intact. -Use this operation for workspace switching rather than rebuilding a runtime or -synthesizing Close/Open batches. `set_environment` changes document/window/viewport -context within the already committed workspace. +Bottom top-edge dragging uses the typed `SetBottomHeight` mutation. Registered +`panel.resize` with `thickness_only:true` uses the same mutation for Bottom, or +`SetColumnWidth` for a side dock; Floating/Window refuse. Omitted/false retains +full-size behavior. Both size components are validated before ignoring the other +axis. `SetBottomHeight` changes shared row thickness within registered common +bounds while preserving every Bottom width, preferred width, rank and weight. There is no additional public +string command. The side/Bottom separator exists only when side geometry presents; +a Bottom-only 64-point row fits exactly in 64 points of capacity. -- `Open` targets kind **and** instance. New instances require an explicit destination; - an existing closed instance can reopen from its remembered placement and size. - Repeating an open is idempotent unless a new placement is supplied; use `Move`. -- `NewSection` and `JoinTab` are distinct destinations. Section insertion indexes - address the global ordered section list **after** detachment; tab indexes address - the destination list after detachment. Both reject invalid indexes. Empty groups - are removed. Joining retains the group's active tab, dimensions and collapse state. -- `Activate` selects an already-open tab, without requesting keyboard focus or - uncollapsing it. `Focus` can reopen retained closed state, select its tab, - uncollapse it and request host focus. `Peek` temporarily presents a collapsed - tab, without changing persisted size or collapse. Dismiss is transient too. -- `ResizePair` requires adjacent sections of one dock, conserves their split-axis - extent and changes no cross-axis dimension. `ResetPair` returns the pair to - the ratio of active members' registered defaults within intersected bounds. - `SetSize` is a typed explicit outer-size mutation. -- `Close` retains placement/size memory. `Destroy` removes an already-closed - instance and its retained controllers across workspaces/owners. `NativeClose` redocks the whole section - to its recorded return destination, optionally rejoining a stable former tab - group. Missing/reparented groups use the recorded dock fallback; valid joins - retain target activation. It does not close/cancel the content. +`PanelController::measure(&self, owner, models, spec)` captures an immutable +`Arc` snapshot. Its bounded `measure(request)` answers +assigned-width requests without a renderer or mutable services. `revision()` must +change whenever any answer could change, including responsive policy. The default +reports registered preferred outer height explicitly; it does not claim intrinsic +content measurement. Adapters supply real bounded metrics. `host_measure_requests` +uses the same width allocator as resolution; candidate widths are measured before +a preview is shown. Missing/stale data rejects. Replacing metric data cancels the +old candidate. The host retains the same snapshot identity while its revision is +unchanged, avoiding geometry feedback from an already stretched parent. -A transaction is prepared on a bounded copy and validated before commit. Rejected -transactions preserve layout, revision, interaction, retained controllers and hosts. -Lifecycle preflight is side-effect-free. It checks explicit Close/Reopen/Reparent/ -Destroy events before committing; applying those prepared events is infallible. -State notifications are observational and cannot veto a mutation. Factories stage -fresh controllers without publishing external effects, since staging can be -discarded. Native preflight similarly must establish that commit can finish. -Adapters must reserve/stage fallible work, not discover a failure after commit. -Only explicit content actions may Apply/Finish/Cancel/Stop; hiding, tab changes, -collapse, reparent and native redock never implicitly invoke them. Explicit close -cancels transactional controllers for the affected instance across retained owners; -one cancellation refusal rejects the entire batch. -Close or Destroy combined with any other instance-targeted operation on the same -instance in a batch is rejected with `Lifecycle` before mutations/effects. This -includes Close/Open, Close/Move/Open and Destroy/Open; independent instance and -section mutations can still be batched. Explicit Close cancels a live hidden -transaction even if its saved entry was already marked closed by `Replace`. +`HostLayout` separates intended section slots, scroll extent, actual clipped +paint/input/occlusion footprints and usable-space contour. `ResolvedPanel.body` +and `PanelContext.usable_body` are optional. Collapsed hosts have no content body. +Expanded Wide geometry at or below `theme::PANEL_INLINE_MAX_HEIGHT` (88 logical +points) has one total row: the real shared title/grip, registered actions, dedicated +inline content, menu, chevron and optional quick close, fully mirrored in RTL. It calls +`render_inline`, whose compatibility default delegates to Body. It does not call +Header/Body/Footer again or add a second title band. Controllers can override the +inline slot with a compact representation. This generic capability is demonstrated +by an editable inline specimen, not a substitute History timeline. -`ControllerState` distinguishes requested-open, available, presented, activated -and destroyed. Presented requires usable resolved geometry; activated additionally -requires the selected tab/peek. Keyboard focus is separate in `PanelContext`. -`destroy_owner` performs explicit cleanup without editing layout, leaves a bounded -tombstone, and requires `revive_owner` to create fresh content again. `shutdown` -preflights all owners before clearing any and makes the runtime terminal. +Shared chrome uses the existing adaptive `ui_kit::Container`, panel fill, title +fonts, six-dot grip and header separator. Each section has one header row. A single +panel uses a text-only title and grip; a tab group uses one leading section grip +and individual text-only tab headings in that same row, with no duplicate active +title. Grip, tabs and controls have disjoint hitboxes at the same y and height. +The grip drags the active tab; each tab retains its own select, drag and reorder +target. Header title typography is independent of icon metadata, which remains +available to other presentations. Collapsed groups retain their tabs across the +full-width header. Inline groups use their allocated title region for grip/tabs, +preserving the actual inline editor and one total row. Compact tab overflow keeps +the active heading visible whenever its minimum width fits beside the overflow +button; the bounded accessible menu retains every tab. Measurements and allocation +count only the shared header, content toolbar and footer, with no extra tab-row +height. Floating shell spacing comes from +`Container::gap()` and participates in allocation, previews and input geometry; +compact surfaces join without a sizing gap. In LTR, the +trailing controls are custom actions, menu, chevron, optional quick close; RTL +mirrors their geometry. Collapse retains these controls and one click on its +chevron restores the body. There is no rail, hover-peek or pin-open product UI. +Published `panel.peek`/`panel.dismiss` compatibility commands retain their wire +meaning without creating a new host affordance. -Independent updates attempt every retained controller even when staging or another -controller fails. `update_errors` aggregates at most two bounded typed errors per -controller plus staging/reconciliation errors (258 total). Invalid availability -reports become `Availability` failures. Failing content is unavailable, loses stale -presentation/input ownership and cannot become healthy merely by moving it; a -successful later update restores availability. Reconciliation still runs before -the aggregate failure is returned. Injected-provider refresh failures also do not -skip the independent controller update loop. +Overflow retains actual panels at minimum dimensions. Narrow scroll tracks and +unconsumed wheel input over actual panel paint change presentation offset. The +scroll canvas itself has no full-viewport response; uncovered gaps stay navigable. +Content retains its own scroll area and gets first use of wheel input. -## Final product decisions +## Exact candidates and admission -- Zones are logical Left, Right, Bottom, Floating and Window. Top remains reserved - for ribbon/application chrome. RTL mirrors the physical side; persisted IDs and - tab order remain logical. -- `PinOuter` follows whichever logical side the panel occupies, requires its section - first on that edge and excludes Bottom in registry data. It is inactive in free/ - native hosts. Competing pinned **instances**, including in one group, are rejected; - no existing panel is silently displaced. -- Tab groups use the intersection of every member's minimum and maximum **width - and height**. Impossible joins and dimensions outside that intersection fail. -- min/default/max are outer logical dimensions. Geometry reports actual outer and - usable body bounds separately. egui applies scale once. Free/native flow starts - Wide at aspect >= 1, otherwise Tall; Tall switches above 1.1 and Wide below 0.9. - Size classes use the shorter usable edge: Compact < 240, Regular 240..480, - Wide > 480. Invalid/nonfinite/oversized dimensions are rejected. -- Capacity shortages produce transient unpresented/overflow records, never reduced - below-minimum content or saved-dimension/collapse rewrites. Collapsed rails are - chrome. Hosts expose overflow access and retry presentation when capacity returns. -- New Open/Focus/Activate/Peek requests for unavailable content fail with an - availability reason. Saved requested-open content remains dormant and reappears - when its owner/context is available. Missing bindings are dormant too. -- Combined History-in-Browser and History Bodies/Origin stay content preferences - or shared components. They do not merge or depend on panel host identity. -- Opaque surface requests win over Translucent, then zone defaults apply (bottom/ - native opaque, side/free translucent). Contrast resolution can raise background - alpha only. If full opacity cannot make authored tokens readable, return - `RetainReadableFallback` with a typed reason and keep the validated fallback/last - good tokens and raw imported intent. No claim of 4.5:1 or text recolouring is - permitted to disguise failure. Theme resolution is implemented by the surface child. +`prepare_host_layout` produces a non-Clone `PreparedHostLayout` containing private +engine state, proposed geometry, reference geometry and scope. Both app commands +and pointer actions use this preparation and allocator. Missing host/environment +refuses structural app commands. `NO_SPACE` refuses neutral or worsening overflow +except Close, Collapse (including expansion), Focus, or a strict improvement of one +extent without increasing the other. -## Geometry and local services +Drags start after six logical points. Invisible card-edge regions select adjacent +columns or stacked sections; the centre joins tabs and measured tab halves choose +insertion. Side ordering accounts for both dock side and RTL. Empty space has no +implicit float fallback. Floating is an explicit menu/command action. -`ResolvedPanel` contains outer/body geometry plus explicit paint and input regions. -Validation bounds regions and requires input inside paint; the viewport outside -these regions belongs to the existing camera/navigation path. Semantic controls -carry stable IDs, roles, accessible names and keyboard-focusability. Hosts may use -`consumes_pointer` to compose input ownership without a full-window shield. -The reference `resolve_geometry` is deterministic synthetic mounting geometry, -not production docking. It reports overflow instead of changing desired state. +Once a Move crosses that threshold, the current moved instance's full presentation +title follows the cursor on the existing preview paint layer, including over +invalid or absent landing targets. Its original header or tab title uses half +its existing ink opacity; other text, grips, actions and panel content keep their +normal appearance. The paint-only badge uses theme tokens, mirrors its cursor +offset in RTL and clamps within the render domain and current clip. It keeps +the full display-ordered title on one line without automatic wrapping or +ellipsis. Physically oversized text clips, aligned left in LTR and right in RTL +so its reading start stays visible. It adds no widget, input, occlusion or +usable-space reservation. Mere presses, +clicks, resize and paired-resize gestures have no title feedback. -`PanelContext` carries presentation geometry, owner/scope identities, flow, size -class, direction, focus and motion; services are a separate argument. Content -has Header/Body/Footer slots and chooses scrolling itself. `EguiPanelHost` uses -one kit Container, title/status/attention and semantic content actions; its action -strip can scroll independently of the body. Reduced motion resolves duration to -zero, without delaying identity/focus/lifecycle changes. -The reference egui adapter accepts exactly one full-outer paint rectangle and one -full-outer Surface input region. It rejects sparse, empty-input or partial-input -records with `Capability` before painting or creating widgets. Rich region-aware -surfaces belong to #11307. Every child clip intersects the existing parent clip. +Window docking takes priority over panel targets: Bottom first, then sides, +measured tab insertion, relative edges and centre joins. Side bands are 16 logical +points wide (56 on empty sides); the Bottom band is 64 points high. Only the +innermost presented receiving column's centre-facing edge reaches 64 points into +clear canvas. Other outward column edges retain 18 points. Added reach stops at +painted panels or chrome and preserves the original edge-band tie-breaking. -Keyboard ownership, focus, file/pointer drops, overlays, clipboard and picking use -`PanelLocalServices` with explicit workspace/document/viewport scope. Native viewport -identity uses the native host's stable string in the viewport ID domain; platform -adapters map that identity to their actual viewport handle. Reparenting releases -old host-local focus/overlays/drop routing; the controller survives. Never route -a native service request through the root viewport or a different document. +The Below region extends through clear column space under a short panel, stopping +at the next visible panel, chrome or placement boundary. It adds no idle widget +or canvas obstacle. New stacked sections use the anchor's relative weight scale; +logical pixel heights do not become weights against normalized proportions. -## Persistence and bounds +Only the selected successful candidate's complete landing, changed neighbours +and tab marker are painted. Targets are data, never idle widgets. Preview does +not mutate committed layout, preferences, controllers, identities, document or +camera. Release consumes the unchanged shown candidate once. It does not rerun +an action reconstructed from the preview. Runtime performs lifecycle, action and +native preflight before committing that same prepared engine state. Resize uses +the same ownership protocol. Invalid/outside release, Escape, cancellation, +focus/visibility/modal loss, independent commands, changed scope, revision, +availability, metrics or environment discard capture without mutation. +Pointer leave hides the preview and discards its candidate while retaining a +valid held gesture. Re-entry resolves a fresh candidate. A button released +outside cannot resume a drag on re-entry; actual focus loss still cancels it. +The held Move's source text stays dim during pointer absence, but its badge has +no position and is hidden until a fresh inside Move. Cancellation or release +removes the badge and requests a repaint to restore the already-painted source +text. These visual observations derive from capture, never from `HostPreview` +or a second gesture state. -Envelope format is `solidcraft.panel-layout`, envelope/layout versions are both 1. -`PANEL_API_VERSION` and each live reply's `api_version` are also 1. -Public schema functions describe actions, replies and envelopes. Serde/schema -values are **untrusted wire data**, not validity proofs. Use `decode_action`, -`decode`, `encode` and the reducer. The engine owns versions; persistence adapters -own atomic storage and migration policy, not a second layout model. +The runtime owns one private proposal containing B's prepared host layout and +one staged incoming controller cohort. B captures once from a pure owner/topology +projection before numeric pair normalization. Controller construction does not +use temporary placement dimensions. Every numeric prefix and final admission use +that same availability/provider snapshot; lifecycle preflight and commit reuse +those exact objects. An explicit Open/Move can change the stack before a pair, +and a newly available floating owner need not match outgoing membership. +Availability freshness compares the captured proposed cohort, including unavailable +or unbound dormant instances, with fresh read-only answers from the same objects. +Mounting, activation and registered actions share active-or-first-available +selection while preserving remembered activation. Existing controllers are retained. -Limits: 64-byte IDs, 128 kinds/layout instances/retained instance identities, -64 sections, -32 tabs per section, 64 mutations per transaction, 262144-byte encoded envelope, -32768 logical units per positive size dimension, finite bounded coordinates. -Opaque JSON is limited to 8192 nodes and depth 32; availability reasons to 256 -bytes. Region/control, service payload and retained-owner collections are bounded. -Encoding uses a capped writer, not an unbounded serialization followed by a check. -Runtime retention has separate limits: 32 document owners, 128 other owners, -128 controllers per owner, and 20,480 controllers overall. These limits preserve -the application's supported document count without evicting live drafts. +`commands::execute_layout_action` stages the app's injected catalogue before +consuming the candidate once. Its retained-candidate sink returns the exact proposed +layout during projection and never replays a reducer on pointer release. Current +full-envelope preparation context is captured through `current_envelope_snapshot` +and `host_identity_reservations` before generators run. It includes dormant/native/ +quarantine identities, effective recovery priority records and completeness. +`ActionSink::project_in_context` and `dispatch_in_context` forward this full context; +a retained proposal refuses any supplied-context mismatch without replay. Incoming +workspace preparation context is retained separately from outgoing paint freshness. +Bare host defaults remain incomplete; admission fixtures read a complete synthetic +envelope rather than claiming empty recovery metadata is authoritative. The engine +command staging boundary must compare the current catalogue's full source context +again after fallible storage preparation, even when service revision is unchanged; +a differing context refuses publication of the retained proposal. +Standalone registered HeaderAction is an owner command without placement/storage +dependency; mixed structural transactions refuse. Preset/workspace replacement +uses the existing command executor with its complete incoming envelope. -Unknown panel records and raw future fields are retained in bounded quarantine. -`section_snapshots` stores each raw section once, including future fields, desired -tab order and pending activation; quarantined/retained records refer to its ID. -The bounded `section_order` list ranks **all** saved sections, including dormant -sections and known survivors without snapshots. Restoration uses those ranks, not -insertion indexes clamped into an incomplete list, so instance/quarantine processing -order and staged registry reappearance cannot reorder the saved complete layout. -Known live ordering remains authoritative when edited: surviving visible entries -take their latest relative order while dormant gaps remain; newly added entries -anchor before their next surviving visible neighbour. +Changed metrics/reservations discard pending widget intents, cached proposals, +drag and the old painted frame. Widget admission requires fresh paint. Independent +commands and batches cancel capture before parsing, even if subsequently refused. +Explicit Close/Open intent remains attached when the exact candidate is consumed, +so lifecycle guards cannot disappear during conversion to prepared engine state. -A retained snapshot from a fully restored episode is opaque metadata, not stale -layout authority. Before newly unknown members are removed on load, current saved -section semantics refresh its tabs, activation, placement, dimensions, collapse -state and rank. Existing opaque keys absent from typed live data are preserved; -current raw values for the same keys supply the latest saved intent. In an active -partial episode, still-dormant members remain in the complete order. Each snapshot's -optional `projected` section records the last materialized state: changed visible -activation overrides a pending choice, while an unchanged generated fallback does -not replace the desired dormant active member. Newly generated fallback selections -are recorded after quarantine filtering, so they cannot be mistaken for user edits. -The same merge runs before direct restoration after an in-memory live edit. +## Application and surface boundaries -These v1 fields have serde defaults. Earlier v1 envelopes without `section_order` -derive missing section ranks from sorted snapshot indexes; missing projections -conservatively retain dormant activation until a materialized baseline is recorded. -Both the complete rank list and projected sections obey the existing section/tab/ -ID limits, plus the envelope's global byte/node/depth bounds. Known layout starts -independently, and known survivors/extra current tabs remain intact during restores. -`restore_quarantine_with_availability` can defer unavailable entries; invalid bounds -or constraints also leave entries quarantined. Successful restoration preserves -raw instance fields in `retained_data` and shared raw section fields/order in -`section_snapshots`, even across later unregister/register cycles. Adapters consume -these explicitly. Restore stages the whole envelope and applies it only if encoding -fits global byte/node/depth caps; successful decode is guaranteed encodable by this -version. An unrepresentable lossless result returns fallback/recovery, not silent -field loss. Unknown corruption, invalid known layouts or future versions -return a validated preset fallback plus a once-reportable notice and bounded rejected -bytes for recovery. The adapter must preserve unrelated preference keys. +`SolveApp::enable_panel_runtime` installs an explicit retained runtime and +`AppPanelServices`; `enable_universal_panel_host` enables workspace composition. +Disabling the host unmounts the root cohort while keeping services alive. Whole +runtime teardown preflights every retained owner. Command, prepare, mount, paint +and finish boundaries refresh read-only Session context without an extra service +tick. Failure suspends stale presentation and remains inspectable in `last_error`. +The app exposes immutable runtime inspection; callers cannot replace its stored +native resource owner while native hosts exist. -## Executable fixtures +The app paints the full-domain scene through its existing navigation path, paints +host chrome, and finalizes host input after later windows/modals. Initial presses +must belong to the actual enabled top-layer widget; exported geometry alone does +not authorize input through another window. Modal/hidden/focus loss cancels capture. +Foreign overlay raises and owner-scoped popup provenance use shared Container +services. Root and each native host mount complete separate cohorts, so unmounting +one does not deactivate another. -`synthetic_registry`, `fixture_service`, `fixture_open`, `transaction`, -`FakePersistence` and `FIXTURE_LAYOUT_V1` are public engine fixtures. The v1 JSON -lives at `crates/engine/src/panels/fixtures/layout-v1.json`. It is authored contract -data, not a captured production design or a generated schema snapshot. +Panel operations never change camera, zoom, projection, focus or model screen +position. Explicit Fit uses actual usable space and may zoom. Centre/Look At +preserves zoom/distance and requested orientation, centring only focus if the +current model footprint cannot fit. Navbar/compass use their measured footprints. +Current persistent legacy forms, redefine controls, sketch palette and confirmation +paint remain obstacles after all producer passes. Sizing, closed, stale and Noop-only +hosts must not create obstacles. Transient menus shield input but do not become +framing targets. The existing semantic-content finalization and Browser editors +remain in the application shell. +The opt-in shell calls `browser::editors` once before sketch palette and +confirmation producers, retaining Move/Copy, Capture Position, Canvas, Point Cloud +and Sketch Attachment windows, drafts and command guards. Their existing shared +Window wrappers publish actual per-pass footprints; invisible sizing and closed +windows do not reserve usable space. Sketch Attachment has no second host call. -`PanelMountHarness` combines the actual runtime/action service with synthetic -application-owned content, document-owned transactional editor, workspace-owned multi-instance log/pin -controllers, fake models/command sink/local services/native adapter, fake mount -host and persistence adapter. `FixtureProbe` provides snapshots and bounded draft/ -failure controls. `apply_layout` exercises saved-layout/workspace transitions through -the actual sink; `without_content` exercises dormant missing bindings. Fake host mounting invokes all three real controller slots with -an egui context; it is headless and does not establish visual correctness. +Suppressing the root Assistant clears only its cached panel, drop and dock-space +geometry, so an undrawn floating card cannot narrow legacy tool bounds. Desired +open state, conversation, backend and layout preferences remain owned by the +existing Assistant. A popped Assistant still uses `agent_chat::show` and its +existing native-window path, which performs the service poll itself; other host +composition passes call `agent_chat::poll` instead. This does not migrate or +reparent the window. -```rust -use solidcraft_engine::panels::*; -use solidcraft_ui_egui::panel_runtime::PanelMountHarness; +The default adapter truthfully advertises no native windows. Actual Window +placement needs the native sibling's monitor/DPI, focus and close/redock services. +The renderer retains the shared Container's fill alpha; captured `paint_alpha` +reports it separately from declarative surface intent. Input and occlusion remain +reserved regardless of alpha. Unsupported translucent effective policies still +refuse. Contrast proof, comprehensive accessibility/keyboard bindings, persisted +workspace rollout and real content adapters remain their named peers' work. -fn specimen() -> PanelResult<()> { - let mut h = PanelMountHarness::new(false)?; - h.dispatch(vec![fixture_open( - "fixture.editor", "editor", "editor-section", Zone::Left, 0, - )?])?; - h.tick()?; // independent services, even with no host mounted - h.mount(LogicalRect { - origin: Point { x: 0.0, y: 0.0 }, - size: Size { width: 1200.0, height: 800.0 }, - })?; - h.save()?; - Ok(()) -} -``` +## Specimens and verification boundary -Engine and UI domain test modules contain hostile action sequences, bounds and -collection limits, exactly-once constraints, pins, atomic failures, incompatible -tabs, overflow restoration, availability, close/reopen, schema/envelope fixtures, -controller retention, hidden service updates, explicit editor actions, native -preflight/redock, scoped input, RTL/reduced motion and document/cache isolation. +`ui.panel_fixture` is authenticated, off by default, and refuses to replace another +runtime. Presets: `docks`, `tabs`, `collapsed`, `floating`, `overflow` (24 instances), +`pinned`, `columns` (three independent Left columns), `stack_tabs`, `content_fill` +(short Content versus Fill), and `inline` (one editable total row). The old `rails` +preset is replaced by `collapsed`; it is not an alias to the retired experience. +The original synthetic controllers expose draft, transaction, action, lifecycle, +render and service counters plus process-local equality tokens. They do not expose +fake production actions or pretend to perform CAD work. + +The existing engine, panel-runtime, kit, shell and viewport test files and JSON +scenarios are the locations for authored regression cases. This source describes +contracts and review fixtures; it does not claim tests, native screenshots, +performance budgets or visual acceptance have been verified. Root owns runnable +milestone builds, screenshots, user visual approval and the final checks. diff --git a/docs/screenshots/7452/demo-01-extrude5-edge-frame.png b/docs/screenshots/7452/demo-01-extrude5-edge-frame.png new file mode 100644 index 000000000..8e139540e Binary files /dev/null and b/docs/screenshots/7452/demo-01-extrude5-edge-frame.png differ diff --git a/docs/screenshots/7452/demo-04-preview-outer-l11.png b/docs/screenshots/7452/demo-04-preview-outer-l11.png new file mode 100644 index 000000000..8e6dea9d8 Binary files /dev/null and b/docs/screenshots/7452/demo-04-preview-outer-l11.png differ diff --git a/docs/screenshots/7452/demo-05-preview-inner-l8.png b/docs/screenshots/7452/demo-05-preview-inner-l8.png new file mode 100644 index 000000000..952028bfc Binary files /dev/null and b/docs/screenshots/7452/demo-05-preview-inner-l8.png differ diff --git a/docs/screenshots/7452/demo-06-result-outer-120.png b/docs/screenshots/7452/demo-06-result-outer-120.png new file mode 100644 index 000000000..73b90089f Binary files /dev/null and b/docs/screenshots/7452/demo-06-result-outer-120.png differ diff --git a/docs/screenshots/7452/demo-07-preview-360.png b/docs/screenshots/7452/demo-07-preview-360.png new file mode 100644 index 000000000..d657e8af7 Binary files /dev/null and b/docs/screenshots/7452/demo-07-preview-360.png differ diff --git a/docs/screenshots/7452/demo-08-cancelled.png b/docs/screenshots/7452/demo-08-cancelled.png new file mode 100644 index 000000000..fcc0e9bd8 Binary files /dev/null and b/docs/screenshots/7452/demo-08-cancelled.png differ diff --git a/docs/screenshots/7452/demo-13-colliding-id.png b/docs/screenshots/7452/demo-13-colliding-id.png new file mode 100644 index 000000000..b2278f6d7 Binary files /dev/null and b/docs/screenshots/7452/demo-13-colliding-id.png differ diff --git a/docs/screenshots/7452/demo-14-surface-l1.png b/docs/screenshots/7452/demo-14-surface-l1.png new file mode 100644 index 000000000..6ea7aac22 Binary files /dev/null and b/docs/screenshots/7452/demo-14-surface-l1.png differ diff --git a/docs/screenshots/7452/demo-15-surface-result.png b/docs/screenshots/7452/demo-15-surface-result.png new file mode 100644 index 000000000..187591539 Binary files /dev/null and b/docs/screenshots/7452/demo-15-surface-result.png differ diff --git a/docs/screenshots/7452/revolve-edge-frame.solidcraft b/docs/screenshots/7452/revolve-edge-frame.solidcraft new file mode 100644 index 000000000..da1f2feb2 Binary files /dev/null and b/docs/screenshots/7452/revolve-edge-frame.solidcraft differ diff --git a/docs/screenshots/7452/revolve-selected-edge.mp4 b/docs/screenshots/7452/revolve-selected-edge.mp4 new file mode 100644 index 000000000..bcc3400c8 Binary files /dev/null and b/docs/screenshots/7452/revolve-selected-edge.mp4 differ diff --git a/docs/ui-kit.md b/docs/ui-kit.md index 3ca4ef19d..8b39f2001 100644 --- a/docs/ui-kit.md +++ b/docs/ui-kit.md @@ -1,14 +1,116 @@ # SolidCraft UI kit -The internal opt-in [universal panel foundation](panel-foundation.md) separates -engine layout/specs from retained UI controllers and host-local services. -`panel_runtime::EguiPanelHost` mounts bounded Header/Body/Footer slots through one -existing `ui_kit::Container`; content controls its own scrolling. This reference -adapter requires a full rectangular paint/input surface, rejects sparse geometry, -and preserves parent clipping. `SolveApp::mount_panels` uses the enabled runtime's -injected services. It adds no default -placement/content change. Production docking and panel migrations remain separate. +The opt-in [universal panel foundation](panel-foundation.md) separates engine +layout, retained content controllers and viewport-local services. Its production +content adapters are sibling work; existing content, Classic and shipping defaults +remain available. `WorkspacePanelHost` uses the existing Container policy, theme +tokens and stable semantic widgets. No second shell or camera path is added. +Shared headers span their complete column width when collapsed. They retain the +active identity and declared custom actions, menu, chevron and optional quick +close, in that LTR order and mirrored in RTL. `hot_closable` controls quick close; +`closable` independently controls permission. One click on the same chevron +restores the body. There is no rail, hover-peek or pin-open product presentation. +Registered actions are bound to retained controllers and validated through the +same engine command route as `panel.action`; unbound/disabled actions cannot run. + +Tab groups place text-only tab headings in this same header row, replacing the +single active title. One leading six-dot section grip drags the active tab; +individual tabs keep their select, drag and reorder responses. Grip, tabs, +compact overflow and actual controls use disjoint hitboxes, mirrored in RTL. +Collapsed groups retain their headings; inline groups use the allocated title +region without displacing editable inline content. Overflow reserves one compact +control width, preserving the active label when it fits and keeping every entry +reachable through the accessible menu. Single titles retain the heading font +without placeholder icons. Icon metadata remains available to other consumers. +Neither `HostMetrics` nor `AllocationEnvironment` has a second-row tab metric; +measurement chrome counts the shared header only once. + +After the existing six-point Move threshold, only the dragged instance's title +ink fades to 50% of its current opacity. Group grips have no title ink; the +matching tab fades instead. Font selection, other labels, icons, grips, actions, +fills and bodies stay unchanged. A paint-only badge shows the full live title +next to the pointer on the existing preview tooltip layer, independently of +landing validity. Theme typography, padding, radius and opaque backing keep it +legible; the offset mirrors in RTL, and the badge clamps to the render-domain clip. +The full title remains in its existing display order on one line, with no +automatic wrapping, second bidi pass or ellipsis. Oversized text clips from a +left-aligned galley in LTR or a right-aligned galley in RTL, preserving its reading +start. Explicit metadata newlines retain their existing meaning. +There is no added widget, container or input/occlusion/usable-space footprint. +Pointer absence hides the badge while the held source remains dim; re-entry +uses a fresh position. Release and cancellation clear feedback and repaint the +source. Presses, clicks and either resize kind retain their normal appearance. + +Expanded content receives bounded Header/Body/Footer slots and owns its scrolling. +`HostOptions::content_header_height` can reserve a content toolbar. Collapsed +content has no body and renders none of these slots. Expanded Wide hosts below +`theme::PANEL_INLINE_MAX_HEIGHT` use one total row with the shared title/grip, leading registered actions, +a dedicated inline content slot, then menu, chevron and optional quick close. The +complete row mirrors in RTL. Only `render_inline` runs; its safe default delegates +to Body and adapters may supply a compact view. There is no extra title band or +duplicated footer. The inline specimen contains a working synthetic text input; +it does not replace real History playback or timeline content. + +Columns have independent widths and stacked tab sections. Sole side Content +panels use bounded preferred metrics at their assigned width and leave uncovered +space below; declared Fill panels use available height within the same limits. +`PanelController::measure` captures immutable `HostContentMetrics` snapshots, +including a revision that changes whenever any answer changes. The default +reports the registration's preferred outer height honestly. Real adapters supply +bounded intrinsic/preferred metrics without rendering hidden bodies or enumerating +unbounded lists. Candidate and committed allocation use the same captured metrics. + +Tiny windows keep real panels at minimum dimensions in a bounded scroll extent. +Scroll tracks own narrow input regions; leftover wheel input over actual panel +paint scrolls presentation after content scrolling. The scroll canvas has no +full-viewport response. Uncovered gaps stay navigable. Actual clipped paint, +input/occlusion and usable contour remain separate from the full render domain +below the application bar, including behind the ribbon. Panel changes never move +the camera. Fit/Centre and independent navbar/compass placement include persistent +legacy forms, palettes and confirmations after all producer passes. + +Pointer and app commands use `prepare_host_layout_with_snapshot` and the same +NO_SPACE admission. Pointer release stages the injected layout catalogue, then +consumes the exact owned `PreparedHostLayout` after lifecycle and native preflight; it never reconstructs an action. Only the selected successful +candidate's landing, changed neighbours and tab marker paint. No idle targets or +rejected-target grid is shown. Escape, invalid/outside release, focus/visibility/ +modal loss, independent commands and changed environment/metrics cancel capture. +Missing host/environment refuses structural app commands. A standalone registered +HeaderAction follows the owning controller route without placement or layout-store +staging. Availability, fallback selection and binding permission still validate. +Projection and commit reuse one staged incoming cohort; metric/reservation changes +invalidate pending widgets and cached proposals as well as drag and the old frame. +The next widget admission requires fresh paint. + +The app paints through `show_host_deferred`, then finalizes after later windows +and modals using actual enabled top-layer responses. Geometry alone cannot +permission input through a foreign window. `Container::bring_to_front` and +owner-scoped popup layer registration preserve current layer ownership. Root and +native windows mount complete separate cohorts. `HostFrame::layout` retains +intended section geometry; its published controls and actual footprint arrays +exclude invisible Area sizing passes. `reply`, `Committed` and +`PreparedCommitted` events describe committed state, while `next_layout` describes +a pending repaint. Transient menus shield input without becoming Fit targets. + +`AppPanelRuntime` retains the installed native adapter and read-only Session +provider. Inspection exposes an immutable runtime; callers cannot replace an +adapter while native placements exist. The default adapter truthfully supplies no +native Window service. Host cards reuse adaptive Container styling, title fonts, +the six-dot grip and header separator. Shared shell gaps are allocation space. +Captured frame alpha is reported separately from declarative surface intent; +unsupported effective translucency still refuses. Native windows, contrast proof, comprehensive accessibility/keyboard +bindings, saved workspace rollout and real content migrations remain peer work. + +The authenticated `ui.panel_fixture` seam is off by default and rejects replacing +an existing runtime. Presets are `docks`, `tabs`, `collapsed`, `floating`, `overflow` +(24 instances), `pinned`, `columns`, `stack_tabs`, `content_fill` and `inline`. +Drafts, controller identities and lifecycle/service/action counters are inspectable. +The native specimen exposes editor Apply/Finish/Cancel actions. Separate +action-binding fixtures retain their declared test actions. +Strings use pending `ui.panel_fixture.*` / `ui.panel_host.*` catalog entries. +Authored source cases and scenarios do not establish visual or automated +verification; root owns builds, screenshots, visual acceptance and checks. `viewport_status_item` and `viewport_status_row` draw persistent viewport pills on `Surface::ViewportStatus`. Callers supply translated names, formatted settings, kind, stable identity and key availability, and dispatch returned clear/edit actions. @@ -673,6 +775,25 @@ border strip without changing logical panel allocations. The application bar has an independent surface role. The saved `Prefs::layout` is changed through `view.layout`; `ui.set` may still make a transient automation override. +With the universal host enabled, the model render domain fills the area below the application bar in both layout modes, +including behind ribbon, docked and floating chrome. Paint/input footprints remain +separate: transparent styling does not expose controls to picking. The usable +region follows actual occupied edges, retains short-panel gaps and floating-panel +holes, and supplies explicit Fit/Centre and measured navbar/compass placement. +This contour also includes actually painted persistent surfaces outside the host, +such as the active sketch palette. Closing one releases its footprint; transient +menus shield input without changing fitting or control placement. +Ordinary panel operations preserve the camera and its framing. Fit may change +zoom; explicit Look At/`view.normal_to` centring preserves zoom, distance, +orientation and selected focus. If the selection cannot fit at the current zoom, +only its focus moves to stable usable space; it does not trigger a zoom-out. + +Universal title/tab drags offer explicit dock, split and tab targets. Their landing +preview uses the same prepared geometry as the final transaction, including +affected neighbours and insertion index. Releasing outside a valid target cancels; +floating placement is an explicit action or command. Previewing never changes the +committed usable region or the render projection. + ## File/start presentation `FileView` owns File surfaces and controls. It accepts translated strings, existing @@ -893,7 +1014,7 @@ these shared pieces; the pages themselves arrive in later steps. Sizes follow | `preset_card(ui, name, word, selected, enabled, &icon, width)` | A 70 pt card with a 38 pt icon box (`icon` paints into it in the ink it is given), a name, one word and an accent check. Used for Performance, Quality and Custom. | as above, `pref_well` | | `help_icon(ui, text)` | The (i) after a label. Shows `text` as a tooltip and exposes it as the widget's label. | `form_dim`, `form_ink` | | `shortcut_binding(ui, chord, editable)` | Complete mono keycaps using the command-search painter; one focusable recorder target per binding, or a read-only label. Empty chords show dim Not assigned. `shortcut_binding_width` measures the same font and padding, including literal plus keys. Gallery: `shortcut_binding`. | `font_small/label`, `control_height`, `form_dim`, `form_primary`, `space_4/8/10`, `radius_sm` | -| `carousel(ui, id, count, item_width, item_height, item)` | A row of items between a previous and a next arrow (both labelled from the `prefs.carousel_*` messages). `carousel_window(count, offset, available, item_width, gap, arrow)` says which items show; an arrow moves by the number of items that fit, the last page ends on the last item, and the arrow at an end is dimmed (0.35) and inert. The first shown index is kept in the Ui's temporary memory under `id`. | `dialog_border`, `control_fill`, `hover`, `form_ink`, `radius_lg` | +| `theme_browser(ui, id, count, grid, reveal, item)` | The Appearance theme list: a carousel (one clipped row, an edge fade in the container fill, round arrows on a side with more cards, an arrow moves by the cards that fit, drag and horizontal wheel scroll while vertical wheel input goes to the page) or a 5-across grid with its own vertical scroll. `reveal` scrolls an index into view. The box and fades use the `settings_card_frame` fill and stroke. | `dialog_border`, `dialog_border`, `control_fill`, `hover`, `form_ink`, `radius_lg` | `card_look(selected, enabled, hovered, focused)` holds the state rules (border width, fill, ink, weight, dimming, focus ring) apart from the painting so they can be tested. @@ -929,7 +1050,7 @@ Theme thumbnails (`paint_theme_thumbnail`, `paint_theme_system`) take a `ThemeSa The Orientation figures and the visual-style icon are not repeated here: the app already has them. New pieces and figures each have an entry in `gallery::ELEMENTS` (`picture_card`, `toggle_tile`, -`preset_card`, `help_icon`, `carousel`, `preference_theme_thumbnails`, `preference_figures`), checked +`preset_card`, `help_icon`, `theme_browser`, `preference_theme_thumbnails`, `preference_figures`), checked in both themes. `SOLIDCRAFT_PREFERENCE_WIDGET_EVIDENCE=` keeps the CPU-rendered boards (`preferences-widgets-*.png`, `preferences-figures-*.png`) from `preference_widgets_and_figures_board_in_both_themes`. diff --git a/tests/kernel-cases/EXEMPT b/tests/kernel-cases/EXEMPT index 75ab63e6d..52933595b 100644 --- a/tests/kernel-cases/EXEMPT +++ b/tests/kernel-cases/EXEMPT @@ -114,6 +114,7 @@ motion.delete removes a motion study motion.export writes a study's results to a file motion.export_animation writes an animation motion.list a listing of motion studies +panel.action controller actions; no geometry (crates/engine/src/panels/tests.rs and crates/ui-egui/src/panel_runtime/tests.rs) panel.activate application panel layout; no geometry (engine/UI/MCP tests) panel.close application panel layout; no geometry (engine/UI/MCP tests) panel.collapse application panel layout; no geometry (engine/UI/MCP tests) @@ -284,6 +285,7 @@ sketch.loose_ends.tie 2D sketch only (the sketch solver and engine t sketch.mirror 2D sketch only (the sketch solver and engine tests); no kernel operation sketch.move 2D sketch only (the sketch solver and engine tests); no kernel operation sketch.move3d 2D sketch only (the sketch solver and engine tests); no kernel operation +sketch.move_points 2D sketch only; crates/engine/src/cmd/sketch_ux_tests.rs: move_points_moves_each_point_to_its_own_target and move_points_refuses_a_near_that_two_points_answer sketch.offset 2D sketch only (the sketch solver and engine tests); no kernel operation sketch.offset.break 2D sketch only (the sketch solver and engine tests); no kernel operation sketch.paste 2D sketch only (the sketch solver and engine tests); no kernel operation