Panels: inspect and change layouts through commands (#11304) (#11454)

* claim: #11218

* Panels: add shared layout rules and retained content runtime

* claim: #11304

* Panels: inspect and change layouts through shared commands (#11304)

* Panels: account for layout commands in geometry coverage
This commit is contained in:
Nathan Dane authored and GitHub committed 2026-11-03 13:55:50 +00:00
1 parent 372136fa6a
commit fbd30b0bd0
37 files changed
+11837 -13

No files matched your search

+5 -1
View File
@@ -465,7 +465,11 @@ fn snapshot_runs_its_script_on_the_in_design() {
fn unknown_command_suggests_the_closest_id() {
let output = cli().args(["exec", "file.open"]).output().unwrap();
assert_eq!(output.status.code(), Some(1));
assert!(String::from_utf8_lossy(&output.stderr).contains("did you mean `doc.open`?"), "{}", String::from_utf8_lossy(&output.stderr));
assert!(
String::from_utf8_lossy(&output.stderr).contains("did you mean `doc.open` or `panel.open`?"),
"{}",
String::from_utf8_lossy(&output.stderr)
);
}
/// #1833: `--timings` reports each command's time instead of the measurement, `--profile` adds
@@ -0,0 +1,338 @@
{
"en": {
"cmd.layout.apply": "Apply Layout",
"cmd.layout.get": "Inspect Layout",
"cmd.layout.reset": "Reset Layout",
"cmd.layout.save": "Save Layout",
"cmd.layout.workspace.select": "Select Layout Workspace",
"cmd.panel.activate": "Activate Panel Tab",
"cmd.panel.close": "Close Panel",
"cmd.panel.collapse": "Collapse Panel Section",
"cmd.panel.dismiss": "Dismiss Panel Peek",
"cmd.panel.float": "Float Panel",
"cmd.panel.focus": "Focus Panel",
"cmd.panel.list": "List Panels",
"cmd.panel.move": "Move Panel",
"cmd.panel.native_close": "Redock Native Panel Section",
"cmd.panel.open": "Open Panel",
"cmd.panel.peek": "Peek Collapsed Panel",
"cmd.panel.popout": "Pop Out Panel",
"cmd.panel.reset_pair": "Reset Panel Sash",
"cmd.panel.resize": "Resize Panel Section",
"cmd.panel.resize_pair": "Resize Panel Sash",
"help.layout.apply": "Apply a saved layout to the current workspace. Retained editors keep their drafts.",
"help.layout.get": "Read the committed layout and discover registered workspaces.",
"help.layout.reset": "Restore the current workspace's registered default layout. User presets remain available.",
"help.layout.save": "Save the complete layout under a name. Replacing a user preset requires explicit overwrite permission.",
"help.layout.workspace.select": "Select a registered layout workspace and remember the outgoing layout.",
"help.panel.activate": "Select an open panel tab without requesting keyboard focus.",
"help.panel.close": "Close a panel through its content lifecycle guard. Its placement is remembered.",
"help.panel.collapse": "Collapse or expand a panel section while retaining its requested dimensions.",
"help.panel.dismiss": "Dismiss the temporary view of a collapsed panel.",
"help.panel.float": "Move a panel into an explicitly positioned floating section.",
"help.panel.focus": "Focus a panel, reopening its retained state and expanding its section when needed.",
"help.panel.list": "Read registered panel kinds, committed instances, active tabs, availability and host capabilities.",
"help.panel.move": "Move a panel into a new section or join an existing tab group.",
"help.panel.native_close": "Return a native panel section to its remembered dock without cancelling its content.",
"help.panel.open": "Open a panel kind with an explicit instance identity and placement for a new instance.",
"help.panel.peek": "Temporarily show a collapsed panel without changing its saved size or collapse state.",
"help.panel.popout": "Move a panel to a native host when supported. Browser hosts use a floating section.",
"help.panel.reset_pair": "Restore an adjacent dock pair's default size ratio within its shared bounds.",
"help.panel.resize": "Set a panel section's outer width and height within every tab's bounds.",
"help.panel.resize_pair": "Resize adjacent dock sections together while conserving their shared extent."
},
"ar": {
"cmd.layout.apply": "تطبيق التخطيط",
"cmd.layout.get": "فحص التخطيط",
"cmd.layout.reset": "إعادة ضبط التخطيط",
"cmd.layout.save": "حفظ التخطيط",
"cmd.layout.workspace.select": "اختيار مساحة عمل التخطيط",
"cmd.panel.activate": "تنشيط علامة تبويب اللوحة",
"cmd.panel.close": "إغلاق اللوحة",
"cmd.panel.collapse": "طي قسم اللوحة",
"cmd.panel.dismiss": "إغلاق العرض المؤقت للوحة",
"cmd.panel.float": "تعويم اللوحة",
"cmd.panel.focus": "تركيز اللوحة",
"cmd.panel.list": "سرد اللوحات",
"cmd.panel.move": "نقل اللوحة",
"cmd.panel.native_close": "إعادة إرساء قسم اللوحة من نافذته المستقلة",
"cmd.panel.open": "فتح اللوحة",
"cmd.panel.peek": "عرض اللوحة المطوية مؤقتًا",
"cmd.panel.popout": "نقل اللوحة إلى نافذة مستقلة",
"cmd.panel.reset_pair": "إعادة ضبط فاصل اللوحة",
"cmd.panel.resize": "تغيير حجم قسم اللوحة",
"cmd.panel.resize_pair": "تحريك فاصل اللوحة",
"help.layout.apply": "تطبيق تخطيط محفوظ على مساحة العمل الحالية. تحتفظ أدوات التحرير القائمة بمسوداتها.",
"help.layout.get": "قراءة التخطيط المعتمد وعرض مساحات العمل المسجلة.",
"help.layout.reset": "استعادة التخطيط الافتراضي المسجل لمساحة العمل الحالية. تبقى إعدادات المستخدم المسبقة متاحة.",
"help.layout.save": "حفظ التخطيط الكامل باسم محدد. يتطلب استبدال إعداد مسبق للمستخدم إذنًا صريحًا بالكتابة فوقه.",
"help.layout.workspace.select": "اختيار مساحة عمل تخطيط مسجلة وتذكر التخطيط السابق.",
"help.panel.activate": "اختيار علامة تبويب لوحة مفتوحة دون طلب تركيز لوحة المفاتيح.",
"help.panel.close": "إغلاق اللوحة بعد التحقق من دورة حياة محتواها. يُحفظ موضعها.",
"help.panel.collapse": "طي قسم اللوحة أو توسيعه مع الاحتفاظ بأبعاده المطلوبة.",
"help.panel.dismiss": "إغلاق العرض المؤقت للوحة مطوية.",
"help.panel.float": "نقل لوحة إلى قسم عائم ذي موضع محدد صراحةً.",
"help.panel.focus": "تركيز لوحة وإعادة فتح حالتها المحفوظة وتوسيع قسمها عند الحاجة.",
"help.panel.list": "قراءة أنواع اللوحات المسجلة والمثيلات المعتمدة وعلامات التبويب النشطة والتوافر وإمكانات المضيف.",
"help.panel.move": "نقل لوحة إلى قسم جديد أو ضمها إلى مجموعة علامات تبويب موجودة.",
"help.panel.native_close": "إعادة قسم لوحة من نافذته المستقلة إلى موضع الإرساء المحفوظ دون إلغاء محتواه.",
"help.panel.open": "فتح نوع لوحة بمعرّف مثيل صريح. يتطلب المثيل الجديد تحديد موضعه.",
"help.panel.peek": "إظهار لوحة مطوية مؤقتًا دون تغيير حجمها المحفوظ أو حالة طيها.",
"help.panel.popout": "نقل لوحة إلى نافذة مستقلة عند دعم ذلك. يستخدم مضيف المتصفح قسمًا عائمًا.",
"help.panel.reset_pair": "استعادة نسبة الحجم الافتراضية لقسمي إرساء متجاورين ضمن حدودهما المشتركة.",
"help.panel.resize": "تعيين العرض والارتفاع الخارجيين لقسم اللوحة ضمن حدود جميع علامات التبويب.",
"help.panel.resize_pair": "تغيير حجم قسمي إرساء متجاورين معًا مع الحفاظ على امتدادهما الكلي المشترك."
},
"de": {
"cmd.layout.apply": "Layout anwenden",
"cmd.layout.get": "Layout prüfen",
"cmd.layout.reset": "Layout zurücksetzen",
"cmd.layout.save": "Layout speichern",
"cmd.layout.workspace.select": "Layout-Arbeitsbereich auswählen",
"cmd.panel.activate": "Panel-Registerkarte aktivieren",
"cmd.panel.close": "Panel schließen",
"cmd.panel.collapse": "Panel-Bereich einklappen",
"cmd.panel.dismiss": "Panel-Vorschau schließen",
"cmd.panel.float": "Panel frei platzieren",
"cmd.panel.focus": "Panel fokussieren",
"cmd.panel.list": "Panels auflisten",
"cmd.panel.move": "Panel verschieben",
"cmd.panel.native_close": "Nativen Panel-Bereich wieder andocken",
"cmd.panel.open": "Panel öffnen",
"cmd.panel.peek": "Eingeklapptes Panel anzeigen",
"cmd.panel.popout": "Panel in eigenes Fenster verschieben",
"cmd.panel.reset_pair": "Panel-Trennlinie zurücksetzen",
"cmd.panel.resize": "Panel-Bereich skalieren",
"cmd.panel.resize_pair": "Panel-Trennlinie verschieben",
"help.layout.apply": "Ein gespeichertes Layout auf den aktuellen Arbeitsbereich anwenden. Geöffnete Editoren behalten ihre Entwürfe.",
"help.layout.get": "Das übernommene Layout lesen und registrierte Arbeitsbereiche anzeigen.",
"help.layout.reset": "Das registrierte Standardlayout des aktuellen Arbeitsbereichs wiederherstellen. Eigene Vorlagen bleiben erhalten.",
"help.layout.save": "Das vollständige Layout unter einem Namen speichern. Eine vorhandene eigene Vorlage wird nur mit ausdrücklicher Erlaubnis überschrieben.",
"help.layout.workspace.select": "Einen registrierten Layout-Arbeitsbereich auswählen und das bisherige Layout merken.",
"help.panel.activate": "Eine geöffnete Panel-Registerkarte auswählen, ohne den Tastaturfokus anzufordern.",
"help.panel.close": "Ein Panel unter Beachtung seines Inhaltslebenszyklus schließen. Seine Platzierung wird gespeichert.",
"help.panel.collapse": "Einen Panel-Bereich ein- oder ausklappen und seine gewünschten Abmessungen beibehalten.",
"help.panel.dismiss": "Die vorübergehende Ansicht eines eingeklappten Panels schließen.",
"help.panel.float": "Ein Panel in einen frei positionierten Bereich verschieben.",
"help.panel.focus": "Ein Panel fokussieren, seinen gespeicherten Zustand bei Bedarf wieder öffnen und seinen Bereich ausklappen.",
"help.panel.list": "Registrierte Panel-Arten, übernommene Instanzen, aktive Registerkarten, Verfügbarkeit und Host-Funktionen lesen.",
"help.panel.move": "Ein Panel in einen neuen Bereich verschieben oder einer vorhandenen Registerkartengruppe hinzufügen.",
"help.panel.native_close": "Einen nativen Panel-Bereich an seine gespeicherte Position zurückbringen, ohne seinen Inhalt abzubrechen.",
"help.panel.open": "Eine Panel-Art mit einer ausdrücklichen Instanzkennung öffnen. Neue Instanzen benötigen eine Platzierung.",
"help.panel.peek": "Ein eingeklapptes Panel vorübergehend anzeigen, ohne seine gespeicherte Größe oder seinen Klappzustand zu ändern.",
"help.panel.popout": "Ein Panel bei Unterstützung in ein natives Fenster verschieben. Im Browser wird ein frei positionierter Bereich verwendet.",
"help.panel.reset_pair": "Das Standardgrößenverhältnis zweier benachbarter Andockbereiche innerhalb ihrer gemeinsamen Grenzen wiederherstellen.",
"help.panel.resize": "Die äußere Breite und Höhe eines Panel-Bereichs innerhalb der Grenzen aller Registerkarten festlegen.",
"help.panel.resize_pair": "Benachbarte Andockbereiche gemeinsam skalieren und ihre gemeinsame Ausdehnung beibehalten."
},
"he": {
"cmd.layout.apply": "החלת פריסה",
"cmd.layout.get": "בדיקת פריסה",
"cmd.layout.reset": "איפוס פריסה",
"cmd.layout.save": "שמירת פריסה",
"cmd.layout.workspace.select": "בחירת סביבת עבודה לפריסה",
"cmd.panel.activate": "הפעלת לשונית חלונית",
"cmd.panel.close": "סגירת חלונית",
"cmd.panel.collapse": "כיווץ מקטע חלונית",
"cmd.panel.dismiss": "סגירת תצוגה זמנית של חלונית",
"cmd.panel.float": "הצפת חלונית",
"cmd.panel.focus": "מיקוד חלונית",
"cmd.panel.list": "הצגת רשימת חלוניות",
"cmd.panel.move": "העברת חלונית",
"cmd.panel.native_close": "עיגון מחדש של מקטע חלונית מחלון נפרד",
"cmd.panel.open": "פתיחת חלונית",
"cmd.panel.peek": "הצגה זמנית של חלונית מכווצת",
"cmd.panel.popout": "העברת חלונית לחלון נפרד",
"cmd.panel.reset_pair": "איפוס מפריד חלוניות",
"cmd.panel.resize": "שינוי גודל מקטע חלונית",
"cmd.panel.resize_pair": "הזזת מפריד חלוניות",
"help.layout.apply": "החלת פריסה שמורה על סביבת העבודה הנוכחית. העורכים הקיימים שומרים על הטיוטות שלהם.",
"help.layout.get": "קריאת הפריסה שאושרה והצגת סביבות העבודה הרשומות.",
"help.layout.reset": "שחזור פריסת ברירת המחדל הרשומה של סביבת העבודה הנוכחית. הגדרות המשתמש השמורות נשארות זמינות.",
"help.layout.save": "שמירת הפריסה המלאה בשם. החלפת הגדרה שמורה של משתמש מחייבת הרשאה מפורשת לדריסה.",
"help.layout.workspace.select": "בחירת סביבת עבודה רשומה לפריסה ושמירת הפריסה שממנה יוצאים.",
"help.panel.activate": "בחירת לשונית חלונית פתוחה בלי לבקש מיקוד מקלדת.",
"help.panel.close": "סגירת חלונית דרך בדיקת מחזור החיים של התוכן שלה. המיקום שלה נשמר.",
"help.panel.collapse": "כיווץ או הרחבה של מקטע חלונית תוך שמירת המידות המבוקשות.",
"help.panel.dismiss": "סגירת התצוגה הזמנית של חלונית מכווצת.",
"help.panel.float": "העברת חלונית למקטע צף שמיקומו מוגדר במפורש.",
"help.panel.focus": "מיקוד חלונית, פתיחה מחדש של מצבה השמור והרחבת המקטע שלה לפי הצורך.",
"help.panel.list": "קריאת סוגי החלוניות הרשומים, המופעים שאושרו, הלשוניות הפעילות, הזמינות ויכולות המארח.",
"help.panel.move": "העברת חלונית למקטע חדש או צירופה לקבוצת לשוניות קיימת.",
"help.panel.native_close": "החזרת מקטע חלונית מחלון נפרד למיקום העיגון השמור בלי לבטל את התוכן שלו.",
"help.panel.open": "פתיחת סוג חלונית עם מזהה מופע מפורש. מופע חדש דורש מיקום.",
"help.panel.peek": "הצגה זמנית של חלונית מכווצת בלי לשנות את הגודל השמור או את מצב הכיווץ שלה.",
"help.panel.popout": "העברת חלונית לחלון נפרד כאשר יש תמיכה בכך. במארח דפדפן נעשה שימוש במקטע צף.",
"help.panel.reset_pair": "שחזור יחס הגדלים המוגדר כברירת מחדל לשני מקטעי עיגון סמוכים, במסגרת הגבולות המשותפים שלהם.",
"help.panel.resize": "הגדרת הרוחב והגובה החיצוניים של מקטע חלונית במסגרת המגבלות של כל הלשוניות.",
"help.panel.resize_pair": "שינוי גודלם של מקטעי עיגון סמוכים יחד תוך שמירה על האורך הכולל המשותף שלהם."
},
"ja": {
"cmd.layout.apply": "レイアウトを適用",
"cmd.layout.get": "レイアウトを確認",
"cmd.layout.reset": "レイアウトをリセット",
"cmd.layout.save": "レイアウトを保存",
"cmd.layout.workspace.select": "レイアウトのワークスペースを選択",
"cmd.panel.activate": "パネルのタブをアクティブ化",
"cmd.panel.close": "パネルを閉じる",
"cmd.panel.collapse": "パネルのセクションを折りたたむ",
"cmd.panel.dismiss": "パネルの一時表示を閉じる",
"cmd.panel.float": "パネルをフロート表示",
"cmd.panel.focus": "パネルにフォーカス",
"cmd.panel.list": "パネルを一覧表示",
"cmd.panel.move": "パネルを移動",
"cmd.panel.native_close": "別ウィンドウのパネルを再ドッキング",
"cmd.panel.open": "パネルを開く",
"cmd.panel.peek": "折りたたんだパネルを一時表示",
"cmd.panel.popout": "パネルを別ウィンドウに移動",
"cmd.panel.reset_pair": "パネルの区切りをリセット",
"cmd.panel.resize": "パネルのセクションのサイズを変更",
"cmd.panel.resize_pair": "パネルの区切りを移動",
"help.layout.apply": "保存したレイアウトを現在のワークスペースに適用します。保持されているエディターの下書きは維持されます。",
"help.layout.get": "確定したレイアウトと登録済みのワークスペースを確認します。",
"help.layout.reset": "現在のワークスペースに登録された既定のレイアウトを復元します。ユーザープリセットは保持されます。",
"help.layout.save": "レイアウト全体に名前を付けて保存します。ユーザープリセットの置き換えには明示的な上書き許可が必要です。",
"help.layout.workspace.select": "登録済みのレイアウト用ワークスペースを選択し、移動前のレイアウトを記憶します。",
"help.panel.activate": "キーボードフォーカスを要求せずに、開いているパネルのタブを選択します。",
"help.panel.close": "内容のライフサイクルの確認を経てパネルを閉じます。配置は記憶されます。",
"help.panel.collapse": "要求された寸法を保持したまま、パネルのセクションを折りたたむか展開します。",
"help.panel.dismiss": "折りたたんだパネルの一時表示を閉じます。",
"help.panel.float": "パネルを明示的に指定した位置のフローティングセクションに移動します。",
"help.panel.focus": "パネルにフォーカスします。必要に応じて保持された状態を再度開き、セクションを展開します。",
"help.panel.list": "登録済みのパネル種類、確定したインスタンス、アクティブなタブ、利用可否、ホストの機能を確認します。",
"help.panel.move": "パネルを新しいセクションに移動するか、既存のタブグループに追加します。",
"help.panel.native_close": "別ウィンドウのパネルセクションを、内容をキャンセルせずに記憶されたドックに戻します。",
"help.panel.open": "パネルの種類と明示的なインスタンス識別子を指定して開きます。新しいインスタンスには配置を指定します。",
"help.panel.peek": "保存されたサイズや折りたたみ状態を変更せずに、折りたたんだパネルを一時表示します。",
"help.panel.popout": "対応している場合はパネルを別ウィンドウに移動します。ブラウザーではフローティングセクションを使用します。",
"help.panel.reset_pair": "隣接するドックのペアを、共通の制約内で既定のサイズ比率に戻します。",
"help.panel.resize": "すべてのタブの制約内で、パネルセクションの外側の幅と高さを設定します。",
"help.panel.resize_pair": "共有する全体の長さを維持しながら、隣接するドックセクションのサイズを同時に変更します。"
},
"ko": {
"cmd.layout.apply": "레이아웃 적용",
"cmd.layout.get": "레이아웃 확인",
"cmd.layout.reset": "레이아웃 초기화",
"cmd.layout.save": "레이아웃 저장",
"cmd.layout.workspace.select": "레이아웃 작업 공간 선택",
"cmd.panel.activate": "패널 탭 활성화",
"cmd.panel.close": "패널 닫기",
"cmd.panel.collapse": "패널 구역 접기",
"cmd.panel.dismiss": "패널 임시 보기 닫기",
"cmd.panel.float": "패널 띄우기",
"cmd.panel.focus": "패널에 초점 맞추기",
"cmd.panel.list": "패널 목록",
"cmd.panel.move": "패널 이동",
"cmd.panel.native_close": "별도 창의 패널 구역 다시 도킹",
"cmd.panel.open": "패널 열기",
"cmd.panel.peek": "접힌 패널 임시 보기",
"cmd.panel.popout": "패널을 별도 창으로 이동",
"cmd.panel.reset_pair": "패널 구분선 초기화",
"cmd.panel.resize": "패널 구역 크기 조정",
"cmd.panel.resize_pair": "패널 구분선 이동",
"help.layout.apply": "저장된 레이아웃을 현재 작업 공간에 적용합니다. 유지 중인 편집기의 초안은 보존됩니다.",
"help.layout.get": "확정된 레이아웃과 등록된 작업 공간을 확인합니다.",
"help.layout.reset": "현재 작업 공간에 등록된 기본 레이아웃을 복원합니다. 사용자 사전 설정은 유지됩니다.",
"help.layout.save": "전체 레이아웃에 이름을 지정해 저장합니다. 사용자 사전 설정을 바꾸려면 명시적인 덮어쓰기 허용이 필요합니다.",
"help.layout.workspace.select": "등록된 레이아웃 작업 공간을 선택하고 이전 레이아웃을 기억합니다.",
"help.panel.activate": "키보드 초점을 요청하지 않고 열린 패널 탭을 선택합니다.",
"help.panel.close": "콘텐츠 수명 주기 검사를 거쳐 패널을 닫습니다. 배치는 기억됩니다.",
"help.panel.collapse": "요청한 치수를 유지하면서 패널 구역을 접거나 펼칩니다.",
"help.panel.dismiss": "접힌 패널의 임시 보기를 닫습니다.",
"help.panel.float": "패널을 위치가 명시된 부동 구역으로 이동합니다.",
"help.panel.focus": "패널에 초점을 맞춥니다. 필요하면 유지된 상태를 다시 열고 구역을 펼칩니다.",
"help.panel.list": "등록된 패널 종류, 확정된 인스턴스, 활성 탭, 사용 가능 여부와 호스트 기능을 확인합니다.",
"help.panel.move": "패널을 새 구역으로 이동하거나 기존 탭 그룹에 추가합니다.",
"help.panel.native_close": "콘텐츠를 취소하지 않고 별도 창의 패널 구역을 기억된 도킹 위치로 되돌립니다.",
"help.panel.open": "패널 종류와 명시적인 인스턴스 식별자로 패널을 엽니다. 새 인스턴스에는 배치가 필요합니다.",
"help.panel.peek": "저장된 크기나 접힘 상태를 바꾸지 않고 접힌 패널을 임시로 표시합니다.",
"help.panel.popout": "지원되는 경우 패널을 별도 창으로 이동합니다. 브라우저에서는 부동 구역을 사용합니다.",
"help.panel.reset_pair": "인접한 도킹 구역 쌍을 공통 제약 안에서 기본 크기 비율로 복원합니다.",
"help.panel.resize": "모든 탭의 제약 안에서 패널 구역의 바깥 너비와 높이를 설정합니다.",
"help.panel.resize_pair": "공유하는 전체 길이를 유지하면서 인접한 도킹 구역의 크기를 함께 조정합니다."
},
"vi": {
"cmd.layout.apply": "Áp dụng bố cục",
"cmd.layout.get": "Kiểm tra bố cục",
"cmd.layout.reset": "Đặt lại bố cục",
"cmd.layout.save": "Lưu bố cục",
"cmd.layout.workspace.select": "Chọn không gian làm việc của bố cục",
"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",
"cmd.panel.dismiss": "Đóng chế độ xem tạm của bảng",
"cmd.panel.float": "Thả nổi bảng",
"cmd.panel.focus": "Đặt tiêu điểm vào bảng",
"cmd.panel.list": "Liệt kê các bảng",
"cmd.panel.move": "Di chuyển bảng",
"cmd.panel.native_close": "Gắn lại vùng bảng từ cửa sổ riêng",
"cmd.panel.open": "Mở bảng",
"cmd.panel.peek": "Xem tạm bảng đã thu gọn",
"cmd.panel.popout": "Chuyển bảng sang cửa sổ riêng",
"cmd.panel.reset_pair": "Đặt lại thanh chia bảng",
"cmd.panel.resize": "Đổi kích thước vùng bảng",
"cmd.panel.resize_pair": "Di chuyển thanh chia bảng",
"help.layout.apply": "Áp dụng bố cục đã lưu cho không gian làm việc hiện tại. Các trình chỉnh sửa được giữ lại vẫn giữ bản nháp.",
"help.layout.get": "Đọc bố cục đã xác nhận và xem các không gian làm việc đã đăng ký.",
"help.layout.reset": "Khôi phục bố cục mặc định đã đăng ký của không gian làm việc hiện tại. Các thiết lập sẵn của người dùng vẫn được giữ lại.",
"help.layout.save": "Lưu toàn bộ bố cục với một tên. Việc thay thế thiết lập sẵn của người dùng cần được cho phép ghi đè rõ ràng.",
"help.layout.workspace.select": "Chọn không gian làm việc của bố cục đã đăng ký và ghi nhớ bố cục trước đó.",
"help.panel.activate": "Chọn một thẻ bảng đang mở mà không yêu cầu tiêu điểm bàn phím.",
"help.panel.close": "Đóng bảng sau khi kiểm tra vòng đời nội dung. Vị trí của bảng được ghi nhớ.",
"help.panel.collapse": "Thu gọn hoặc mở rộng vùng bảng trong khi giữ nguyên các kích thước đã yêu cầu.",
"help.panel.dismiss": "Đóng chế độ xem tạm thời của bảng đã thu gọn.",
"help.panel.float": "Di chuyển bảng vào một vùng thả nổi có vị trí được chỉ định rõ ràng.",
"help.panel.focus": "Đặt tiêu điểm vào bảng, mở lại trạng thái được giữ và mở rộng vùng của bảng khi cần.",
"help.panel.list": "Đọc các loại bảng đã đăng ký, các phiên bản đã xác nhận, thẻ đang hoạt động, tính khả dụng và khả năng của môi trường chứa.",
"help.panel.move": "Di chuyển bảng vào vùng mới hoặc thêm vào nhóm thẻ hiện có.",
"help.panel.native_close": "Đưa vùng bảng từ cửa sổ riêng về vị trí gắn đã ghi nhớ mà không hủy nội dung.",
"help.panel.open": "Mở một loại bảng với mã phiên bản rõ ràng. Phiên bản mới cần được chỉ định vị trí.",
"help.panel.peek": "Tạm hiển thị bảng đã thu gọn mà không thay đổi kích thước đã lưu hoặc trạng thái thu gọn.",
"help.panel.popout": "Di chuyển bảng sang cửa sổ riêng khi được hỗ trợ. Trình duyệt sử dụng vùng thả nổi.",
"help.panel.reset_pair": "Khôi phục tỷ lệ kích thước mặc định của hai vùng gắn liền kề trong giới hạn chung.",
"help.panel.resize": "Đặt chiều rộng và chiều cao bên ngoài của vùng bảng trong giới hạn của mọi thẻ.",
"help.panel.resize_pair": "Đổi kích thước các vùng gắn liền kề cùng nhau trong khi giữ nguyên tổng chiều dài chung."
},
"zh": {
"cmd.layout.apply": "应用布局",
"cmd.layout.get": "检查布局",
"cmd.layout.reset": "重置布局",
"cmd.layout.save": "保存布局",
"cmd.layout.workspace.select": "选择布局工作区",
"cmd.panel.activate": "激活面板选项卡",
"cmd.panel.close": "关闭面板",
"cmd.panel.collapse": "折叠面板分区",
"cmd.panel.dismiss": "关闭面板临时预览",
"cmd.panel.float": "浮动面板",
"cmd.panel.focus": "聚焦面板",
"cmd.panel.list": "列出面板",
"cmd.panel.move": "移动面板",
"cmd.panel.native_close": "重新停靠独立窗口中的面板分区",
"cmd.panel.open": "打开面板",
"cmd.panel.peek": "临时预览折叠面板",
"cmd.panel.popout": "将面板移至独立窗口",
"cmd.panel.reset_pair": "重置面板分隔条",
"cmd.panel.resize": "调整面板分区大小",
"cmd.panel.resize_pair": "移动面板分隔条",
"help.layout.apply": "将保存的布局应用到当前工作区。保留的编辑器会继续保留其草稿。",
"help.layout.get": "读取已提交的布局并查看已注册的工作区。",
"help.layout.reset": "恢复当前工作区注册的默认布局。用户预设仍会保留。",
"help.layout.save": "为完整布局命名并保存。替换用户预设需要明确允许覆盖。",
"help.layout.workspace.select": "选择已注册的布局工作区,并记住离开前的布局。",
"help.panel.activate": "选择已打开的面板选项卡,而不请求键盘焦点。",
"help.panel.close": "通过内容生命周期检查后关闭面板。其位置会被记住。",
"help.panel.collapse": "折叠或展开面板分区,同时保留所需尺寸。",
"help.panel.dismiss": "关闭折叠面板的临时视图。",
"help.panel.float": "将面板移至位置明确指定的浮动分区。",
"help.panel.focus": "聚焦面板,必要时重新打开其保留状态并展开分区。",
"help.panel.list": "读取已注册的面板种类、已提交的实例、活动选项卡、可用状态和宿主能力。",
"help.panel.move": "将面板移至新分区,或加入现有的选项卡组。",
"help.panel.native_close": "将独立窗口中的面板分区返回记住的停靠位置,而不取消其内容。",
"help.panel.open": "使用明确的实例标识打开指定种类的面板。新实例需要指定位置。",
"help.panel.peek": "临时显示折叠的面板,而不更改保存的尺寸或折叠状态。",
"help.panel.popout": "支持时将面板移至独立窗口。浏览器宿主会使用浮动分区。",
"help.panel.reset_pair": "在共同约束内恢复相邻停靠分区对的默认尺寸比例。",
"help.panel.resize": "在所有选项卡的约束内设置面板分区的外部宽度和高度。",
"help.panel.resize_pair": "同时调整相邻停靠分区的尺寸,并保持其共同总长度。"
}
}
+15 -2
View File
@@ -33,7 +33,7 @@ impl Refusal {
/// The batch reply for a batch refused before its first step: as a failed step's reply,
/// with nothing completed, nothing undone and every step not run.
pub fn reply(&self, steps: usize) -> Value {
json!({
let mut reply = json!({
"completed": 0,
"results": [],
"failed": {"index": self.index, "command": self.command, "error": self.error},
@@ -41,7 +41,11 @@ impl Refusal {
"rolled_back": false,
"not_run": (0..steps).collect::<Vec<_>>(),
"note": "nothing was run: the batch was checked before its first step",
})
});
if let Some(reason) = crate::panels::commands::structured_error(&self.error) {
reply["failed"]["panel_error"] = reason;
}
reply
}
}
@@ -82,6 +86,15 @@ pub fn contracts(steps: &[Value]) -> Option<Refusal> {
/// Step `index`'s refusal when its parameters break the typed contract of its command `id`.
fn contract_refusal(index: usize, id: &str, step: &Value) -> Option<Refusal> {
if crate::panels::commands::is_command(id) {
let empty = json!({});
let params = step.get("params").filter(|p| !p.is_null()).unwrap_or(&empty);
return crate::panels::commands::parse_command(id, params).err().map(|reason| Refusal {
index,
command: Some(id.into()),
error: crate::panels::commands::error_text(reason),
});
}
let first = crate::schema::issues(id, step.get("params").unwrap_or(&Value::Null)).into_iter().next()?;
Some(Refusal { index, command: Some(id.to_string()), error: crate::params::bad(id, first.message).to_string() })
}
+2
View File
@@ -87,6 +87,7 @@ pub(crate) use measure_sel::{measure_items, shape_of};
pub(crate) use measure_shape::Shape;
#[cfg(test)]
mod kernel_heal_tests;
mod panels;
mod parameter_sweep;
mod parameters;
mod plastic;
@@ -340,6 +341,7 @@ pub fn command_specs() -> Vec<&'static CommandSpec> {
v.extend(joints::COMMANDS.iter());
v.extend(clearance::COMMANDS.iter());
v.extend(motion::COMMANDS.iter());
v.extend(panels::COMMANDS.iter());
v.extend(config::COMMANDS.iter());
v.extend(parts::COMMANDS.iter());
v.extend(bom::COMMANDS.iter());
+175
View File
@@ -0,0 +1,175 @@
//! Registry metadata for externally injected application-layout commands.
use super::CommandSpec;
use crate::schema::panels as wire;
fn unavailable(_: &mut crate::Session, _: &serde_json::Value) -> crate::Result<serde_json::Value> {
Err(crate::EngineError::Panel(crate::panels::error(crate::panels::Rule::Capability, "application layout backend was not injected")))
}
macro_rules! command {
($id:literal, $icon:literal, $label:literal, $input:ty, $output:ty, $params:literal) => {
CommandSpec::new($id, $label, crate::checked!($id, unavailable))
.icon($icon)
.noundo()
.doc_only()
.contract(&wire::CommandContract::<$input>::new($id))
.output(wire::strict_output::<$output>)
.params($params)
};
}
pub static COMMANDS: &[CommandSpec] = &[
command!(
"layout.apply",
"open",
"Apply Layout",
wire::Apply,
crate::panels::LayoutReply,
"name, expected_revision?: apply preset to current workspace through retained runtime"
),
command!("layout.get", "list", "Inspect Layout", wire::Empty, wire::GetReply, "{}: committed state and registered workspace summaries"),
command!(
"layout.reset",
"restore",
"Reset Layout",
wire::Revision,
crate::panels::LayoutReply,
"expected_revision?: restore current workspace's registered default"
),
command!(
"layout.save",
"save",
"Save Layout",
wire::Save,
wire::SaveReply,
"name, overwrite?: false, expected_revision?: save complete envelope in injected catalogue"
),
command!(
"layout.workspace.select",
"display",
"Select Layout Workspace",
wire::WorkspaceSelect,
wire::WorkspaceReply,
"workspace, expected_revision?: atomically remember outgoing and replace with destination"
),
command!(
"panel.activate",
"activate",
"Activate Panel Tab",
wire::Select,
crate::panels::LayoutReply,
"target or legacy id, expected_revision?: activate open tab without focus"
),
command!(
"panel.close",
"close",
"Close Panel",
wire::Select,
crate::panels::LayoutReply,
"target or legacy id, expected_revision?: explicit guarded close"
),
command!(
"panel.collapse",
"fold",
"Collapse Panel Section",
wire::Collapse,
crate::panels::LayoutReply,
"target or legacy id, collapsed, expected_revision?"
),
command!(
"panel.dismiss",
"close",
"Dismiss Panel Peek",
wire::Revision,
crate::panels::LayoutReply,
"expected_revision?: dismiss temporary collapsed-panel presentation"
),
command!(
"panel.float",
"move",
"Float Panel",
wire::Move,
crate::panels::LayoutReply,
"target or legacy id, destination: new_section with floating location, expected_revision?"
),
command!(
"panel.focus",
"fit",
"Focus Panel",
wire::Select,
crate::panels::LayoutReply,
"target or legacy id, expected_revision?: reopen retained state, activate and request focus"
),
command!(
"panel.list",
"list",
"List Panels",
wire::Empty,
wire::ListReply,
"{}: committed state, active tabs, capabilities, availability and registered kinds"
),
command!(
"panel.move",
"move",
"Move Panel",
wire::Move,
crate::panels::LayoutReply,
"target or legacy id, destination: new_section or join_tab, expected_revision?"
),
command!(
"panel.native_close",
"restore",
"Redock Native Panel Section",
wire::Select,
crate::panels::LayoutReply,
"target: native_host, expected_revision?: native close redocks without cancelling content"
),
command!(
"panel.open",
"open",
"Open Panel",
wire::Open,
crate::panels::LayoutReply,
"kind, instance, destination?: required for new instance, expected_revision?"
),
command!(
"panel.peek",
"eye",
"Peek Collapsed Panel",
wire::Select,
crate::panels::LayoutReply,
"target or legacy id, expected_revision?: transient presentation without resizing"
),
command!(
"panel.popout",
"display",
"Pop Out Panel",
wire::Move,
crate::panels::LayoutReply,
"target or legacy id, destination: new_section with window location, expected_revision?: web lowers to floating"
),
command!(
"panel.reset_pair",
"restore",
"Reset Panel Sash",
wire::ResetPair,
crate::panels::LayoutReply,
"first, second, expected_revision?: reset adjacent dock pair to registered default ratio"
),
command!(
"panel.resize",
"scale",
"Resize Panel Section",
wire::Resize,
crate::panels::LayoutReply,
"target or legacy id, size: {width,height}, expected_revision?"
),
command!(
"panel.resize_pair",
"scale",
"Resize Panel Sash",
wire::ResizePair,
crate::panels::LayoutReply,
"first, second, first_size, second_size, expected_revision?: conserve adjacent dock pair extent"
),
];
+5 -3
View File
@@ -81,9 +81,11 @@ fn classify(e: &EngineError) -> Outcome {
let msg = e.to_string();
match e {
EngineError::Internal(..) => Outcome::new("panic", msg),
EngineError::BadParams { .. } | EngineError::Disabled(..) | EngineError::Refused { .. } | EngineError::UnknownCommand(_) => {
Outcome::new("rejected", msg)
}
EngineError::Panel(_)
| EngineError::BadParams { .. }
| EngineError::Disabled(..)
| EngineError::Refused { .. }
| EngineError::UnknownCommand(_) => Outcome::new("rejected", msg),
// A failed boolean is a failure even when it says "not supported": those are the cases
// to fix. Features the kernel doesn't do yet are limitations.
// Picks the generator got wrong (a centroid off its face).
+9
View File
@@ -21,6 +21,7 @@ pub mod frames;
pub mod fuzz;
pub mod licences;
pub mod occurrences;
pub mod panels;
pub mod params;
pub mod product_scene;
pub mod recovery;
@@ -66,6 +67,8 @@ pub const MAX_LINE: usize = 16 << 20;
#[derive(Debug, thiserror::Error)]
pub enum EngineError {
#[error("{text}", text = panels::commands::error_text(.0.clone()))]
Panel(#[from] panels::PanelError),
#[error("unknown command `{0}`{hint}", hint = cmd::did_you_mean(.0))]
UnknownCommand(String),
#[error("`{0}` is not available right now: {1}")]
@@ -1610,6 +1613,12 @@ impl Session {
/// the model up to date before anything reads it.
pub fn execute(&mut self, id: &str, params: &Value) -> Result<Value> {
let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?;
if panels::commands::is_command(spec.id) {
// Layout is application state. Even a missing capability must not
// clear live links, map picks, snapshot, evaluate or refresh a design.
panels::commands::parse_command(spec.id, params)?;
return Err(EngineError::Panel(panels::error(panels::Rule::Capability, "application layout backend was not injected")));
}
// The command, the evaluation it causes and the refresh after it: one profiler span.
let _span = solidcraft_profile::span("command", spec.id);
let host_viewport = self.render_viewport.clone();
+946
View File
@@ -0,0 +1,946 @@
//! Application-owned command execution shared by UI, control and headless MCP.
//! No Session, document, geometry, dialogs or camera are reachable here.
mod catalogue;
use std::collections::BTreeMap;
use std::sync::Arc;
use serde::de::DeserializeOwned;
use serde_json::{Value, json};
use super::*;
use crate::schema::panels as wire;
pub const MAX_USER_PRESETS: usize = 64;
pub const MAX_WORKSPACES: usize = 64;
pub const MAX_CATALOGUE_BYTES: usize = 4 * 1024 * 1024;
pub const MAX_CATALOGUE_METADATA_BYTES: usize = 16 * 1024;
/// Framing is bounded separately from the aggregate payload/metadata budgets.
pub const MAX_CATALOGUE_SNAPSHOT_BYTES: usize = MAX_CATALOGUE_BYTES + MAX_CATALOGUE_METADATA_BYTES + 8192;
pub const MAX_COMMAND_BYTES: usize = 16 * 1024;
/// Full envelope plus bounded rejected recovery intent. Arc makes catalogue
/// preparation bounded without copying each maximum-sized envelope 64 times.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StoredEnvelope {
bytes: Arc<[u8]>,
rejected: Option<Arc<[u8]>>,
}
impl StoredEnvelope {
pub fn new(envelope: &LayoutEnvelope, rejected: Option<&[u8]>, registry: &PanelRegistry) -> PanelResult<Self> {
if rejected.is_some_and(|bytes| bytes.len() > MAX_ENVELOPE_BYTES) {
return Err(error(Rule::CollectionLimit, "rejected recovery byte cap"));
}
Ok(Self { bytes: encode(envelope, registry)?.into(), rejected: rejected.map(Arc::from) })
}
/// Exact retained inspection, including saved instances whose kinds are now
/// absent. This is not a live-layout admission check; stage with
/// `project_envelope` before submitting through the authoritative sink.
pub fn envelope(&self, registry: &PanelRegistry, workspace: &WorkspaceId) -> PanelResult<LayoutEnvelope> {
decode_retained(&self.bytes, registry, workspace)
}
/// Explicitly stage current-registry quarantine before a guarded live use.
/// Exact inspection above deliberately keeps absent-kind saved instances.
pub fn project_envelope(&self, registry: &PanelRegistry, workspace: &WorkspaceId) -> PanelResult<LayoutEnvelope> {
project_retained_record(&self.bytes, registry, workspace)
}
/// Hydration retains the original validated bytes. In particular, optional
/// order/projection metadata is not filled and recounted against the cap.
fn from_record(bytes: &[u8], rejected: Option<&[u8]>, registry: &PanelRegistry) -> PanelResult<Self> {
if rejected.is_some_and(|bytes| bytes.len() > MAX_ENVELOPE_BYTES) {
return Err(error(Rule::CollectionLimit, "rejected recovery byte cap"));
}
decode_retained_record(bytes, registry)?;
Ok(Self { bytes: Arc::from(bytes), rejected: rejected.map(Arc::from) })
}
pub fn rejected(&self) -> Option<&[u8]> {
self.rejected.as_deref()
}
pub fn bytes(&self) -> &[u8] {
&self.bytes
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WorkspaceDescriptor {
pub id: WorkspaceId,
pub title_key: String,
pub default_preset: String,
}
/// Fields are private: registrations and prepared updates must obey aggregate
/// bounds before cloning or publishing. There is no independently stored selection.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct CatalogueState {
workspaces: BTreeMap<WorkspaceId, WorkspaceDescriptor>,
builtins: BTreeMap<String, StoredEnvelope>,
users: BTreeMap<String, StoredEnvelope>,
remembered: BTreeMap<WorkspaceId, StoredEnvelope>,
}
impl CatalogueState {
pub fn summaries(&self) -> Vec<wire::WorkspaceSummary> {
self.workspaces
.values()
.map(|item| wire::WorkspaceSummary {
id: item.id.clone(),
title_key: item.title_key.clone(),
default_preset: item.default_preset.clone(),
has_remembered_layout: self.remembered.contains_key(&item.id),
})
.collect()
}
pub fn user_count(&self) -> usize {
self.users.len()
}
pub fn user_presets(&self) -> impl Iterator<Item = (&str, &StoredEnvelope)> {
self.users.iter().map(|(name, record)| (name.as_str(), record))
}
pub fn remembered(&self, workspace: &WorkspaceId) -> Option<&StoredEnvelope> {
self.remembered.get(workspace)
}
pub fn preset(&self, name: &str) -> PanelResult<&StoredEnvelope> {
self.builtins.get(name).or_else(|| self.users.get(name)).ok_or_else(|| error(Rule::MissingTarget, "layout preset not registered"))
}
fn validate(&self) -> PanelResult<()> {
if self.users.keys().any(|name| self.builtins.contains_key(name)) {
return Err(error(Rule::DuplicateId, "user preset collides with immutable built-in"));
}
if self.users.len() > MAX_USER_PRESETS
|| self.builtins.len() > MAX_USER_PRESETS
|| self.workspaces.len() > MAX_WORKSPACES
|| self.remembered.len() > MAX_WORKSPACES
{
return Err(error(Rule::CollectionLimit, "layout catalogue count cap"));
}
let mut metadata = 0_usize;
for (id, item) in &self.workspaces {
valid_id(&id.0)?;
valid_id(&item.title_key)?;
if item.id != *id || !self.builtins.contains_key(&item.default_preset) {
return Err(error(Rule::MissingTarget, "workspace requires a registered immutable default"));
}
metadata = metadata.saturating_add(id.0.len() + item.title_key.len() + item.default_preset.len());
}
let mut bytes = 0_usize;
for (name, stored) in self.builtins.iter().chain(&self.users) {
if preset_name(name)? != *name {
return Err(error(Rule::Schema, "preset name must be normalised"));
}
metadata = metadata.saturating_add(name.len());
bytes = bytes.saturating_add(stored.bytes.len() + stored.rejected.as_ref().map_or(0, |r| r.len()));
}
for (id, stored) in &self.remembered {
valid_id(&id.0)?;
metadata = metadata.saturating_add(id.0.len());
bytes = bytes.saturating_add(stored.bytes.len() + stored.rejected.as_ref().map_or(0, |r| r.len()));
}
if metadata > MAX_CATALOGUE_METADATA_BYTES || bytes > MAX_CATALOGUE_BYTES {
return Err(error(Rule::CollectionLimit, "aggregate layout catalogue byte cap"));
}
Ok(())
}
}
pub struct PreparedCatalogue(CatalogueState);
impl PreparedCatalogue {
pub fn new(state: CatalogueState) -> PanelResult<Self> {
state.validate()?;
Ok(Self(state))
}
pub fn state(&self) -> &CatalogueState {
&self.0
}
pub fn into_state(self) -> CatalogueState {
self.0
}
}
/// Prepare MUST stage every fallible storage operation. Publish MUST be infallible.
/// The executor holds the exclusive catalogue borrow across guarded dispatch.
pub trait LayoutCatalogue {
fn state(&self) -> &CatalogueState;
fn prepare(&mut self, next: CatalogueState) -> PanelResult<PreparedCatalogue>;
fn publish(&mut self, prepared: PreparedCatalogue);
}
#[derive(Default)]
pub struct InMemoryCatalogue {
state: CatalogueState,
/// Failure-injectable storage staging; no state has been published on failure.
pub fail_stage: bool,
}
impl LayoutCatalogue for InMemoryCatalogue {
fn state(&self) -> &CatalogueState {
&self.state
}
fn prepare(&mut self, next: CatalogueState) -> PanelResult<PreparedCatalogue> {
if self.fail_stage {
return Err(error(Rule::Capability, "layout storage staging unavailable"));
}
PreparedCatalogue::new(next)
}
fn publish(&mut self, prepared: PreparedCatalogue) {
self.state = prepared.into_state();
}
}
impl InMemoryCatalogue {
/// Hydration builds a validated candidate, without live dispatch or changing
/// the mutability of saved user presets. Production storage remains external.
pub fn from_snapshot(bytes: &[u8], registry: &PanelRegistry) -> PanelResult<Self> {
Ok(Self { state: CatalogueState::hydrate(bytes, registry)?, fail_stage: false })
}
/// Explicit fixture/peer registration, never populated with invented products.
pub fn register_builtin(&mut self, name: &str, envelope: &LayoutEnvelope, registry: &PanelRegistry) -> PanelResult<()> {
let name = preset_name(name)?;
if self.state.builtins.contains_key(&name) || self.state.users.contains_key(&name) {
return Err(error(Rule::DuplicateId, "preset already registered"));
}
let stored = StoredEnvelope::new(envelope, None, registry)?;
let mut next = self.state.clone();
next.builtins.insert(name, stored);
let prepared = self.prepare(next)?;
self.publish(prepared);
Ok(())
}
pub fn register_workspace(&mut self, descriptor: WorkspaceDescriptor) -> PanelResult<()> {
valid_id(&descriptor.id.0)?;
valid_id(&descriptor.title_key)?;
if self.state.workspaces.contains_key(&descriptor.id) {
return Err(error(Rule::DuplicateId, "workspace already registered"));
}
let mut next = self.state.clone();
next.workspaces.insert(descriptor.id.clone(), descriptor);
let prepared = self.prepare(next)?;
self.publish(prepared);
Ok(())
}
pub fn remember(&mut self, envelope: &LayoutEnvelope, rejected: Option<&[u8]>, registry: &PanelRegistry) -> PanelResult<()> {
let stored = StoredEnvelope::new(envelope, rejected, registry)?;
let mut next = self.state.clone();
next.remembered.insert(envelope.layout.workspace.clone(), stored);
let prepared = self.prepare(next)?;
self.publish(prepared);
Ok(())
}
}
pub fn preset_name(raw: &str) -> PanelResult<String> {
// Bound BEFORE trimming, allocating or iterating over scalars.
if raw.len() > 1024 {
return Err(error(Rule::CollectionLimit, "raw preset name byte cap"));
}
let name = raw.trim();
if name.is_empty() || name.len() > 256 || name.chars().count() > 64 || raw.chars().any(char::is_control) {
return Err(error(Rule::Schema, "preset name requires 1..64 Unicode scalars without controls"));
}
Ok(name.into())
}
pub fn is_command(id: &str) -> bool {
crate::find_command(id).is_some_and(|spec| IDS.contains(&spec.id))
}
pub const IDS: &[&str] = &[
"layout.apply",
"layout.get",
"layout.reset",
"layout.save",
"layout.workspace.select",
"panel.activate",
"panel.close",
"panel.collapse",
"panel.dismiss",
"panel.float",
"panel.focus",
"panel.list",
"panel.move",
"panel.native_close",
"panel.open",
"panel.peek",
"panel.popout",
"panel.reset_pair",
"panel.resize",
"panel.resize_pair",
];
#[derive(Debug)]
pub enum PanelCommand {
List,
Get,
Open(wire::Open),
Select { operation: &'static str, params: wire::Select },
Move { operation: &'static str, params: wire::Move },
Resize(wire::Resize),
Collapse(wire::Collapse),
Dismiss(wire::Revision),
ResizePair(wire::ResizePair),
ResetPair(wire::ResetPair),
Save(wire::Save),
Apply(wire::Apply),
Reset(wire::Revision),
Workspace(wire::WorkspaceSelect),
}
fn read<T: DeserializeOwned>(value: &Value) -> PanelResult<T> {
serde_json::from_value(value.clone()).map_err(|_| error(Rule::Schema, "invalid panel command fields or types"))
}
pub fn parse_command(id: &str, params: &Value) -> PanelResult<PanelCommand> {
// Keep the engine/control convention: absent/null params mean an empty form.
let empty = json!({});
let params = if params.is_null() { &empty } else { params };
if !params.is_object() {
return Err(error(Rule::Schema, "panel command parameters must be an object"));
}
bounded_json(params)?;
// Capped writer protects direct callers as well as transports, before clone.
struct Counter(usize);
impl std::io::Write for Counter {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
self.0 = self.0.saturating_add(bytes.len());
if self.0 > MAX_COMMAND_BYTES {
return Err(std::io::Error::other("command byte cap"));
}
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
serde_json::to_writer(Counter(0), params).map_err(|_| error(Rule::CollectionLimit, "panel command byte cap"))?;
let id = crate::find_command(id).map(|s| s.id).ok_or_else(|| error(Rule::MissingTarget, "unknown panel command"))?;
let command = match id {
"panel.list" => {
let _: wire::Empty = read(params)?;
PanelCommand::List
}
"layout.get" => {
let _: wire::Empty = read(params)?;
PanelCommand::Get
}
"panel.open" => PanelCommand::Open(read(params)?),
"panel.close" | "panel.activate" | "panel.focus" | "panel.peek" | "panel.native_close" => {
PanelCommand::Select { operation: id, params: read(params)? }
}
"panel.move" | "panel.float" | "panel.popout" => PanelCommand::Move { operation: id, params: read(params)? },
"panel.resize" => PanelCommand::Resize(read(params)?),
"panel.collapse" => PanelCommand::Collapse(read(params)?),
"panel.dismiss" => PanelCommand::Dismiss(read(params)?),
"panel.resize_pair" => PanelCommand::ResizePair(read(params)?),
"panel.reset_pair" => PanelCommand::ResetPair(read(params)?),
"layout.save" => PanelCommand::Save(read(params)?),
"layout.apply" => PanelCommand::Apply(read(params)?),
"layout.reset" => PanelCommand::Reset(read(params)?),
"layout.workspace.select" => PanelCommand::Workspace(read(params)?),
_ => return Err(error(Rule::MissingTarget, "not an application layout command")),
};
// Validate hostile values even when no application capability is injected.
validate_command(&command)?;
Ok(command)
}
fn validate_selector(target: &Option<wire::Target>, id: &Option<String>) -> PanelResult<()> {
match (target, id) {
(Some(target), None) => match target {
wire::Target::Instance(id) => valid_id(&id.0),
wire::Target::Section(id) => valid_id(&id.0),
wire::Target::Workspace(id) => valid_id(&id.0),
wire::Target::NativeHost(id) => valid_id(&id.0),
},
(None, Some(id)) => valid_id(id),
_ => Err(error(Rule::Schema, "supply exactly one typed target or legacy id")),
}
}
fn validate_destination(destination: Destination) -> PanelResult<()> {
match destination {
Destination::NewSection { section, index, location, size } => {
valid_id(&section.0)?;
location.validate()?;
size.validate()?;
if index > MAX_SECTIONS {
return Err(error(Rule::Bounds, "section index cap"));
}
}
Destination::JoinTab { section, index } => {
valid_id(&section.0)?;
if index >= MAX_TABS {
return Err(error(Rule::Bounds, "tab index cap"));
}
}
}
Ok(())
}
fn validate_command(command: &PanelCommand) -> PanelResult<()> {
match command {
PanelCommand::Open(p) => {
valid_id(&p.kind.0)?;
valid_id(&p.instance.0)?;
if let Some(destination) = &p.destination {
validate_destination(destination.clone().into())?;
}
}
PanelCommand::Select { params, .. } => validate_selector(&params.target, &params.id)?,
PanelCommand::Move { params, .. } => {
validate_selector(&params.target, &params.id)?;
validate_destination(params.destination.clone().into())?;
}
PanelCommand::Resize(p) => {
validate_selector(&p.target, &p.id)?;
Size::from(p.size).validate()?;
}
PanelCommand::Collapse(p) => validate_selector(&p.target, &p.id)?,
PanelCommand::ResizePair(p) => {
valid_id(&p.first.0)?;
valid_id(&p.second.0)?;
Size::from(p.first_size).validate()?;
Size::from(p.second_size).validate()?;
}
PanelCommand::ResetPair(p) => {
valid_id(&p.first.0)?;
valid_id(&p.second.0)?;
}
PanelCommand::Save(p) => {
preset_name(&p.name)?;
}
PanelCommand::Apply(p) => {
preset_name(&p.name)?;
}
PanelCommand::Workspace(p) => valid_id(&p.workspace.0)?,
_ => {}
}
Ok(())
}
pub struct PanelCommandContext<'a> {
pub sink: &'a mut dyn ActionSink,
pub registry: &'a PanelRegistry,
pub catalogue: &'a mut dyn LayoutCatalogue,
/// Web popout is an explicit host policy, never inferred from no native support.
pub web: bool,
}
fn target(target: Option<wire::Target>, legacy: Option<String>, layout: &Layout, registry: &PanelRegistry) -> PanelResult<LayoutTarget> {
if let Some(target) = target {
return Ok(target.into());
}
let id = legacy.ok_or_else(|| error(Rule::Schema, "target required"))?;
let instance = InstanceId::new(id.clone())?;
if layout.instance(&instance).is_ok() {
return Ok(LayoutTarget::Instance(instance));
}
let kind = PanelKind::new(id)?;
let spec = registry.get(&kind)?;
if spec.features.multi_instance {
return Err(error(Rule::ExactlyOnce, "kind selector is ambiguous for multi-instance panels; supply typed instance"));
}
let matches: Vec<_> = layout.instances.iter().filter(|p| p.kind == kind).collect();
if matches.len() != 1 {
return Err(error(Rule::MissingTarget, "kind requires one canonical retained instance"));
}
Ok(LayoutTarget::Instance(matches.first().ok_or_else(|| error(Rule::MissingTarget, "canonical instance absent"))?.id.clone()))
}
fn instance(target: LayoutTarget, layout: &Layout) -> PanelResult<InstanceId> {
match target {
LayoutTarget::Instance(id) => {
layout.instance(&id)?;
Ok(id)
}
_ => Err(error(Rule::Schema, "operation requires instance target")),
}
}
fn section(target: LayoutTarget, layout: &Layout) -> PanelResult<SectionId> {
match target {
LayoutTarget::Section(id) => {
layout.section(&id)?;
Ok(id)
}
LayoutTarget::Instance(id) => Ok(layout.containing(&id)?.id.clone()),
_ => Err(error(Rule::Schema, "operation requires section or open instance target")),
}
}
fn revision(expected: Option<u64>, state: &LayoutReply) -> PanelResult<()> {
if expected.is_some_and(|r| r != state.revision) {
return Err(error(Rule::Revision, "stale layout revision"));
}
Ok(())
}
fn lower(command: PanelCommand, state: &LayoutReply, registry: &PanelRegistry, web: bool) -> PanelResult<Mutation> {
let layout = &state.layout;
Ok(match command {
PanelCommand::Open(p) => {
revision(p.expected_revision, state)?;
Mutation::Open { kind: p.kind, instance: p.instance, destination: p.destination.map(Into::into) }
}
PanelCommand::Select { operation, params: p } => {
revision(p.expected_revision, state)?;
let selected = target(p.target, p.id, layout, registry)?;
if operation == "panel.native_close" {
let LayoutTarget::NativeHost(host) = selected else {
return Err(error(Rule::Schema, "native close requires typed native_host target"));
};
Mutation::NativeClose { host }
} else {
let instance = instance(selected, layout)?;
match operation {
"panel.close" => Mutation::Close { instance },
"panel.focus" => Mutation::Focus { instance },
"panel.activate" => Mutation::Activate { instance },
"panel.peek" => Mutation::Peek { instance },
_ => return Err(error(Rule::Schema, "unknown target operation")),
}
}
}
PanelCommand::Move { operation, params: p } => {
revision(p.expected_revision, state)?;
let instance = instance(target(p.target, p.id, layout, registry)?, layout)?;
let mut destination: Destination = p.destination.into();
if operation == "panel.float" && !matches!(&destination, Destination::NewSection { location: SectionLocation::Floating { .. }, .. }) {
return Err(error(Rule::Placement, "panel.float requires new_section with floating location"));
}
if operation == "panel.popout" {
if !registry.get(&layout.instance(&instance)?.kind)?.features.popout {
return Err(error(Rule::FeatureDisabled, "panel cannot pop out"));
}
match &mut destination {
Destination::NewSection { location, .. } => match location {
SectionLocation::Window { origin, .. } => {
if web {
*location = SectionLocation::Floating { origin: *origin };
}
}
_ => return Err(error(Rule::Placement, "panel.popout requires new_section with window location")),
},
_ => return Err(error(Rule::Placement, "panel.popout requires a new section")),
}
}
Mutation::Move { instance, destination }
}
PanelCommand::Resize(p) => {
revision(p.expected_revision, state)?;
Mutation::SetSize { section: section(target(p.target, p.id, layout, registry)?, layout)?, size: p.size.into() }
}
PanelCommand::Collapse(p) => {
revision(p.expected_revision, state)?;
Mutation::Collapse { section: section(target(p.target, p.id, layout, registry)?, layout)?, collapsed: p.collapsed }
}
PanelCommand::Dismiss(p) => {
revision(p.expected_revision, state)?;
Mutation::DismissPeek
}
PanelCommand::ResizePair(p) => {
revision(p.expected_revision, state)?;
Mutation::ResizePair { first: p.first, second: p.second, first_size: p.first_size.into(), second_size: p.second_size.into() }
}
PanelCommand::ResetPair(p) => {
revision(p.expected_revision, state)?;
Mutation::ResetPair { first: p.first, second: p.second }
}
_ => return Err(error(Rule::Capability, "catalogue/query commands require individual transactions")),
})
}
fn current_envelope(catalogue: &CatalogueState, state: &LayoutReply, registry: &PanelRegistry) -> PanelResult<(LayoutEnvelope, Option<Arc<[u8]>>)> {
let workspace = &state.layout.workspace;
match catalogue.remembered.get(workspace) {
Some(stored) => {
Ok((with_live_layout(&stored.project_envelope(registry, workspace)?, state.layout.clone(), registry)?, stored.rejected.clone()))
}
None => Ok((LayoutEnvelope::new(state.layout.clone()), None)),
}
}
/// Preserve all opaque sidecars. Reusing an identity with different opaque intent
/// is an error, never silently resolved by choosing one preset's value.
fn merge_envelopes(current: &LayoutEnvelope, mut next: LayoutEnvelope, registry: &PanelRegistry) -> PanelResult<LayoutEnvelope> {
next.layout.workspace = current.layout.workspace.clone();
for item in &current.quarantine {
if next.layout.instances.iter().any(|known| known.id == item.instance) {
return Err(error(Rule::DuplicateId, "preset collides with quarantined identity"));
}
match next.quarantine.iter().find(|q| q.instance == item.instance) {
Some(existing) if existing != item => return Err(error(Rule::DuplicateId, "quarantine sidecar collision")),
Some(_) => {}
None => next.quarantine.push(item.clone()),
}
}
for (id, data) in &current.retained_data {
if next.retained_data.get(id).is_some_and(|existing| existing != data) {
return Err(error(Rule::DuplicateId, "retained data collision"));
}
if let (Ok(old), Ok(new)) = (current.layout.instance(id), next.layout.instance(id))
&& old.kind != new.kind
{
return Err(error(Rule::DuplicateId, "retained instance kind collision"));
}
next.retained_data.insert(id.clone(), data.clone());
}
for (id, snapshot) in &current.section_snapshots {
if next.section_snapshots.get(id).is_some_and(|existing| existing != snapshot) {
return Err(error(Rule::DuplicateId, "section sidecar collision"));
}
next.section_snapshots.insert(id.clone(), snapshot.clone());
}
// Preserve dormant gaps from current; subsequent refresh overlays live order.
let dormant: std::collections::BTreeSet<_> = next.quarantine.iter().filter_map(|q| q.section.clone()).collect();
let live: std::collections::BTreeSet<_> = next.layout.sections.iter().map(|s| s.id.clone()).collect();
let mut order: Vec<_> = current.section_order.iter().filter(|id| dormant.contains(*id) || live.contains(*id)).cloned().collect();
for id in &next.section_order {
if !order.contains(id) {
order.push(id.clone());
}
}
next.section_order = order;
let layout = next.layout.clone();
with_live_layout(&next, layout, registry)
}
fn stage_current(
context: &mut PanelCommandContext<'_>,
state: &LayoutReply,
action: &LayoutAction,
envelope: &LayoutEnvelope,
recovery: Option<Arc<[u8]>>,
mut next: CatalogueState,
) -> PanelResult<(LayoutReply, CatalogueState)> {
let projected = context.sink.project(action.clone())?;
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);
let prepared = context.catalogue.prepare(next)?;
// 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 {
return Err(error(Rule::Revision, "layout changed during storage staging"));
}
let committed = if *action == LayoutAction::Inspect {
let current = context.sink.inspect();
revision(Some(state.revision), &current)?;
current
} else {
context.sink.dispatch(action.clone())?
};
context.catalogue.publish(prepared);
Ok((committed, context.catalogue.state().clone()))
}
pub fn execute_command(command: PanelCommand, context: &mut PanelCommandContext<'_>) -> PanelResult<Value> {
validate_command(&command)?;
let state = context.sink.inspect();
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() }),
PanelCommand::Workspace(ref p) if p.workspace == state.layout.workspace => {
revision(p.expected_revision, &state)?;
return value(wire::WorkspaceReply {
previous_workspace: state.layout.workspace.clone(),
source: wire::WorkspaceSource::Unchanged,
state,
});
}
_ => {}
}
let mut next = context.catalogue.state().clone();
let (current, recovery) = current_envelope(&next, &state, context.registry)?;
match command {
PanelCommand::Save(p) => {
revision(p.expected_revision, &state)?;
let name = preset_name(&p.name)?;
if next.builtins.contains_key(&name) {
return Err(error(Rule::Capability, "built-in presets are immutable"));
}
let overwritten = next.users.contains_key(&name);
if overwritten && !p.overwrite {
return Err(error(Rule::DuplicateId, "preset exists; overwrite must be explicit"));
}
if !overwritten && next.users.len() >= MAX_USER_PRESETS {
return Err(error(Rule::CollectionLimit, "user preset count cap"));
}
next.users.insert(name.clone(), StoredEnvelope::new(&current, recovery.as_deref(), context.registry)?);
let action = LayoutAction::Inspect;
let (state, _) = stage_current(context, &state, &action, &current, recovery, next)?;
value(wire::SaveReply { name, overwritten, state })
}
PanelCommand::Apply(p) => {
revision(p.expected_revision, &state)?;
let stored = next.preset(&preset_name(&p.name)?)?;
let mut envelope: LayoutEnvelope =
serde_json::from_slice(stored.bytes()).map_err(|_| error(Rule::Schema, "invalid registered envelope"))?;
// Decode using its original workspace before rebinding to the current one.
envelope = stored.project_envelope(context.registry, &envelope.layout.workspace)?;
let mut envelope = merge_envelopes(&current, envelope, context.registry)?;
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)
}
PanelCommand::Reset(p) => {
revision(p.expected_revision, &state)?;
let descriptor = next
.workspaces
.get(&state.layout.workspace)
.ok_or_else(|| error(Rule::Capability, "selected workspace has no registered default"))?;
let stored = next.preset(&descriptor.default_preset)?;
let raw: LayoutEnvelope = serde_json::from_slice(stored.bytes()).map_err(|_| error(Rule::Schema, "invalid default envelope"))?;
let mut envelope = merge_envelopes(&current, stored.project_envelope(context.registry, &raw.layout.workspace)?, context.registry)?;
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)
}
PanelCommand::Workspace(p) => {
revision(p.expected_revision, &state)?;
let previous_workspace = state.layout.workspace.clone();
if p.workspace == previous_workspace {
return value(wire::WorkspaceReply { previous_workspace, source: wire::WorkspaceSource::Unchanged, state });
}
let descriptor = next.workspaces.get(&p.workspace).ok_or_else(|| error(Rule::MissingTarget, "workspace not registered"))?;
let (stored, source) = match next.remembered.get(&p.workspace) {
Some(stored) => (stored, wire::WorkspaceSource::Remembered),
None => (next.preset(&descriptor.default_preset)?, wire::WorkspaceSource::DefaultPreset),
};
let raw: LayoutEnvelope = serde_json::from_slice(stored.bytes()).map_err(|_| error(Rule::Schema, "invalid workspace envelope"))?;
let mut envelope = stored.project_envelope(context.registry, &raw.layout.workspace)?;
envelope.layout.workspace = p.workspace;
restore_quarantine(&mut envelope, context.registry)?;
let incoming_recovery = stored.rejected.clone();
next.remembered.insert(previous_workspace.clone(), StoredEnvelope::new(&current, 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)?;
value(wire::WorkspaceReply { previous_workspace, source, state })
}
command => {
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, &current, recovery, next)?.0)
}
}
}
fn merge_recovery(first: Option<Arc<[u8]>>, second: Option<Arc<[u8]>>) -> PanelResult<Option<Arc<[u8]>>> {
if first.is_some() && second.is_some() && first != second {
return Err(error(Rule::DuplicateId, "rejected recovery intent collision"));
}
Ok(first.or(second))
}
fn value(value: impl serde::Serialize) -> PanelResult<Value> {
serde_json::to_value(value).map_err(|_| error(Rule::Schema, "cannot encode committed layout reply"))
}
pub fn execute(id: &str, params: &Value, context: &mut PanelCommandContext<'_>) -> PanelResult<Value> {
execute_command(parse_command(id, params)?, context)
}
/// A private transaction planner reuses the common executor and the LIVE sink's
/// pure projection. It owns no reducer or LayoutService and cannot publish live
/// effects. Only the final guarded action and prepared catalogue are published.
struct PlanningSink<'a> {
authoritative: &'a dyn ActionSink,
state: LayoutReply,
mutations: Vec<Mutation>,
replaced: bool,
}
impl ActionSink for PlanningSink<'_> {
fn inspect(&self) -> LayoutReply {
self.state.clone()
}
fn project(&self, action: LayoutAction) -> PanelResult<Layout> {
match action {
LayoutAction::Inspect => Ok(self.state.layout.clone()),
LayoutAction::Replace { expected_revision, layout } => {
revision(expected_revision, &self.state)?;
if !self.mutations.is_empty() {
return Err(error(
Rule::Capability,
"atomic batches cannot combine snapshot replacement and explicit panel mutations; use rollback:false",
));
}
self.authoritative.project(LayoutAction::Replace { expected_revision: Some(self.state.revision), layout })
}
LayoutAction::Apply { expected_revision, mutations } => {
revision(expected_revision, &self.state)?;
if self.replaced {
return Err(error(
Rule::Capability,
"atomic batches cannot combine snapshot replacement and explicit panel mutations; use rollback:false",
));
}
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(LayoutAction::Apply { expected_revision: Some(self.state.revision), mutations: combined })
}
}
}
fn dispatch(&mut self, action: LayoutAction) -> PanelResult<LayoutReply> {
let layout = self.project(action.clone())?;
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.
/// Same-workspace selection remains a no-op and may accompany mutations.
pub fn preflight_batch(steps: &[Value], workspace: &WorkspaceId) -> PanelResult<()> {
if steps.is_empty() || steps.len() > MAX_MUTATIONS {
return Err(error(Rule::CollectionLimit, "layout batch requires 1..64 steps"));
}
let mut selected = workspace.clone();
let mut replacement = false;
let mut mutation = 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::Apply(_) | PanelCommand::Reset(_) => replacement = true,
PanelCommand::Workspace(params) => {
replacement |= params.workspace != selected;
selected = params.workspace;
}
_ => mutation = true,
}
}
if replacement && mutation {
return Err(error(Rule::Capability, "atomic batches cannot combine snapshot replacement and explicit panel mutations; use rollback:false"));
}
Ok(())
}
/// Atomic batches use one Apply or Replace and one catalogue/native/controller
/// preflight. Explicit lifecycle intent is never flattened into a replacement.
pub fn execute_batch(steps: &[Value], context: &mut PanelCommandContext<'_>) -> PanelResult<Value> {
if steps.is_empty() || steps.len() > MAX_MUTATIONS {
return Err(error(Rule::CollectionLimit, "layout batch requires 1..64 steps"));
}
let state = context.sink.inspect();
preflight_batch(steps, &state.layout.workspace)?;
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 mut rows = Vec::new();
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 id = crate::find_command(id).map(|spec| spec.id).ok_or_else(|| error(Rule::MissingTarget, "batch command not registered"))?;
let empty = json!({});
let result = execute(
id,
step.get("params").filter(|p| !p.is_null()).unwrap_or(&empty),
&mut PanelCommandContext { sink: &mut sink, registry: context.registry, catalogue: &mut planned, web: context.web },
)?;
rows.push((id, result));
}
let action = if sink.replaced {
LayoutAction::Replace { expected_revision: Some(state.revision), layout: sink.state.layout.clone() }
} else if !sink.mutations.is_empty() {
LayoutAction::Apply { expected_revision: Some(state.revision), mutations: sink.mutations.clone() }
} else {
LayoutAction::Inspect
};
let planned_state = sink.state.clone();
let changed = planned.state != *context.catalogue.state() || action != LayoutAction::Inspect;
// Release the immutable authoritative borrow before committing through it.
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
} else {
context.sink.inspect()
};
let mut results = Vec::new();
for (id, mut result) in rows {
match id {
"panel.list" => result = value(wire::ListReply { state: committed.clone(), kinds: context.registry.specs().cloned().collect() })?,
"layout.get" => result = value(wire::GetReply { state: committed.clone(), workspaces: context.catalogue.state().summaries() })?,
"layout.save" | "layout.workspace.select" => result["state"] = value(committed.clone())?,
_ => result = value(committed.clone())?,
}
results.push(result);
}
Ok(json!({"completed":steps.len(),"results":results,"undone":0}))
}
/// Transport-compatible error text retains the structured foundation identity.
/// Control/MCP also expose this as panel_error beside their usual error string.
pub fn error_text(reason: PanelError) -> String {
serde_json::to_string(&reason).unwrap_or_else(|_| "{\"rule\":\"schema\",\"detail\":\"layout error encoding failed\"}".into())
}
pub fn structured_error(text: &str) -> Option<Value> {
if text.len() > 4096 {
return None;
}
serde_json::from_str::<PanelError>(text).ok().and_then(|reason| value(error(reason.rule, reason.detail)).ok())
}
pub fn sequential_failure(index: usize, command: Option<&str>, text: String, results: Vec<Value>) -> Value {
let mut failed = json!({"index":index,"command":command,"error":text});
if let Some(reason) = structured_error(&text) {
failed["panel_error"] = reason;
}
json!({"completed":index,"results":results,"failed":failed,"undone":0,"rolled_back":false})
}
/// One owned, persistent in-memory headless backend, outside Session. No kinds,
/// presets or workspace descriptors are invented. Peers/fixtures may inject them.
pub struct InMemoryPanelBackend {
pub service: LayoutService,
pub catalogue: InMemoryCatalogue,
}
/// In-process layout has no native realization. Even a supplied service with
/// native flags cannot make this adapter claim that it opened an OS window.
struct HeadlessSink<'a>(&'a mut LayoutService);
impl ActionSink for HeadlessSink<'_> {
fn inspect(&self) -> LayoutReply {
let mut state = self.0.inspect();
state.capabilities.native_windows = false;
state.capabilities.max_native_hosts = 0;
state
}
fn project(&self, action: LayoutAction) -> PanelResult<Layout> {
let prepared = self.0.prepare(action)?;
if prepared.effects().iter().any(|effect| matches!(effect, HostEffect::CreateNative { .. } | HostEffect::RebindNative { .. })) {
return Err(error(Rule::Capability, "headless has no native host adapter"));
}
Ok(prepared.layout().clone())
}
fn dispatch(&mut self, action: LayoutAction) -> PanelResult<LayoutReply> {
self.project(action.clone())?;
let mut state = self.0.dispatch(action)?;
state.capabilities.native_windows = false;
state.capabilities.max_native_hosts = 0;
Ok(state)
}
}
impl InMemoryPanelBackend {
pub fn new(service: LayoutService, catalogue: InMemoryCatalogue) -> Self {
Self { service, catalogue }
}
pub fn empty() -> PanelResult<Self> {
Ok(Self::new(
LayoutService::new(PanelRegistry::default(), Layout::empty(WorkspaceId::new("headless")?), HostCapabilities::default())?,
InMemoryCatalogue::default(),
))
}
pub fn execute(&mut self, id: &str, params: &Value) -> PanelResult<Value> {
let registry = self.service.registry().clone();
execute(
id,
params,
&mut PanelCommandContext { sink: &mut HeadlessSink(&mut self.service), registry: &registry, catalogue: &mut self.catalogue, web: false },
)
}
pub fn batch(&mut self, steps: &[Value]) -> PanelResult<Value> {
let registry = self.service.registry().clone();
execute_batch(
steps,
&mut PanelCommandContext { sink: &mut HeadlessSink(&mut self.service), registry: &registry, catalogue: &mut self.catalogue, web: false },
)
}
}
@@ -0,0 +1,158 @@
//! Small versioned storage seam for application preferences, not design files.
//! Length-prefixed records keep arbitrary recovery bytes exact and bound every
//! allocation before copying. Envelopes retain their foundation JSON limits.
use super::*;
const HEADER: &[u8] = b"SCPCAT01";
impl CatalogueState {
/// Export all immutable registrations, mutable users and remembered full
/// envelopes. No storage, live action, selection or Session is touched.
pub fn export(&self) -> PanelResult<Vec<u8>> {
self.validate()?;
let mut writer = Writer(Vec::new());
writer.put(HEADER)?;
for presets in [&self.builtins, &self.users] {
writer.count(presets.len())?;
for (name, record) in presets {
writer.bytes(name.as_bytes())?;
writer.record(record)?;
}
}
writer.count(self.workspaces.len())?;
for descriptor in self.workspaces.values() {
writer.bytes(descriptor.id.0.as_bytes())?;
writer.bytes(descriptor.title_key.as_bytes())?;
writer.bytes(descriptor.default_preset.as_bytes())?;
}
writer.count(self.remembered.len())?;
for (workspace, record) in &self.remembered {
writer.bytes(workspace.0.as_bytes())?;
writer.record(record)?;
}
Ok(writer.0)
}
/// Build a private validated candidate. Counts, duplicate identities,
/// names/IDs, envelope node/depth/byte bounds, rejected recovery and total
/// budgets are checked before the result can be published by any catalogue.
pub fn hydrate(bytes: &[u8], registry: &PanelRegistry) -> PanelResult<Self> {
if bytes.len() > MAX_CATALOGUE_SNAPSHOT_BYTES {
return Err(error(Rule::CollectionLimit, "catalogue snapshot byte cap"));
}
let mut reader = Reader { bytes, at: 0 };
if reader.take(HEADER.len())? != HEADER {
return Err(error(Rule::Version, "unsupported catalogue snapshot"));
}
let mut next = Self::default();
for builtin in [true, false] {
let count = reader.count(MAX_USER_PRESETS)?;
for _ in 0..count {
let name = reader.text(256)?;
if preset_name(&name)? != name {
return Err(error(Rule::Schema, "stored preset name is not normalised"));
}
if next.builtins.contains_key(&name) || next.users.contains_key(&name) {
return Err(error(Rule::DuplicateId, "duplicate stored preset identity"));
}
let record = reader.record(registry)?;
if builtin {
next.builtins.insert(name, record);
} else {
next.users.insert(name, record);
}
}
}
for _ in 0..reader.count(MAX_WORKSPACES)? {
let id = WorkspaceId::new(reader.text(MAX_ID_BYTES)?)?;
let title_key = reader.text(MAX_ID_BYTES)?;
valid_id(&title_key)?;
let default_preset = reader.text(256)?;
if next.workspaces.contains_key(&id) {
return Err(error(Rule::DuplicateId, "duplicate stored workspace identity"));
}
next.workspaces.insert(id.clone(), WorkspaceDescriptor { id, title_key, default_preset });
}
for _ in 0..reader.count(MAX_WORKSPACES)? {
let workspace = WorkspaceId::new(reader.text(MAX_ID_BYTES)?)?;
if next.remembered.contains_key(&workspace) {
return Err(error(Rule::DuplicateId, "duplicate remembered workspace identity"));
}
let record = reader.record(registry)?;
// A remembered record belongs to its key, unlike a reusable preset.
record.envelope(registry, &workspace)?;
next.remembered.insert(workspace, record);
}
if reader.at != bytes.len() {
return Err(error(Rule::Schema, "trailing catalogue snapshot data"));
}
next.validate()?;
Ok(next)
}
}
struct Writer(Vec<u8>);
impl Writer {
fn put(&mut self, bytes: &[u8]) -> PanelResult<()> {
if self.0.len().saturating_add(bytes.len()) > MAX_CATALOGUE_SNAPSHOT_BYTES {
return Err(error(Rule::CollectionLimit, "catalogue snapshot byte cap"));
}
self.0.extend_from_slice(bytes);
Ok(())
}
fn count(&mut self, count: usize) -> PanelResult<()> {
let count = u32::try_from(count).map_err(|_| error(Rule::CollectionLimit, "catalogue framing cap"))?;
self.put(&count.to_le_bytes())
}
fn bytes(&mut self, bytes: &[u8]) -> PanelResult<()> {
self.count(bytes.len())?;
self.put(bytes)
}
fn record(&mut self, record: &StoredEnvelope) -> PanelResult<()> {
self.bytes(record.bytes())?;
match record.rejected() {
Some(rejected) => {
self.put(&[1])?;
self.bytes(rejected)
}
None => self.put(&[0]),
}
}
}
struct Reader<'a> {
bytes: &'a [u8],
at: usize,
}
impl<'a> Reader<'a> {
fn take(&mut self, count: usize) -> PanelResult<&'a [u8]> {
let end = self.at.checked_add(count).ok_or_else(|| error(Rule::CollectionLimit, "catalogue framing overflow"))?;
let bytes = self.bytes.get(self.at..end).ok_or_else(|| error(Rule::Schema, "truncated catalogue snapshot"))?;
self.at = end;
Ok(bytes)
}
fn count(&mut self, max: usize) -> PanelResult<usize> {
let raw = <[u8; 4]>::try_from(self.take(4)?).map_err(|_| error(Rule::Schema, "invalid catalogue length"))?;
let count = usize::try_from(u32::from_le_bytes(raw)).map_err(|_| error(Rule::CollectionLimit, "catalogue length overflow"))?;
if count > max {
return Err(error(Rule::CollectionLimit, "catalogue record/count cap"));
}
Ok(count)
}
fn bytes(&mut self, max: usize) -> PanelResult<&'a [u8]> {
let count = self.count(max)?;
self.take(count)
}
fn text(&mut self, max: usize) -> PanelResult<String> {
std::str::from_utf8(self.bytes(max)?).map(str::to_owned).map_err(|_| error(Rule::Schema, "invalid catalogue UTF-8"))
}
fn record(&mut self, registry: &PanelRegistry) -> PanelResult<StoredEnvelope> {
let bytes = self.bytes(MAX_ENVELOPE_BYTES)?;
let rejected = match self.take(1)? {
[0] => None,
[1] => Some(self.bytes(MAX_ENVELOPE_BYTES)?),
_ => return Err(error(Rule::Schema, "invalid catalogue recovery tag")),
};
StoredEnvelope::from_record(bytes, rejected, registry)
}
}
+110
View File
@@ -0,0 +1,110 @@
//! Executable synthetic contracts for independent host/command/persistence work.
//! These identifiers are fixtures, never production registrations or UI strings.
use std::collections::BTreeMap;
use super::*;
pub const FIXTURE_LAYOUT_V1: &[u8] = include_bytes!("fixtures/layout-v1.json");
pub fn synthetic_registry() -> PanelResult<PanelRegistry> {
let mut registry = PanelRegistry::default();
for (kind, multi, pinned) in
[("fixture.application", false, false), ("fixture.editor", false, false), ("fixture.log", true, false), ("fixture.pin", true, true)]
{
let mut allowed_zones: std::collections::BTreeSet<_> =
[Zone::Left, Zone::Right, Zone::Bottom, Zone::Floating, Zone::Window].into_iter().collect();
if pinned {
allowed_zones.remove(&Zone::Bottom);
}
registry.register(PanelSpec {
kind: PanelKind::new(kind)?,
title_key: "ui.panel".into(),
icon: "panel".into(),
allowed_zones,
default_zone: Zone::Left,
min_size: Size { width: 160.0, height: 120.0 },
default_size: Size { width: 280.0, height: 240.0 },
max_size: Size { width: 1200.0, height: 1200.0 },
edge_rule: if pinned { EdgeRule::PinOuter } else { EdgeRule::None },
surface: PanelSurface::FollowZone,
features: PanelFeatures { multi_instance: multi, ..PanelFeatures::default() },
})?;
}
Ok(registry)
}
pub fn fixture_open(kind: &str, instance: &str, section: &str, zone: Zone, index: usize) -> PanelResult<Mutation> {
Ok(Mutation::Open {
kind: PanelKind::new(kind)?,
instance: InstanceId::new(instance)?,
destination: Some(Destination::NewSection {
section: SectionId::new(section)?,
index,
location: if zone == Zone::Floating {
SectionLocation::Floating { origin: Point { x: 40.0, y: 40.0 } }
} else {
SectionLocation::Dock { zone }
},
size: Size { width: 280.0, height: 240.0 },
}),
})
}
pub fn fixture_service(native: bool) -> PanelResult<LayoutService> {
LayoutService::new(
synthetic_registry()?,
Layout::empty(WorkspaceId::new("fixture.workspace")?),
HostCapabilities { native_windows: native, max_native_hosts: if native { 8 } else { 0 }, persistence: true },
)
}
pub fn transaction(mutations: Vec<Mutation>) -> LayoutAction {
LayoutAction::Apply { expected_revision: None, mutations }
}
/// Synthetic catalogue shared by command/control/MCP tests; never registered by
/// application startup. Two descriptors may deliberately share one default.
pub fn fixture_command_catalogue(registry: &PanelRegistry) -> PanelResult<commands::InMemoryCatalogue> {
let mut catalogue = commands::InMemoryCatalogue::default();
let empty = LayoutEnvelope::new(Layout::empty(WorkspaceId::new("fixture.workspace")?));
catalogue.register_builtin("Fixture default", &empty, registry)?;
for id in ["fixture.workspace", "fixture.other"] {
catalogue.register_workspace(commands::WorkspaceDescriptor {
id: WorkspaceId::new(id)?,
title_key: "ui.panel".into(),
default_preset: "Fixture default".into(),
})?;
}
Ok(catalogue)
}
pub fn fixture_command_backend() -> PanelResult<commands::InMemoryPanelBackend> {
let service = fixture_service(false)?;
let catalogue = fixture_command_catalogue(service.registry())?;
Ok(commands::InMemoryPanelBackend::new(service, catalogue))
}
#[derive(Default)]
pub struct FakePersistence {
/// Deliberately separate map demonstrates that layout writes own one key.
pub unrelated_preferences: BTreeMap<String, String>,
pub layouts: BTreeMap<WorkspaceId, Vec<u8>>,
pub fail_save: bool,
}
impl LayoutPersistence for FakePersistence {
fn load(&mut self, workspace: &WorkspaceId) -> PanelResult<Option<Vec<u8>>> {
valid_id(&workspace.0)?;
Ok(self.layouts.get(workspace).cloned())
}
fn save(&mut self, workspace: &WorkspaceId, envelope: &[u8]) -> PanelResult<()> {
valid_id(&workspace.0)?;
if envelope.len() > MAX_ENVELOPE_BYTES || (!self.layouts.contains_key(workspace) && self.layouts.len() >= MAX_SECTIONS) {
return Err(error(Rule::CollectionLimit, "fake persistence capacity"));
}
if self.fail_save {
return Err(error(Rule::Capability, "synthetic atomic write failure"));
}
self.layouts.insert(workspace.clone(), envelope.to_vec());
Ok(())
}
}
@@ -0,0 +1,37 @@
{
"format": "solidcraft.panel-layout",
"version": 1,
"layout": {
"version": 1,
"workspace": "fixture.workspace",
"instances": [
{
"id": "editor",
"kind": "fixture.editor",
"requested_open": true,
"memory": {
"section": "editor-section",
"location": { "type": "dock", "zone": "left" },
"section_index": 0,
"tab_index": 0,
"size": { "width": 280.0, "height": 240.0 },
"collapsed": false
}
}
],
"sections": [
{
"id": "editor-section",
"location": { "type": "dock", "zone": "left" },
"tabs": ["editor"],
"active": "editor",
"size": { "width": 280.0, "height": 240.0 },
"collapsed": false
}
]
},
"quarantine": [],
"section_snapshots": {},
"section_order": ["editor-section"],
"retained_data": {}
}
+410
View File
@@ -0,0 +1,410 @@
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use super::*;
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct Point {
pub x: f32,
pub y: f32,
}
impl Point {
pub fn validate(self) -> PanelResult<()> {
if !self.x.is_finite() || !self.y.is_finite() || self.x.abs() > MAX_LOGICAL || self.y.abs() > MAX_LOGICAL {
return Err(error(Rule::Bounds, "invalid logical position"));
}
Ok(())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct LogicalRect {
pub origin: Point,
pub size: Size,
}
impl LogicalRect {
pub fn validate(self) -> PanelResult<()> {
self.origin.validate()?;
self.size.validate()?;
if (self.origin.x + self.size.width).abs() > MAX_LOGICAL || (self.origin.y + self.size.height).abs() > MAX_LOGICAL {
return Err(error(Rule::Bounds, "logical rectangle extent out of range"));
}
Ok(())
}
pub fn contains(self, p: Point) -> bool {
p.x >= self.origin.x && p.y >= self.origin.y && p.x <= self.origin.x + self.size.width && p.y <= self.origin.y + self.size.height
}
pub fn contains_rect(self, other: Self) -> bool {
self.contains(other.origin) && self.contains(Point { x: other.origin.x + other.size.width, y: other.origin.y + other.size.height })
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum Flow {
Tall,
Wide,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum SizeClass {
Compact,
Regular,
Wide,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum Direction {
Ltr,
Rtl,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum PhysicalEdge {
Left,
Right,
Bottom,
}
impl Direction {
pub fn edge(self, zone: Zone) -> PanelResult<PhysicalEdge> {
match (self, zone) {
(Self::Ltr, Zone::Left) | (Self::Rtl, Zone::Right) => Ok(PhysicalEdge::Left),
(Self::Ltr, Zone::Right) | (Self::Rtl, Zone::Left) => Ok(PhysicalEdge::Right),
(_, Zone::Bottom) => Ok(PhysicalEdge::Bottom),
_ => Err(error(Rule::Placement, "free host has no logical dock edge")),
}
}
}
/// Usable logical units: egui applies scale exactly once, outside this contract.
/// Free/native flow starts at aspect 1, switches Tall->Wide above 1.1, Wide->Tall
/// below 0.9, and retains the previous flow inside that band.
pub fn responsive(zone: Zone, usable: Size, previous: Option<Flow>) -> PanelResult<(Flow, SizeClass)> {
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,
},
};
let shorter = usable.width.min(usable.height);
let class = if shorter < 240.0 {
SizeClass::Compact
} else if shorter <= 480.0 {
SizeClass::Regular
} else {
SizeClass::Wide
};
Ok((flow, class))
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum InputRole {
Surface,
Header,
Tab,
Sash,
Action,
Rail,
Overlay,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct InputRegion {
pub control: ControlId,
pub role: InputRole,
pub bounds: LogicalRect,
pub keyboard_focusable: bool,
/// Translation key or a runtime title resolved by the host.
pub accessible_name: String,
}
impl InputRegion {
pub fn validate(&self) -> PanelResult<()> {
valid_id(&self.control.0)?;
self.bounds.validate()?;
if self.accessible_name.is_empty() || self.accessible_name.len() > 256 {
return Err(error(Rule::Bounds, "accessible name requires 1..256 bytes"));
}
Ok(())
}
}
/// Host-resolved geometry has separate outer, body, paint and input bounds. No
/// transparent/full-window input shield is implied by an overlay surface.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct ResolvedPanel {
pub instance: InstanceId,
pub section: SectionId,
pub zone: Zone,
pub outer: LogicalRect,
pub body: LogicalRect,
pub painted: Vec<LogicalRect>,
pub input: Vec<InputRegion>,
}
impl ResolvedPanel {
pub fn validate(&self) -> PanelResult<()> {
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 self.painted.is_empty() || self.painted.len() > MAX_TABS || self.input.len() > MAX_INSTANCES {
return Err(error(Rule::CollectionLimit, "resolved region count"));
}
for rect in &self.painted {
rect.validate()?;
if !self.outer.contains_rect(*rect) {
return Err(error(Rule::Bounds, "paint outside host"));
}
}
let mut ids = std::collections::BTreeSet::new();
for region in &self.input {
region.validate()?;
if !ids.insert(&region.control) {
return Err(error(Rule::DuplicateId, "semantic control id repeated"));
}
if !self.painted.iter().any(|r| r.contains_rect(region.bounds)) {
return Err(error(Rule::Bounds, "input must be contained in painted area"));
}
}
Ok(())
}
pub fn consumes_pointer(&self, at: Point) -> bool {
self.input.iter().any(|r| r.bounds.contains(at))
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum UnpresentedReason {
MinimumOverflow,
Unavailable,
NativeUnsupported,
Collapsed,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct UnpresentedSection {
pub section: SectionId,
pub reason: UnpresentedReason,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct ResolvedLayout {
pub panels: Vec<ResolvedPanel>,
/// Accessible rail controls are chrome, never sub-minimum content bodies.
pub rails: Vec<InputRegion>,
pub unpresented: Vec<UnpresentedSection>,
}
impl ResolvedLayout {
pub fn validate(&self) -> PanelResult<()> {
if self.panels.len() > MAX_SECTIONS || self.rails.len() > MAX_SECTIONS || self.unpresented.len() > MAX_SECTIONS {
return Err(error(Rule::CollectionLimit, "resolved layout cap"));
}
let mut instances = std::collections::BTreeSet::new();
let mut sections = std::collections::BTreeSet::new();
let mut rails = std::collections::BTreeSet::new();
for panel in &self.panels {
panel.validate()?;
if !instances.insert(&panel.instance) || !sections.insert(&panel.section) {
return Err(error(Rule::ExactlyOnce, "duplicate resolved instance/section"));
}
}
for rail in &self.rails {
rail.validate()?;
if rail.role != InputRole::Rail || !rails.insert(&rail.control) {
return Err(error(Rule::DuplicateId, "invalid or duplicate rail control"));
}
}
for record in &self.unpresented {
valid_id(&record.section.0)?;
if !sections.insert(&record.section) {
return Err(error(Rule::ExactlyOnce, "section both presented/unpresented or duplicated"));
}
}
Ok(())
}
}
/// Reference geometry for synthetic mounts. Production docking owns its richer
/// resolver; both return the same meaningful geometry contract. No layout writes.
pub fn resolve_geometry(service: &LayoutService, capacity: LogicalRect, direction: Direction, chrome: f32) -> PanelResult<ResolvedLayout> {
capacity.validate()?;
if !chrome.is_finite() || chrome < 0.0 || chrome > 256.0 {
return Err(error(Rule::Bounds, "invalid header/footer chrome extent"));
}
let mut result = ResolvedLayout::default();
let mut left = capacity.origin.x;
let mut right = capacity.origin.x + capacity.size.width;
let mut bottom = capacity.origin.y + capacity.size.height;
let mut left_y = capacity.origin.y;
let mut right_y = capacity.origin.y;
let mut bottom_x = capacity.origin.x;
let mut rail_y = capacity.origin.y;
let mut occupied: Vec<LogicalRect> = Vec::new();
for section in &service.layout().sections {
let id = &section.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 {
None
};
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 &section.location {
SectionLocation::Floating { origin } | SectionLocation::Window { origin, .. } => *origin,
SectionLocation::Dock { zone } => match direction.edge(*zone)? {
PhysicalEdge::Left => Point { x: left, y: left_y },
PhysicalEdge::Right => Point { x: right - size.width, y: right_y },
PhysicalEdge::Bottom => Point { x: bottom_x, y: bottom - size.height },
},
};
let outer = LogicalRect { origin, size };
let overlaps_dock = zone.docked()
&& !section.collapsed
&& occupied.iter().any(|r| {
r.origin.x < origin.x + size.width
&& origin.x < r.origin.x + r.size.width
&& r.origin.y < origin.y + size.height
&& origin.y < r.origin.y + r.size.height
});
if !capacity.contains_rect(outer) || size.height <= chrome || overlaps_dock {
result.unpresented.push(UnpresentedSection { section: section.id.clone(), reason: UnpresentedReason::MinimumOverflow });
append_rail(&mut result, service, active, capacity, direction, zone, &mut rail_y)?;
continue;
}
if zone.docked() && !section.collapsed {
occupied.push(outer);
match direction.edge(zone)? {
PhysicalEdge::Left => {
left_y += size.height;
left = left.max(origin.x);
}
PhysicalEdge::Right => {
right_y += size.height;
right = right.min(origin.x + size.width);
}
PhysicalEdge::Bottom => {
bottom_x += size.width;
bottom = bottom.min(origin.y + size.height);
}
}
}
let body =
LogicalRect { origin: Point { x: origin.x, y: origin.y + chrome / 2.0 }, size: Size { width: size.width, height: size.height - chrome } };
let panel = ResolvedPanel {
instance: active.clone(),
section: section.id.clone(),
zone,
outer,
body,
painted: vec![outer],
input: vec![InputRegion {
control: ControlId::new(format!("host.{}", section.id.0).chars().take(MAX_ID_BYTES).collect::<String>())?,
role: InputRole::Surface,
bounds: outer,
keyboard_focusable: true,
accessible_name: service.registry().get(&service.layout().instance(active)?.kind)?.title_key.clone(),
}],
};
panel.validate()?;
result.panels.push(panel);
}
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;
}
Ok(())
}
/// Surfaces child resolves theme tokens. Invalid authored pairs retain raw import
/// intent and last good tokens; they cannot be reported as accessible by recolouring.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "state", rename_all = "snake_case")]
pub enum ContrastOutcome {
Readable { effective_background_alpha: f32 },
RetainReadableFallback { reason: ContrastFailure },
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ContrastFailure {
InvalidTokens,
UnreadableAtFullOpacity,
}
impl ContrastOutcome {
/// The surfaces adapter proves readability. This boundary enforces finite
/// alpha and the policy that effective background alpha may only increase.
pub fn validate(&self, requested_alpha: f32) -> PanelResult<()> {
if !requested_alpha.is_finite() || !(0.0..=1.0).contains(&requested_alpha) {
return Err(error(Rule::Bounds, "invalid requested background alpha"));
}
if let Self::Readable { effective_background_alpha } = self
&& (!effective_background_alpha.is_finite() || *effective_background_alpha < requested_alpha || *effective_background_alpha > 1.0)
{
return Err(error(Rule::Bounds, "resolved background alpha must be finite and only raised"));
}
Ok(())
}
}
/// Shared surface precedence: Opaque wins, then explicit Translucent, then zone
/// default (bottom/native opaque, sides/free translucent). No colour implementation.
pub fn group_surface<'a>(zone: Zone, specs: impl IntoIterator<Item = &'a PanelSpec>) -> PanelSurface {
let mut translucent = false;
for spec in specs {
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 }
}
+18
View File
@@ -0,0 +1,18 @@
//! Application/workspace layout, deliberately independent of Session and egui.
//! Consumers must use `LayoutService` (or its `ActionSink`) for committed mutations.
//! The serde values are wire data, not proof of validity; see `validate` and `decode`.
pub mod commands;
mod fixtures;
mod geometry;
mod model;
mod persistence;
mod reducer;
pub use fixtures::*;
pub use geometry::*;
pub use model::*;
pub use persistence::*;
pub use reducer::*;
#[cfg(test)]
mod tests;
+480
View File
@@ -0,0 +1,480 @@
use std::collections::{BTreeMap, BTreeSet};
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 MAX_ID_BYTES: usize = 64;
pub const MAX_INSTANCES: usize = 128;
pub const MAX_SECTIONS: usize = 64;
pub const MAX_TABS: usize = 32;
pub const MAX_MUTATIONS: usize = 64;
pub const MAX_LOGICAL: f32 = 32_768.0;
pub const MAX_ENVELOPE_BYTES: usize = 262_144;
/// Classic is a permanent compatibility contract; this foundation does not
/// select a new preset or migrate existing preferences.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum CompatibilityPreset {
Classic,
}
/// Stable machine-readable rule names; presentation translates these in the adapter.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum Rule {
Availability,
Bounds,
Capability,
CollectionLimit,
DuplicateId,
ExactlyOnce,
FeatureDisabled,
Id,
IncompatibleTabs,
Lifecycle,
MissingTarget,
PinConflict,
PinOrder,
Placement,
Revision,
Schema,
Version,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema, thiserror::Error)]
#[error("{rule:?}: {detail}")]
pub struct PanelError {
pub rule: Rule,
pub detail: String,
}
pub type PanelResult<T> = std::result::Result<T, PanelError>;
pub fn error(rule: Rule, detail: impl Into<String>) -> PanelError {
// Error replies are bounded too; never echo a hostile payload in full.
PanelError { rule, detail: detail.into().chars().take(256).collect() }
}
pub fn valid_id(value: &str) -> PanelResult<()> {
if value.is_empty() || value.len() > MAX_ID_BYTES || !value.bytes().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || b"._-".contains(&c)) {
return Err(error(Rule::Id, "expected a nonempty bounded lowercase identifier"));
}
Ok(())
}
macro_rules! identity {
($($name:ident),+ $(,)?) => {$ (
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, JsonSchema)]
#[serde(transparent)]
pub struct $name(pub String);
impl $name {
pub fn new(value: impl Into<String>) -> PanelResult<Self> {
let value = value.into();
valid_id(&value)?;
Ok(Self(value))
}
}
)+};
}
identity!(PanelKind, InstanceId, SectionId, 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)]
#[serde(rename_all = "snake_case")]
pub enum Zone {
Left,
Right,
Bottom,
Floating,
Window,
}
impl Zone {
pub fn docked(self) -> bool {
matches!(self, Self::Left | Self::Right | Self::Bottom)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum EdgeRule {
None,
PinOuter,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum PanelSurface {
FollowZone,
Opaque,
Translucent,
}
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct Size {
pub width: f32,
pub height: f32,
}
impl Size {
pub fn validate(self) -> PanelResult<()> {
if !self.width.is_finite()
|| !self.height.is_finite()
|| self.width <= 0.0
|| self.height <= 0.0
|| self.width > MAX_LOGICAL
|| self.height > MAX_LOGICAL
{
return Err(error(Rule::Bounds, "outer size must be finite and in (0, 32768] logical units"));
}
Ok(())
}
pub fn within(self, min: Self, max: Self) -> bool {
self.width >= min.width && self.height >= min.height && self.width <= max.width && self.height <= max.height
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct PanelFeatures {
pub collapsible: bool,
pub closable: bool,
pub popout: bool,
pub tabbable: bool,
pub multi_instance: bool,
}
impl Default for PanelFeatures {
fn default() -> Self {
Self { collapsible: true, closable: true, popout: true, tabbable: true, multi_instance: false }
}
}
/// 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,
pub allowed_zones: BTreeSet<Zone>,
pub default_zone: Zone,
pub min_size: Size,
pub default_size: Size,
pub max_size: Size,
pub edge_rule: EdgeRule,
pub surface: PanelSurface,
pub features: PanelFeatures,
}
#[derive(Clone, Debug, Default)]
pub struct PanelRegistry {
specs: BTreeMap<PanelKind, PanelSpec>,
}
impl PanelRegistry {
pub fn register(&mut self, spec: PanelSpec) -> PanelResult<()> {
valid_id(&spec.kind.0)?;
valid_id(&spec.title_key)?;
valid_id(&spec.icon)?;
spec.min_size.validate()?;
spec.max_size.validate()?;
spec.default_size.validate()?;
if !spec.default_size.within(spec.min_size, spec.max_size) {
return Err(error(Rule::Bounds, "min <= default <= max required in both dimensions"));
}
if !spec.allowed_zones.contains(&Zone::Floating) || !spec.allowed_zones.contains(&spec.default_zone) {
return Err(error(Rule::Placement, "Floating and default_zone must be allowed"));
}
if spec.edge_rule == EdgeRule::PinOuter && spec.allowed_zones.contains(&Zone::Bottom) {
return Err(error(Rule::Placement, "PinOuter must exclude Bottom"));
}
if self.specs.contains_key(&spec.kind) {
return Err(error(Rule::DuplicateId, "panel kind already registered"));
}
if self.specs.len() >= MAX_INSTANCES {
return Err(error(Rule::CollectionLimit, "registry full"));
}
self.specs.insert(spec.kind.clone(), spec);
Ok(())
}
pub fn get(&self, kind: &PanelKind) -> PanelResult<&PanelSpec> {
self.specs.get(kind).ok_or_else(|| error(Rule::MissingTarget, "unregistered panel kind"))
}
pub fn specs(&self) -> impl Iterator<Item = &PanelSpec> {
self.specs.values()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum SectionLocation {
Dock { zone: Zone },
Floating { origin: Point },
Window { host: HostId, origin: Point, return_to: DockReturn },
}
impl SectionLocation {
pub fn zone(&self) -> Zone {
match self {
Self::Dock { zone } => *zone,
Self::Floating { .. } => Zone::Floating,
Self::Window { .. } => Zone::Window,
}
}
pub fn validate(&self) -> PanelResult<()> {
match self {
Self::Dock { zone } if !zone.docked() => Err(error(Rule::Placement, "dock must name a docked zone")),
Self::Dock { .. } => Ok(()),
Self::Floating { origin } => origin.validate(),
Self::Window { host, origin, return_to } => {
valid_id(&host.0)?;
origin.validate()?;
return_to.validate()
}
}
}
}
/// Native return destinations never recursively contain another native host.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct DockReturn {
pub zone: Zone,
pub index: usize,
pub size: Size,
pub collapsed: bool,
/// Restore a former tab group when it still occupies the recorded dock.
/// Missing/reparented groups use the nonrecursive dock fallback above.
#[serde(default)]
pub join: Option<ReturnTab>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct ReturnTab {
pub section: SectionId,
pub index: usize,
}
impl DockReturn {
pub fn validate(&self) -> PanelResult<()> {
if !self.zone.docked() || self.index > MAX_SECTIONS {
return Err(error(Rule::Placement, "invalid native return destination"));
}
self.size.validate()?;
if let Some(join) = &self.join {
valid_id(&join.section.0)?;
if join.index >= MAX_TABS {
return Err(error(Rule::Bounds, "native return tab index cap"));
}
}
Ok(())
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct Section {
pub id: SectionId,
pub location: SectionLocation,
pub tabs: Vec<InstanceId>,
pub active: InstanceId,
/// Desired outer dimensions; overflow resolution never modifies these.
pub size: Size,
pub collapsed: bool,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct PlacementMemory {
pub section: SectionId,
pub location: SectionLocation,
pub section_index: usize,
pub tab_index: usize,
pub size: Size,
pub collapsed: bool,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct PanelInstance {
pub id: InstanceId,
pub kind: PanelKind,
pub requested_open: bool,
pub memory: PlacementMemory,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct Layout {
pub version: u32,
pub workspace: WorkspaceId,
pub instances: Vec<PanelInstance>,
/// Stable order, outermost first within each logical dock edge.
pub sections: Vec<Section>,
}
impl Layout {
pub fn empty(workspace: WorkspaceId) -> Self {
Self { version: LAYOUT_VERSION, workspace, instances: Vec::new(), sections: Vec::new() }
}
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"))
}
pub fn section(&self, id: &SectionId) -> PanelResult<&Section> {
self.sections.iter().find(|s| s.id == *id).ok_or_else(|| error(Rule::MissingTarget, "section not found"))
}
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"))
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "state", rename_all = "snake_case")]
pub enum Availability {
Available,
Unavailable { reason: String },
}
impl Availability {
pub fn require(&self) -> PanelResult<()> {
match self {
Self::Available => Ok(()),
Self::Unavailable { reason } => Err(error(Rule::Availability, reason)),
}
}
}
/// Missing entries mean available. Availability is live context, never layout persistence.
pub type AvailabilityMap = BTreeMap<InstanceId, Availability>;
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct HostCapabilities {
pub native_windows: bool,
pub persistence: bool,
pub max_native_hosts: usize,
}
pub fn tab_bounds(layout: &Layout, registry: &PanelRegistry, section: &Section) -> PanelResult<(Size, Size)> {
let mut min = Size { width: 0.0, height: 0.0 };
let mut max = Size { width: MAX_LOGICAL, height: MAX_LOGICAL };
for id in &section.tabs {
let spec = registry.get(&layout.instance(id)?.kind)?;
min.width = min.width.max(spec.min_size.width);
min.height = min.height.max(spec.min_size.height);
max.width = max.width.min(spec.max_size.width);
max.height = max.height.min(spec.max_size.height);
}
if min.width > max.width || min.height > max.height {
return Err(error(Rule::IncompatibleTabs, "tab size 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<()> {
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 {
return Err(error(Rule::CollectionLimit, "layout collection limit"));
}
let mut instances = BTreeSet::new();
let mut kinds = BTreeSet::new();
for p in &layout.instances {
valid_id(&p.id.0)?;
valid_id(&p.kind.0)?;
valid_id(&p.memory.section.0)?;
if !instances.insert(&p.id) {
return Err(error(Rule::DuplicateId, "duplicate instance"));
}
let spec = registry.get(&p.kind)?;
if !spec.features.multi_instance && !kinds.insert(&p.kind) {
return Err(error(Rule::ExactlyOnce, "single-instance kind repeated, including closed instances"));
}
p.memory.location.validate()?;
p.memory.size.validate()?;
if p.memory.tab_index >= MAX_TABS || p.memory.section_index > MAX_SECTIONS {
return Err(error(Rule::Bounds, "invalid placement memory"));
}
if !spec.allowed_zones.contains(&p.memory.location.zone()) {
return Err(error(Rule::Placement, "remembered zone forbidden"));
}
}
let mut sections = BTreeSet::new();
let mut seen = BTreeSet::new();
let mut hosts = BTreeSet::new();
let mut pins = BTreeSet::new();
let mut edges = BTreeSet::new();
for s in &layout.sections {
valid_id(&s.id.0)?;
s.location.validate()?;
s.size.validate()?;
if !sections.insert(&s.id) {
return Err(error(Rule::DuplicateId, "duplicate section"));
}
if s.tabs.is_empty() || s.tabs.len() > MAX_TABS {
return Err(error(Rule::CollectionLimit, "section requires 1..32 tabs"));
}
if !s.tabs.contains(&s.active) {
return Err(error(Rule::MissingTarget, "active tab outside section"));
}
if let SectionLocation::Window { host, .. } = &s.location
&& !hosts.insert(host)
{
return Err(error(Rule::DuplicateId, "native host reused"));
}
let zone = s.location.zone();
let first = edges.insert(zone);
for id in &s.tabs {
let instance = layout.instance(id)?;
let spec = registry.get(&instance.kind)?;
if !instance.requested_open || !seen.insert(id) {
return Err(error(Rule::ExactlyOnce, "closed or duplicate presented instance"));
}
if !spec.allowed_zones.contains(&zone) {
return Err(error(Rule::Placement, "panel zone forbidden"));
}
if s.tabs.len() > 1 && !spec.features.tabbable {
return Err(error(Rule::FeatureDisabled, "panel cannot join tabs"));
}
if s.collapsed && !spec.features.collapsible {
return Err(error(Rule::FeatureDisabled, "panel cannot collapse"));
}
if zone == Zone::Window && !spec.features.popout {
return Err(error(Rule::FeatureDisabled, "panel cannot pop out"));
}
if spec.edge_rule == EdgeRule::PinOuter && matches!(zone, Zone::Left | Zone::Right) {
if !pins.insert(zone) {
return Err(error(Rule::PinConflict, "competing pins on logical edge, including same tab group"));
}
if !first {
return Err(error(Rule::PinOrder, "pinned section must be outermost"));
}
}
}
let (min, max) = tab_bounds(layout, registry, s)?;
if !s.size.within(min, max) {
return Err(error(Rule::Bounds, "section outside intersected tab bounds"));
}
if let SectionLocation::Window { return_to, .. } = &s.location {
for id in &s.tabs {
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.collapsed && !spec.features.collapsible)
{
return Err(error(Rule::Placement, "native return violates member constraints"));
}
}
}
}
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) {
return Err(error(Rule::Bounds, "invalid placement memory"));
}
if p.requested_open != seen.contains(&p.id) {
return Err(error(Rule::ExactlyOnce, "open instance must appear exactly once"));
}
}
Ok(())
}
+762
View File
@@ -0,0 +1,762 @@
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use super::*;
pub const ENVELOPE_FORMAT: &str = "solidcraft.panel-layout";
pub const ENVELOPE_VERSION: u32 = 1;
/// Unknown panel wire values are retained verbatim as JSON values, including
/// fields a future content adapter understands. Total encoded envelope is capped.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct QuarantinedPanel {
pub instance: InstanceId,
pub kind: PanelKind,
pub instance_data: serde_json::Value,
pub section: Option<SectionId>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct SectionSnapshot {
pub data: serde_json::Value,
/// Latest complete rank; also permits reading earlier v1 envelopes without
/// the envelope's explicit complete section_order list.
pub index: usize,
/// Last materialized section, so a live user edit can be distinguished from
/// the fallback active tab/order produced while some members are dormant.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub projected: Option<Section>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct LayoutEnvelope {
pub format: String,
pub version: u32,
pub layout: Layout,
pub quarantine: Vec<QuarantinedPanel>,
/// Shared, lossless section order/activation/future fields, stored once even
/// when many unknown tabs refer to the same section. Retained after restore.
#[serde(default)]
pub section_snapshots: std::collections::BTreeMap<SectionId, SectionSnapshot>,
/// Latest complete section ordering, including currently dormant sections.
/// Retained snapshots alone cannot rank surviving sections without this list.
#[serde(default)]
pub section_order: Vec<SectionId>,
/// Original unknown wire data remains available after registry reappearance.
/// A content/persistence adapter may explicitly consume it; restoring placement
/// alone must not erase a future field that this foundation cannot interpret.
#[serde(default)]
pub retained_data: std::collections::BTreeMap<InstanceId, serde_json::Value>,
}
impl LayoutEnvelope {
pub fn new(layout: Layout) -> Self {
let section_order = layout.sections.iter().map(|section| section.id.clone()).collect();
Self {
format: ENVELOPE_FORMAT.into(),
version: ENVELOPE_VERSION,
layout,
quarantine: Vec::new(),
section_snapshots: std::collections::BTreeMap::new(),
section_order,
retained_data: std::collections::BTreeMap::new(),
}
}
}
#[derive(Clone, Debug)]
pub struct LoadOutcome {
pub envelope: LayoutEnvelope,
/// Adapter reports this once; fallback never blocks startup or touches other preferences.
pub notice: Option<PanelError>,
/// Bounded corrupt/future input, available to a recovery adapter before replacement.
pub rejected: Option<Vec<u8>>,
}
/// Implementations read/write ONLY the workspace panel-layout preference key.
/// `save` must replace atomically, preserving unrelated preferences. Production
/// preference migration is intentionally outside the foundation.
pub trait LayoutPersistence {
fn load(&mut self, workspace: &WorkspaceId) -> PanelResult<Option<Vec<u8>>>;
fn save(&mut self, workspace: &WorkspaceId, envelope: &[u8]) -> PanelResult<()>;
}
pub fn encode(envelope: &LayoutEnvelope, registry: &PanelRegistry) -> PanelResult<Vec<u8>> {
validate_envelope(envelope, registry)?;
encode_record(envelope)
}
fn encode_record(envelope: &LayoutEnvelope) -> PanelResult<Vec<u8>> {
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"))?;
bounded_json(&value)?;
Ok(writer.bytes)
}
struct BoundedEnvelopeWriter {
bytes: Vec<u8>,
}
impl std::io::Write for BoundedEnvelopeWriter {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
if self.bytes.len().saturating_add(bytes.len()) > MAX_ENVELOPE_BYTES {
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "panel envelope byte cap"));
}
self.bytes.extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
fn validate_envelope(envelope: &LayoutEnvelope, registry: &PanelRegistry) -> PanelResult<()> {
if envelope.format != ENVELOPE_FORMAT {
return Err(error(Rule::Schema, "unknown panel envelope format"));
}
if envelope.version != ENVELOPE_VERSION {
return Err(error(Rule::Version, "unknown panel envelope version"));
}
validate(&envelope.layout, registry)?;
validate_envelope_metadata(envelope)
}
fn validate_envelope_metadata(envelope: &LayoutEnvelope) -> PanelResult<()> {
if envelope.quarantine.len() + envelope.layout.instances.len() > MAX_INSTANCES {
return Err(error(Rule::CollectionLimit, "quarantine instance cap"));
}
if envelope.retained_data.len() > MAX_INSTANCES {
return Err(error(Rule::CollectionLimit, "retained data cap"));
}
for (id, data) in &envelope.retained_data {
valid_id(&id.0)?;
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)?;
}
let mut ids = std::collections::BTreeSet::new();
for item in &envelope.quarantine {
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) {
return Err(error(Rule::DuplicateId, "quarantine identity or index invalid"));
}
let instance: PanelInstance =
serde_json::from_value(item.instance_data.clone()).map_err(|_| error(Rule::Schema, "invalid quarantined instance"))?;
if instance.id != item.instance || instance.kind != item.kind {
return Err(error(Rule::Id, "quarantine identity mismatch"));
}
if instance.requested_open != item.section.is_some() {
return Err(error(Rule::ExactlyOnce, "quarantine open/section mismatch"));
}
valid_id(&instance.memory.section.0)?;
instance.memory.location.validate()?;
instance.memory.size.validate()?;
if instance.memory.section_index > MAX_SECTIONS || instance.memory.tab_index >= MAX_TABS {
return Err(error(Rule::CollectionLimit, "quarantine placement cap"));
}
if let Some(id) = &item.section {
let snapshot = envelope.section_snapshots.get(id).ok_or_else(|| error(Rule::MissingTarget, "quarantined section snapshot absent"))?;
let section: Section = serde_json::from_value(snapshot.data.clone()).map_err(|_| error(Rule::Schema, "invalid quarantined section"))?;
if !section.tabs.contains(&item.instance) {
return Err(error(Rule::ExactlyOnce, "quarantined instance absent from section snapshot"));
}
}
}
Ok(())
}
fn validate_section_order(order: &[SectionId]) -> PanelResult<()> {
if order.len() > MAX_SECTIONS {
return Err(error(Rule::CollectionLimit, "complete section order cap"));
}
let mut seen = std::collections::BTreeSet::new();
for id in order {
valid_id(&id.0)?;
if !seen.insert(id) {
return Err(error(Rule::DuplicateId, "duplicate complete section rank"));
}
}
Ok(())
}
fn validate_section_record(section: &Section) -> PanelResult<()> {
valid_id(&section.id.0)?;
section.location.validate()?;
section.size.validate()?;
if section.tabs.is_empty() || section.tabs.len() > MAX_TABS || !section.tabs.contains(&section.active) {
return Err(error(Rule::CollectionLimit, "section snapshot tabs/active bound"));
}
let mut seen = std::collections::BTreeSet::new();
for id in &section.tabs {
valid_id(&id.0)?;
if !seen.insert(id) {
return Err(error(Rule::ExactlyOnce, "section snapshot duplicate tab"));
}
}
Ok(())
}
fn validate_snapshot(id: &SectionId, snapshot: &SectionSnapshot) -> PanelResult<()> {
valid_id(&id.0)?;
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"));
}
validate_section_record(&section)?;
if let Some(projected) = &snapshot.projected {
if projected.id != *id {
return Err(error(Rule::Id, "projected section identity mismatch"));
}
validate_section_record(projected)?;
}
Ok(())
}
/// Overlay the live relative order on its previous slots, keeping dormant gaps.
/// New live entries attach before their next surviving live neighbour, rather
/// than consuming a dormant slot or reversing a run of newly added entries.
fn merge_visible_order<T: Clone + Ord>(saved: &[T], live: &[T], dormant: &std::collections::BTreeSet<T>) -> Vec<T> {
let survivors: std::collections::BTreeSet<_> = saved.iter().filter(|id| live.contains(id)).cloned().collect();
let mut live_survivors = live.iter().filter(|id| survivors.contains(*id));
let mut merged = Vec::new();
for id in saved {
if dormant.contains(id) && !live.contains(id) {
merged.push(id.clone());
} else if survivors.contains(id)
&& let Some(next) = live_survivors.next()
{
merged.push(next.clone());
}
}
for (index, id) in live.iter().enumerate() {
if survivors.contains(id) {
continue;
}
let before = live.iter().skip(index + 1).find(|next| survivors.contains(*next));
let at = before.and_then(|next| merged.iter().position(|old| old == next)).unwrap_or(merged.len());
merged.insert(at, id.clone());
}
merged
}
/// Refresh live semantics before a new quarantine episode, or before a direct
/// restoration after the caller has edited the known layout. Opaque data stays
/// shared; only semantic fields supplied by the current layout are refreshed.
fn refresh_section_memory(
envelope: &mut LayoutEnvelope,
raw: Option<&serde_json::Value>,
capture: &std::collections::BTreeSet<SectionId>,
) -> 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)?;
}
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();
let mut saved_order = envelope.section_order.clone();
if saved_order.is_empty() {
// Read earlier v1 envelopes without the complete rank list. Sort missing
// ranks before insertion, never in instance/quarantine processing order.
saved_order = live_order.clone();
let mut missing = Vec::new();
for id in &dormant_sections {
let snapshot = envelope.section_snapshots.get(id).ok_or_else(|| error(Rule::MissingTarget, "dormant section snapshot missing"))?;
if !saved_order.contains(id) {
missing.push((snapshot.index, id.clone()));
}
}
missing.sort();
for (index, id) in missing {
saved_order.insert(index.min(saved_order.len()), id);
}
} else if dormant_sections.iter().any(|id| !saved_order.contains(id)) {
return Err(error(Rule::MissingTarget, "complete order omits a dormant section"));
}
envelope.section_order = merge_visible_order(&saved_order, &live_order, &dormant_sections);
validate_section_order(&envelope.section_order)?;
for (index, section) in envelope.layout.sections.iter().enumerate() {
let previous = envelope.section_snapshots.get(&section.id);
if previous.is_none() && !capture.contains(&section.id) {
continue;
}
let current = match raw {
Some(raw) => raw
.get("layout")
.and_then(|layout| layout.get("sections"))
.and_then(|sections| sections.get(index))
.cloned()
.ok_or_else(|| error(Rule::Schema, "saved section raw data missing"))?,
None => serde_json::to_value(section).map_err(|_| error(Rule::Schema, "cannot encode live section semantics"))?,
};
let (mut data, projected) = match previous {
Some(previous) => (previous.data.clone(), previous.projected.clone()),
None => (serde_json::json!({}), None),
};
let dormant_tabs: std::collections::BTreeSet<_> =
envelope.quarantine.iter().filter(|item| item.section.as_ref() == Some(&section.id)).map(|item| item.instance.clone()).collect();
let previous_section: Option<Section> = previous
.map(|snapshot| serde_json::from_value(snapshot.data.clone()).map_err(|_| error(Rule::Schema, "invalid section memory")))
.transpose()?;
let tabs = match &previous_section {
Some(saved) if !dormant_tabs.is_empty() => merge_visible_order(&saved.tabs, &section.tabs, &dormant_tabs),
_ => section.tabs.clone(),
};
if tabs.len() > MAX_TABS {
return Err(error(Rule::CollectionLimit, "complete tab order cap"));
}
let active = match &previous_section {
Some(saved)
if dormant_tabs.contains(&saved.active)
&& !section.tabs.contains(&saved.active)
&& !projected.as_ref().is_some_and(|last| last.active != section.active) =>
{
saved.active.clone()
}
_ => section.active.clone(),
};
// 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());
}
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
.section_order
.iter()
.position(|id| *id == section.id)
.ok_or_else(|| error(Rule::MissingTarget, "live section has no complete rank"))?;
envelope.section_snapshots.insert(section.id.clone(), SectionSnapshot { data, index: rank, projected });
}
for (id, snapshot) in &mut envelope.section_snapshots {
if let Some(rank) = envelope.section_order.iter().position(|known| known == id) {
snapshot.index = rank;
}
}
Ok(())
}
fn record_section_projections(envelope: &mut LayoutEnvelope) {
let layout = &envelope.layout;
for (id, snapshot) in &mut envelope.section_snapshots {
snapshot.projected = layout.sections.iter().find(|section| section.id == *id).cloned();
}
}
/// 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<LayoutEnvelope> {
encode(envelope, registry)?;
validate(&layout, registry)?;
let mut next = envelope.clone();
next.layout = layout;
refresh_section_memory(&mut next, None, &std::collections::BTreeSet::new())?;
record_section_projections(&mut next);
encode(&next, registry)?;
Ok(next)
}
/// 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<()> {
let mut stack = vec![(value, 0_usize)];
let mut nodes = 0_usize;
let mut bytes = 0_usize;
while let Some((value, depth)) = stack.pop() {
nodes = nodes.saturating_add(1);
if nodes > 8192 || depth > 32 {
return Err(error(Rule::CollectionLimit, "JSON node/depth cap"));
}
match value {
serde_json::Value::String(s) => bytes = bytes.saturating_add(s.len()),
serde_json::Value::Array(values) => {
if values.len() > 8192 || stack.len().saturating_add(values.len()) > 8192 {
return Err(error(Rule::CollectionLimit, "JSON array cap"));
}
stack.extend(values.iter().map(|value| (value, depth + 1)));
}
serde_json::Value::Object(values) => {
if values.len() > 8192 || stack.len().saturating_add(values.len()) > 8192 {
return Err(error(Rule::CollectionLimit, "JSON object cap"));
}
for (key, value) in values {
bytes = bytes.saturating_add(key.len());
stack.push((value, depth + 1));
}
}
serde_json::Value::Number(n) if n.as_f64().is_some_and(|n| !n.is_finite()) => return Err(error(Rule::Bounds, "nonfinite JSON value")),
_ => {}
}
if bytes > MAX_ENVELOPE_BYTES {
return Err(error(Rule::CollectionLimit, "JSON byte cap"));
}
}
Ok(())
}
/// Decode bounded bytes, quarantine unknown kinds, and retry retained panels when
/// registered again. Corrupt/future input returns a validated safe preset plus notice.
pub fn decode(bytes: &[u8], registry: &PanelRegistry, fallback: &Layout) -> PanelResult<LoadOutcome> {
validate(fallback, registry)?;
match decode_inner(bytes, registry, &fallback.workspace, true) {
Ok(envelope) => Ok(LoadOutcome { envelope, notice: None, rejected: None }),
Err(reason) => Ok(LoadOutcome {
envelope: LayoutEnvelope::new(fallback.clone()),
notice: Some(reason),
rejected: if bytes.len() <= MAX_ENVELOPE_BYTES { Some(bytes.to_vec()) } else { None },
}),
}
}
/// Validate an already-retained record exactly, without generating section order,
/// projections or quarantine/restoration metadata. Missing registrations do not
/// invalidate saved intent. Structure and every applicable known-kind constraint
/// are still validated, but this retained layout is NOT permission to commit it
/// to a live sink. Use `project_retained_record` to stage registry migration.
pub fn decode_retained_record(bytes: &[u8], registry: &PanelRegistry) -> PanelResult<LayoutEnvelope> {
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"))?;
bounded_json(&raw)?;
let envelope: LayoutEnvelope = serde_json::from_value(raw).map_err(|_| error(Rule::Schema, "invalid panel envelope shape"))?;
if envelope.format != ENVELOPE_FORMAT {
return Err(error(Rule::Schema, "unknown panel envelope format"));
}
if envelope.version != ENVELOPE_VERSION {
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)?;
Ok(envelope)
}
/// Read a retained record in its workspace without consuming a reappearance
/// obligation or materializing absent order/projection metadata.
pub fn decode_retained(bytes: &[u8], registry: &PanelRegistry, workspace: &WorkspaceId) -> PanelResult<LayoutEnvelope> {
valid_id(&workspace.0)?;
let envelope = decode_retained_record(bytes, registry)?;
if envelope.layout.workspace != *workspace {
return Err(error(Rule::Schema, "panel envelope workspace mismatch"));
}
Ok(envelope)
}
/// Stage a usable current-registry layout without consuming quarantined
/// reappearance obligations. Newly absent kinds move to the foundation's
/// lossless quarantine. Metadata expansion can fail at the existing caps; the
/// original record remains available for retry and no live state is published.
pub fn project_retained_record(bytes: &[u8], registry: &PanelRegistry, workspace: &WorkspaceId) -> PanelResult<LayoutEnvelope> {
let envelope = decode_retained(bytes, registry, workspace)?;
if envelope.layout.instances.iter().any(|instance| registry.get(&instance.kind).is_err()) {
decode_inner(bytes, registry, workspace, false)
} else {
Ok(envelope)
}
}
fn decode_inner(bytes: &[u8], registry: &PanelRegistry, workspace: &WorkspaceId, restore: bool) -> PanelResult<LayoutEnvelope> {
if bytes.len() > MAX_ENVELOPE_BYTES {
return Err(error(Rule::CollectionLimit, "panel envelope exceeds byte cap"));
}
// 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"))?;
bounded_json(&raw)?;
let mut envelope: LayoutEnvelope = serde_json::from_value(raw.clone()).map_err(|_| error(Rule::Schema, "invalid panel envelope shape"))?;
if envelope.version != ENVELOPE_VERSION || envelope.layout.version != LAYOUT_VERSION {
return Err(error(Rule::Version, "future or unsupported panel layout"));
}
if envelope.format != ENVELOPE_FORMAT || envelope.layout.workspace != *workspace {
return Err(error(Rule::Schema, "panel envelope format/workspace mismatch"));
}
if envelope.layout.instances.len() > MAX_INSTANCES
|| envelope.layout.sections.len() > MAX_SECTIONS
|| envelope.quarantine.len() > MAX_INSTANCES
|| envelope.layout.sections.iter().any(|s| s.tabs.len() > MAX_TABS)
{
return Err(error(Rule::CollectionLimit, "panel collection limit"));
}
validate_retained_layout(&envelope.layout, registry)?;
validate_envelope_metadata(&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
.sections
.iter()
.filter(|section| unknown.iter().any(|p| section.tabs.contains(&p.id)))
.map(|section| section.id.clone())
.collect();
// 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)?;
for instance in unknown {
let section_index = envelope.layout.sections.iter().position(|s| s.tabs.contains(&instance.id));
let instance_data = raw
.get("layout")
.and_then(|l| l.get("instances"))
.and_then(|a| a.as_array())
.and_then(|a| a.iter().find(|v| v.get("id").and_then(|s| s.as_str()) == Some(instance.id.0.as_str())))
.cloned()
.ok_or_else(|| error(Rule::Schema, "unknown instance raw data missing"))?;
let section = if let Some(index) = section_index {
let id = envelope.layout.sections.get(index).ok_or_else(|| error(Rule::MissingTarget, "unknown section absent"))?.id.clone();
Some(id)
} else {
None
};
envelope.quarantine.push(QuarantinedPanel { instance: instance.id.clone(), kind: instance.kind, instance_data, section });
envelope.layout.instances.retain(|p| p.id != instance.id);
}
let retained: std::collections::BTreeSet<_> = envelope.layout.instances.iter().map(|p| p.id.clone()).collect();
for section in &mut envelope.layout.sections {
section.tabs.retain(|id| retained.contains(id));
if !section.tabs.contains(&section.active)
&& let Some(first) = section.tabs.first()
{
section.active = first.clone();
}
}
envelope.layout.sections.retain(|s| !s.tabs.is_empty());
// 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)?;
if restore {
restore_quarantine(&mut envelope, registry)?;
}
// Success means the lossless transformed envelope is itself persistable,
// including its aggregate byte/node/depth budget. Otherwise retain recovery.
encode(&envelope, registry)?;
Ok(envelope)
}
pub fn restore_quarantine(envelope: &mut LayoutEnvelope, registry: &PanelRegistry) -> PanelResult<()> {
restore_quarantine_with_availability(envelope, registry, &AvailabilityMap::new())
}
pub fn restore_quarantine_with_availability(
envelope: &mut LayoutEnvelope,
registry: &PanelRegistry,
availability: &AvailabilityMap,
) -> PanelResult<()> {
validate_envelope(envelope, registry)?;
if availability.len() > MAX_INSTANCES {
return Err(error(Rule::CollectionLimit, "reappearance availability cap"));
}
for (id, state) in availability {
valid_id(&id.0)?;
if matches!(state, Availability::Unavailable { reason } if reason.is_empty() || reason.len() > 256) {
return Err(error(Rule::Availability, "invalid reappearance availability reason"));
}
}
let mut working = envelope.clone();
// 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())?;
// 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();
for item in &envelope.quarantine {
if registry.get(&item.kind).is_err() || availability.get(&item.instance).is_some_and(|state| *state != Availability::Available) {
remaining.push(item.clone());
continue;
}
let mut candidate = working.layout.clone();
let instance: PanelInstance =
serde_json::from_value(item.instance_data.clone()).map_err(|_| error(Rule::Schema, "invalid quarantined instance"))?;
candidate.instances.push(instance.clone());
if instance.requested_open {
let Some(section_id) = &item.section else {
remaining.push(item.clone());
continue;
};
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"))?;
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
.tabs
.iter()
.filter(|id| members.contains(*id))
.cloned()
.chain(section.tabs.iter().filter(|id| !saved.tabs.contains(id)).cloned())
.collect();
if saved.active == instance.id {
section.active = saved.active.clone();
}
} else {
saved.tabs = vec![instance.id.clone()];
saved.active = instance.id.clone();
candidate.sections.push(saved);
}
}
// Rank against the full saved order, not an index clamped into a partial
// list. Sorting also includes surviving sections with no snapshot.
candidate.sections.sort_by_key(|section| working.section_order.iter().position(|id| *id == section.id).unwrap_or(MAX_SECTIONS));
if validate(&candidate, registry).is_ok() {
if working.retained_data.len() >= MAX_INSTANCES && !working.retained_data.contains_key(&item.instance) {
remaining.push(item.clone());
continue;
}
working
.retained_data
.entry(item.instance.clone())
.or_insert_with(|| serde_json::json!({"instance":item.instance_data,"section":item.section}));
working.layout = candidate;
} else {
remaining.push(item.clone());
}
}
working.quarantine = remaining;
record_section_projections(&mut working);
encode(&working, registry)?;
*envelope = working;
Ok(())
}
/// Validate saved identities/ownership independently of optional peers, then use
/// the ordinary validator for known members. The temporary known-only view is
/// validation input only: it is never returned, encoded, or dispatched.
fn validate_retained_layout(layout: &Layout, registry: &PanelRegistry) -> PanelResult<()> {
validate_wire_structure(layout)?;
if layout.instances.iter().all(|instance| registry.get(&instance.kind).is_ok()) {
return validate(layout, registry);
}
let mut edges = std::collections::BTreeSet::new();
for section in &layout.sections {
let zone = section.location.zone();
let first = edges.insert(zone);
for id in &section.tabs {
let instance = layout.instance(id)?;
if let Ok(spec) = registry.get(&instance.kind) {
// Filtering absent tabs/sections must not hide these constraints
// of a known member in the ORIGINAL full saved placement.
if section.tabs.len() > 1 && !spec.features.tabbable {
return Err(error(Rule::FeatureDisabled, "panel cannot join tabs"));
}
if spec.edge_rule == EdgeRule::PinOuter && matches!(zone, Zone::Left | Zone::Right) && !first {
return Err(error(Rule::PinOrder, "pinned section must be outermost"));
}
}
}
}
let mut known = layout.clone();
known.instances.retain(|instance| registry.get(&instance.kind).is_ok());
let ids: std::collections::BTreeSet<_> = known.instances.iter().map(|instance| instance.id.clone()).collect();
for section in &mut known.sections {
section.tabs.retain(|id| ids.contains(id));
if !section.tabs.contains(&section.active)
&& let Some(first) = section.tabs.first()
{
section.active = first.clone();
}
}
known.sections.retain(|section| !section.tabs.is_empty());
validate(&known, registry)
}
fn validate_wire_structure(layout: &Layout) -> PanelResult<()> {
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 {
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();
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()?;
if instance.memory.tab_index >= MAX_TABS || instance.memory.section_index > MAX_SECTIONS {
return Err(error(Rule::Bounds, "invalid placement memory"));
}
if !instances.insert(&instance.id) {
return Err(error(Rule::DuplicateId, "duplicate unknown/known instance"));
}
}
for section in &layout.sections {
valid_id(&section.id.0)?;
section.location.validate()?;
section.size.validate()?;
if !sections.insert(&section.id) {
return Err(error(Rule::DuplicateId, "duplicate unknown/known section"));
}
if section.tabs.len() > MAX_TABS {
return Err(error(Rule::CollectionLimit, "section tab cap"));
}
if let SectionLocation::Window { host, .. } = &section.location
&& !hosts.insert(host)
{
return Err(error(Rule::DuplicateId, "native host reused"));
}
if section.tabs.is_empty() || !section.tabs.contains(&section.active) {
return Err(error(Rule::ExactlyOnce, "invalid unknown/known active tab"));
}
for id in &section.tabs {
if !instances.contains(id) || !seen.insert(id) {
return Err(error(Rule::ExactlyOnce, "unknown/known tab ownership invalid"));
}
}
}
for instance in &layout.instances {
if instance.requested_open != seen.contains(&instance.id) {
return Err(error(Rule::ExactlyOnce, "unknown/known open state invalid"));
}
}
Ok(())
}
/// JSON schema for the wire contract. Semantic constraints are enforced by decode
/// and the reducer; schema alone is never treated as a validation proof.
pub fn layout_action_schema() -> schemars::Schema {
schemars::schema_for!(LayoutAction)
}
pub fn layout_reply_schema() -> schemars::Schema {
schemars::schema_for!(LayoutReply)
}
pub fn layout_error_schema() -> schemars::Schema {
schemars::schema_for!(PanelError)
}
pub fn layout_envelope_schema() -> schemars::Schema {
schemars::schema_for!(LayoutEnvelope)
}
pub fn decode_action(bytes: &[u8]) -> PanelResult<LayoutAction> {
if bytes.len() > MAX_ENVELOPE_BYTES {
return Err(error(Rule::CollectionLimit, "action byte cap"));
}
let value: serde_json::Value = serde_json::from_slice(bytes).map_err(|_| error(Rule::Schema, "invalid action JSON"))?;
bounded_json(&value)?;
let action: LayoutAction = serde_json::from_value(value).map_err(|_| error(Rule::Schema, "invalid action shape"))?;
if let LayoutAction::Apply { mutations, .. } = &action
&& (mutations.is_empty() || mutations.len() > MAX_MUTATIONS)
{
return Err(error(Rule::CollectionLimit, "action mutation cap"));
}
Ok(action)
}
+732
View File
@@ -0,0 +1,732 @@
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use super::*;
/// Joining an existing tab group and creating a split are deliberately distinct.
#[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 },
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Mutation {
Open {
kind: PanelKind,
instance: InstanceId,
destination: Option<Destination>,
},
Close {
instance: InstanceId,
},
/// Explicit owner cleanup, only after close. Hiding is never destruction.
Destroy {
instance: InstanceId,
},
Move {
instance: InstanceId,
destination: Destination,
},
Activate {
instance: InstanceId,
},
Focus {
instance: InstanceId,
},
Peek {
instance: InstanceId,
},
DismissPeek,
Collapse {
section: SectionId,
collapsed: bool,
},
SetSize {
section: SectionId,
size: Size,
},
/// Both neighbours change together; their shared axis extent is conserved.
ResizePair {
first: SectionId,
second: SectionId,
first_size: Size,
second_size: Size,
},
ResetPair {
first: SectionId,
second: SectionId,
},
/// A native window's close button redocks its whole section.
NativeClose {
host: HostId,
},
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum LayoutAction {
Inspect,
Apply {
expected_revision: Option<u64>,
mutations: Vec<Mutation>,
},
/// Apply a complete saved layout/preset, including a workspace change.
/// Omission and requested_open=false hide content without lifecycle intent.
Replace {
expected_revision: Option<u64>,
layout: Layout,
},
}
/// Stable targets for a later command adapter; none are registered with Session yet.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "type", content = "id", rename_all = "snake_case")]
pub enum LayoutTarget {
Workspace(WorkspaceId),
Instance(InstanceId),
Section(SectionId),
NativeHost(HostId),
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum HostEffect {
Focus { instance: InstanceId },
Peek { instance: InstanceId },
DismissPeek,
CreateNative { host: HostId, section: SectionId },
RebindNative { host: HostId, section: SectionId },
ReleaseNative { host: HostId },
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct InteractionState {
pub focused: Option<InstanceId>,
pub peek: Option<InstanceId>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct LayoutReply {
pub api_version: u32,
pub revision: u64,
pub layout: Layout,
pub interaction: InteractionState,
pub effects: Vec<HostEffect>,
pub capabilities: HostCapabilities,
pub availability: AvailabilityMap,
}
/// Same boundary for GUI and programmatic callers. No mutable Session reference.
pub trait ActionSink {
fn dispatch(&mut self, action: LayoutAction) -> PanelResult<LayoutReply>;
fn inspect(&self) -> LayoutReply;
/// Pure projection on the authoritative service. Adapters stage bounded
/// envelope/storage changes from this before guarded dispatch publishes.
fn project(&self, _action: LayoutAction) -> PanelResult<Layout> {
Err(error(Rule::Capability, "layout sink cannot stage commands"))
}
}
#[derive(Debug)]
pub struct LayoutService {
identity: std::sync::Arc<()>,
registry: PanelRegistry,
layout: Layout,
revision: u64,
availability: AvailabilityMap,
interaction: InteractionState,
capabilities: HostCapabilities,
identities: std::collections::BTreeMap<InstanceId, PanelKind>,
}
/// An optimistic, fully validated candidate. Fields stay private so it cannot be forged.
pub struct PreparedLayout {
service_identity: std::sync::Arc<()>,
base_revision: u64,
next: Layout,
interaction: InteractionState,
effects: Vec<HostEffect>,
changed: bool,
availability: AvailabilityMap,
identities: std::collections::BTreeMap<InstanceId, PanelKind>,
}
impl PreparedLayout {
pub fn layout(&self) -> &Layout {
&self.next
}
pub fn effects(&self) -> &[HostEffect] {
&self.effects
}
/// Runtime availability is staged with the same atomic layout commit.
pub fn set_availability(&mut self, availability: AvailabilityMap) -> PanelResult<()> {
validate_availability(&availability)?;
self.changed |= self.availability != availability;
self.availability = availability;
Ok(())
}
}
impl LayoutService {
pub fn new(registry: PanelRegistry, layout: Layout, capabilities: HostCapabilities) -> PanelResult<Self> {
validate(&layout, &registry)?;
if capabilities.max_native_hosts > MAX_SECTIONS {
return Err(error(Rule::CollectionLimit, "native capability exceeds section cap"));
}
// Restored native entries remain data even on web; resolve_geometry marks them
// unpresented. New native mutations still require a capable adapter.
Ok(Self {
identity: std::sync::Arc::new(()),
registry,
identities: layout.instances.iter().map(|p| (p.id.clone(), p.kind.clone())).collect(),
layout,
revision: 0,
availability: AvailabilityMap::new(),
interaction: InteractionState::default(),
capabilities,
})
}
pub fn registry(&self) -> &PanelRegistry {
&self.registry
}
pub fn layout(&self) -> &Layout {
&self.layout
}
pub fn interaction(&self) -> &InteractionState {
&self.interaction
}
pub fn capabilities(&self) -> &HostCapabilities {
&self.capabilities
}
pub fn availability(&self, id: &InstanceId) -> Availability {
self.availability.get(id).cloned().unwrap_or(Availability::Available)
}
pub fn set_availability(&mut self, values: AvailabilityMap) -> PanelResult<()> {
validate_availability(&values)?;
if self.availability != values {
let revision = self.revision.checked_add(1).ok_or_else(|| error(Rule::Revision, "layout revision exhausted"))?;
self.availability = values;
self.revision = revision;
self.reconcile_interaction();
}
Ok(())
}
fn reconcile_interaction(&mut self) {
let layout = &self.layout;
let availability = &self.availability;
let visible = |id: &InstanceId| {
layout.instance(id).is_ok_and(|p| p.requested_open) && availability.get(id).is_none_or(|state| *state == Availability::Available)
};
if self.interaction.focused.as_ref().is_some_and(|id| !visible(id)) {
self.interaction.focused = None;
}
if self.interaction.peek.as_ref().is_some_and(|id| !visible(id)) {
self.interaction.peek = None;
}
}
pub fn prepare(&self, action: LayoutAction) -> PanelResult<PreparedLayout> {
let mut next = self.layout.clone();
let mut interaction = self.interaction.clone();
let mut effects = Vec::new();
let mut availability = self.availability.clone();
let mut destroyed = std::collections::BTreeSet::new();
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)?;
next = layout.clone();
availability.clear();
interaction = InteractionState::default();
}
if let LayoutAction::Apply { expected_revision, mutations } = action {
if expected_revision.is_some_and(|r| r != self.revision) {
return Err(error(Rule::Revision, "stale layout revision"));
}
if mutations.is_empty() || mutations.len() > MAX_MUTATIONS {
return Err(error(Rule::CollectionLimit, "transaction requires 1..64 mutations"));
}
validate_lifecycle_intents(&mutations)?;
for mutation in &mutations {
if let Mutation::Destroy { instance } = mutation {
destroyed.insert(instance.clone());
}
}
for mutation in mutations {
apply(&mut next, &self.registry, &self.availability, &self.capabilities, &mut interaction, &mut effects, mutation)?;
// 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)
{
return Err(error(Rule::CollectionLimit, "transaction collection limit"));
}
}
validate(&next, &self.registry)?;
for before in &self.layout.instances {
if next.instances.iter().any(|after| after.id == before.id && after.kind != before.kind) {
return Err(error(Rule::DuplicateId, "transaction cannot reuse an instance for another kind"));
}
}
}
let mut identities = self.identities.clone();
for id in destroyed {
identities.remove(&id);
}
for p in &next.instances {
if identities.get(&p.id).is_some_and(|kind| *kind != p.kind) {
return Err(error(Rule::DuplicateId, "instance identity cannot change kind across layouts/workspaces"));
}
identities.insert(p.id.clone(), p.kind.clone());
}
if identities.len() > MAX_INSTANCES {
return Err(error(Rule::CollectionLimit, "retained instance identity cap"));
}
// Native effects describe the committed difference, never intermediate windows.
let old = native_hosts(&self.layout);
let new = native_hosts(&next);
for (host, section) in &new {
if !old.iter().any(|(h, _)| h == host) {
if !self.capabilities.native_windows || new.len() > self.capabilities.max_native_hosts {
return Err(error(Rule::Capability, "native hosts unavailable or at capacity"));
}
effects.push(HostEffect::CreateNative { host: host.clone(), section: section.clone() });
} else if self.layout.workspace != next.workspace || old.iter().any(|(h, s)| h == host && s != section) {
if !self.capabilities.native_windows {
return Err(error(Rule::Capability, "cannot rebind unsupported native host"));
}
effects.push(HostEffect::RebindNative { host: host.clone(), section: section.clone() });
}
}
for (host, _) in old {
if !new.iter().any(|(h, _)| *h == host) {
effects.push(HostEffect::ReleaseNative { host });
}
}
if interaction.focused.as_ref().is_some_and(|id| !next.containing(id).is_ok_and(|s| !s.collapsed && s.active == *id)) {
interaction.focused = None;
}
if interaction
.peek
.as_ref()
.is_some_and(|id| !next.instance(id).is_ok_and(|p| p.requested_open) || !next.containing(id).is_ok_and(|s| s.collapsed))
{
interaction.peek = None;
}
effects.retain(|effect| match effect {
HostEffect::Focus { instance } => interaction.focused.as_ref() == Some(instance),
HostEffect::Peek { instance } => interaction.peek.as_ref() == Some(instance),
_ => true,
});
let changed = next != self.layout || interaction != self.interaction || availability != self.availability || !effects.is_empty();
if changed && self.revision == u64::MAX {
return Err(error(Rule::Revision, "layout revision exhausted"));
}
Ok(PreparedLayout {
service_identity: self.identity.clone(),
base_revision: self.revision,
next,
interaction,
effects,
changed,
availability,
identities,
})
}
pub fn commit(&mut self, prepared: PreparedLayout) -> PanelResult<LayoutReply> {
if !std::sync::Arc::ptr_eq(&prepared.service_identity, &self.identity) || prepared.base_revision != self.revision {
return Err(error(Rule::Revision, "candidate became stale"));
}
if prepared.changed {
self.revision = self.revision.checked_add(1).ok_or_else(|| error(Rule::Revision, "layout revision exhausted"))?;
}
self.layout = prepared.next;
self.interaction = prepared.interaction;
self.availability = prepared.availability;
self.identities = prepared.identities;
self.reconcile_interaction();
let mut reply = self.inspect();
reply.effects = prepared.effects;
Ok(reply)
}
}
fn validate_availability(values: &AvailabilityMap) -> PanelResult<()> {
if values.len() > MAX_INSTANCES {
return Err(error(Rule::CollectionLimit, "availability map full"));
}
for (id, state) in values {
valid_id(&id.0)?;
if let Availability::Unavailable { reason } = state
&& (reason.is_empty() || reason.len() > 256)
{
return Err(error(Rule::Availability, "availability reason must contain 1..256 bytes"));
}
}
Ok(())
}
/// Close/Destroy are explicit, irreversible content intents. Do not infer them
/// solely from net layout differences, or permit later mutations to erase them.
pub fn validate_lifecycle_intents(mutations: &[Mutation]) -> PanelResult<()> {
if mutations.len() > MAX_MUTATIONS {
return Err(error(Rule::CollectionLimit, "lifecycle intent batch cap"));
}
let mut counts = std::collections::BTreeMap::<&InstanceId, (usize, bool)>::new();
for mutation in mutations {
let (id, terminal) = match mutation {
Mutation::Close { instance } | Mutation::Destroy { instance } => (instance, true),
Mutation::Open { instance, .. }
| Mutation::Move { instance, .. }
| Mutation::Activate { instance }
| Mutation::Focus { instance }
| Mutation::Peek { instance } => (instance, false),
_ => continue,
};
let entry = counts.entry(id).or_default();
entry.0 += 1;
entry.1 |= terminal;
if entry.1 && entry.0 > 1 {
return Err(error(Rule::Lifecycle, "Close/Destroy cannot share a batch with another operation on that instance"));
}
}
Ok(())
}
impl ActionSink for LayoutService {
fn project(&self, action: LayoutAction) -> PanelResult<Layout> {
Ok(self.prepare(action)?.layout().clone())
}
fn dispatch(&mut self, action: LayoutAction) -> PanelResult<LayoutReply> {
let prepared = self.prepare(action)?;
self.commit(prepared)
}
fn inspect(&self) -> LayoutReply {
LayoutReply {
api_version: PANEL_API_VERSION,
revision: self.revision,
layout: self.layout.clone(),
interaction: self.interaction.clone(),
effects: Vec::new(),
capabilities: self.capabilities.clone(),
availability: self.availability.clone(),
}
}
}
fn native_hosts(layout: &Layout) -> Vec<(HostId, SectionId)> {
layout
.sections
.iter()
.filter_map(|s| match &s.location {
SectionLocation::Window { host, .. } => Some((host.clone(), s.id.clone())),
_ => None,
})
.collect()
}
fn available(map: &AvailabilityMap, id: &InstanceId) -> PanelResult<()> {
if let Some(state) = map.get(id) {
state.require()?;
}
Ok(())
}
fn section_mut<'a>(layout: &'a mut Layout, id: &SectionId) -> PanelResult<&'a mut Section> {
layout.sections.iter_mut().find(|s| s.id == *id).ok_or_else(|| error(Rule::MissingTarget, "section not found"))
}
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 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,
location: section.location,
section_index,
tab_index,
size: section.size,
collapsed: section.collapsed,
};
Ok(())
}
fn detach(layout: &mut Layout, id: &InstanceId) {
for s in &mut layout.sections {
s.tabs.retain(|p| p != id);
if s.active == *id
&& let Some(first) = s.tabs.first()
{
s.active = first.clone();
}
}
layout.sections.retain(|s| !s.tabs.is_empty());
}
fn place(layout: &mut Layout, id: &InstanceId, destination: Destination) -> PanelResult<()> {
match destination {
Destination::NewSection { section, index, location, size } => {
valid_id(&section.0)?;
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 });
}
Destination::JoinTab { section, index } => {
let s = section_mut(layout, &section)?;
if index > s.tabs.len() {
return Err(error(Rule::Bounds, "tab insertion index out of bounds"));
}
s.tabs.insert(index, id.clone());
// Joining never steals active tab or resizes the group.
}
}
Ok(())
}
fn reopen_destination(layout: &Layout, p: &PanelInstance) -> Destination {
if let Ok(s) = layout.section(&p.memory.section) {
Destination::JoinTab { section: s.id.clone(), index: p.memory.tab_index.min(s.tabs.len()) }
} else {
Destination::NewSection {
section: p.memory.section.clone(),
index: p.memory.section_index.min(layout.sections.len()),
location: p.memory.location.clone(),
size: p.memory.size,
}
}
}
fn apply(
layout: &mut Layout,
registry: &PanelRegistry,
availability: &AvailabilityMap,
caps: &HostCapabilities,
interaction: &mut InteractionState,
effects: &mut Vec<HostEffect>,
mutation: Mutation,
) -> PanelResult<()> {
match mutation {
Mutation::Open { kind, instance, destination } => {
valid_id(&instance.0)?;
registry.get(&kind)?;
available(availability, &instance)?;
if let Ok(existing) = layout.instance(&instance) {
if existing.kind != kind {
return Err(error(Rule::DuplicateId, "instance belongs to another kind"));
}
if existing.requested_open {
if destination.is_some() {
return Err(error(Rule::Placement, "use Move for an open instance"));
}
return Ok(());
}
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)?;
if let Some(entry) = layout.instances.iter_mut().find(|p| p.id == instance) {
entry.requested_open = true;
}
if restore_collapsed && let Some(s) = layout.sections.iter_mut().find(|s| s.id == p.memory.section) {
s.collapsed = p.memory.collapsed;
}
} else {
let destination = destination.ok_or_else(|| error(Rule::Placement, "new instance requires explicit destination"))?;
place(layout, &instance, destination)?;
let s = layout.containing(&instance)?.clone();
layout.instances.push(PanelInstance {
id: instance.clone(),
kind,
requested_open: true,
memory: PlacementMemory {
section: s.id,
location: s.location,
section_index: 0,
tab_index: 0,
size: s.size,
collapsed: s.collapsed,
},
});
}
}
Mutation::Close { instance } => {
let p = layout.instance(&instance)?;
if !registry.get(&p.kind)?.features.closable {
return Err(error(Rule::FeatureDisabled, "panel is not closable"));
}
if p.requested_open {
remember(layout, &instance)?;
detach(layout, &instance);
if let Some(p) = layout.instances.iter_mut().find(|p| p.id == instance) {
p.requested_open = false;
}
}
}
Mutation::Destroy { instance } => {
if layout.instance(&instance)?.requested_open {
return Err(error(Rule::Lifecycle, "close before owner destruction"));
}
layout.instances.retain(|p| p.id != instance);
}
Mutation::Move { instance, destination } => {
if !layout.instance(&instance)?.requested_open {
return Err(error(Rule::Placement, "cannot move a closed instance"));
}
let collapsed = layout.containing(&instance)?.collapsed;
remember(layout, &instance)?;
detach(layout, &instance);
let new_section = match &destination {
Destination::NewSection { section, .. } => Some(section.clone()),
_ => None,
};
place(layout, &instance, destination)?;
if let Some(id) = new_section {
section_mut(layout, &id)?.collapsed = collapsed;
}
}
Mutation::Activate { instance } => {
available(availability, &instance)?;
let section = layout.containing(&instance)?.id.clone();
section_mut(layout, &section)?.active = instance;
}
Mutation::Focus { instance } => {
available(availability, &instance)?;
let p = layout.instance(&instance)?.clone();
if !p.requested_open {
let destination = reopen_destination(layout, &p);
place(layout, &instance, destination)?;
if let Some(entry) = layout.instances.iter_mut().find(|p| p.id == instance) {
entry.requested_open = true;
}
}
let section = layout.containing(&instance)?.id.clone();
let s = section_mut(layout, &section)?;
s.active = instance.clone();
s.collapsed = false;
interaction.peek = None;
interaction.focused = Some(instance.clone());
effects.push(HostEffect::Focus { instance });
}
Mutation::Peek { instance } => {
available(availability, &instance)?;
let s = layout.containing(&instance)?;
if !s.collapsed {
return Err(error(Rule::Placement, "peek requires a collapsed section"));
}
interaction.peek = Some(instance.clone());
effects.push(HostEffect::Peek { instance });
}
Mutation::DismissPeek => {
interaction.peek = None;
effects.push(HostEffect::DismissPeek);
}
Mutation::Collapse { section, collapsed } => {
section_mut(layout, &section)?.collapsed = collapsed;
}
Mutation::SetSize { section, size } => {
size.validate()?;
section_mut(layout, &section)?.size = size;
}
Mutation::ResizePair { first, second, first_size, second_size } => {
first_size.validate()?;
second_size.validate()?;
let (a, b, zone) = pair(layout, &first, &second)?;
let sum = |a: Size, b: Size| if zone == Zone::Bottom { a.width + b.width } else { a.height + b.height };
if (sum(a.size, b.size) - sum(first_size, second_size)).abs() > 0.01 {
return Err(error(Rule::Bounds, "paired sash must conserve shared extent"));
}
if zone == Zone::Bottom && (first_size.height != a.size.height || second_size.height != b.size.height)
|| zone != Zone::Bottom && (first_size.width != a.size.width || second_size.width != b.size.width)
{
return Err(error(Rule::Bounds, "paired sash changes only split axis"));
}
section_mut(layout, &first)?.size = first_size;
section_mut(layout, &second)?.size = second_size;
}
Mutation::ResetPair { first, second } => {
let (a, b, zone) = pair(layout, &first, &second)?;
let mut a_size = a.size;
let mut b_size = b.size;
let (a_min, a_max) = tab_bounds(layout, registry, a)?;
let (b_min, b_max) = tab_bounds(layout, registry, b)?;
let axis = |s: Size| if zone == Zone::Bottom { s.width } else { s.height };
let extent = axis(a_size) + axis(b_size);
let lo = axis(a_min).max(extent - axis(b_max));
let hi = axis(a_max).min(extent - axis(b_min));
if lo > hi {
return Err(error(Rule::Bounds, "pair cannot satisfy defaults within bounds"));
}
let a_default = registry.get(&layout.instance(&a.active)?.kind)?.default_size;
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);
if zone == Zone::Bottom {
a_size.width = split;
b_size.width = extent - split;
} else {
a_size.height = split;
b_size.height = extent - split;
}
section_mut(layout, &first)?.size = a_size;
section_mut(layout, &second)?.size = b_size;
}
Mutation::NativeClose { host } => {
valid_id(&host.0)?;
let index = layout
.sections
.iter()
.position(|s| matches!(&s.location, SectionLocation::Window { host: h, .. } if *h == host))
.ok_or_else(|| error(Rule::MissingTarget, "native host not found"))?;
let mut section = layout.sections.remove(index);
let SectionLocation::Window { return_to, .. } = section.location else {
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)
{
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));
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);
}
}
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 {
return Err(error(Rule::Capability, "native host limit"));
}
Ok(())
}
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"));
}
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();
if !zone.docked()
|| b.location.zone() != zone
|| !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"));
}
Ok((a, b, zone))
}
File diff suppressed because it is too large. Load diff
+1
View File
@@ -68,6 +68,7 @@ pub mod joints;
pub mod libraries;
pub mod mass_properties;
pub mod motion;
pub mod panels;
pub mod print_face;
pub mod render;
pub mod render_lights;
+298
View File
@@ -0,0 +1,298 @@
//! Strict external application-layout contracts. These are command parameters,
//! not another persistent layout model.
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use crate::panels::*;
/// Discovery and ParamCheck use the exact parser the injected executor uses.
pub struct CommandContract<P> {
id: &'static str,
typed: super::TypedContract<P>,
}
impl<P> CommandContract<P> {
pub const fn new(id: &'static str) -> Self {
Self { id, typed: super::TypedContract::new() }
}
}
impl<P: serde::de::DeserializeOwned + JsonSchema + 'static> super::Contract for CommandContract<P> {
fn input_schema(&self) -> schemars::Schema {
super::Contract::input_schema(&self.typed)
}
fn allowed_keys(&self) -> std::sync::Arc<std::collections::BTreeSet<String>> {
super::Contract::allowed_keys(&self.typed)
}
fn check(&self, params: &serde_json::Value) -> Vec<super::Issue> {
match crate::panels::commands::parse_command(self.id, params) {
Ok(_) => Vec::new(),
Err(reason) => {
// Keep the shared parser's bounds ahead of deserialization, but
// retain ordinary contract paths and unknown-key suggestions.
if reason.rule == Rule::Schema {
let issues = super::Contract::check(&self.typed, params);
if !issues.is_empty() {
return issues;
}
}
vec![super::Issue { path: String::new(), message: reason.to_string(), suggestion: None }]
}
}
}
}
#[derive(Clone, Debug, Deserialize, JsonSchema)]
#[serde(tag = "type", content = "id", rename_all = "snake_case", deny_unknown_fields)]
pub enum Target {
Workspace(WorkspaceId),
Instance(InstanceId),
Section(SectionId),
NativeHost(HostId),
}
impl From<Target> for LayoutTarget {
fn from(value: Target) -> Self {
match value {
Target::Workspace(id) => Self::Workspace(id),
Target::Instance(id) => Self::Instance(id),
Target::Section(id) => Self::Section(id),
Target::NativeHost(id) => Self::NativeHost(id),
}
}
}
#[derive(Clone, Copy, Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct OuterSize {
pub width: f32,
pub height: f32,
}
impl From<OuterSize> for Size {
fn from(value: OuterSize) -> Self {
Self { width: value.width, height: value.height }
}
}
#[derive(Clone, Copy, Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Origin {
pub x: f32,
pub y: f32,
}
impl From<Origin> for Point {
fn from(value: Origin) -> Self {
Self { x: value.x, y: value.y }
}
}
#[derive(Clone, Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ReturnJoin {
pub section: SectionId,
pub index: usize,
}
#[derive(Clone, Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ReturnTo {
pub zone: Zone,
pub index: usize,
pub size: OuterSize,
pub collapsed: bool,
#[serde(default)]
pub join: Option<ReturnJoin>,
}
impl From<ReturnTo> for DockReturn {
fn from(value: ReturnTo) -> Self {
Self {
zone: value.zone,
index: value.index,
size: value.size.into(),
collapsed: value.collapsed,
join: value.join.map(|join| ReturnTab { section: join.section, index: join.index }),
}
}
}
#[derive(Clone, Debug, Deserialize, JsonSchema)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub enum Location {
Dock { zone: Zone },
Floating { origin: Origin },
Window { host: HostId, origin: Origin, return_to: ReturnTo },
}
impl From<Location> for SectionLocation {
fn from(value: Location) -> Self {
match value {
Location::Dock { zone } => Self::Dock { zone },
Location::Floating { origin } => Self::Floating { origin: origin.into() },
Location::Window { host, origin, return_to } => Self::Window { host, origin: origin.into(), return_to: return_to.into() },
}
}
}
#[derive(Clone, Debug, Deserialize, JsonSchema)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub enum Placement {
NewSection { section: SectionId, index: usize, location: Location, size: OuterSize },
JoinTab { section: SectionId, index: usize },
}
impl From<Placement> for Destination {
fn from(value: Placement) -> Self {
match value {
Placement::NewSection { section, index, location, size } => {
Self::NewSection { section, index, location: location.into(), size: size.into() }
}
Placement::JoinTab { section, index } => Self::JoinTab { section, index },
}
}
}
#[derive(Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Empty {}
#[derive(Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Open {
pub kind: PanelKind,
pub instance: InstanceId,
pub destination: Option<Placement>,
pub expected_revision: Option<u64>,
}
#[derive(Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Select {
pub target: Option<Target>,
/// Compatibility selector: exact instance, or a single-instance canonical kind.
pub id: Option<String>,
pub expected_revision: Option<u64>,
}
#[derive(Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Move {
pub target: Option<Target>,
pub id: Option<String>,
pub destination: Placement,
pub expected_revision: Option<u64>,
}
#[derive(Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Resize {
pub target: Option<Target>,
pub id: Option<String>,
pub size: OuterSize,
pub expected_revision: Option<u64>,
}
#[derive(Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Collapse {
pub target: Option<Target>,
pub id: Option<String>,
pub collapsed: bool,
pub expected_revision: Option<u64>,
}
#[derive(Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Revision {
pub expected_revision: Option<u64>,
}
#[derive(Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ResizePair {
pub first: SectionId,
pub second: SectionId,
pub first_size: OuterSize,
pub second_size: OuterSize,
pub expected_revision: Option<u64>,
}
#[derive(Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ResetPair {
pub first: SectionId,
pub second: SectionId,
pub expected_revision: Option<u64>,
}
#[derive(Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Save {
pub name: String,
#[serde(default)]
pub overwrite: bool,
pub expected_revision: Option<u64>,
}
#[derive(Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Apply {
pub name: String,
pub expected_revision: Option<u64>,
}
#[derive(Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct WorkspaceSelect {
pub workspace: WorkspaceId,
pub expected_revision: Option<u64>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct WorkspaceSummary {
pub id: WorkspaceId,
pub title_key: String,
pub default_preset: String,
pub has_remembered_layout: bool,
}
#[derive(Debug, Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct GetReply {
pub state: LayoutReply,
pub workspaces: Vec<WorkspaceSummary>,
}
#[derive(Debug, Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ListReply {
pub state: LayoutReply,
pub kinds: Vec<PanelSpec>,
}
#[derive(Debug, Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct SaveReply {
pub name: String,
pub overwritten: bool,
pub state: LayoutReply,
}
#[derive(Debug, Serialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum WorkspaceSource {
Remembered,
DefaultPreset,
Unchanged,
}
#[derive(Debug, Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct WorkspaceReply {
pub previous_workspace: WorkspaceId,
pub source: WorkspaceSource,
pub state: LayoutReply,
}
/// Successful wire replies have no extensible object fields. Maps (availability)
/// remain maps. Persistence schemas intentionally retain their own opaque fields.
pub fn strict_output<T: JsonSchema>() -> schemars::Schema {
let mut schema = super::output_schema_for::<T>();
fn seal(value: &mut serde_json::Value) {
match value {
serde_json::Value::Object(object) => {
if object.contains_key("properties") {
object.insert("additionalProperties".into(), false.into());
}
for value in object.values_mut() {
seal(value);
}
}
serde_json::Value::Array(values) => values.iter_mut().for_each(seal),
_ => {}
}
}
if let Some(object) = schema.as_object_mut() {
if object.contains_key("properties") {
object.insert("additionalProperties".into(), false.into());
}
for value in object.values_mut() {
seal(value);
}
}
schema
}
+1 -1
View File
@@ -1182,7 +1182,7 @@ fn only_own_ids_name_commands() {
fn unknown_commands_suggest_the_closest_ids() {
let mut s = Session::default();
let mut msg = |id: &str| s.execute(id, &serde_json::json!({})).unwrap_err().to_string();
assert_eq!(msg("file.open"), "unknown command `file.open` (did you mean `doc.open`?)");
assert_eq!(msg("file.open"), "unknown command `file.open` (did you mean `doc.open` or `panel.open`?)");
assert!(msg("solid.extrud").starts_with("unknown command `solid.extrud` (did you mean `solid.extrude`"), "{}", msg("solid.extrud"));
assert!(msg("Extrude").contains("`solid.extrude`"), "{}", msg("Extrude"));
assert_eq!(msg("FusionFilletEdgesCommand"), "unknown command `FusionFilletEdgesCommand`");
+91 -4
View File
@@ -7,6 +7,8 @@ use std::time::{Duration, Instant};
use serde_json::{Value, json};
use solidcraft_engine::Session;
use solidcraft_engine::control_pending;
use solidcraft_engine::panels::ActionSink;
use solidcraft_engine::panels::commands::LayoutCatalogue;
use solidcraft_engine::render::StandardView;
use solidcraft_engine::schema::ParamCheck;
use solidcraft_engine::view::Guides;
@@ -559,6 +561,11 @@ impl Remote {
/// `strict` refuses a call that breaks its command's contract without sending it, and `warn`
/// sends it and adds the issues to the app's reply.
fn execute_checked(&mut self, params: Value) -> Result<Value, String> {
if let Some(id) = step_command(&params).filter(|id| solidcraft_engine::panels::commands::is_command(id)) {
let empty = json!({});
solidcraft_engine::panels::commands::parse_command(id, params.get("params").filter(|p| !p.is_null()).unwrap_or(&empty))
.map_err(solidcraft_engine::panels::commands::error_text)?;
}
if self.app_checks() {
let params = self.at_level(params);
let reply = self.call_once("engine.execute", params, true);
@@ -616,6 +623,7 @@ impl Backend for Remote {
"control.pending" => self.pending_status(),
"engine.execute" if self.param_check != ParamCheck::Off => self.execute_checked(params),
"engine.batch" if self.param_check != ParamCheck::Off => self.batch_checked(params),
"engine.script" if self.param_check != ParamCheck::Off => self.call_once(method, self.at_level(params), true),
_ => self.call_once(method, params, true),
}
}
@@ -644,6 +652,8 @@ pub struct Headless {
pub session: Session,
/// Orientation for renders; the camera is refitted to the model every time.
pub view: StandardView,
/// Application layout persists across calls, outside Session/document undo.
pub panels: solidcraft_engine::panels::PanelResult<solidcraft_engine::panels::commands::InMemoryPanelBackend>,
}
impl Default for Headless {
@@ -662,16 +672,77 @@ impl Headless {
}
Err(e) => session.log.push(format!("image host unavailable: {e}")),
}
Headless { session, view: StandardView::Iso }
Headless { session, view: StandardView::Iso, panels: solidcraft_engine::panels::commands::InMemoryPanelBackend::empty() }
}
pub fn with_panels(mut self, panels: solidcraft_engine::panels::commands::InMemoryPanelBackend) -> Self {
self.panels = Ok(panels);
self
}
fn execute_command(&mut self, id: &str, params: &Value) -> Result<Value, String> {
use solidcraft_engine::panels::commands;
if commands::is_command(id) {
self.panels.as_mut().map_err(|reason| commands::error_text(reason.clone()))?.execute(id, params).map_err(commands::error_text)
} else {
self.session.execute(id, params).map_err(|e| e.to_string())
}
}
fn panel_sequence(&mut self, method: &str, p: &Value, steps: &[Value]) -> Result<Value, String> {
use solidcraft_engine::panels::{Rule, commands, error};
if steps.len() > 100_000 {
return Err("script too long".into());
}
if method == "engine.batch"
&& let Some(refusal) = solidcraft_engine::batch_preflight::check(steps, self.session.param_check, &[])
{
return Ok(refusal.reply(steps.len()));
}
let panels = steps.iter().filter(|step| step_command(step).is_some_and(commands::is_command)).count();
if method == "engine.batch" && p.get("rollback").and_then(Value::as_bool).unwrap_or(true) {
if panels != steps.len() {
return Err(commands::error_text(error(
Rule::Capability,
"atomic mixed document/layout batches are unavailable; use rollback:false or separate transactions",
)));
}
return self.panels.as_mut().map_err(|reason| commands::error_text(reason.clone()))?.batch(steps).map_err(commands::error_text);
}
let mut results = Vec::new();
for (i, step) in steps.iter().enumerate() {
let empty = json!({});
let params = step.get("params").filter(|p| !p.is_null()).unwrap_or(&empty);
let result = step_command(step).ok_or_else(|| "missing command".to_string()).and_then(|id| self.execute_command(id, params));
match result {
Ok(result) => results.push(result),
Err(error) if method == "engine.batch" => return Ok(commands::sequential_failure(i, step_command(step), error, results)),
Err(error) => return Err(error),
}
}
if method == "engine.batch" { Ok(json!({"completed":results.len(),"results":results,"undone":0})) } else { Ok(json!(results)) }
}
}
fn step_command(step: &Value) -> Option<&str> {
step.get("command").or_else(|| step.get("id")).and_then(Value::as_str)
}
fn dim(p: &Value, k: &str, default: f64) -> u32 {
p.get(k).and_then(Value::as_f64).filter(|x| x.is_finite()).unwrap_or(default).clamp(16.0, 4096.0) as u32
}
impl Backend for Headless {
fn call(&mut self, method: &str, p: Value) -> Result<Value, String> {
impl Headless {
fn call_at_current_level(&mut self, method: &str, p: Value) -> Result<Value, String> {
if matches!(method, "engine.execute" | "command") && step_command(&p).is_some_and(solidcraft_engine::panels::commands::is_command) {
let empty = json!({});
return self.execute_command(step_command(&p).unwrap_or_default(), p.get("params").filter(|p| !p.is_null()).unwrap_or(&empty));
}
if matches!(method, "engine.script" | "engine.batch")
&& let Some(steps) = p
.as_array()
.or_else(|| p.get("commands").and_then(Value::as_array))
.filter(|steps| steps.iter().any(|step| step_command(step).is_some_and(solidcraft_engine::panels::commands::is_command)))
{
return self.panel_sequence(method, &p, steps);
}
let s = &mut self.session;
let str_p = |k: &str| p.get(k).and_then(Value::as_str);
match method {
@@ -738,6 +809,19 @@ impl Backend for Headless {
other => Err(format!("unknown method `{other}`")),
}
}
}
impl Backend for Headless {
fn call(&mut self, method: &str, p: Value) -> Result<Value, String> {
let own = self.session.param_check;
if matches!(method, "engine.execute" | "command" | "engine.batch" | "engine.script")
&& let Some(value) = p.get("param_check")
{
self.session.param_check = value.as_str().and_then(ParamCheck::parse).ok_or("`param_check` must be off, warn or strict")?;
}
let reply = self.call_at_current_level(method, p);
self.session.param_check = own;
reply
}
fn has_ui(&self) -> bool {
false
}
@@ -773,7 +857,10 @@ impl Auto {
/// Switch to the app when the session is still empty and one is running.
fn look_for_app(&mut self) {
let empty = self.headless.as_ref().is_some_and(|h| h.session.doc.features.is_empty());
let empty = self.headless.as_ref().is_some_and(|h| {
h.session.doc.features.is_empty()
&& h.panels.as_ref().is_ok_and(|panels| panels.service.inspect().revision == 0 && panels.catalogue.state().user_count() == 0)
});
if !empty {
return;
}
+309
View File
@@ -10,6 +10,315 @@ fn server() -> Server {
Server::new(Box::new(Headless::default()))
}
fn panel_headless() -> Headless {
Headless::new(solidcraft_engine::Session::default()).with_panels(solidcraft_engine::panels::fixture_command_backend().unwrap())
}
fn panel_mcp_steps() -> Vec<Value> {
vec![
json!({"command":"panel.open","params":{"kind":"fixture.log","instance":"log","destination":{"type":"new_section","section":"logs","index":0,
"location":{"type":"dock","zone":"left"},"size":{"width":280,"height":240}}}}),
json!({"command":"panel.collapse","params":{"target":{"type":"instance","id":"log"},"collapsed":true}}),
]
}
#[test]
fn headless_panel_single_batch_and_script_keep_one_backend_and_never_change_the_session() {
use crate::Backend;
let mut one = panel_headless();
let mut batch = panel_headless();
let mut script = panel_headless();
let doc = one.session.doc.clone();
let model = one.session.model.state();
let before = (one.session.document_id.clone(), one.session.revision, one.session.undo.len(), one.session.is_dirty(), one.session.camera);
for step in panel_mcp_steps() {
one.call("engine.execute", step).unwrap();
}
batch.call("engine.batch", json!({"commands":panel_mcp_steps()})).unwrap();
script.call("engine.script", json!({"commands":panel_mcp_steps()})).unwrap();
let state = one.call("engine.execute", json!({"command":"layout.get"})).unwrap();
assert_eq!(batch.call("engine.execute", json!({"command":"layout.get"})).unwrap()["state"]["layout"], state["state"]["layout"]);
assert_eq!(script.call("engine.execute", json!({"command":"layout.get"})).unwrap()["state"]["layout"], state["state"]["layout"]);
assert_eq!(state["state"]["capabilities"]["native_windows"], false);
assert_eq!((one.session.document_id.clone(), one.session.revision, one.session.undo.len(), one.session.is_dirty(), one.session.camera), before);
assert!(std::sync::Arc::ptr_eq(&doc, &one.session.doc));
assert!(std::sync::Arc::ptr_eq(&model, &one.session.model.state()));
one.call("engine.script", json!({"commands":[{"command":"layout.save","params":{"name":"MCP saved"}},{"command":"layout.reset"}]})).unwrap();
one.call("engine.execute", json!({"command":"layout.apply","params":{"name":"MCP saved"}})).unwrap();
assert_eq!(one.call("engine.execute", json!({"command":"layout.get"})).unwrap()["state"]["layout"], state["state"]["layout"]);
}
#[test]
fn mcp_panel_tools_publish_structured_errors_and_committed_state_through_shared_backend() {
let mut s = Server::new(Box::new(panel_headless()));
let input = panel_mcp_steps()[0].clone();
let result = tool(&mut s, "execute", input);
assert_eq!(result["layout"]["instances"][0]["id"], "log");
let result = tool(
&mut s,
"batch",
json!({"commands":[
{"command":"panel.collapse","params":{"target":{"type":"instance","id":"log"},"collapsed":true}},
{"command":"panel.peek","params":{"target":{"type":"instance","id":"log"}}}]}),
);
assert_eq!(result["completed"], 2);
let result = raw_tool(&mut s, "execute", json!({"command":"panel.focus","params":{"id":"fixture.log"}}));
assert_eq!(result["result"]["isError"], true);
assert_eq!(result["result"]["structuredContent"]["panel_error"]["rule"], "exactly_once");
let result = raw_tool(&mut s, "execute", json!({"command":"layout.get","params":{"unknown":true}}));
assert_eq!(result["result"]["structuredContent"]["panel_error"]["rule"], "schema");
}
#[test]
fn headless_catalogue_atomic_batch_failure_keeps_presets_and_layout_and_session_only_is_truthful() {
use crate::Backend;
use solidcraft_engine::panels::{ActionSink, commands::LayoutCatalogue};
let mut h = panel_headless();
let state = h.panels.as_ref().unwrap().service.inspect();
let catalogue = h.panels.as_ref().unwrap().catalogue.state().clone();
let error = h
.call(
"engine.batch",
json!({"commands":[
{"command":"layout.save","params":{"name":"Not committed"}},
{"command":"layout.workspace.select","params":{"workspace":"not-registered"}}]}),
)
.unwrap_err();
assert_eq!(solidcraft_engine::panels::commands::structured_error(&error).unwrap()["rule"], "missing_target");
assert_eq!(h.panels.as_ref().unwrap().service.inspect(), state);
assert_eq!(h.panels.as_ref().unwrap().catalogue.state(), &catalogue);
let mut plain = Headless::default();
let got = plain.call("engine.execute", json!({"command":"panel.list"})).unwrap();
assert!(got["kinds"].as_array().unwrap().is_empty());
assert_eq!(got["state"]["capabilities"]["native_windows"], false);
assert!(plain.call("engine.execute", json!({"command":"layout.reset"})).is_err());
assert!(solidcraft_engine::Session::default().run_script(&json!({"commands":[{"command":"layout.get"}]})).is_err());
}
#[test]
fn auto_backend_keeps_headless_layout_work_even_without_document_features() {
use crate::Backend;
use std::cell::Cell;
use std::rc::Rc;
let mut headless = panel_headless();
headless.call("engine.execute", json!({"command":"layout.save","params":{"name":"Owned headless layout"}})).unwrap();
let discoveries = Rc::new(Cell::new(0));
let seen = discoveries.clone();
let mut auto = crate::Auto::new(
headless,
Box::new(move || {
seen.set(seen.get() + 1);
None
}),
None,
);
assert_eq!(auto.call("engine.execute", json!({"command":"layout.get"})).unwrap()["state"]["layout"]["workspace"], "fixture.workspace");
assert_eq!(discoveries.get(), 0, "owned layout must not be discarded while probing for an app");
}
#[test]
fn remote_panel_single_batch_and_script_forward_to_one_authoritative_backend() {
use crate::Backend;
let authoritative = std::sync::Arc::new(std::sync::Mutex::new(solidcraft_engine::panels::fixture_command_backend().unwrap()));
let state = authoritative.clone();
// This is an authored local transport fixture, never run during implementation.
let (addr, seen) = scripted_app(move |request| {
let mut backend = state.lock().unwrap();
let params = &request["params"];
let result = match request["method"].as_str() {
Some("engine.execute") => backend.execute(params["command"].as_str().unwrap(), params.get("params").unwrap_or(&json!({}))),
Some("engine.batch") => backend.batch(params["commands"].as_array().unwrap()),
Some("engine.script") => {
let mut replies = Vec::new();
for step in params["commands"].as_array().unwrap() {
replies.push(backend.execute(step["command"].as_str().unwrap(), step.get("params").unwrap_or(&json!({}))).unwrap());
}
Ok(json!(replies))
}
_ => return json!({"ok":false,"error":"unknown method"}),
};
match result {
Ok(result) => json!({"ok":true,"result":result}),
Err(reason) => json!({"ok":false,"error":solidcraft_engine::panels::commands::error_text(reason)}),
}
});
let mut remote = crate::Remote::connect_with_token(&addr, Some("0123456789abcdef0123456789abcdef")).unwrap();
remote.call("engine.execute", panel_mcp_steps()[0].clone()).unwrap();
remote
.call(
"engine.batch",
json!({"commands":[panel_mcp_steps()[1].clone(),{"command":"panel.peek","params":{"target":{"type":"instance","id":"log"}}}]}),
)
.unwrap();
authoritative.lock().unwrap().execute("panel.collapse", &json!({"target":{"type":"instance","id":"log"},"collapsed":false})).unwrap();
assert_eq!(
remote.call("engine.execute", json!({"command":"layout.get"})).unwrap()["state"]["layout"]["sections"][0]["collapsed"],
false,
"remote reads external live changes"
);
remote
.call("engine.script", json!({"commands":[{"command":"layout.save","params":{"name":"Remote saved"}},{"command":"layout.reset"}]}))
.unwrap();
assert!(remote.call("engine.execute", json!({"command":"layout.get"})).unwrap()["state"]["layout"]["instances"].as_array().unwrap().is_empty());
let seen = seen.lock().unwrap();
assert!(seen.1.iter().any(|method| method == "engine.batch"));
assert!(seen.1.iter().any(|method| method == "engine.script"));
}
#[test]
fn headless_null_params_match_all_panel_routes_and_normal_document_sequences() {
use crate::Backend;
let mut headless = panel_headless();
let expected = headless.call("engine.execute", json!({"command":"panel.list","params":null})).unwrap();
for (method, rollback) in [("engine.batch", true), ("engine.batch", false), ("engine.script", false)] {
let reply = headless
.call(
method,
json!({"rollback":rollback,"commands":[
{"command":"panel.list","params":null},{"command":"layout.get","params":null},
]}),
)
.unwrap();
let results = if method == "engine.script" { &reply } else { &reply["results"] };
assert_eq!(results[0], expected);
assert_eq!(results[1]["state"], expected["state"]);
}
for method in ["engine.batch", "engine.script"] {
let previous = headless.session.document_id.clone();
let reply = headless
.call(
method,
json!({"rollback":false,"commands":[
{"command":"file.new","params":null},{"command":"panel.list","params":null},{"command":"parameters.list","params":null},
]}),
)
.unwrap();
assert!(reply.get("failed").is_none(), "{reply}");
assert_ne!(headless.session.document_id, previous);
}
}
struct LayoutFallbackBackend {
headless: Headless,
calls: Vec<(String, String)>,
}
impl LayoutFallbackBackend {
fn new() -> Self {
Self { headless: panel_headless(), calls: Vec::new() }
}
}
impl crate::Backend for LayoutFallbackBackend {
fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
self.calls.push((method.into(), params.get("command").and_then(Value::as_str).unwrap_or_default().into()));
if method == "engine.batch" {
return Err("engine.batch unavailable: fixture has no atomic endpoint".into());
}
crate::Backend::call(&mut self.headless, method, params)
}
fn has_ui(&self) -> bool {
false
}
fn in_process(&self) -> bool {
true
}
fn describe(&self) -> String {
"synthetic layout fallback boundary".into()
}
}
fn fallback_tool_reply(backend: &mut LayoutFallbackBackend, args: Value) -> (Value, Value) {
let tool = crate::tools::call_tool(backend, "batch", &args);
let body = serde_json::from_str(tool["content"][0]["text"].as_str().unwrap()).unwrap();
(tool, body)
}
#[test]
fn atomic_tool_layout_batches_never_emulate_an_unavailable_backend_with_document_undo() {
use solidcraft_engine::panels::{ActionSink, commands::LayoutCatalogue};
let open = panel_mcp_steps()[0].clone();
for steps in [
json!([open.clone()]),
json!([open.clone(),{"command":"parameters.change","params":{"name":"broken","expression":"("}}]),
json!([{"command":"execute","params":{"command":"panel.open","params":open["params"]}}]),
] {
let mut backend = LayoutFallbackBackend::new();
let before = backend.headless.panels.as_ref().unwrap().service.inspect();
let catalogue = backend.headless.panels.as_ref().unwrap().catalogue.state().clone();
let document = backend.headless.session.doc.clone();
let model = backend.headless.session.model.state();
let session = (backend.headless.session.revision, backend.headless.session.undo.len(), backend.headless.session.is_dirty());
let (tool, body) = fallback_tool_reply(&mut backend, json!({"commands":steps}));
assert_eq!(tool["isError"], true);
assert_eq!(tool["structuredContent"]["panel_error"]["rule"], "capability");
assert_eq!(body["completed"], 0);
assert_eq!(body["applied"], json!([]));
assert_eq!(body["rolled_back"], false);
assert_eq!(backend.calls, vec![("engine.batch".into(), String::new())], "no checkpoint, inspection or single layout call");
assert_eq!(backend.headless.panels.as_ref().unwrap().service.inspect(), before);
assert_eq!(backend.headless.panels.as_ref().unwrap().catalogue.state(), &catalogue);
assert!(std::sync::Arc::ptr_eq(&document, &backend.headless.session.doc));
assert!(std::sync::Arc::ptr_eq(&model, &backend.headless.session.model.state()));
assert_eq!((backend.headless.session.revision, backend.headless.session.undo.len(), backend.headless.session.is_dirty()), session);
}
}
#[test]
fn oversized_atomic_tool_layout_batch_refuses_before_any_backend_or_checkpoint_call() {
use solidcraft_engine::panels::{ActionSink, commands::LayoutCatalogue};
let mut backend = LayoutFallbackBackend::new();
let before = backend.headless.panels.as_ref().unwrap().service.inspect();
let catalogue = backend.headless.panels.as_ref().unwrap().catalogue.state().clone();
let document = backend.headless.session.doc.clone();
let model = backend.headless.session.model.state();
let args = json!({"commands":[panel_mcp_steps()[0],{"command":"parameters.change","params":{"name":"broken","expression":"x".repeat(solidcraft_engine::MAX_LINE-32768)}}]});
assert!(args.to_string().len() < solidcraft_engine::MAX_LINE, "fixture fits the incoming line but exceeds the outgoing margin");
let (tool, body) = fallback_tool_reply(&mut backend, args);
assert_eq!(tool["isError"], true);
assert_eq!(tool["structuredContent"]["panel_error"]["rule"], "collection_limit");
assert_eq!(body["completed"], 0);
assert_eq!(body["applied"], json!([]));
assert!(backend.calls.is_empty());
assert_eq!(backend.headless.panels.as_ref().unwrap().service.inspect(), before);
assert_eq!(backend.headless.panels.as_ref().unwrap().catalogue.state(), &catalogue);
assert!(std::sync::Arc::ptr_eq(&document, &backend.headless.session.doc));
assert!(std::sync::Arc::ptr_eq(&model, &backend.headless.session.model.state()));
}
#[test]
fn sequential_tool_layout_fallback_truthfully_retains_completed_changes_without_checkpointing() {
use solidcraft_engine::panels::{ActionSink, InstanceId, commands::LayoutCatalogue};
let mut backend = LayoutFallbackBackend::new();
let (_, body) = fallback_tool_reply(
&mut backend,
json!({"rollback":false,"commands":[
panel_mcp_steps()[0],{"command":"parameters.change","params":{"name":"broken","expression":"("}},
]}),
);
assert_eq!(body["ok"], false);
assert_eq!(body["completed"], 1);
assert_eq!(body["applied"], json!([0]));
assert_eq!(body["rolled_back"], false);
assert_eq!(body["undone"], 0);
let panels = backend.headless.panels.as_ref().unwrap();
assert!(panels.service.layout().instance(&InstanceId::new("log").unwrap()).unwrap().requested_open);
assert_eq!(panels.service.inspect().revision, 1);
assert!(panels.catalogue.state().remembered(&panels.service.layout().workspace).is_some());
assert!(!backend.calls.iter().any(|(_, command)| command == "edit.checkpoint" || command == "edit.restore_checkpoint"));
assert_eq!(backend.calls.iter().filter(|(_, command)| command == "panel.open").count(), 1);
}
#[test]
fn document_only_atomic_tool_fallback_keeps_existing_checkpoint_rollback_behavior() {
let mut backend = LayoutFallbackBackend::new();
let (_, body) = fallback_tool_reply(
&mut backend,
json!({"commands":[
{"command":"parameters.change","params":{"name":"temporary","expression":1}},
{"command":"parameters.change","params":{"name":"broken","expression":"("}},
]}),
);
assert_eq!(body["rolled_back"], true, "{body}");
assert_eq!(body["applied"], json!([]));
assert!(backend.headless.session.doc.param("temporary").is_none());
assert!(backend.calls.iter().any(|(_, command)| command == "edit.checkpoint"));
assert!(backend.calls.iter().any(|(_, command)| command == "edit.restore_checkpoint"));
}
/// Screenshots are drawn on the GPU by the renderer the host installs (`solidcraft-cli mcp`); the
/// tests install the same one. `false`, with the reason printed, on a machine without a GPU
/// adapter: the screenshots are then left out of the test.
+49 -1
View File
@@ -514,6 +514,13 @@ fn text_result(v: &Value, is_error: bool) -> Value {
let mut r = json!({"content": [{"type": "text", "text": text}]});
if is_error {
r["isError"] = json!(true);
if let Some(reason) = v
.as_str()
.and_then(solidcraft_engine::panels::commands::structured_error)
.or_else(|| v.get("failed").and_then(|failed| failed.get("panel_error")).cloned())
{
r["structuredContent"] = json!({"panel_error":reason});
}
}
r
}
@@ -1161,12 +1168,36 @@ fn batch(b: &mut dyn Backend, a: &Map<String, Value>) -> Value {
}
}
fn layout_step(step: &Value) -> bool {
let command = step.get("command").or_else(|| step.get("id")).and_then(Value::as_str).unwrap_or_default();
let command = if command == "execute" {
step.get("params").and_then(|params| params.get("command")).and_then(Value::as_str).unwrap_or_default()
} else {
command
};
command.split('.').next().is_some_and(|area| area.eq_ignore_ascii_case("panel") || area.eq_ignore_ascii_case("layout"))
}
fn atomic_layout_refusal(count: usize, rule: solidcraft_engine::panels::Rule, detail: &str) -> (Value, bool) {
use solidcraft_engine::panels::{commands, error};
let mut reply = commands::sequential_failure(0, None, commands::error_text(error(rule, detail)), Vec::new());
reply["ok"] = json!(false);
reply["applied"] = json!([]);
reply["not_run"] = if count <= MAX_BATCH { json!((0..count).collect::<Vec<_>>()) } else { json!([]) };
reply["not_run_count"] = json!(count);
reply["note"] = json!("nothing was run: atomic application layout requires the authoritative backend transaction");
(reply, true)
}
/// The batch itself: its reply and whether it failed.
fn batch_run(b: &mut dyn Backend, a: &Map<String, Value>) -> (Value, bool) {
let Some(steps) = a.get("commands").and_then(Value::as_array) else {
return (json!("`commands` must be an array of {command, params}"), true);
};
if steps.len() > MAX_BATCH {
if a.get("rollback").and_then(Value::as_bool).unwrap_or(true) && steps.iter().any(layout_step) {
return atomic_layout_refusal(steps.len(), solidcraft_engine::panels::Rule::CollectionLimit, "atomic layout batch step count cap");
}
return (json!(format!("batch too long ({} steps, at most {MAX_BATCH})", steps.len())), true);
}
let rollback = a.get("rollback").and_then(Value::as_bool).unwrap_or(true);
@@ -1217,6 +1248,7 @@ fn batch_run(b: &mut dyn Backend, a: &Map<String, Value>) -> (Value, bool) {
}
}
let steps = &mapped;
let atomic_layout = rollback && steps.iter().any(layout_step);
// A step the batch would refuse at its turn refuses it now, before anything runs (#5853).
// Only where the commands run in this process: a running app may be another version, with
// commands this one lacks, and checks the batch against its own registry when it gets it.
@@ -1251,7 +1283,8 @@ fn batch_run(b: &mut dyn Backend, a: &Map<String, Value>) -> (Value, bool) {
o.insert("timings".into(), Value::Bool(true));
o.insert("profile".into(), Value::Bool(profile));
}
if params.to_string().len() + 64 * 1024 <= solidcraft_engine::MAX_LINE {
let fits_transport = params.to_string().len().saturating_add(64 * 1024) <= solidcraft_engine::MAX_LINE;
if fits_transport {
match b.call("engine.batch", params) {
Ok(mut r) => {
if let Some(failed) = r.get_mut("failed")
@@ -1266,6 +1299,7 @@ fn batch_run(b: &mut dyn Backend, a: &Map<String, Value>) -> (Value, bool) {
}
// Older apps and the headless session, or the app wants the steps one by one.
Err(e) if e.starts_with("unknown method") || e.starts_with("engine.batch unavailable") => {}
Err(e) if solidcraft_engine::panels::commands::structured_error(&e).is_some() => return (Value::String(e), true),
// Never sent: no app to send it to. Or sent and still running (it was not cancelled):
// the `pending` tool gets its result.
Err(e) if e.starts_with(crate::backend::NOT_RUNNING) || e.starts_with(STILL_RUNNING) => {
@@ -1278,6 +1312,20 @@ fn batch_run(b: &mut dyn Backend, a: &Map<String, Value>) -> (Value, bool) {
}
}
}
// Application layout is outside document checkpoints. Neither an unavailable
// batch endpoint nor an oversized transport request authorizes a sequential
// emulation of an atomic layout/mixed transaction.
if atomic_layout {
return atomic_layout_refusal(
steps.len(),
if fits_transport { solidcraft_engine::panels::Rule::Capability } else { solidcraft_engine::panels::Rule::CollectionLimit },
if fits_transport {
"authoritative atomic layout batch capability is unavailable"
} else {
"atomic layout batch exceeds transport size cap"
},
);
}
let start = if rollback { Undo::begin(b) } else { Undo::None };
let mut results = Vec::with_capacity(steps.len());
let mut rows = Vec::new();
+3
View File
@@ -272,6 +272,9 @@ fn batch_targets(steps: &[Value]) -> Vec<(Pos2, &'static str)> {
/// The places a command's parameters pick, in the world: [x, y, z] points (faces, edges,
/// vertices, positions), active-sketch [x, y] points, and a new sketch's plane.
pub fn picks(app: &SolveApp, command: &str, params: &Value) -> Vec<Vec3> {
if solidcraft_engine::panels::commands::is_command(command) {
return Vec::new();
}
let id = solidcraft_engine::find_command(command).map_or(command, |c| c.id);
let mut out = Vec::new();
if id == "sketch.create"
+20
View File
@@ -91,6 +91,11 @@ pub const DOCUMENTED: &[&str] = &[
"joint.reach",
"joint.rigid_group",
"joint.screw",
"layout.apply",
"layout.get",
"layout.reset",
"layout.save",
"layout.workspace.select",
"library.apply",
"library.export",
"library.inspect",
@@ -101,6 +106,21 @@ pub const DOCUMENTED: &[&str] = &[
"motion.trace",
"occurrence.ground",
"occurrence.move",
"panel.activate",
"panel.close",
"panel.collapse",
"panel.dismiss",
"panel.float",
"panel.focus",
"panel.list",
"panel.move",
"panel.native_close",
"panel.open",
"panel.peek",
"panel.popout",
"panel.reset_pair",
"panel.resize",
"panel.resize_pair",
"parameters.change",
"parameters.export",
"parameters.graph",
+226 -1
View File
@@ -176,7 +176,12 @@ fn ok(v: Value) -> Outcome {
Outcome::Done(json!({"ok": true, "result": v}))
}
fn err(e: impl std::fmt::Display) -> Outcome {
Outcome::Done(json!({"ok": false, "error": e.to_string()}))
let text = e.to_string();
let mut reply = json!({"ok": false, "error": text});
if let Some(reason) = solidcraft_engine::panels::commands::structured_error(&text) {
reply["panel_error"] = reason;
}
Outcome::Done(reply)
}
fn wrap(r: Result<Value, String>) -> Outcome {
match r {
@@ -266,6 +271,10 @@ fn key_from(name: &str) -> Option<egui::Key> {
/// Run one command as `engine.execute` does: through `app.run`, then the first-body fit and the
/// camera the command asked for.
fn execute(app: &mut SolveApp, id: &str, params: Value) -> Result<Value, String> {
if solidcraft_engine::panels::commands::is_command(id) {
// No first-body meshing, camera-follow or fit tail for application layout.
return app.run(id, params);
}
// User bindings live in the UI. A bridged agent needs the same key the menus show,
// including null for a cleared binding; the standalone engine keeps its defaults.
if id == "engine.commands" {
@@ -379,6 +388,38 @@ fn batch(app: &mut SolveApp, p: &Value) -> Outcome {
let Some(steps) = p.get("commands").and_then(Value::as_array).filter(|s| s.len() <= MAX_BATCH) else {
return err(format!("engine.batch: commands must be an array of at most {MAX_BATCH} steps"));
};
let panels = steps.iter().filter(|step| command(step).is_some_and(solidcraft_engine::panels::commands::is_command)).count();
if panels > 0 {
if let Some(why) = batch_refusal(steps) {
return err(why);
}
if let Some(refusal) = solidcraft_engine::batch_preflight::check(steps, app.session.param_check, &["view.pick"]) {
return ok(refusal.reply(steps.len()));
}
let rollback = p.get("rollback").and_then(Value::as_bool).unwrap_or(true);
if rollback {
if panels != steps.len() {
return err(solidcraft_engine::panels::commands::error_text(solidcraft_engine::panels::error(
solidcraft_engine::panels::Rule::Capability,
"atomic mixed document/layout batches are unavailable; use rollback:false or separate transactions",
)));
}
return wrap(app.run_panel_batch(steps).map_err(solidcraft_engine::panels::commands::error_text));
}
// Explicit sequential mode has per-command atomicity and no document
// checkpoint; previous application changes are truthfully retained.
let mut results = Vec::new();
for (i, step) in steps.iter().enumerate() {
let result = command(step)
.ok_or_else(|| "missing command".to_string())
.and_then(|id| execute(app, id, step.get("params").cloned().filter(|p| !p.is_null()).unwrap_or(json!({}))));
match result {
Ok(result) => results.push(result),
Err(error) => return ok(solidcraft_engine::panels::commands::sequential_failure(i, command(step), error, results)),
}
}
return ok(json!({"completed":results.len(),"results":results,"undone":0}));
}
// (With the agent cursor shown, the pointer has already acted out a short summary of the
// batch: `agent_cursor::intercept`.)
if let Some(why) = batch_refusal(steps) {
@@ -684,6 +725,30 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) ->
if let Some(c) = steps.and_then(|steps| steps.iter().find_map(switches_design)) {
return err(format!("engine.script unavailable: {c} switches to another design (send it on its own)"));
}
if let Some(steps) =
steps.filter(|steps| steps.iter().any(|step| command(step).is_some_and(solidcraft_engine::panels::commands::is_command)))
{
if steps.len() > 100_000 {
return err("script too long");
}
let mut results = Vec::new();
for (i, step) in steps.iter().enumerate() {
let result = command(step)
.ok_or_else(|| "missing command".to_string())
.and_then(|id| execute(app, id, step.get("params").cloned().filter(|p| !p.is_null()).unwrap_or(json!({}))));
match result {
Ok(result) => results.push(result),
Err(error) => {
let mut reply = json!({"ok":false,"error":error,"step":i + 1});
if let Some(reason) = solidcraft_engine::panels::commands::structured_error(&error) {
reply["panel_error"] = reason;
}
return Outcome::Done(reply);
}
}
}
return ok(json!(results));
}
let mut replaced = false;
let r = app
.session
@@ -1466,6 +1531,166 @@ pub(crate) fn write_screenshot(image: &egui::ColorImage, path: &str) -> Result<(
#[cfg(test)]
mod tests {
fn panel_command_app() -> crate::SolveApp {
use crate::panel_runtime::*;
let h = PanelMountHarness::new(false).unwrap();
let catalogue = solidcraft_engine::panels::fixture_command_catalogue(h.runtime.layout().registry()).unwrap();
let mut app = crate::SolveApp::new(solidcraft_engine::Session::default(), Default::default());
app.enable_panel_runtime(h.runtime, Box::<FakeAppPanelServices>::default()).unwrap();
app.panel_runtime_mut().unwrap().set_command_adapters(Box::new(catalogue), Box::new(FakeNativeAdapter::new(false))).unwrap();
app
}
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) {
super::Outcome::Done(reply) => reply,
_ => panic!("unexpected screenshot"),
}
}
fn panel_steps() -> Vec<serde_json::Value> {
vec![
json!({"command":"panel.open","params":{"kind":"fixture.log","instance":"log","destination":{"type":"new_section","section":"logs","index":0,
"location":{"type":"dock","zone":"left"},"size":{"width":280,"height":240}}}}),
json!({"command":"panel.collapse","params":{"target":{"type":"instance","id":"log"},"collapsed":true}}),
]
}
#[test]
fn panel_control_single_atomic_batch_and_script_share_live_runtime_without_geometry_or_camera_work() {
use solidcraft_engine::panels::ActionSink;
let mut single = panel_command_app();
let mut batch = panel_command_app();
let mut script = panel_command_app();
// A one-body design with a deliberately different camera exercises the
// old first-body-fit condition, rather than making it vacuously false.
for app in [&mut single, &mut batch, &mut script] {
app.run("solid.box", json!({"length":10,"width":10,"height":10})).unwrap();
app.cam.distance *= 1.5;
app.session.mark_saved();
}
let doc = single.session.doc.clone();
let model = single.session.model.state();
let camera = single.cam;
let meshes: Vec<_> = model.bodies.iter().map(|body| body.cached_mesh()).collect();
let invariant = (single.session.document_id.clone(), single.session.revision, single.session.undo.len(), single.session.is_dirty());
for step in panel_steps() {
assert_eq!(panel_control(&mut single, "engine.execute", step)["ok"], true);
}
assert_eq!(panel_control(&mut batch, "engine.batch", json!({"commands":panel_steps(),"param_check":"strict"}))["ok"], true);
assert_eq!(panel_control(&mut script, "engine.script", json!({"commands":panel_steps(),"param_check":"strict"}))["ok"], true);
let live = single.panel_runtime().unwrap().layout().inspect();
assert_eq!(batch.panel_runtime().unwrap().layout().layout(), &live.layout);
assert_eq!(script.panel_runtime().unwrap().layout().layout(), &live.layout);
assert_eq!(panel_control(&mut single, "engine.execute", json!({"command":"layout.get"}))["result"]["state"]["revision"], live.revision);
assert!(crate::agent_cursor::picks(&single, "panel.open", &panel_steps()[0]["params"]).is_empty());
assert_eq!(single.cam, camera);
assert_eq!((single.session.document_id.clone(), single.session.revision, single.session.undo.len(), single.session.is_dirty()), invariant);
assert!(std::sync::Arc::ptr_eq(&doc, &single.session.doc));
assert!(std::sync::Arc::ptr_eq(&model, &single.session.model.state()));
for (old, new) in meshes.iter().zip(single.session.model.state().bodies.iter().map(|body| body.cached_mesh())) {
match (old, new) {
(Some(a), Some(b)) => assert!(std::sync::Arc::ptr_eq(a, &b)),
(None, None) => {}
_ => panic!("layout changed tessellation cache"),
}
}
}
#[test]
fn panel_control_reports_structured_missing_capability_unknown_fields_and_lifecycle_batch_errors() {
use solidcraft_engine::panels::ActionSink;
let mut disabled = crate::SolveApp::new(solidcraft_engine::Session::default(), Default::default());
let reply = panel_control(&mut disabled, "engine.execute", json!({"command":"layout.get"}));
assert_eq!(reply["ok"], false);
assert_eq!(reply["panel_error"]["rule"], "capability");
let mut app = panel_command_app();
for check in ["off", "warn", "strict"] {
let reply = panel_control(&mut app, "engine.execute", json!({"command":"panel.list","params":{"unknown":true},"param_check":check}));
assert_eq!(reply["ok"], false);
assert_eq!(reply["panel_error"]["rule"], "schema");
assert_eq!(reply["param_check"], check);
}
panel_control(&mut app, "engine.execute", panel_steps()[0].clone());
let before = app.panel_runtime().unwrap().layout().inspect();
let reply = panel_control(
&mut app,
"engine.batch",
json!({"commands":[
{"command":"panel.close","params":{"target":{"type":"instance","id":"log"}}},
{"command":"panel.open","params":{"kind":"fixture.log","instance":"log"}}]}),
);
assert_eq!(reply["ok"], false);
assert_eq!(reply["panel_error"]["rule"], "lifecycle");
assert_eq!(app.panel_runtime().unwrap().layout().inspect(), before);
}
#[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());
let reply = panel_control(
&mut app,
"engine.batch",
json!({"commands":[
{"command":"layout.save","params":{"name":"Control saved"}},
{"command":"layout.reset"}, {"command":"layout.apply","params":{"name":"Control saved"}}, {"command":"layout.get"}]}),
);
assert_eq!(reply["ok"], true, "{reply}");
assert_eq!(reply["result"]["completed"], 4);
assert_eq!(reply["result"]["results"][3]["state"]["layout"]["instances"][0]["id"], "log");
let mixed = json!({"commands":[{"command":"layout.get"},{"command":"file.new"}]});
let before = app.session.document_id.clone();
let reply = panel_control(&mut app, "engine.batch", mixed);
assert_eq!(reply["panel_error"]["rule"], "capability");
assert_eq!(app.session.document_id, before);
let reply = panel_control(
&mut app,
"engine.script",
json!({"commands":[
{"command":"layout.workspace.select","params":{"workspace":"fixture.other"}},
{"command":"layout.apply","params":{"name":"Control saved"}}, {"command":"layout.get"}]}),
);
assert_eq!(reply["ok"], true, "{reply}");
assert_eq!(reply["result"][2]["state"]["layout"]["workspace"], "fixture.other");
}
#[test]
fn null_panel_params_match_single_atomic_sequential_and_script_routes() {
let mut app = panel_command_app();
let expected = app.run("panel.list", json!({})).unwrap();
assert_eq!(app.run("panel.list", serde_json::Value::Null).unwrap(), expected);
let single = panel_control(&mut app, "engine.execute", json!({"command":"panel.list","params":null}));
assert_eq!(single["result"], expected);
for (method, rollback) in [("engine.batch", true), ("engine.batch", false), ("engine.script", false)] {
let reply = panel_control(
&mut app,
method,
json!({"rollback":rollback,"commands":[
{"command":"panel.list","params":null},{"command":"layout.get","params":null},
]}),
);
assert_eq!(reply["ok"], true, "{method}: {reply}");
let results = if method == "engine.script" { &reply["result"] } else { &reply["result"]["results"] };
assert_eq!(results[0], expected, "{method}");
assert_eq!(results[1]["state"], expected["state"]);
}
}
#[test]
fn null_normal_document_params_remain_accepted_in_panel_containing_sequences() {
for method in ["engine.batch", "engine.script"] {
let mut app = panel_command_app();
let previous = app.session.document_id.clone();
let reply = panel_control(
&mut app,
method,
json!({"rollback":false,"commands":[
{"command":"file.new","params":null},{"command":"panel.list","params":null},{"command":"parameters.list","params":null},
]}),
);
assert_eq!(reply["ok"], true, "{reply}");
assert!(reply["result"].get("failed").is_none(), "{reply}");
assert_ne!(app.session.document_id, previous);
assert_eq!(app.panel_runtime().unwrap().environment().document.as_ref().unwrap().0, app.session.document_id);
}
}
#[test]
fn blur_control_validates_before_mutation_and_reports_no_gpu() {
let mut h = crate::scenario::Harness::new();
+14
View File
@@ -194,6 +194,7 @@ pub mod network_prompt;
pub mod op_auto;
pub mod open_elsewhere;
pub(crate) mod open_meshing;
pub mod panel_runtime;
pub mod params_dialog;
pub mod personal_sheet_rules;
pub(crate) mod pick_index;
@@ -509,6 +510,8 @@ pub(crate) enum EscapeOwner {
}
pub struct SolveApp {
/// Common panel foundation, internal opt-in; stays on the app across document tabs.
pub(crate) panel_runtime: Option<panel_runtime::AppPanelRuntime>,
pub blur: blur::State,
pub(crate) viewport_status: ui_kit::StatusPresentation,
pub(crate) viewport_status_fixture: viewport_status_fixture::Fixture,
@@ -784,6 +787,7 @@ impl SolveApp {
#[cfg(not(target_arch = "wasm32"))]
solidcraft_engine::slicer_files::clean_old();
let mut app = SolveApp {
panel_runtime: None,
viewport_status: Default::default(),
blur: Default::default(),
viewport_status_fixture: Default::default(),
@@ -1159,6 +1163,9 @@ impl SolveApp {
/// Run a command programmatically (JSON parameters, no dialogs).
pub fn run(&mut self, id: &str, params: Value) -> Result<Value, String> {
if solidcraft_engine::panels::commands::is_command(id) {
return self.run_panel_command(id, &params).map_err(solidcraft_engine::panels::commands::error_text);
}
if self.file_load.busy() || self.file_picker.is_some() || self.saving.is_some() {
return Err("a file operation is in progress".into());
}
@@ -1550,6 +1557,12 @@ impl SolveApp {
}
fn start_with_variant_memory(&mut self, id: &str, remember_variant: bool, opener: Option<egui::Rect>, section_edit: bool) {
if solidcraft_engine::panels::commands::is_command(id) {
if let Err(why) = self.run(id, json!({})) {
self.set_status(why, true);
}
return;
}
self.tree.clear_folder_pick();
if id == "timeline.play" {
if let Err(why) = self.run(id, json!({})) {
@@ -2794,6 +2807,7 @@ impl SolveApp {
/// Per-frame logic before layout.
pub fn logic(&mut self, ctx: &egui::Context) {
panel_runtime::tick_app(self);
// 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);
+211
View File
@@ -0,0 +1,211 @@
use solidcraft_engine::Session;
use solidcraft_engine::panels::*;
use super::*;
/// Later content adapters supply their own services. The app integration exposes
/// only an immutable Session during refresh; a layout tick cannot run a document
/// command. Explicit content commands stay on the separate supplied sink.
pub trait AppPanelServices {
fn refresh_read_only(&mut self, session: &Session) -> PanelResult<()>;
fn services(&mut self) -> ContentServices<'_>;
}
pub struct AppPanelRuntime {
runtime: PanelRuntime,
services: Box<dyn AppPanelServices>,
last_error: Option<PanelError>,
catalogue: Box<dyn commands::LayoutCatalogue>,
native: Box<dyn NativeHostAdapter>,
adapters_set: bool,
}
impl AppPanelRuntime {
pub fn new(runtime: PanelRuntime, services: Box<dyn AppPanelServices>) -> Self {
Self {
runtime,
services,
last_error: None,
catalogue: Box::<commands::InMemoryCatalogue>::default(),
native: Box::new(UnavailableNative),
adapters_set: false,
}
}
pub fn last_error(&self) -> Option<&PanelError> {
self.last_error.as_ref()
}
pub fn runtime(&self) -> &PanelRuntime {
&self.runtime
}
/// Internal capability injection. Production preferences/native realization
/// remain peer work. Installation is once-only and precedes native hosts.
pub fn set_command_adapters(&mut self, catalogue: Box<dyn commands::LayoutCatalogue>, native: Box<dyn NativeHostAdapter>) -> PanelResult<()> {
if self.adapters_set {
return Err(error(Rule::Lifecycle, "application panel adapters are already installed"));
}
if self.runtime.layout().layout().sections.iter().any(|s| matches!(&s.location, SectionLocation::Window { .. })) {
return Err(error(Rule::Lifecycle, "cannot replace adapters with live native hosts"));
}
self.catalogue = catalogue;
self.native = native;
self.adapters_set = true;
Ok(())
}
/// Actual application boundaries refresh the current document/model context
/// even when no frame tick ran between two sequential programmatic steps.
fn refresh_context(&mut self, session: &Session) -> PanelResult<()> {
self.services.refresh_read_only(session)?;
let mut environment = self.runtime.environment().clone();
environment.document = Some(DocumentId::new(session.document_id.clone())?);
let services = self.services.services();
self.runtime.set_environment(environment, services.local)?;
self.runtime.refresh_context(services.models, services.local)
}
pub fn command(&mut self, session: &Session, id: &str, params: &serde_json::Value) -> PanelResult<serde_json::Value> {
self.refresh_context(session)?;
let registry = self.runtime.layout().registry().clone();
let mut services = self.services.services();
let mut sink = RuntimeActionSink { runtime: &mut self.runtime, native: self.native.as_mut(), services: &mut services };
commands::execute(
id,
params,
&mut commands::PanelCommandContext {
sink: &mut sink,
registry: &registry,
catalogue: self.catalogue.as_mut(),
web: cfg!(target_arch = "wasm32"),
},
)
}
pub fn command_batch(&mut self, session: &Session, steps: &[serde_json::Value]) -> PanelResult<serde_json::Value> {
// 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 {
sink: &mut sink,
registry: &registry,
catalogue: self.catalogue.as_mut(),
web: cfg!(target_arch = "wasm32"),
},
)
}
/// All forwarding borrows the exact provider injected at enablement.
fn with_services<R>(&mut self, use_services: impl FnOnce(&mut PanelRuntime, &mut ContentServices<'_>) -> PanelResult<R>) -> PanelResult<R> {
let mut services = self.services.services();
use_services(&mut self.runtime, &mut services)
}
pub fn dispatch(&mut self, session: &Session, action: LayoutAction) -> PanelResult<LayoutReply> {
self.refresh_context(session)?;
let mut services = self.services.services();
RuntimeActionSink { runtime: &mut self.runtime, native: self.native.as_mut(), services: &mut services }.dispatch(action)
}
pub fn mount(&mut self, resolved: &ResolvedLayout, host: &mut dyn PanelHost) -> PanelResult<()> {
self.with_services(|runtime, services| runtime.mount(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))
}
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)
}
/// 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!(&section.location, SectionLocation::Window { .. })) {
return Err(error(Rule::Lifecycle, "redock native panels before disabling their application adapter"));
}
let services = self.services.services();
self.runtime.shutdown(services.local)
}
}
impl crate::SolveApp {
pub fn run_panel_command(&mut self, id: &str, params: &serde_json::Value) -> PanelResult<serde_json::Value> {
// Parse even without a runtime: hostile/unknown fields never become a
// misleading capability success or reach the document command path.
match self.panel_runtime.as_mut() {
Some(integration) => integration.command(&self.session, id, params),
None => {
commands::parse_command(id, params)?;
Err(error(Rule::Capability, "application panel runtime is not enabled"))
}
}
}
pub fn run_panel_batch(&mut self, steps: &[serde_json::Value]) -> PanelResult<serde_json::Value> {
self.panel_runtime
.as_mut()
.ok_or_else(|| error(Rule::Capability, "application panel runtime is not enabled"))?
.command_batch(&self.session, steps)
}
/// Internal opt-in only: no preference, control method, command or default change.
pub fn enable_panel_runtime(&mut self, runtime: PanelRuntime, services: Box<dyn AppPanelServices>) -> PanelResult<()> {
if self.panel_runtime.is_some() {
return Err(error(Rule::Lifecycle, "panel runtime already enabled"));
}
let mut integration = AppPanelRuntime::new(runtime, services);
integration.tick(&self.session)?;
self.panel_runtime = Some(integration);
Ok(())
}
pub fn panel_runtime(&self) -> Option<&PanelRuntime> {
self.panel_runtime.as_ref().map(|integration| &integration.runtime)
}
pub fn panel_runtime_mut(&mut self) -> Option<&mut AppPanelRuntime> {
self.panel_runtime.as_mut()
}
pub fn dispatch_panel_layout(&mut self, action: LayoutAction) -> PanelResult<LayoutReply> {
self.panel_runtime.as_mut().ok_or_else(|| error(Rule::Lifecycle, "panel runtime disabled"))?.dispatch(&self.session, action)
}
pub fn mount_panels(&mut self, resolved: &ResolvedLayout, host: &mut dyn PanelHost) -> PanelResult<()> {
self.panel_runtime.as_mut().ok_or_else(|| error(Rule::Lifecycle, "panel runtime disabled"))?.mount(resolved, host)
}
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)
}
pub fn tick_panel_runtime(&mut self) -> PanelResult<()> {
self.panel_runtime.as_mut().ok_or_else(|| error(Rule::Lifecycle, "panel runtime disabled"))?.tick(&self.session)
}
pub fn disable_panel_runtime(&mut self) -> PanelResult<()> {
if let Some(integration) = &mut self.panel_runtime {
integration.shutdown()?;
}
self.panel_runtime = None;
Ok(())
}
}
/// 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) {
if let Some(integration) = &mut app.panel_runtime {
// Errors remain inspectable without inventing untranslated production UI.
integration.last_error = integration.tick(&app.session).err();
}
}
@@ -0,0 +1,571 @@
//! Shared executable mount/editor/native fixtures. These are synthetic specimens,
//! not production panel migrations, UI commands or evidence of visual correctness.
use std::cell::RefCell;
use std::collections::{BTreeMap, VecDeque};
use std::rc::Rc;
use solidcraft_engine::panels::*;
use super::*;
#[derive(Clone, Debug, Default)]
pub struct FixtureState {
pub updates: u64,
pub renders: u64,
pub cancels: u64,
pub reopens: u64,
pub applies: u64,
pub finishes: u64,
pub reparents: u64,
pub destroys: u64,
pub transaction_live: bool,
pub reject_cancel: bool,
pub reject_reopen: bool,
pub fail_update: bool,
pub invalid_availability: bool,
pub last_state: Option<ControllerState>,
pub draft: String,
pub last_clip: Option<egui::Rect>,
}
#[derive(Clone, Default)]
pub struct FixtureProbe {
states: Rc<RefCell<BTreeMap<ControllerKey, Rc<RefCell<FixtureState>>>>>,
}
impl FixtureProbe {
pub fn state(&self, key: &ControllerKey) -> PanelResult<FixtureState> {
let states = self.states.try_borrow().map_err(|_| error(Rule::Lifecycle, "fixture probe borrowed"))?;
let state = states.get(key).ok_or_else(|| error(Rule::MissingTarget, "fixture controller missing"))?;
let value = state.try_borrow().map_err(|_| error(Rule::Lifecycle, "fixture state borrowed"))?.clone();
Ok(value)
}
pub fn edit(&self, key: &ControllerKey, edit: impl FnOnce(&mut FixtureState)) -> PanelResult<()> {
let states = self.states.try_borrow().map_err(|_| error(Rule::Lifecycle, "fixture probe borrowed"))?;
let state = states.get(key).ok_or_else(|| error(Rule::MissingTarget, "fixture controller missing"))?;
let mut value = state.try_borrow_mut().map_err(|_| error(Rule::Lifecycle, "fixture state borrowed"))?;
edit(&mut value);
if value.draft.len() > 4096 {
value.draft = value.draft.chars().take(1024).collect();
}
Ok(())
}
fn publish(&self, key: ControllerKey, state: Rc<RefCell<FixtureState>>) -> PanelResult<()> {
let mut states = self.states.try_borrow_mut().map_err(|_| error(Rule::Lifecycle, "fixture probe borrowed"))?;
if states.len() >= MAX_RETAINED_CONTROLLERS && !states.contains_key(&key) {
return Err(error(Rule::CollectionLimit, "fixture state cap"));
}
states.insert(key, state);
Ok(())
}
}
struct FixtureController {
state: Rc<RefCell<FixtureState>>,
editor: bool,
instance: InstanceId,
probe: FixtureProbe,
key: ControllerKey,
}
impl PanelController for FixtureController {
fn availability(&self, owner: &ContentOwner, models: &dyn PanelModels) -> Availability {
if self.state.try_borrow().is_ok_and(|state| state.invalid_availability) {
return Availability::Unavailable { reason: String::new() };
}
if self.editor {
match models.read(owner, "fixture.editable") {
Ok(serde_json::Value::Bool(true)) => Availability::Available,
_ => Availability::Unavailable { reason: "synthetic editor requires editable document context".into() },
}
} else {
Availability::Available
}
}
fn update(&mut self, _owner: &ContentOwner, _services: &mut ContentServices<'_>) -> PanelResult<()> {
self.probe.publish(self.key.clone(), self.state.clone())?;
let mut state = self.state.try_borrow_mut().map_err(|_| error(Rule::Lifecycle, "fixture state borrowed"))?;
state.updates = state.updates.saturating_add(1);
if state.fail_update {
return Err(error(Rule::Lifecycle, "synthetic service update failed"));
}
Ok(())
}
fn presentation(&self) -> PanelPresentation {
let summary = self.state.try_borrow().ok().map(|s| (s.updates, s.transaction_live));
PanelPresentation {
title: format!("Specimen {}", self.instance.0),
icon: "panel".into(),
status: summary.map(|(updates, live)| format!("updates={updates}; transaction={live}")),
attention: self.editor,
actions: if self.editor {
["apply", "cancel", "finish"]
.into_iter()
.map(|id| RuntimeAction { id: ControlId(id.into()), label: id.into(), enabled: true, disabled_reason: None })
.collect()
} else {
Vec::new()
},
}
}
fn prepare_lifecycle(&self, event: &LifecycleEvent) -> PanelResult<()> {
let state = self.state.try_borrow_mut().map_err(|_| error(Rule::Lifecycle, "fixture state borrowed"))?;
if self.editor && state.transaction_live && state.reject_cancel && matches!(event, LifecycleEvent::Close | LifecycleEvent::DestroyOwner) {
return Err(error(Rule::Lifecycle, "synthetic editor cannot safely cancel"));
}
if state.reject_reopen && matches!(event, LifecycleEvent::Reopen) {
return Err(error(Rule::Lifecycle, "synthetic controller cannot safely reopen"));
}
Ok(())
}
fn lifecycle(&mut self, event: &LifecycleEvent) {
// Publishing diagnostics happens after commit, never in a staged factory.
let _ = self.probe.publish(self.key.clone(), self.state.clone());
// This fixture's preflight prohibits concurrent borrows. An adapter must
// make commit infallible; it must not defer fallible work into this hook.
if let Ok(mut state) = self.state.try_borrow_mut() {
match event {
LifecycleEvent::Close => {
if self.editor && state.transaction_live {
state.cancels = state.cancels.saturating_add(1);
state.transaction_live = false;
}
}
LifecycleEvent::Reopen => {
state.reopens = state.reopens.saturating_add(1);
if self.editor {
state.transaction_live = true;
}
}
LifecycleEvent::Reparent => state.reparents = state.reparents.saturating_add(1),
LifecycleEvent::DestroyOwner => {
if self.editor && state.transaction_live {
state.cancels = state.cancels.saturating_add(1);
state.transaction_live = false;
}
state.destroys = state.destroys.saturating_add(1);
state.last_state = Some(ControllerState { destroyed: true, ..ControllerState::default() });
}
LifecycleEvent::State(value) => state.last_state = Some(value.clone()),
}
}
}
fn render(&mut self, slot: ContentSlot, ui: &mut egui::Ui, _context: &PanelContext, _services: &mut ContentServices<'_>) -> PanelResult<()> {
if slot == ContentSlot::Body {
let mut state = self.state.try_borrow_mut().map_err(|_| error(Rule::Lifecycle, "fixture state borrowed"))?;
state.renders = state.renders.saturating_add(1);
state.last_clip = Some(ui.clip_rect());
}
Ok(())
}
fn action(&mut self, owner: &ContentOwner, action: &ControlId, services: &mut ContentServices<'_>) -> PanelResult<()> {
if !self.editor {
return Err(error(Rule::MissingTarget, "log has no editor actions"));
}
let mut state = self.state.try_borrow_mut().map_err(|_| error(Rule::Lifecycle, "fixture state borrowed"))?;
match action.0.as_str() {
"apply" => {
// Only this explicit content command reaches the model sink.
services.commands.execute(owner, "fixture.apply", serde_json::json!({"draft":state.draft}))?;
state.applies = state.applies.saturating_add(1);
}
"cancel" => {
if state.reject_cancel {
return Err(error(Rule::Lifecycle, "synthetic cancel rejected"));
}
state.cancels = state.cancels.saturating_add(1);
state.transaction_live = false;
}
"finish" => {
services.commands.execute(owner, "fixture.finish", serde_json::json!({"draft":state.draft}))?;
state.finishes = state.finishes.saturating_add(1);
state.transaction_live = false;
}
_ => return Err(error(Rule::MissingTarget, "unknown synthetic action")),
}
Ok(())
}
}
pub fn bind_synthetic_controllers(runtime: &mut PanelRuntime, probe: &FixtureProbe) -> PanelResult<()> {
for (kind, editor, ownership) in [
("fixture.application", false, Ownership::Application),
("fixture.editor", true, Ownership::Document),
("fixture.log", false, Ownership::Workspace),
("fixture.pin", false, Ownership::Workspace),
] {
runtime.register(PanelKind::new(kind)?, fixture_controller_binding(probe, editor, ownership))?;
}
Ok(())
}
/// Bind the same synthetic lifecycle to another registered kind/ownership policy.
/// This lets capacity fixtures exercise several document editors without adding
/// production registrations or changing the pure layout registry.
pub fn fixture_controller_binding(probe: &FixtureProbe, editor: bool, ownership: Ownership) -> ControllerBinding {
let probe = probe.clone();
ControllerBinding {
ownership,
create: Box::new(move |instance, owner| {
let key = ControllerKey { instance: instance.id.clone(), owner: owner.clone() };
Ok(Box::new(FixtureController {
state: Rc::new(RefCell::new(FixtureState { transaction_live: editor && instance.requested_open, ..FixtureState::default() })),
editor,
instance: instance.id.clone(),
probe: probe.clone(),
key,
}))
}),
}
}
#[derive(Default)]
pub struct FakeModels {
pub editable: bool,
}
/// Synthetic app provider for command/control fixtures, with the same retained
/// model/command/local-service bindings as PanelMountHarness.
#[derive(Default)]
pub struct FakeAppPanelServices {
pub models: FakeModels,
pub commands: FakeContentCommands,
pub local: FakeLocalServices,
}
impl AppPanelServices for FakeAppPanelServices {
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 }
}
}
impl PanelModels for FakeModels {
fn read(&self, _owner: &ContentOwner, key: &str) -> PanelResult<serde_json::Value> {
match key {
"fixture.editable" => Ok(serde_json::Value::Bool(self.editable)),
_ => Err(error(Rule::MissingTarget, "unknown synthetic model read")),
}
}
}
#[derive(Default)]
pub struct FakeContentCommands {
pub calls: u64,
pub fail: bool,
}
impl ContentCommandSink for FakeContentCommands {
fn execute(&mut self, _owner: &ContentOwner, command: &str, input: serde_json::Value) -> PanelResult<serde_json::Value> {
valid_id(command)?;
bounded_json(&input)?;
if serde_json::to_vec(&input).map_err(|_| error(Rule::Schema, "invalid synthetic command"))?.len() > MAX_ENVELOPE_BYTES {
return Err(error(Rule::CollectionLimit, "synthetic command cap"));
}
if self.fail {
return Err(error(Rule::Lifecycle, "synthetic content command failed"));
}
self.calls = self.calls.saturating_add(1);
Ok(serde_json::Value::Null)
}
}
#[derive(Default)]
pub struct FakeLocalServices {
pub scopes: BTreeMap<InstanceId, LocalScope>,
pub keyboard: BTreeMap<LocalScope, (InstanceId, ControlId)>,
pub requests: VecDeque<(LocalScope, LocalRequest)>,
pub releases: u64,
}
impl FakeLocalServices {
pub fn bind(&mut self, instance: InstanceId, scope: LocalScope) -> PanelResult<()> {
valid_id(&instance.0)?;
scope.validate()?;
if self.scopes.len() >= MAX_INSTANCES && !self.scopes.contains_key(&instance) {
return Err(error(Rule::CollectionLimit, "local scope cap"));
}
if let Some(old) = self.scopes.get(&instance).cloned() {
if old == scope {
return Ok(());
}
self.release(&old, &instance);
}
self.scopes.insert(instance, scope);
Ok(())
}
}
impl PanelLocalServices for FakeLocalServices {
fn request(&mut self, scope: &LocalScope, request: LocalRequest) -> PanelResult<()> {
scope.validate()?;
request.validate()?;
if self.scopes.get(request.instance()) != Some(scope) {
return Err(error(Rule::Placement, "cross-document or cross-viewport service request"));
}
match &request {
LocalRequest::KeyboardOwner { instance, control } => {
if self.keyboard.get(scope).is_some_and(|(owner, _)| owner != instance) {
return Err(error(Rule::Lifecycle, "keyboard owned by another panel"));
}
self.keyboard.insert(scope.clone(), (instance.clone(), control.clone()));
}
LocalRequest::ReleaseKeyboard { instance } => {
if self.keyboard.get(scope).is_some_and(|(owner, _)| owner == instance) {
self.keyboard.remove(scope);
}
}
LocalRequest::ClearOverlays { instance } => {
self.requests.retain(|(at, req)| at != scope || req.instance() != instance || !matches!(req, LocalRequest::Overlay { .. }))
}
_ => {}
}
if self.requests.len() >= MAX_INSTANCES {
self.requests.pop_front();
}
self.requests.push_back((scope.clone(), request));
Ok(())
}
fn release(&mut self, scope: &LocalScope, instance: &InstanceId) {
if self.keyboard.get(scope).is_some_and(|(owner, _)| owner == instance) {
self.keyboard.remove(scope);
}
self.requests.retain(|(at, request)| at != scope || request.instance() != instance);
if self.scopes.get(instance) == Some(scope) {
self.scopes.remove(instance);
}
self.releases = self.releases.saturating_add(1);
}
}
pub struct FakeNativeAdapter {
pub capabilities: HostCapabilities,
pub hosts: BTreeMap<HostId, SectionId>,
pub fail_prepare: bool,
pub commits: u64,
}
impl FakeNativeAdapter {
pub fn new(native: bool) -> Self {
Self {
capabilities: HostCapabilities { native_windows: native, persistence: true, max_native_hosts: if native { 8 } else { 0 } },
hosts: BTreeMap::new(),
fail_prepare: false,
commits: 0,
}
}
}
impl NativeHostAdapter for FakeNativeAdapter {
fn capabilities(&self) -> HostCapabilities {
self.capabilities.clone()
}
fn prepare(&self, effects: &[HostEffect]) -> PanelResult<()> {
if self.fail_prepare {
return Err(error(Rule::Capability, "synthetic native preparation failure"));
}
if effects.len() > MAX_MUTATIONS * 3 {
return Err(error(Rule::CollectionLimit, "native effect cap"));
}
let mut hosts = self.hosts.clone();
for effect in effects {
match effect {
HostEffect::CreateNative { host, section } => {
if !self.capabilities.native_windows {
return Err(error(Rule::Capability, "native windows unsupported"));
}
if hosts.insert(host.clone(), section.clone()).is_some() {
return Err(error(Rule::DuplicateId, "native host already exists"));
}
}
HostEffect::RebindNative { host, section } => {
if !self.capabilities.native_windows {
return Err(error(Rule::Capability, "native rebind unsupported"));
}
if !hosts.contains_key(host) {
return Err(error(Rule::MissingTarget, "native rebind host absent"));
}
hosts.insert(host.clone(), section.clone());
}
HostEffect::ReleaseNative { host } => {
hosts.remove(host);
}
_ => {}
}
}
if hosts.len() > self.capabilities.max_native_hosts {
return Err(error(Rule::Capability, "native host capacity"));
}
Ok(())
}
fn commit(&mut self, effects: &[HostEffect]) {
for effect in effects {
match effect {
HostEffect::CreateNative { host, section } | HostEffect::RebindNative { host, section } => {
self.hosts.insert(host.clone(), section.clone());
}
HostEffect::ReleaseNative { host } => {
self.hosts.remove(host);
}
_ => {}
}
}
self.commits = self.commits.saturating_add(1);
}
}
#[derive(Clone, Debug)]
pub struct MountRecord {
pub geometry: ResolvedPanel,
pub presentation: PanelPresentation,
pub context: PanelContext,
}
#[derive(Default)]
pub struct FakePanelHost {
pub mounts: VecDeque<MountRecord>,
pub slot_calls: u64,
pub context: egui::Context,
}
impl PanelHost for FakePanelHost {
fn mount(
&mut self,
geometry: &ResolvedPanel,
presentation: &PanelPresentation,
context: &PanelContext,
content: &mut dyn PanelController,
services: &mut ContentServices<'_>,
) -> PanelResult<()> {
geometry.validate()?;
presentation.validate()?;
context.validate()?;
let mut failure = None;
let ctx = self.context.clone();
let _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() {
break;
}
if let Err(reason) = content.render(slot, ui, context, services) {
failure = Some(reason);
}
self.slot_calls = self.slot_calls.saturating_add(1);
}
});
});
if let Some(reason) = failure {
return Err(reason);
}
if self.mounts.len() >= MAX_INSTANCES {
self.mounts.pop_front();
}
self.mounts.push_back(MountRecord { geometry: geometry.clone(), presentation: presentation.clone(), context: context.clone() });
Ok(())
}
}
/// Reusable harness uses actual reducer, controller, host and services interfaces.
pub struct PanelMountHarness {
pub runtime: PanelRuntime,
pub probe: FixtureProbe,
pub models: FakeModels,
pub commands: FakeContentCommands,
pub local: FakeLocalServices,
pub native: FakeNativeAdapter,
pub host: FakePanelHost,
pub persistence: FakePersistence,
pub catalogue: commands::InMemoryCatalogue,
}
impl PanelMountHarness {
pub fn command(&mut self, id: &str, params: &serde_json::Value) -> PanelResult<serde_json::Value> {
let registry = self.runtime.layout().registry().clone();
let mut services = ContentServices { models: &self.models, commands: &mut self.commands, local: &mut self.local };
let mut sink = RuntimeActionSink { runtime: &mut self.runtime, native: &mut self.native, services: &mut services };
commands::execute(
id,
params,
&mut commands::PanelCommandContext { sink: &mut sink, registry: &registry, catalogue: &mut self.catalogue, web: false },
)
}
pub fn command_batch(&mut self, steps: &[serde_json::Value]) -> PanelResult<serde_json::Value> {
let registry = self.runtime.layout().registry().clone();
let mut services = ContentServices { models: &self.models, commands: &mut self.commands, local: &mut self.local };
let mut sink = RuntimeActionSink { runtime: &mut self.runtime, native: &mut self.native, services: &mut services };
commands::execute_batch(
steps,
&mut commands::PanelCommandContext { sink: &mut sink, registry: &registry, catalogue: &mut self.catalogue, web: false },
)
}
pub fn apply_layout(&mut self, layout: Layout, expected_revision: Option<u64>) -> PanelResult<LayoutReply> {
self.runtime.dispatch(
LayoutAction::Replace { expected_revision, layout },
&mut self.native,
&mut ContentServices { models: &self.models, commands: &mut self.commands, local: &mut self.local },
)
}
pub fn new(native: bool) -> PanelResult<Self> {
Self::configured(native, true)
}
pub fn without_content(native: bool) -> PanelResult<Self> {
Self::configured(native, false)
}
fn configured(native: bool, bind: bool) -> PanelResult<Self> {
let layout = fixture_service(native)?;
let catalogue = fixture_command_catalogue(layout.registry())?;
let environment = RuntimeEnvironment {
workspace: layout.layout().workspace.clone(),
document: Some(DocumentId::new("fixture.document")?),
window: HostId::new("fixture.window")?,
viewport: ViewportId::new("fixture.viewport")?,
direction: Direction::Ltr,
motion: Motion::Reduced,
};
let mut runtime = PanelRuntime::new(layout, environment)?;
let probe = FixtureProbe::default();
if bind {
bind_synthetic_controllers(&mut runtime, &probe)?;
}
Ok(Self {
runtime,
probe,
models: FakeModels { editable: true },
commands: FakeContentCommands::default(),
local: FakeLocalServices::default(),
native: FakeNativeAdapter::new(native),
host: FakePanelHost::default(),
persistence: FakePersistence::default(),
catalogue,
})
}
pub fn dispatch(&mut self, mutations: Vec<Mutation>) -> PanelResult<LayoutReply> {
self.runtime.dispatch(
transaction(mutations),
&mut self.native,
&mut ContentServices { models: &self.models, commands: &mut self.commands, local: &mut self.local },
)
}
pub fn tick(&mut self) -> PanelResult<()> {
self.runtime.update(&mut ContentServices { models: &self.models, commands: &mut self.commands, local: &mut self.local })
}
pub fn mount(&mut self, capacity: LogicalRect) -> PanelResult<ResolvedLayout> {
self.tick()?;
let environment = self.runtime.environment().clone();
let resolved = resolve_geometry(self.runtime.layout(), capacity, environment.direction, 48.0)?;
for panel in &resolved.panels {
let viewport = match &self.runtime.layout().layout().section(&panel.section)?.location {
SectionLocation::Window { host, .. } => ViewportId::new(host.0.clone())?,
_ => environment.viewport.clone(),
};
self.local.bind(
panel.instance.clone(),
LocalScope { workspace: environment.workspace.clone(), document: environment.document.clone(), viewport },
)?;
}
self.runtime.mount(
&resolved,
&mut self.host,
&mut ContentServices { models: &self.models, commands: &mut self.commands, local: &mut self.local },
)?;
Ok(resolved)
}
pub fn save(&mut self) -> PanelResult<()> {
let layout = self.runtime.layout().layout();
let bytes = encode(&LayoutEnvelope::new(layout.clone()), self.runtime.layout().registry())?;
self.persistence.save(&layout.workspace, &bytes)
}
}
+316
View File
@@ -0,0 +1,316 @@
use solidcraft_engine::panels::*;
/// Content receives this value separately from state/model/command services. All
/// geometry is already in logical units; do not multiply it by egui UI scale.
#[derive(Clone, Debug, PartialEq)]
pub struct PanelContext {
pub instance: InstanceId,
pub owner: super::ContentOwner,
pub workspace: WorkspaceId,
pub document: Option<DocumentId>,
pub viewport: ViewportId,
pub native_host: Option<HostId>,
pub outer: LogicalRect,
pub usable_body: LogicalRect,
pub flow: Flow,
pub size_class: SizeClass,
pub focused: bool,
pub direction: Direction,
pub motion: Motion,
}
impl PanelContext {
pub fn validate(&self) -> PanelResult<()> {
valid_id(&self.instance.0)?;
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(host) = &self.native_host {
valid_id(&host.0)?;
if self.viewport.0 != host.0 {
return Err(error(Rule::Placement, "native presentation has wrong local viewport"));
}
}
if let super::ContentOwner::Document(document) = &self.owner
&& self.document.as_ref() != Some(document)
{
return Err(error(Rule::Placement, "presentation document differs from content owner"));
}
if let super::ContentOwner::Workspace(workspace) = &self.owner
&& self.workspace != *workspace
{
return Err(error(Rule::Placement, "presentation workspace differs from content owner"));
}
Ok(())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Motion {
Reduced,
Animated,
}
impl Motion {
/// Reparent/focus must not wait for animation completion, including at zero duration.
pub fn duration_ms(self, requested: u16) -> u16 {
if self == Self::Reduced { 0 } else { requested.min(500) }
}
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct LocalScope {
pub workspace: WorkspaceId,
pub document: Option<DocumentId>,
pub viewport: ViewportId,
}
impl LocalScope {
pub fn validate(&self) -> PanelResult<()> {
valid_id(&self.workspace.0)?;
valid_id(&self.viewport.0)?;
if let Some(id) = &self.document {
valid_id(&id.0)?;
}
Ok(())
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum LocalRequest {
KeyboardOwner { instance: InstanceId, control: ControlId },
ReleaseKeyboard { instance: InstanceId },
Focus { instance: InstanceId, control: ControlId },
FileDrop { instance: InstanceId, name: String, bytes: Vec<u8> },
PointerDrop { instance: InstanceId, at: Point, payload: String },
Overlay { instance: InstanceId, region: InputRegion },
ClearOverlays { instance: InstanceId },
Clipboard { instance: InstanceId, text: String },
Pick { instance: InstanceId, at: Point },
}
impl LocalRequest {
pub fn instance(&self) -> &InstanceId {
match self {
Self::KeyboardOwner { instance, .. }
| Self::ReleaseKeyboard { instance }
| Self::Focus { instance, .. }
| Self::FileDrop { instance, .. }
| Self::PointerDrop { instance, .. }
| Self::Overlay { instance, .. }
| Self::ClearOverlays { instance }
| Self::Clipboard { instance, .. }
| Self::Pick { instance, .. } => instance,
}
}
pub fn validate(&self) -> PanelResult<()> {
valid_id(&self.instance().0)?;
match self {
Self::KeyboardOwner { control, .. } | Self::Focus { control, .. } => valid_id(&control.0)?,
Self::FileDrop { name, bytes, .. } => {
if name.is_empty() || name.len() > 256 || bytes.len() > MAX_ENVELOPE_BYTES {
return Err(error(Rule::CollectionLimit, "file drop bound"));
}
}
Self::PointerDrop { at, payload, .. } => {
at.validate()?;
if payload.len() > 4096 {
return Err(error(Rule::CollectionLimit, "pointer drop payload bound"));
}
}
Self::Overlay { region, .. } => {
valid_id(&region.control.0)?;
region.bounds.validate()?;
if region.accessible_name.is_empty() || region.accessible_name.len() > 256 {
return Err(error(Rule::Bounds, "overlay semantic name bound"));
}
}
Self::Clipboard { text, .. } if text.len() > MAX_ENVELOPE_BYTES => return Err(error(Rule::CollectionLimit, "clipboard bound")),
Self::Pick { at, .. } => at.validate()?,
_ => {}
}
Ok(())
}
}
/// Services must reject cross-document/viewport delivery. A native redock drops
/// host-local focus/overlays but retains the content controller and its owner.
pub trait PanelLocalServices {
fn request(&mut self, scope: &LocalScope, request: LocalRequest) -> PanelResult<()>;
fn release(&mut self, scope: &LocalScope, instance: &InstanceId);
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RuntimeAction {
pub id: ControlId,
pub label: String,
pub enabled: bool,
pub disabled_reason: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PanelPresentation {
/// Already localised by content; fixtures use specimen text only.
pub title: String,
pub icon: String,
pub status: Option<String>,
pub attention: bool,
pub actions: Vec<RuntimeAction>,
}
impl PanelPresentation {
pub fn validate(&self) -> PanelResult<()> {
if self.title.is_empty() || self.title.len() > 256 || self.status.as_ref().is_some_and(|s| s.len() > 1024) || self.actions.len() > MAX_TABS {
return Err(error(Rule::CollectionLimit, "presentation bound"));
}
valid_id(&self.icon)?;
let mut ids = std::collections::BTreeSet::new();
for action in &self.actions {
valid_id(&action.id.0)?;
if !ids.insert(&action.id) {
return Err(error(Rule::DuplicateId, "duplicate content action"));
}
if action.label.is_empty()
|| action.label.len() > 256
|| action.disabled_reason.as_ref().is_some_and(|r| r.is_empty() || r.len() > 256)
|| !action.enabled && action.disabled_reason.is_none()
{
return Err(error(Rule::Bounds, "content action label/reason bound"));
}
}
Ok(())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ContentSlot {
Header,
Body,
Footer,
}
/// Shared host adapter seam. Geometry is resolved by the host; content chooses
/// its own scrolling within slots. The egui adapter below owns one kit Container.
pub trait PanelHost {
fn mount(
&mut self,
geometry: &ResolvedPanel,
presentation: &PanelPresentation,
context: &PanelContext,
content: &mut dyn PanelController,
services: &mut ContentServices<'_>,
) -> PanelResult<()>;
}
/// Two-phase host effects. `prepare` is side-effect-free and fallible; `commit`
/// cannot fail. Native adapters must stage resources before acknowledging prepare
/// and retain/restorable resources until the layout transaction commits.
pub trait NativeHostAdapter {
fn capabilities(&self) -> HostCapabilities;
fn prepare(&self, effects: &[HostEffect]) -> PanelResult<()>;
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> {
pub ui: &'a mut egui::Ui,
}
impl PanelHost for EguiPanelHost<'_> {
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, "host geometry differs from presentation context"));
}
// This reference adapter draws/interacts with one full rectangular card.
// Rich sparse/translucent regions belong to the surface host adapter.
if geometry.painted.len() != 1
|| geometry.painted.first() != Some(&geometry.outer)
|| geometry.input.len() != 1
|| !geometry.input.first().is_some_and(|region| region.role == InputRole::Surface && region.bounds == geometry.outer)
{
return Err(error(Rule::Capability, "reference egui host requires one full painted/input surface"));
}
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 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),
|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)] {
if failure.is_some() {
break;
}
ui.scope_builder(egui::UiBuilder::new().id_salt(slot as u8).max_rect(bounds), |ui| {
ui.set_clip_rect(ui.clip_rect().intersect(bounds));
if slot == ContentSlot::Header {
// Dynamic title/status have semantic metadata; content owns
// additional controls and returns requests through services.
let tokens = crate::theme::Tokens::get();
let ink = if presentation.attention { tokens.form_primary } else { tokens.form_ink };
let mut response = ui.label(egui::RichText::new(&presentation.title).color(ink));
if let Some(status) = &presentation.status {
response = response.on_hover_text(status);
}
response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, true, &presentation.title));
}
if slot == ContentSlot::Footer && !presentation.actions.is_empty() {
egui::ScrollArea::horizontal().id_salt("panel_actions").show(ui, |ui| {
ui.horizontal(|ui| {
for action in &presentation.actions {
let response = ui
.push_id(&action.id.0, |ui| {
ui.add_enabled_ui(action.enabled, |ui| {
crate::ui_kit::button(ui, action.label.as_str(), crate::ui_kit::Button::Small)
})
.inner
})
.inner;
let clicked = response.clicked();
if let Some(reason) = &action.disabled_reason {
response.on_disabled_hover_text(reason);
}
if clicked
&& failure.is_none()
&& let Err(reason) = content.action(&context.owner, &action.id, services)
{
failure = Some(reason);
}
}
});
});
}
if let Err(reason) = content.render(slot, ui, context, services) {
failure = Some(reason);
}
});
}
ui.set_min_size(outer.size());
});
},
);
if let Some(reason) = failure {
return Err(reason);
}
Ok(())
}
}
use super::{ContentServices, PanelController};
+14
View File
@@ -0,0 +1,14 @@
//! Opt-in common panel runtime. No production registrations, gestures or preferences.
//! Model/commands, controller state, presentation and layout have separate owners.
mod app;
mod fixtures;
mod host;
mod runtime;
pub use app::*;
pub use fixtures::*;
pub use host::*;
pub use runtime::*;
#[cfg(test)]
mod tests;
+799
View File
@@ -0,0 +1,799 @@
use std::collections::{BTreeMap, BTreeSet};
use solidcraft_engine::panels::*;
use super::*;
/// 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.
pub const MAX_RETAINED_OTHER_OWNERS: usize = MAX_INSTANCES;
/// Total retained owners; also bounds the separate destroyed-owner tombstone set.
pub const MAX_RETAINED_OWNERS: usize = MAX_RETAINED_DOCUMENT_OWNERS + MAX_RETAINED_OTHER_OWNERS;
/// Each owner can retain a full layout's controllers, including hidden ones.
pub const MAX_RETAINED_CONTROLLERS_PER_OWNER: usize = MAX_INSTANCES;
/// Layout instance limits remain unchanged; retention never evicts live content.
pub const MAX_RETAINED_CONTROLLERS: usize = MAX_RETAINED_OWNERS * MAX_RETAINED_CONTROLLERS_PER_OWNER;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Ownership {
Application,
Workspace,
Document,
Window,
}
/// Window ownership is explicit content ownership, independent of native placement.
/// Redocking does not turn a document editor into a new window-owned controller.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ContentOwner {
Application,
Workspace(WorkspaceId),
Document(DocumentId),
Window(HostId),
}
impl ContentOwner {
pub fn validate(&self) -> PanelResult<()> {
match self {
Self::Application => Ok(()),
Self::Workspace(id) => valid_id(&id.0),
Self::Document(id) => valid_id(&id.0),
Self::Window(id) => valid_id(&id.0),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RuntimeEnvironment {
pub workspace: WorkspaceId,
pub document: Option<DocumentId>,
pub window: HostId,
pub viewport: ViewportId,
pub direction: Direction,
pub motion: Motion,
}
impl RuntimeEnvironment {
pub fn validate(&self) -> PanelResult<()> {
valid_id(&self.workspace.0)?;
valid_id(&self.window.0)?;
valid_id(&self.viewport.0)?;
if let Some(doc) = &self.document {
valid_id(&doc.0)?;
}
Ok(())
}
fn owner(&self, policy: Ownership) -> PanelResult<ContentOwner> {
Ok(match policy {
Ownership::Application => ContentOwner::Application,
Ownership::Workspace => ContentOwner::Workspace(self.workspace.clone()),
Ownership::Document => {
ContentOwner::Document(self.document.clone().ok_or_else(|| error(Rule::Availability, "document-bound panel needs a document"))?)
}
Ownership::Window => ContentOwner::Window(self.window.clone()),
})
}
}
/// Content model access is owner-scoped and read-only. Layout code never receives
/// a Session. Consumers may implement richer views behind the same trait.
pub trait PanelModels {
fn read(&self, owner: &ContentOwner, key: &str) -> PanelResult<serde_json::Value>;
}
/// Explicit content commands have their own typed owner. They are separate from
/// layout actions and are never implicitly sent when a panel is hidden/reparented.
pub trait ContentCommandSink {
fn execute(&mut self, owner: &ContentOwner, command: &str, input: serde_json::Value) -> PanelResult<serde_json::Value>;
}
pub struct ContentServices<'a> {
pub models: &'a dyn PanelModels,
pub commands: &'a mut dyn ContentCommandSink,
pub local: &'a mut dyn PanelLocalServices,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ControllerState {
pub requested_open: bool,
pub available: Availability,
pub presented: bool,
pub activated: bool,
pub destroyed: bool,
}
impl Default for ControllerState {
fn default() -> Self {
Self { requested_open: false, available: Availability::Available, presented: false, activated: false, destroyed: false }
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LifecycleEvent {
State(ControllerState),
/// Only explicit close calls this; deactivation never cancels a transaction.
Close,
Reopen,
Reparent,
DestroyOwner,
}
pub trait PanelController {
/// Availability may depend on document/tool context, independent of visibility.
fn availability(&self, owner: &ContentOwner, models: &dyn PanelModels) -> Availability;
/// Runs for retained controllers, including hidden, closed and inactive documents.
fn update(&mut self, owner: &ContentOwner, services: &mut ContentServices<'_>) -> PanelResult<()>;
fn presentation(&self) -> PanelPresentation;
/// 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.
fn prepare_lifecycle(&self, event: &LifecycleEvent) -> PanelResult<()>;
/// 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<()>;
/// Apply/Finish/Cancel/Stop stay explicit content actions, never layout mutations.
fn action(&mut self, owner: &ContentOwner, action: &ControlId, services: &mut ContentServices<'_>) -> PanelResult<()>;
}
pub struct ControllerBinding {
pub ownership: Ownership,
/// Staging may be discarded on failure; do not publish external side effects.
pub create: Box<dyn Fn(&PanelInstance, &ContentOwner) -> PanelResult<Box<dyn PanelController>>>,
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct ControllerKey {
pub instance: InstanceId,
pub owner: ContentOwner,
}
struct RetainedController {
controller: Box<dyn PanelController>,
/// A controller created closed, or explicitly closed after creation, needs
/// Reopen before reuse. Snapshot hiding never sets this lifecycle flag.
needs_reopen: bool,
state: ControllerState,
scope: LocalScope,
section: Option<SectionId>,
native_host: Option<HostId>,
flow: Option<Flow>,
availability: Availability,
}
/// 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 {
layout: LayoutService,
bindings: BTreeMap<PanelKind, ControllerBinding>,
controllers: BTreeMap<ControllerKey, RetainedController>,
environment: RuntimeEnvironment,
destroyed_owners: BTreeSet<ContentOwner>,
destroyed: bool,
update_errors: Vec<RuntimeUpdateError>,
}
#[derive(Clone, Debug)]
pub struct RuntimeUpdateError {
pub controller: Option<ControllerKey>,
pub error: PanelError,
}
/// 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> {
pub runtime: &'a mut PanelRuntime,
pub native: &'a mut dyn NativeHostAdapter,
pub services: &'a mut ContentServices<'services>,
}
impl ActionSink for RuntimeActionSink<'_, '_> {
fn project(&self, action: LayoutAction) -> PanelResult<Layout> {
self.runtime.layout.project(action)
}
fn dispatch(&mut self, action: LayoutAction) -> PanelResult<LayoutReply> {
let mut reply = self.runtime.dispatch(action, self.native, self.services)?;
let native = self.native.capabilities();
reply.capabilities.native_windows &= native.native_windows;
reply.capabilities.max_native_hosts = reply.capabilities.max_native_hosts.min(native.max_native_hosts);
Ok(reply)
}
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
}
}
impl PanelRuntime {
pub fn new(layout: LayoutService, environment: RuntimeEnvironment) -> PanelResult<Self> {
environment.validate()?;
if layout.layout().workspace != environment.workspace {
return Err(error(Rule::Placement, "runtime workspace differs from layout service"));
}
Ok(Self {
layout,
bindings: BTreeMap::new(),
controllers: BTreeMap::new(),
environment,
destroyed_owners: BTreeSet::new(),
destroyed: false,
update_errors: Vec::new(),
})
}
pub fn register(&mut self, kind: PanelKind, binding: ControllerBinding) -> PanelResult<()> {
self.require_live()?;
self.layout.registry().get(&kind)?;
if self.bindings.contains_key(&kind) {
return Err(error(Rule::DuplicateId, "controller binding already registered"));
}
if self.bindings.len() >= MAX_INSTANCES {
return Err(error(Rule::CollectionLimit, "binding cap"));
}
self.bindings.insert(kind, binding);
Ok(())
}
pub fn layout(&self) -> &LayoutService {
&self.layout
}
pub fn environment(&self) -> &RuntimeEnvironment {
&self.environment
}
pub fn controller_count(&self) -> usize {
self.controllers.len()
}
pub fn update_errors(&self) -> &[RuntimeUpdateError] {
&self.update_errors
}
fn require_live(&self) -> PanelResult<()> {
if self.destroyed {
return Err(error(Rule::Lifecycle, "runtime destroyed"));
}
Ok(())
}
pub fn state(&self, key: &ControllerKey) -> Option<&ControllerState> {
self.controllers.get(key).map(|c| &c.state)
}
pub fn presentation(&self, key: &ControllerKey) -> PanelResult<PanelPresentation> {
let value = self.controllers.get(key).ok_or_else(|| error(Rule::MissingTarget, "controller not retained"))?.controller.presentation();
value.validate()?;
Ok(value)
}
fn key(&self, instance: &PanelInstance) -> PanelResult<ControllerKey> {
self.key_in(instance, &self.environment)
}
fn key_in(&self, instance: &PanelInstance, environment: &RuntimeEnvironment) -> PanelResult<ControllerKey> {
let binding = self.bindings.get(&instance.kind).ok_or_else(|| error(Rule::Availability, "no content binding available"))?;
let owner = environment.owner(binding.ownership)?;
if self.destroyed_owners.contains(&owner) {
return Err(error(Rule::Availability, "content owner destroyed"));
}
Ok(ControllerKey { instance: instance.id.clone(), owner })
}
fn scope(&self) -> LocalScope {
LocalScope {
workspace: self.environment.workspace.clone(),
document: self.environment.document.clone(),
viewport: self.environment.viewport.clone(),
}
}
/// Changes active context without dropping editors/conversations of inactive
/// documents. Their independent service updates keep running under their owner.
pub fn set_environment(&mut self, environment: RuntimeEnvironment, local: &mut dyn PanelLocalServices) -> PanelResult<()> {
self.require_live()?;
environment.validate()?;
if environment.workspace != self.layout.layout().workspace {
return Err(error(Rule::Placement, "apply the saved workspace layout through LayoutAction::Replace"));
}
if self.environment == environment {
return Ok(());
}
// Capacity/factory refusal must leave the active owner and local input
// untouched, just like a refused layout replacement.
let staged = self.stage_controllers(self.layout.layout(), &environment)?;
let mut events = Vec::new();
for (key, retained) in &self.controllers {
let mut state = retained.state.clone();
state.presented = false;
state.activated = false;
events.push((key.clone(), state));
}
for (key, state) in events {
if let Some(retained) = self.controllers.get_mut(&key) {
local.release(&retained.scope, &key.instance);
retained.controller.lifecycle(&LifecycleEvent::State(state.clone()));
retained.state = state;
}
}
self.environment = environment;
self.controllers.extend(staged);
Ok(())
}
fn stage_controllers(&self, layout: &Layout, environment: &RuntimeEnvironment) -> PanelResult<BTreeMap<ControllerKey, RetainedController>> {
let mut staged = BTreeMap::new();
let mut owner_counts = BTreeMap::<ContentOwner, usize>::new();
for key in self.controllers.keys() {
*owner_counts.entry(key.owner.clone()).or_default() += 1;
}
let mut document_owners = owner_counts.keys().filter(|owner| matches!(owner, ContentOwner::Document(_))).count();
let mut other_owners = owner_counts.len() - document_owners;
for p in &layout.instances {
let key = match self.key_in(p, environment) {
Ok(key) => key,
Err(_) => continue,
};
if self.controllers.contains_key(&key) || staged.contains_key(&key) {
continue;
}
if self.controllers.len() + staged.len() >= MAX_RETAINED_CONTROLLERS {
return Err(error(Rule::CollectionLimit, "retained controller cap"));
}
if !owner_counts.contains_key(&key.owner) {
if matches!(&key.owner, ContentOwner::Document(_)) {
if document_owners >= MAX_RETAINED_DOCUMENT_OWNERS {
return Err(error(Rule::CollectionLimit, "retained document owner cap"));
}
document_owners += 1;
} else {
if other_owners >= MAX_RETAINED_OTHER_OWNERS {
return Err(error(Rule::CollectionLimit, "retained application/workspace/window owner cap"));
}
other_owners += 1;
}
}
let count = owner_counts.entry(key.owner.clone()).or_default();
if *count >= MAX_RETAINED_CONTROLLERS_PER_OWNER {
return Err(error(Rule::CollectionLimit, "retained controller cap for content owner"));
}
*count += 1;
let binding = self.bindings.get(&p.kind).ok_or_else(|| error(Rule::Availability, "binding disappeared"))?;
let controller = (binding.create)(p, &key.owner)?;
staged.insert(
key,
RetainedController {
controller,
needs_reopen: !p.requested_open,
state: ControllerState::default(),
scope: LocalScope {
workspace: environment.workspace.clone(),
document: environment.document.clone(),
viewport: environment.viewport.clone(),
},
section: None,
native_host: None,
flow: None,
availability: Availability::Available,
},
);
}
Ok(staged)
}
/// Refresh command/query availability from the current read-only provider.
/// This does not tick content, evaluate models or invent presentation geometry.
/// A failed retained service stays failed until a real update recovers it.
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);
}
self.layout.set_availability(availability.clone())?;
self.controllers.extend(staged);
for instance in &self.layout.layout().instances {
if let Ok(key) = self.key(instance)
&& let Some(retained) = self.controllers.get_mut(&key)
&& let Some(state) = availability.get(&instance.id)
{
retained.availability = state.clone();
}
}
self.sync_states(None, local);
Ok(())
}
/// Independent tick: all retained services, then current-owner availability.
/// No geometry or painting is required for this method.
pub fn update(&mut self, services: &mut ContentServices<'_>) -> PanelResult<()> {
if self.destroyed {
return Err(error(Rule::Lifecycle, "runtime destroyed"));
}
self.update_errors.clear();
match self.stage_controllers(self.layout.layout(), &self.environment) {
Ok(staged) => self.controllers.extend(staged),
Err(reason) => self.update_errors.push(RuntimeUpdateError { controller: None, error: error(reason.rule, reason.detail) }),
}
for (key, retained) in &mut self.controllers {
let update = retained.controller.update(&key.owner, services);
let availability = retained.controller.availability(&key.owner, services.models);
let invalid = matches!(&availability, Availability::Unavailable { reason } if reason.is_empty() || reason.len() > 256);
let failed = update.is_err() || invalid;
if let Err(reason) = update {
self.update_errors.push(RuntimeUpdateError { controller: Some(key.clone()), error: error(reason.rule, reason.detail) });
}
if invalid {
self.update_errors.push(RuntimeUpdateError {
controller: Some(key.clone()),
error: error(Rule::Availability, "controller availability reason bound"),
});
}
if failed {
retained.availability = Availability::Unavailable {
reason: if invalid { "invalid availability report".into() } else { "content service update failed".into() },
};
} else {
retained.availability = availability;
}
}
let mut availability = AvailabilityMap::new();
for p in &self.layout.layout().instances {
let state = match self.key(p) {
Ok(key) => self
.controllers
.get(&key)
.map(|c| c.availability.clone())
.unwrap_or(Availability::Unavailable { reason: "content controller unavailable".into() }),
Err(reason) => Availability::Unavailable { reason: reason.detail },
};
availability.insert(p.id.clone(), state);
}
if let Err(reason) = self.layout.set_availability(availability) {
self.update_errors.push(RuntimeUpdateError { controller: None, error: reason });
}
self.sync_states(None, services.local);
// At most two errors per retained controller, plus staging/reconciliation.
if self.update_errors.is_empty() {
Ok(())
} else {
Err(error(Rule::Lifecycle, format!("{} panel service failures; inspect update_errors", self.update_errors.len())))
}
}
/// Lifecycle preflight and native preflight happen before layout commit. A
/// failed close/cancel leaves layout, interaction, controllers and host intact.
pub fn dispatch(
&mut self,
action: LayoutAction,
native: &mut dyn NativeHostAdapter,
services: &mut ContentServices<'_>,
) -> PanelResult<LayoutReply> {
if action == LayoutAction::Inspect {
return Ok(self.layout.inspect());
}
if self.destroyed {
return Err(error(Rule::Lifecycle, "runtime destroyed"));
}
let requests: Vec<_> = match &action {
LayoutAction::Apply { mutations, .. } => mutations
.iter()
.filter_map(|m| match m {
Mutation::Open { instance, .. }
| Mutation::Focus { instance }
| Mutation::Activate { instance }
| Mutation::Peek { instance } => Some(instance.clone()),
_ => None,
})
.collect(),
LayoutAction::Inspect | LayoutAction::Replace { .. } => Vec::new(),
};
let replacement = matches!(&action, 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 {
for mutation in mutations {
match mutation {
Mutation::Close { instance } => {
explicit_close.insert(instance.clone());
}
Mutation::Destroy { instance } => {
explicit_destroy.insert(instance.clone());
}
Mutation::Open { instance, .. } | Mutation::Focus { instance } => {
explicit_open.insert(instance.clone());
}
_ => {}
}
}
}
let mut prepared = self.layout.prepare(action)?;
let mut environment = self.environment.clone();
environment.workspace = prepared.layout().workspace.clone();
let capabilities = native.capabilities();
if capabilities.max_native_hosts > MAX_SECTIONS {
return Err(error(Rule::Capability, "native adapter reports invalid capacity"));
}
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)
&& let Some(state) = availability.get(&instance.id)
{
state.require()?;
}
}
let mut events: Vec<(ControllerKey, LifecycleEvent)> = Vec::new();
for (key, retained) in self.controllers.iter().chain(staged.iter()) {
let before = self.layout.layout().instances.iter().find(|p| p.id == key.instance);
let after = prepared.layout().instances.iter().find(|p| p.id == key.instance);
let affected = !matches!(&key.owner, ContentOwner::Workspace(workspace) if *workspace != self.environment.workspace);
if explicit_destroy.contains(&key.instance) {
retained.controller.prepare_lifecycle(&LifecycleEvent::DestroyOwner)?;
events.push((key.clone(), LifecycleEvent::DestroyOwner));
} else if affected && explicit_close.contains(&key.instance) {
retained.controller.prepare_lifecycle(&LifecycleEvent::Close)?;
events.push((key.clone(), LifecycleEvent::Close));
} else if !matches!(&key.owner, ContentOwner::Workspace(workspace) if *workspace != environment.workspace)
&& (replacement || explicit_open.contains(&key.instance))
&& retained.needs_reopen
&& after.is_some_and(|p| p.requested_open)
{
retained.controller.prepare_lifecycle(&LifecycleEvent::Reopen)?;
events.push((key.clone(), LifecycleEvent::Reopen));
}
let old = self.layout.layout().containing(&key.instance).ok().map(|s| (&s.id, &s.location));
let new = prepared.layout().containing(&key.instance).ok().map(|s| (&s.id, &s.location));
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)
&& before.is_some_and(|p| p.requested_open)
&& after.is_some_and(|p| p.requested_open)
{
retained.controller.prepare_lifecycle(&LifecycleEvent::Reparent)?;
events.push((key.clone(), LifecycleEvent::Reparent));
}
}
// Effects are available from the same candidate, before irreversible work.
native.prepare(prepared.effects())?;
let reply = self.layout.commit(prepared)?;
self.controllers.extend(staged);
if replacement {
for (key, retained) in &self.controllers {
services.local.release(&retained.scope, &key.instance);
}
}
self.environment = environment;
let current_keys: BTreeSet<_> = self.layout.layout().instances.iter().filter_map(|p| self.key(p).ok()).collect();
for (key, retained) in &mut self.controllers {
if current_keys.contains(key)
&& let Some(state) = availability.get(&key.instance)
{
retained.availability = state.clone();
}
}
for (key, event) in events {
if let Some(retained) = self.controllers.get_mut(&key) {
if matches!(event, LifecycleEvent::Close | LifecycleEvent::Reparent | LifecycleEvent::DestroyOwner) {
services.local.release(&retained.scope, &key.instance);
}
retained.controller.lifecycle(&event);
match event {
LifecycleEvent::Close => retained.needs_reopen = true,
LifecycleEvent::Reopen => retained.needs_reopen = false,
_ => {}
}
}
if event == LifecycleEvent::DestroyOwner {
self.controllers.remove(&key);
}
}
native.commit(&reply.effects);
// Presentation will be reconciled by mount/update; layout changes do not
// force content drawing or touch model revisions/undo/tessellation.
self.sync_states(None, services.local);
Ok(reply)
}
fn sync_states(&mut self, resolved: Option<&ResolvedLayout>, 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 mut pending = Vec::new();
for (key, retained) in &self.controllers {
let instance = self.layout.layout().instance(&key.instance).ok();
let current = active_keys.contains(key);
let available = retained.availability.clone();
let requested_open = current && instance.is_some_and(|p| p.requested_open);
let section = if current { self.layout.layout().containing(&key.instance).ok() } else { None };
let section_id = section.map(|s| s.id.clone());
let host = section.and_then(|s| match &s.location {
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));
let geometry_presented = match resolved {
Some(r) => r.panels.iter().any(|p| p.instance == key.instance),
None => retained.state.presented && retained.section == section_id && retained.native_host == host && selected,
};
let presented = current && requested_open && available == Availability::Available && geometry_presented;
let activated = presented && selected;
let state = ControllerState { requested_open, available, presented, activated, destroyed: false };
pending.push((key.clone(), state, section_id, host, current));
}
for (key, state, section, host, current) in pending {
if let Some(retained) = self.controllers.get_mut(&key) {
let mut target_scope = scope.clone();
if let Some(host) = &host {
target_scope.viewport = ViewportId(host.0.clone());
}
if retained.state.presented && !state.presented || current && (retained.scope != target_scope || retained.native_host != host) {
local.release(&retained.scope, &key.instance);
}
if state != retained.state {
retained.controller.lifecycle(&LifecycleEvent::State(state.clone()));
}
retained.state = state;
retained.section = section;
retained.native_host = host;
if current {
retained.scope = target_scope;
}
}
}
}
pub fn mount(&mut self, resolved: &ResolvedLayout, host: &mut dyn PanelHost, services: &mut ContentServices<'_>) -> PanelResult<()> {
self.require_live()?;
resolved.validate()?;
for record in &resolved.unpresented {
self.layout.layout().section(&record.section)?;
}
let mut ids = BTreeSet::new();
for geometry in &resolved.panels {
geometry.validate()?;
if !ids.insert(&geometry.instance) {
return Err(error(Rule::ExactlyOnce, "panel mounted twice"));
}
let section = self.layout.layout().containing(&geometry.instance)?;
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 {
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) {
return Err(error(Rule::Bounds, "host violates tab outer bounds"));
}
if self.layout.availability(&geometry.instance) != Availability::Available {
return Err(error(Rule::Availability, "cannot mount unavailable content"));
}
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);
let interaction = self.layout.interaction().clone();
for geometry in &resolved.panels {
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 context = PanelContext {
instance: geometry.instance.clone(),
owner: key.owner.clone(),
workspace: self.environment.workspace.clone(),
document: self.environment.document.clone(),
viewport: retained.scope.viewport.clone(),
native_host: retained.native_host.clone(),
outer: geometry.outer,
usable_body: geometry.body,
flow,
size_class,
focused: interaction.focused.as_ref() == Some(&geometry.instance),
direction: self.environment.direction,
motion: self.environment.motion,
};
let presentation = retained.controller.presentation();
presentation.validate()?;
host.mount(geometry, &presentation, &context, retained.controller.as_mut(), services)?;
retained.flow = Some(flow);
}
Ok(())
}
pub fn content_action(&mut self, instance: &InstanceId, action: &ControlId, services: &mut ContentServices<'_>) -> PanelResult<()> {
self.require_live()?;
valid_id(&action.0)?;
self.layout.availability(instance).require()?;
let key = self.key(self.layout.layout().instance(instance)?)?;
let retained = self.controllers.get_mut(&key).ok_or_else(|| error(Rule::MissingTarget, "controller not retained"))?;
retained.availability.require()?;
let presentation = retained.controller.presentation();
presentation.validate()?;
let command =
presentation.actions.iter().find(|a| a.id == *action).ok_or_else(|| error(Rule::MissingTarget, "content action not advertised"))?;
if !command.enabled {
return Err(error(Rule::Availability, command.disabled_reason.as_deref().unwrap_or("content action unavailable")));
}
retained.controller.action(&key.owner, action, services)
}
pub fn destroy_owner(&mut self, owner: &ContentOwner, local: &mut dyn PanelLocalServices) -> PanelResult<()> {
self.require_live()?;
owner.validate()?;
if self.destroyed_owners.len() >= MAX_RETAINED_OWNERS && !self.destroyed_owners.contains(owner) {
return Err(error(Rule::CollectionLimit, "destroyed owner cap"));
}
for (key, retained) in &self.controllers {
if key.owner == *owner {
retained.controller.prepare_lifecycle(&LifecycleEvent::DestroyOwner)?;
}
}
self.controllers.retain(|key, retained| {
if key.owner != *owner {
return true;
}
local.release(&retained.scope, &key.instance);
retained.controller.lifecycle(&LifecycleEvent::DestroyOwner);
false
});
self.destroyed_owners.insert(owner.clone());
Ok(())
}
/// Explicitly rebind a previously destroyed owner; it receives fresh content
/// controllers on update, never a silent resurrection during hidden ticks.
pub fn revive_owner(&mut self, owner: &ContentOwner) -> PanelResult<()> {
self.require_live()?;
owner.validate()?;
self.destroyed_owners.remove(owner);
Ok(())
}
pub fn shutdown(&mut self, local: &mut dyn PanelLocalServices) -> PanelResult<()> {
for retained in self.controllers.values() {
retained.controller.prepare_lifecycle(&LifecycleEvent::DestroyOwner)?;
}
for (key, retained) in &mut self.controllers {
local.release(&retained.scope, &key.instance);
retained.controller.lifecycle(&LifecycleEvent::DestroyOwner);
}
self.controllers.clear();
self.destroyed = true;
Ok(())
}
}
File diff suppressed because it is too large. Load diff
+207
View File
@@ -1,5 +1,212 @@
# Control protocol
The [universal panel foundation](panel-foundation.md) supplies typed layout actions
and retained runtime guards. The application-layout commands below are registered
engine commands reached through `engine.execute`, `engine.batch`, `engine.script`
and MCP's existing `execute`/`batch` tools. They require an injected application
backend; enabling the internal panel runtime remains an explicit integration step.
Current product defaults and the production shell are unchanged.
### Application panel and layout commands
Every command has input and output schemas through ordinary command discovery.
Inputs are strict at every parameter-check level: unknown fields, including nested
placement fields, are errors. As with other engine calls, omitted/null parameters
mean an empty object. IDs use the foundation's bounded lowercase ID domains;
dimensions are finite positive outer logical units, at most 32768. Requests are
bounded to 16384 encoded bytes before cloning or deserialising. No command opens a
dialog, edits the document, changes dirty/undo/revision, evaluates or tessellates a
model, fits a body, follows a camera request or selects a ribbon/tool/document tab.
Layout revision is independent of document revision.
Canonical existing targets are typed: `{"target":{"type":"instance","id":"log"}}`.
`section`, `workspace` and `native_host` are the other foundation target types;
each command accepts only the domains listed below. A legacy `id` may replace
`target`, but both together are rejected. It first resolves an exact instance ID.
A kind ID resolves only when its registration is single-instance and exactly one
canonical instance exists, including retained closed state. Multi-instance kinds
are rejected even when only one instance currently exists. No first-match guessing
or implicit instance creation occurs. `panel.open` instead requires separate `kind`
and `instance` fields.
All mutations accept optional `expected_revision:u64`. A stale revision produces
the foundation `revision` rule and leaves the command's layout and catalogue
unchanged. Successful mutations return the committed `LayoutReply` (layout,
revision, interaction, effects, capabilities and availability), never an echoed
placement request. `layout` includes all retained instances with `requested_open`,
ordered sections and their active tabs. Missing availability entries mean available.
Query replies contain no new host effects.
| Command | Parameters and behaviour |
|---|---|
| `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.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.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. |
| `panel.reset_pair` | `{first,second,expected_revision?}`. Resets adjacent sections to the registered default ratio within intersected bounds. |
| `panel.native_close` | `{target:{type:"native_host",id:HostId},expected_revision?}`. Native window close redocks its whole section; it does not explicitly close/cancel content. |
| `layout.save` | `{name,overwrite?:false,expected_revision?}` → `{name,overwritten,state}`. Saves the complete current envelope in the injected catalogue. |
| `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. |
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}
```
New-section indices address the global section order after detachment; join indices
address the destination's tab list after detachment. Joining keeps the destination's
activation, collapse and dimensions. Locations are `dock` (left/right/bottom),
`floating` (`origin:{x,y}`), or `window` (`host`, `origin`, `return_to`). Native
`return_to` contains `{zone,index,size,collapsed,join?:{section,index}}`; it never
recursively contains another native host. Pins and placement/size intersections
retain the foundation's structured refusal rules.
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.
There are at most 64 user presets. Collisions reject unless `overwrite:true` is
explicit; built-ins are immutable. No production kinds, preset contents or workspace
descriptors are invented. Headless starts with an empty registry/catalogue and an
internal current-layout identity, not a registered product workspace. Fixtures and
peer integrations can inject synthetic or real registrations. Missing capabilities
return errors rather than guessed defaults or disk/native success.
Workspace selection stages the outgoing full envelope, destination and selected
workspace together, then uses one guarded `Replace` on the retained runtime.
Same-workspace selection is a true no-op, preserving revision, focus, peek and
effects even if storage staging is unavailable. Applying/resetting a preset never
selects a workspace. Replacements hide omitted content without implicit Close or
Cancel; retained editors, conversations and hidden services survive A→B→A.
Catalogue preparation uses encoded full `LayoutEnvelope` records and explicit
aggregate caps: 64 registered workspaces, 64 built-ins, 64 remembered envelopes,
64 user presets, 16384 metadata bytes, and 4194304 aggregate envelope/recovery bytes.
Each envelope/rejected recovery buffer remains at most 262144 bytes and obeys the
foundation node/depth/collection caps. Quarantine, retained data, shared section
snapshots including projected sections, complete section order and bounded rejected
recovery intent survive save/apply/reset. Conflicting opaque identities, snapshots,
retained data or recovery intent reject atomically. Restoration uses the foundation
decoder and reappearance logic. Storage preparation finishes before live dispatch;
catalogue publication is infallible after successful native/controller guards.
Revision changes during staging reject the staged catalogue. No fallible storage
write after live commit is treated as an atomic success. The shipped catalogue is
in-memory; production preference durability and migrations remain peer work.
Atomic layout batches contain 1..64 commands, using the same parser/executor and
one final guarded Apply or Replace plus one catalogue publication. Queries and
saves may accompany mutations; save/apply/reset/workspace sequences can stage
together. Replies describe the **final committed** state, not hypothetical
intermediate live states. Every `expected_revision` in an atomic batch refers to
the initial live revision. Explicit Close/Open conflicts remain `lifecycle` errors.
Atomic batches cannot combine a snapshot replacement with explicit panel mutations,
or mix document commands with application layout; they return `capability` before
publishing anything. This preserves the foundation's explicit lifecycle intents.
Use `rollback:false` for sequential per-command transactions across these domains;
failures report `rolled_back:false`, `undone:0` and completed results. Scripts use
the same injected backend sequentially and stop at the first failure. A Session-only
executor (including ordinary CLI design scripts without an injected backend)
returns a structured missing-capability error for layout commands.
The GUI route uses the enabled runtime's actual content-service provider and an
injected `NativeHostAdapter`, never a reconstructed LayoutService. Headless MCP
owns one persistent application backend distinct from Session; Remote forwards to
the app and keeps no mirrored layout. Auto mode does not discard headless layout
work when an app appears. Foundation errors retain `{rule,detail}` with bounded
details: control replies add `panel_error` alongside the existing error string;
MCP tool errors add `structuredContent.panel_error`. The error string also encodes
that object, preserving identity through older string-only backend boundaries.
Rust integrations implement `ActionSink::project(LayoutAction)` as a pure
projection on the authoritative service. Its default returns `capability` so an
older inspect/dispatch-only sink cannot accidentally publish unstaged commands.
`LayoutService` and `RuntimeActionSink` provide it using the foundation's own
preparation path. `with_live_layout` refreshes the envelope's shared section memory
and projections without discarding opaque fields, then encodes against the same
foundation limits before publication.
Storage consumers can enumerate `CatalogueState::user_presets()` read-only and
round-trip a complete validated catalogue with `export()` and
`CatalogueState::hydrate(bytes,registry)` or `InMemoryCatalogue::from_snapshot`.
Hydration is independent of live commands; restored users remain explicitly
overwritable users, while built-ins remain immutable. Workspace descriptors,
remembered full envelopes, and rejected recovery bytes are included. The versioned
snapshot uses `SCPCAT01`, then length-prefixed little-endian u32 counts/UTF-8 names
and raw byte records, in built-ins/users/workspaces/remembered order. Each envelope
record contains length-prefixed envelope JSON, a recovery-presence byte (0/1), and,
when present, length-prefixed exact recovery bytes. Workspace descriptors contain
ID/title-key/default-name strings. The snapshot has an additional 8192-byte framing
allowance above the existing aggregate payload/metadata caps (4218880 bytes total).
Every count/string/record is bounded before allocation, and hydration rejects
duplicate names across users/built-ins, duplicate workspace keys, corrupt framing,
trailing data, invalid envelope identities and all existing aggregate/node/depth
limits before a candidate can be published. This seam performs no disk storage.
Reading a retained envelope does not consume quarantine merely because the registry
has grown. `decode_retained_record` validates an already-retained record exactly;
`decode_retained` additionally checks its workspace. Neither reader generates
section order/projections or performs quarantine migration/reappearance. Hydration
preserves the original validated record bytes and rejected binary data, including
records at the per-envelope or aggregate cap when optional panel kinds disappear
or return. Missing registrations do not invalidate unrelated users, built-ins or
workspace memories. Retained validation checks structural ownership, placement
bounds and all applicable known-kind constraints, without invented descriptors.
An exact retained layout can still contain absent kinds and is not live admission.
`StoredEnvelope::project_envelope` (or foundation `project_retained_record`) stages
missing-kind quarantine before a guarded live use, preserving full section order,
activation and opaque records. This staging does not consume existing quarantine;
ordinary save/live overlays therefore keep reappearance retryable after registry
growth. Foundation `decode` also stages migration and attempts restoration, with
its existing fallback/rejected-input result contract.
Materialization may legitimately exceed a cap and reject its staged candidate;
reading/hydrating the accepted original record does not materialize it.
Apply/reset/workspace replacement
explicitly stage restoration, and consume it only with a successful authoritative
Replace and catalogue publication. A failed action leaves the restore obligation
retryable. `panel.popout` requires the panel's `features.popout` on both web and
native policies before any enabled web fallback; `panel.float` remains separate.
Application command, atomic-batch and GUI action boundaries refresh the current
read-only provider/document environment and availability. A document or contextual
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.
Unsupported atomic intent mixtures are rejected by pure structural preflight
before any context/controller publication as well as before layout/native effects.
At MCP tool level, an atomic batch containing any panel/layout command must reach
the authoritative batch transaction. If the endpoint is unavailable or the encoded
request exceeds its transport margin, a structured zero-effect capability/size
refusal replaces the old sequential fallback. No document checkpoint or individual
layout command is sent. Explicit `rollback:false` keeps the sequential fallback
and reports completed layout changes honestly. Document-only batch fallback keeps
its existing checkpoint/rollback behaviour. Explicit null parameters normalize to
an empty object in single, atomic, sequential and script routes for GUI/headless.
Compatibility: `view.layout` still means Floating/Compact **surface styling**.
History-in-Browser, History Bodies/Origin and Render search/options remain content
preferences. Existing `view.history_layout`/`view.render_dock` controls continue to
serve the existing shell. There is no safe universal alias without registered
instance identities: `browser`/`under_browser` combine content with placement, and
Render dock changes can affect a pair. They are not silently mapped to universal
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.
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
+309
View File
@@ -0,0 +1,309 @@
# 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.
## Ownership and integration boundaries
| 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. |
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 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.
`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.
`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.
## Actions and atomicity
`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.
`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.
- `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.
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`.
`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.
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.
## Final product decisions
- 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.
## Geometry and local services
`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.
`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.
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.
## Persistence and bounds
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.
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.
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.
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.
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.
## Executable fixtures
`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.
`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.
```rust
use solidcraft_engine::panels::*;
use solidcraft_ui_egui::panel_runtime::PanelMountHarness;
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(())
}
```
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.
+9
View File
@@ -1,5 +1,14 @@
# 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.
`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.
+20
View File
@@ -91,6 +91,11 @@ inspect.curvature_map display analysis: shading
inspect.environment_map display analysis: shading
inspect.silhouette display analysis: outline
inspect.zebra display analysis: shading
layout.apply application panel layout; no geometry (engine/UI/MCP tests)
layout.get application panel layout; no geometry (engine/UI/MCP tests)
layout.reset application panel layout; no geometry (engine/UI/MCP tests)
layout.save application panel layout; no geometry (engine/UI/MCP tests)
layout.workspace.select application panel layout; no geometry (engine/UI/MCP tests)
library.apply material and appearance libraries
library.export material and appearance libraries
library.inspect material and appearance libraries
@@ -107,6 +112,21 @@ 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.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)
panel.dismiss application panel layout; no geometry (engine/UI/MCP tests)
panel.float application panel layout; no geometry (engine/UI/MCP tests)
panel.focus application panel layout; no geometry (engine/UI/MCP tests)
panel.list application panel layout; no geometry (engine/UI/MCP tests)
panel.move application panel layout; no geometry (engine/UI/MCP tests)
panel.native_close application panel layout; no geometry (engine/UI/MCP tests)
panel.open application panel layout; no geometry (engine/UI/MCP tests)
panel.peek application panel layout; no geometry (engine/UI/MCP tests)
panel.popout application panel layout; no geometry (engine/UI/MCP tests)
panel.reset_pair application panel layout; no geometry (engine/UI/MCP tests)
panel.resize application panel layout; no geometry (engine/UI/MCP tests)
panel.resize_pair application panel layout; no geometry (engine/UI/MCP tests)
parameters.comment parameter bookkeeping; a value change that rebuilds is parameters.change, which cases use
parameters.complete parameter bookkeeping; a value change that rebuilds is parameters.change, which cases use
parameters.delete parameter bookkeeping; a value change that rebuilds is parameters.change, which cases use