DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Docking trial: craft-ui f4f9e5b, DockCommand, hit rects, iconic column
aionggb66c3223f1fc
diff --git a/Cargo.lock b/Cargo.lockindex 1e77d5344..5db9c5acd 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -849,7 +849,7 @@ dependencies = [[[package]]name = "craft-ui"version = "0.1.0"-source = "git+https://github.com/aiongg/craft-libs?rev=c94ab4d313832ea9a84da721a6d3e7a7838dacef#c94ab4d313832ea9a84da721a6d3e7a7838dacef"+source = "git+https://github.com/aiongg/craft-libs?rev=f4f9e5b206a721d28ea1214ef8bf85b8e30bb779#f4f9e5b206a721d28ea1214ef8bf85b8e30bb779"dependencies = ["egui","serde",diff --git a/Cargo.toml b/Cargo.tomlindex 9ecd08b25..63ea8c527 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -126,4 +126,4 @@ hayro-jbig2 = { git = "https://github.com/storytold/pdfcraft", rev = "b5467d93a0# Docking trial: craft-ui from the craft-libs `docking` branch.[patch."https://github.com/storytold/craft-libs"]-craft-ui = { git = "https://github.com/aiongg/craft-libs", rev = "c94ab4d313832ea9a84da721a6d3e7a7838dacef" }+craft-ui = { git = "https://github.com/aiongg/craft-libs", rev = "f4f9e5b206a721d28ea1214ef8bf85b8e30bb779" }diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rsindex eea906ee6..6041f8790 100644--- a/crates/ui-egui/src/chrome.rs+++ b/crates/ui-egui/src/chrome.rs@@ -1249,7 +1249,7 @@ mod tests {h.run_steps(3);// Preflight is in the iconic column: `window.panel` shows it.assert!(crate::panel_docking::showing(&h.state().app, "preflight"));- h.get_by_label("Preflight");+ assert!(h.query_all_by_label("Preflight").count() >= 2, "its icon and its tab in the flyout");// With the panel already showing, the entry keeps it open.h.get_by_label("No errors ▾").click();h.run_steps(3);@@ -1270,9 +1270,12 @@ mod tests {count.click();h.run_steps(3);assert!(crate::panel_docking::showing(&h.state().app, "preflight"));- h.get_by_label("Preflight");+ assert!(h.query_all_by_label("Preflight").count() >= 2, "its icon and its tab in the flyout");assert!(h.query_by_label("Preflight Panel…").is_none(), "the menu isn't left open");- // A double-click with the panel already showing keeps it open.+ // A double-click with the panel already showing keeps it open (the first click closes+ // its flyout, the double-click opens it again). Past the double-click time, so the+ // clicks are not counted with the ones before.+ h.run_steps(30);let count = h.get_by_label("No errors ▾");count.click();count.click();diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rsindex ea81c278e..1ff3218de 100644--- a/crates/ui-egui/src/control.rs+++ b/crates/ui-egui/src/control.rs@@ -78,7 +78,7 @@ pub fn inspect(app: &DesignApp, ctx: &egui::Context) -> Value {"ui": serde_json::to_value(&app.ui).unwrap_or_default(),"view": app.view().map(|v| serde_json::to_value(v).unwrap_or_default()),"canvasRect": app.canvas_rect.map(|c| json!([c.left(), c.top(), c.width(), c.height()])),- "docking": crate::panel_docking::inspect(app),+ "docking": crate::panel_docking::inspect(app, ctx),"window": [r.width(), r.height()],"documents": app.session@@ -171,7 +171,7 @@ fn handle_request(app: &mut DesignApp, ctx: &egui::Context, req: &ControlRequest"engine.commands" => ok(all_commands(app)),"document.inspect" => wrap(app.run("document.inspect", json!({}))),"ui.inspect" => ok(inspect(app, ctx)),- "ui.docking" => ok(crate::panel_docking::inspect(app)),+ "ui.docking" => ok(crate::panel_docking::inspect(app, ctx)),"ui.menu.list" => ok(serde_json::to_value(menus::MENUS).unwrap_or_default()),"ui.tool.select" => wrap(app.run("tool.select", json!({"tool": s("tool").unwrap_or("")}))),"ui.tool.list" => ok(serde_json::to_value(designcraft_tools::TOOL_GROUPS).unwrap_or_default()),diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 370388317..de859f4ff 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -22,6 +22,7 @@ mod modal_drag;mod new_document;mod object_control;mod panel_docking;+mod panel_icons;pub mod panels;mod prefs;pub mod render_worker;@@ -88,6 +89,59 @@ pub struct Services {pub clipboard_text: Option<ClipboardFn>,}+/// Closed panels, each with where it goes back, in craft-ui's `Workspace::hidden` shape+/// (`[[panel, location], …]`). A floating panel's entry is where Dock Panel returns it.+/// Files from before this shape hold an object keyed by panel; it still loads.+#[derive(Clone, Debug, Default, PartialEq, Serialize)]+#[serde(transparent)]+pub struct HiddenPanels(pub Vec<(String, craft_ui::docking::Location<String>)>);++impl<'de> Deserialize<'de> for HiddenPanels {+ fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {+ #[derive(Deserialize)]+ #[serde(untagged)]+ enum Shape {+ List(Vec<(String, craft_ui::docking::Location<String>)>),+ Keyed(std::collections::BTreeMap<String, craft_ui::docking::Location<String>>),+ }+ let entries = match Shape::deserialize(deserializer)? {+ Shape::List(entries) => entries,+ Shape::Keyed(entries) => entries.into_iter().collect(),+ };+ let mut hidden = Self::default();+ for (panel, location) in entries {+ hidden.insert(panel, location);+ }+ Ok(hidden)+ }+}++impl HiddenPanels {+ pub fn is_empty(&self) -> bool {+ self.0.is_empty()+ }+ pub fn contains_key(&self, panel: &str) -> bool {+ self.0.iter().any(|(p, _)| p == panel)+ }+ pub fn get(&self, panel: &str) -> Option<&craft_ui::docking::Location<String>> {+ self.0.iter().find(|(p, _)| p == panel).map(|(_, location)| location)+ }+ /// Record where `panel` goes back, replacing an earlier entry.+ pub fn insert(&mut self, panel: String, location: craft_ui::docking::Location<String>) {+ self.remove(&panel);+ self.0.push((panel, location));+ }+ pub fn remove(&mut self, panel: &str) {+ self.0.retain(|(p, _)| p != panel);+ }+ pub fn keys(&self) -> impl Iterator<Item = &String> {+ self.0.iter().map(|(p, _)| p)+ }+ pub fn clear(&mut self) {+ self.0.clear();+ }+}+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub enum ScreenMode {@@ -115,8 +169,8 @@ pub struct SavedWorkspace {/// Custom panel membership and placement; absent in older workspace files.#[serde(default, skip_serializing_if = "Option::is_none")]pub docking: Option<craft_ui::docking::Layout<String>>,- #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]- pub docking_hidden: std::collections::BTreeMap<String, craft_ui::docking::Location<String>>,+ #[serde(default, skip_serializing_if = "HiddenPanels::is_empty")]+ pub docking_hidden: HiddenPanels,/// The workspace's own iconic column (see [`UiState::icon_groups`]).#[serde(default, skip_serializing_if = "Option::is_none")]pub icon_groups: Option<Vec<Vec<String>>>,@@ -267,8 +321,8 @@ pub struct UiState {/// (`panel_docking::default_layout`).#[serde(default, skip_serializing_if = "Option::is_none")]pub docking: Option<craft_ui::docking::Layout<String>>,- #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]- pub docking_hidden: std::collections::BTreeMap<String, craft_ui::docking::Location<String>>,+ #[serde(default, skip_serializing_if = "HiddenPanels::is_empty")]+ pub docking_hidden: HiddenPanels,/// The panel (or the canvas) last clicked or selected in the docking layout.#[serde(skip)]pub docking_focused: Option<String>,@@ -281,6 +335,12 @@ pub struct UiState {/// The panel last revealed explicitly, which `ui.set closePanel` closes.#[serde(skip)]pub docking_opened: Option<String>,+ /// The panel whose iconic-column flyout is open, as of the last frame or a command that+ /// opened it.+ #[serde(skip)]+ pub docking_flyout: Option<String>,+ /// Auto-Collapse Iconic Panels: a flyout closes on Escape or a click outside it.+ pub dock_auto_collapse: bool,/// Whether the default layout's outer column is expanded (false: collapsed to icons).pub dock_expanded: bool,/// A workspace's iconic panel groups (Essentials Classic), shown with their names in the@@ -413,6 +473,8 @@ impl Default for UiState {docking_generation: 0,docking_raise: None,docking_opened: None,+ docking_flyout: None,+ dock_auto_collapse: true,docking_focused: None,dock_expanded: true,icon_groups: None,diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rsindex 9e4ceda19..abed8cea7 100644--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@ -236,7 +236,7 @@ pub const UI_COMMANDS: &[(&str, &str, Option<&str>, &str)] = &[None,"{panel: properties|pages|layers|swatches|paragraphStyles|characterStyles|stroke|character|paragraph|textWrap|links|table|preflight}",),- ("window.floatPanel", "Float Panel", None, "{panel, x?, y?} — the panel in its own floating window (window.panel.float)"),+ ("window.floatPanel", "Float Panel", None, "{panel, x?, y?, width?, height?} — the panel in its own floating window (window.panel.float)"),("window.panel.layout","Change Panel Layout",@@ -247,13 +247,38 @@ pub const UI_COMMANDS: &[(&str, &str, Option<&str>, &str)] = &["window.panel.move","Move Panel",None,- "{panel, anchor, zone?: tab|center|left|right|top|bottom, before?: panel} — group, split or reorder a panel",+ "{panel, anchor, zone?: tab|center|left|right|top|bottom|above|below, before?: panel|null, group?, placement?} — group, split or reorder a panel (group: its whole tab group)",+ ),+ (+ "window.panel.float",+ "Float Panel",+ None,+ "{panel, x?, y?, width?, height?, group?, column?} — detach a panel (or its group, or its dock column) inside the application window",+ ),+ (+ "window.panel.dock",+ "Dock Panel",+ None,+ "{panel, anchor?, zone?, before?, group?, column?, side?: Start|End} — dock a floating panel: beside anchor, in a new column at side, or back where it floated from",),- ("window.panel.float", "Float Panel", None, "{panel, x?, y?, width?, height?} — detach a panel inside the application window"),- ("window.panel.dock", "Dock Panel", None, "{panel, anchor?, zone?, before?} — return a floating panel to a dock group"),("window.panel.activate", "Activate Panel", None, "{panel} — show and select a panel in its current group"),("window.panel.close", "Close Panel", None, "{panel} — hide a panel"),("window.panel.closeGroup", "Close Tab Group", None, "{panel} — hide the panel and the panels tabbed with it"),+ ("window.panel.closeOthers", "Close Other Panels in Group", None, "{panel} — hide the panels tabbed with it"),+ ("window.panel.minimize", "Minimize", None, "{panel, minimized?} — minimize the panel's group to its tab strip (toggles without minimized)"),+ ("window.panel.iconic", "Collapse to Icons", None, "{panel, iconic?} — collapse the panel's dock column to icons (toggles without iconic)"),+ ("window.panel.window", "Move Panel to New Window", None, "{panel, native?} — not available: DesignCraft keeps panels in its window"),+ ("window.workspace.new", "New Workspace", None, "{name} — save the current workspace (window.newWorkspace)"),+ ("window.workspace.delete", "Delete Workspace", None, "{name} — delete a saved workspace (window.deleteWorkspace)"),+ ("window.workspace.reset", "Reset Workspace", None, "{} — back to the current workspace as saved (window.resetWorkspace)"),+ ("window.workspace.lock", "Lock Workspace", None, "{locked?} — not available in DesignCraft"),+ (+ "ui.dock",+ "Change Panel Layout",+ None,+ "{action} | {operation: open|close|activate|float|moveFloating|move|setStackOpen|resizeStack|resizeSplit, …} — craft-ui's shared ui.dock shape",+ ),+ ("ui.dock.reset", "Reset Workspace", None, "{} — window.workspace.reset"),("window.collapseToIcons", "Collapse to Icons", None, "{} — the panel dock shrinks to its column of icons"),("window.dockPanel", "Dock Panel", None, "{panel} — back to its place in the dock (window.panel.dock)"),("window.controlBar", "Control", Some("Cmd+Alt+6"), "{}"),@@ -1848,6 +1873,7 @@ fn run_ui_inner(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Valueapp.ui.docking_generation = app.ui.docking_generation.wrapping_add(1);app.ui.docking_raise = None;app.ui.docking_opened = None;+ app.ui.docking_flyout = None;let name = p.get("name").and_then(Value::as_str).unwrap_or("Essentials");if let Some(w) = app.ui.custom_workspaces.iter().find(|w| w.name == name).cloned() {if let Some(hidden) = w.hidden_menu_items {@@ -2080,6 +2106,10 @@ pub fn enabled(app: &DesignApp, id: &str) -> bool {if is_window_control(id) {return window_control_available(app, id);}+ // Shared docking commands DesignCraft does not provide (native panel windows, Lock Workspace).+ if matches!(id, "window.panel.window" | "window.workspace.lock") {+ return false;+ }match designcraft_engine::find_command(id) {Some(c) => (c.enabled)(&app.session).is_ok(),None => true,diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rsindex c0e0cfd5f..44b327196 100644--- a/crates/ui-egui/src/panel_docking.rs+++ b/crates/ui-egui/src/panel_docking.rs@@ -4,7 +4,9 @@//! protected `canvas` panel and a dock at the logical end edge (the right in left-to-right//! languages, the left in right-to-left ones).-use craft_ui::docking::{Action, Column, Floating, Group, Layout, Node, Permissions, Placement, Side, Target, Zone};+use craft_ui::docking::{+ Action, Column, DockCommand, DockOperation, Floating, Group, Layout, Node, Permissions, Placement, Side, Target, UiDock, Workspace,+};use serde_json::{Value, json};use crate::DesignApp;@@ -222,9 +224,12 @@ fn layout_of(app: &DesignApp) -> Layout<String> {app.ui.docking.clone().unwrap_or_else(|| default_layout(&app.ui))}-/// Is `panel` showing: in front of its group, and not in a column collapsed to icons?+/// Is `panel` showing: in front of its group and not in a column collapsed to icons, or in+/// the open flyout of an iconic column?pub(crate) fn showing(app: &DesignApp, panel: &str) -> bool {- layout_of(app).panel_state(&panel.to_string()) == craft_ui::docking::PanelState::Front+ let layout = layout_of(app);+ layout.panel_state(&panel.to_string()) == craft_ui::docking::PanelState::Front+ || (app.ui.docking_flyout.as_deref() == Some(panel) && in_iconic_column(&layout, panel))}/// Is `panel` in a dock column collapsed to icons?@@ -323,12 +328,7 @@ fn first_dock_panel(layout: &Layout<String>, except: &str) -> Option<String> {})}-fn ensure(layout: &mut Layout<String>, panel: &str) -> Result<(), String> {- let anchor = first_dock_panel(layout, panel);- apply(layout, Action::Open { panel: panel.into(), anchor })-}--fn apply(layout: &mut Layout<String>, action: Action<String>) -> Result<(), String> {+fn apply(layout: &mut Layout<String>, action: Action<String>) -> Result<Vec<String>, String> {layout.apply_with_permissions(action, model_permissions).map_err(|e| e.to_string())}@@ -343,122 +343,253 @@ fn number(params: &Value, key: &str, default: f32) -> Result<f32, String> {}}-/// The side of the dock holding `panel`, if a dock column holds it.-fn dock_side(layout: &Layout<String>, panel: &str) -> Option<Side> {- let mut visit: Vec<&Node<String>> = layout.root.iter().collect();- let mut seen = 0usize;- while let Some(node) = visit.pop() {- seen = seen.saturating_add(1);- if seen > 2 * craft_ui::docking::MAX_PANELS {- break;- }- match node {- Node::Split { first, second, .. } => {- visit.push(first);- visit.push(second);- }- Node::Dock { side, columns } if columns.iter().flat_map(|c| &c.groups).any(|g| g.panels.iter().any(|p| p == panel)) => {- return Some(*side);- }- _ => {}- }+/// The shared docking command a DesignCraft command id names. `window.floatPanel` and+/// `window.dockPanel` are DesignCraft's names for Float Panel and Dock Panel. `window.workspace`+/// stays DesignCraft's own command (same id and params), with the other workspace commands.+fn shared_id(id: &str) -> Option<&'static str> {+ match id {+ "window.floatPanel" => Some("window.panel.float"),+ "window.dockPanel" => Some("window.panel.dock"),+ "window.workspace" => None,+ _ => DockCommand::<String>::IDS.iter().copied().find(|known| *known == id),}- None-}--/// The placement a `zone` names beside `anchor`. In a dock column or a floating window, top and-/// bottom add a group above or below the anchor's group; in a dock column, left and right add a-/// column on that side of the anchor's. Elsewhere the sides split the anchor's group.-fn placement(params: &Value, layout: &Layout<String>, anchor: &str, rtl: bool) -> Result<Placement<String>, String> {- if let Some(before) = params.get("before") {- let id = before.as_str().and_then(normalize).ok_or("before must name a panel")?;- return Ok(Placement::Tab { before: Some(id.into()) });- }- let zone = match params.get("zone") {- None => "tab",- Some(value) => value.as_str().ok_or("zone must be a string")?,- };- let side = dock_side(layout, anchor);- let floating = layout.floating.iter().any(|w| w.contains(anchor));- Ok(match zone {- "tab" => Placement::Tab { before: None },- "center" => Placement::Split(Zone::Center),- "top" | "bottom" if side.is_some() || floating => Placement::Group { below: zone == "bottom" },- "left" | "right" if floating => return Err("a floating window has no columns; use top, bottom or tab".into()),- "left" | "right" if let Some(side) = side => {- // Columns count from the window edge inwards; `after` is away from the edge.- let edge_is_right = (side == Side::End) != rtl;- Placement::Column { after: (zone == "right") != edge_is_right }- }- "left" => Placement::Split(Zone::Left),- "right" => Placement::Split(Zone::Right),- "top" => Placement::Split(Zone::Top),- "bottom" => Placement::Split(Zone::Bottom),- _ => return Err("zone must be tab, center, left, right, top or bottom".into()),- })}pub(crate) fn command(app: &mut DesignApp, id: &str, params: &Value) -> Option<Result<Value, String>> {if id == "app.tablePanel" {- return Some(change(app, if showing(app, "table") { "close" } else { "activate" }, &json!({"panel": "table"})));+ let id = if showing(app, "table") { "window.panel.close" } else { "window.panel.activate" };+ return Some(shared_command(app, id, &json!({"panel": "table"})));}if id == "window.collapseToIcons" {return Some(set_iconic(app, true));}- if id == "window.panel.closeGroup" {- return Some(- params- .get("panel")- .and_then(Value::as_str)- .and_then(normalize)- .ok_or_else(|| "panel must name a registered panel".to_string())- .and_then(|panel| apply_action(app, Action::CloseGroup { panel: panel.into() })),- );- }if matches!(id, "window.floatPanel" | "window.dockPanel" | "window.panel.float" | "window.panel.dock")&& let Some(panel) = params.get("panel").and_then(Value::as_str).filter(|p| crate::dock::float_only(p)){return Some(float_only_panel(app, id, panel, params));}- if id == "window.panel"- && let Some(result) = open_floating_group(app, params)- {- return Some(result);- }- if id == "window.panel.layout" {- return Some(- params- .get("action")- .ok_or_else(|| "action is required".to_string())- .and_then(|value| serde_json::from_value::<Action<String>>(value.clone()).map_err(|error| error.to_string()))- .and_then(|action| apply_action(app, action)),- );- }- let operation = match id {- "window.panel.move" => "move",- "window.panel.float" | "window.floatPanel" => "float",- "window.panel.dock" | "window.dockPanel" => "dock",- "window.panel.activate" => "activate",- "window.panel.close" => "close",+ if id == "window.panel" {+ if let Some(result) = open_floating_group(app, params) {+ return Some(result);+ }// Float-only panels (Type › Tabs) are not in the layout.- "window.panel" if params.get("panel").and_then(Value::as_str).and_then(normalize).is_some() => "activate",- _ => return None,+ params.get("panel").and_then(Value::as_str).and_then(normalize)?;+ return Some(shared_command(app, "window.panel.activate", params));+ }+ let id = shared_id(id)?;+ Some(shared_command(app, id, params))+}++/// Command params with DesignCraft's panel names resolved (a panel id or English name, in any+/// case) and `onto` read as `anchor`.+fn resolve_panels(params: &Value) -> Result<Value, String> {+ let mut params = if params.is_null() { json!({}) } else { params.clone() };+ let fields = params.as_object_mut().ok_or("params must be an object")?;+ if let Some(onto) = fields.remove("onto") {+ fields.entry("anchor").or_insert(onto);+ }+ for key in ["panel", "anchor", "target", "before"] {+ let Some(value) = fields.get_mut(key) else { continue };+ if key == "before" && value.is_null() {+ continue;+ }+ let id = value.as_str().and_then(normalize).ok_or_else(|| format!("{key} must name a registered panel"))?;+ *value = Value::String(id.to_owned());+ }+ Ok(params)+}++/// The panel `params` names, resolved, if it names one.+fn named_panel(params: &Value) -> Option<String> {+ params.get("panel").and_then(Value::as_str).map(str::to_owned)+}++/// Is `panel` alone in a floating window?+fn floats_alone(layout: &Layout<String>, panel: &str) -> bool {+ layout.floating.iter().any(|w| w.contains(&panel.to_string()) && w.panels().count() == 1)+}++/// A shared docking command (`window.panel.*`, `window.workspace.*`, `ui.dock`) on the layout in+/// use, all or nothing. craft-ui's `DockCommand` parses it and makes the layout actions;+/// DesignCraft resolves panel names, shows a hidden panel before moving, floating or docking+/// it, floats a panel at its own size, and returns a floated panel to its dock place on Dock+/// Panel.+fn shared_command(app: &mut DesignApp, id: &str, params: &Value) -> Result<Value, String> {+ let mut params = resolve_panels(params)?;+ if id == "window.panel.float"+ && let Some(panel) = named_panel(¶ms)+ && !floats_alone(&layout_of(app), &panel)+ && let Some(fields) = params.as_object_mut()+ {+ let size = floating_size(&panel);+ for (key, default) in [("x", 400.0), ("y", 140.0), ("width", size.x), ("height", size.y)] {+ fields.entry(key).or_insert(json!(default));+ }+ }+ if let Some(fields) = params.as_object_mut() {+ fields.insert("command".into(), Value::String(id.to_owned()));+ }+ let command: DockCommand<String> = serde_json::from_value(params).map_err(|e| e.to_string())?;+ match &command {+ DockCommand::Workspace { name } => return app.run("window.workspace", json!({"name": name})),+ DockCommand::NewWorkspace { name } => return app.run("window.newWorkspace", json!({"name": name})),+ DockCommand::DeleteWorkspace { name } => return app.run("window.deleteWorkspace", json!({"name": name})),+ DockCommand::ResetWorkspace {} => return app.run("window.resetWorkspace", json!({})),+ DockCommand::Lock { .. } => return Err("Lock Workspace is not available in DesignCraft".into()),+ DockCommand::Window { .. } => return Err("DesignCraft does not move panels to their own windows".into()),+ _ => {}+ }+ let rtl = crate::i18n::is_rtl(&app.ui.language);+ let mut txn = Transaction::begin(app)?;+ let shows = match &command {+ DockCommand::Activate { panel }+ | DockCommand::Move { panel, .. }+ | DockCommand::Float { panel, .. }+ | DockCommand::Dock { panel, .. }+ | DockCommand::UiDock(UiDock::Operation(DockOperation::Open { panel } | DockOperation::Activate { panel })) => Some(panel.clone()),+ _ => None,+ };+ let mut shown = false;+ if let Some(panel) = shows.as_ref().filter(|p| !txn.workspace.layout.contains(p)) {+ let fallback = first_dock_panel(&txn.workspace.layout, panel);+ txn.workspace.set_visible(panel.clone(), true, fallback).map_err(|e| e.to_string())?;+ shown = true;+ }+ let returned = match &command {+ DockCommand::Dock { panel, anchor: None, side: None, group: false, column: false, .. } if !shown => txn.dock_back(panel)?,+ _ => false,};- Some(change(app, operation, params))+ let actions = match &command {+ // Showing it was the whole command (craft-ui's `DockCommand::apply` does the same).+ DockCommand::Dock { anchor: None, side: None, .. } if shown || returned => Vec::new(),+ _ => command.to_actions(&txn.workspace, rtl).map_err(|e| e.to_string())?,+ };+ let reveal = match &command {+ DockCommand::Layout { action } | DockCommand::UiDock(UiDock::Action { action }) => match action {+ Action::Activate { panel } | Action::Open { panel, .. } | Action::OpenAt { panel, .. } => Some(panel.clone()),+ _ => None,+ },+ DockCommand::UiDock(UiDock::Operation(+ DockOperation::Float { panel, .. } | DockOperation::MoveFloating { panel, .. } | DockOperation::Move { panel, .. },+ )) => Some(panel.clone()),+ _ => shows,+ };+ let mut closed = Vec::new();+ for action in actions {+ closed.extend(txn.apply(action)?);+ }+ Ok(txn.commit(app, closed, reveal))+}++/// A change to the layout in use, committed only when every step succeeded.+struct Transaction {+ /// The layout, and the closed panels with where each one goes back.+ workspace: Workspace<String>,+ /// Where each floating panel was docked before it floated, for Dock Panel.+ returns: crate::HiddenPanels,+}++impl Transaction {+ fn begin(app: &DesignApp) -> Result<Self, String> {+ if app.ui.docking.as_ref().is_some_and(|layout| !valid(layout)) {+ return Err("saved panel layout is invalid; reset the workspace first".into());+ }+ let layout = layout_of(app);+ let mut workspace = Workspace::new(layout);+ let mut returns = crate::HiddenPanels::default();+ for (panel, location) in+ app.ui.docking_hidden.0.iter().filter(|(id, _)| normalize(id) == Some(id.as_str())).take(craft_ui::docking::MAX_PANELS)+ {+ if !workspace.layout.contains(panel) {+ workspace.hidden.push((panel.clone(), location.clone()));+ } else if workspace.layout.floating.iter().any(|w| w.contains(panel)) {+ returns.insert(panel.clone(), location.clone());+ }+ }+ Ok(Self { workspace, returns })+ }++ /// Dock Panel for a floating panel that floated from the dock: back to that place, while+ /// the panel it was beside is still docked. True when it went back.+ fn dock_back(&mut self, panel: &String) -> Result<bool, String> {+ let layout = &self.workspace.layout;+ if !layout.floating.iter().any(|w| w.contains(panel)) {+ return Ok(false);+ }+ let docked = Layout { root: layout.root.clone(), floating: Vec::new() };+ let Some(location) = self+ .returns+ .get(panel)+ .filter(|location| location.floating.is_none() && location.anchor.as_ref().is_none_or(|anchor| docked.contains(anchor)))+ else {+ return Ok(false);+ };+ let mut candidate = layout.clone();+ apply(&mut candidate, Action::Close { panel: panel.clone() })?;+ if candidate.restore(panel.clone(), location).is_err() {+ return Ok(false);+ }+ self.workspace.layout = candidate;+ self.returns.remove(panel);+ Ok(true)+ }++ /// One action from a command or the renderer, for registered panels only. Floating a+ /// docked panel remembers its place for Dock Panel.+ fn apply(&mut self, action: Action<String>) -> Result<Vec<String>, String> {+ if !known(&action) {+ return Err("docking action contains an unknown panel or an excessive split path".into());+ }+ if let Action::Float { panel, .. } = &action+ && let Ok(location) = self.workspace.layout.location(panel)+ && location.floating.is_none()+ {+ self.returns.insert(panel.clone(), location);+ }+ self.workspace.apply(action, model_permissions).map_err(|e| e.to_string())+ }++ /// Store the result. `reveal` is the panel the command showed, raised (or its flyout opened)+ /// on the next frame.+ fn commit(self, app: &mut DesignApp, closed: Vec<String>, reveal: Option<String>) -> Value {+ let Self { workspace, returns } = self;+ let layout = workspace.layout;+ let floating = |p: &String| layout.floating.iter().any(|w| w.contains(p));+ let mut hidden = crate::HiddenPanels(workspace.hidden);+ for (panel, location) in returns.0 {+ if floating(&panel) && !hidden.contains_key(&panel) {+ hidden.0.push((panel, location));+ }+ }+ let reveal = reveal.filter(|panel| layout.contains(panel));+ let flyout = reveal.as_ref().filter(|panel| in_iconic_column(&layout, panel)).cloned();+ app.ui.docking = Some(layout);+ app.ui.docking_hidden = hidden;+ release_closed(app, &closed);+ keep_float_only(app);+ if let Some(panel) = reveal {+ app.ui.docking_opened = Some(panel.clone());+ app.ui.docking_raise = Some(panel);+ app.ui.docking_flyout = flyout;+ } else if app.ui.docking_opened.as_ref().is_some_and(|panel| !app.ui.docking.as_ref().is_some_and(|layout| layout.contains(panel))) {+ app.ui.docking_opened = None;+ }+ app.ui.open_panel = None;+ json!({"layout": app.ui.docking, "closed": closed, "floating": floating_panels(app)})+ }}-// UI output and automation share this atomic dispatcher. The application owns the registry-// and saved return locations; craft-ui owns tree validation and structural changes.-fn apply_action(app: &mut DesignApp, action: Action<String>) -> Result<Value, String> {+/// Whether every panel an action names is registered (and a split path is not excessive).+/// The application owns the registry; craft-ui owns tree validation and structural changes.+fn known(action: &Action<String>) -> bool {let registered = |id: &String| self::registered(id);- let known = match &action {+ let tab = |placement: &Placement<String>| match placement {+ Placement::Tab { before: Some(id) } => registered(id),+ _ => true,+ };+ match action {Action::Move { panel, anchor, placement } | Action::OpenAt { panel, anchor, placement } => {- registered(panel)- && registered(anchor)- && match placement {- Placement::Tab { before: Some(id) } => registered(id),- _ => true,- }+ registered(panel) && registered(anchor) && tab(placement)}Action::Open { panel, anchor } => registered(panel) && anchor.as_ref().is_none_or(registered),Action::Float { panel, .. }@@ -471,13 +602,7 @@ fn apply_action(app: &mut DesignApp, action: Action<String>) -> Result<Value, StAction::MoveGroup { panel, to } | Action::MoveColumn { panel, to } | Action::MoveWindow { panel, to } => {registered(panel)&& match to {- Target::At { anchor, placement } => {- registered(anchor)- && match placement {- Placement::Tab { before: Some(id) } => registered(id),- _ => true,- }- }+ Target::At { anchor, placement } => registered(anchor) && tab(placement),_ => true,}}@@ -491,42 +616,7 @@ fn apply_action(app: &mut DesignApp, action: Action<String>) -> Result<Value, St| Action::ResizeIconic { panel, .. } => registered(panel),// Native OS windows are not enabled in DesignCraft; newer actions are rejected._ => false,- };- if !known {- return Err("docking action contains an unknown panel or an excessive split path".into());- }- if app.ui.docking.as_ref().is_some_and(|layout| !valid(layout)) {- return Err("saved panel layout is invalid; reset the workspace first".into());- }- let mut layout = layout_of(app);- let closed = layout.closed_by(&action).map_err(|e| e.to_string())?;- // Window › a closed panel, and Dock Panel after a float, bring it back where it was.- let returning: Vec<_> = match &action {- Action::Float { panel, .. } => {- layout.location(panel).ok().filter(|location| location.floating.is_none()).map(|location| (panel.clone(), location)).into_iter().collect()- }- _ => closed.iter().filter_map(|panel| layout.location(panel).ok().map(|location| (panel.clone(), location))).collect(),- };- let reveal = match &action {- Action::Activate { panel } | Action::Open { panel, .. } | Action::OpenAt { panel, .. } => Some(panel.clone()),- _ => None,- };- apply(&mut layout, action)?;- for (panel, location) in returning {- app.ui.docking_hidden.insert(panel, location);- }- app.ui.docking = Some(layout);- release_closed(app, &closed);- keep_float_only(app);- if let Some(panel) = reveal {- app.ui.docking_opened = Some(panel.clone());- app.ui.docking_raise = Some(panel);- app.ui.dock_expanded = true;- } else if app.ui.docking_opened.as_ref().is_some_and(|panel| !app.ui.docking.as_ref().is_some_and(|layout| layout.contains(panel))) {- app.ui.docking_opened = None;}- app.ui.open_panel = None;- Ok(json!({"layout": app.ui.docking, "closed": closed}))}/// Type › Tabs and the other float-only panels: their own windows outside the docking layout,@@ -559,65 +649,13 @@ pub(crate) fn floating_panels(app: &DesignApp) -> Vec<String> {docked.chain(app.ui.floating.iter().filter(|(id, _)| crate::dock::float_only(id)).map(|(id, _)| id.clone())).collect()}-/// The panel in front of each tab group in the dock (not the floating groups).-fn front_tabs(layout: &Layout<String>) -> Vec<String> {- let mut out = Vec::new();- let mut visit: Vec<&Node<String>> = layout.root.iter().collect();- while let Some(node) = visit.pop() {- if out.len() > craft_ui::docking::MAX_PANELS {- break;- }- match node {- Node::Split { first, second, .. } => {- visit.push(first);- visit.push(second);- }- Node::Tabs { panels, active } => out.extend(panels.get(*active).cloned()),- Node::Dock { columns, .. } => out.extend(columns.iter().flat_map(|c| &c.groups).filter_map(|g| g.active_panel().cloned())),- _ => {}- }- }- out-}--/// Bring each of `front` back in front of the dock tab group that holds it.-fn restore_front_tabs(layout: &mut Layout<String>, front: &[String]) {- let mut visit: Vec<&mut Node<String>> = layout.root.iter_mut().collect();- let mut seen = 0usize;- while let Some(node) = visit.pop() {- seen = seen.saturating_add(1);- if seen > 2 * craft_ui::docking::MAX_PANELS {- break;- }- match node {- Node::Split { first, second, .. } => {- visit.push(first);- visit.push(second);- }- Node::Tabs { panels, active } => {- if let Some(i) = panels.iter().position(|p| front.contains(p)) {- *active = i;- }- }- Node::Dock { columns, .. } => {- for group in columns.iter_mut().flat_map(|c| &mut c.groups) {- if let Some(i) = group.panels.iter().position(|p| front.contains(p)) {- group.active = i;- }- }- }- _ => {}- }- }-}-/// Panels InDesign opens together as one floating group from the Window menu, in tab order:/// Window › Styles › Paragraph Styles (or Character Styles) brings both.const FLOATING_GROUPS: &[&[&str]] = &[&["characterStyles", "paragraphStyles"]];/// Window › a panel of a [`FLOATING_GROUPS`] group none of whose panels is showing: the group-/// opens floating over the right of the canvas, with that panel in front. None otherwise (the-/// panel opens as before).+/// opens as one floating window over the right of the canvas, with that panel in front. None+/// otherwise (the panel opens as before).fn open_floating_group(app: &mut DesignApp, params: &Value) -> Option<Result<Value, String>> {let panel = params.get("panel").and_then(Value::as_str).and_then(normalize)?;let group = FLOATING_GROUPS.iter().find(|g| g.contains(&panel))?;@@ -626,7 +664,7 @@ fn open_floating_group(app: &mut DesignApp, params: &Value) -> Option<Result<Valreturn None;}// A panel closed from a place in the dock comes back there.- if group.iter().any(|p| app.ui.docking_hidden.get(*p).is_some_and(|l| l.floating.is_none())) {+ if group.iter().any(|p| app.ui.docking_hidden.get(p).is_some_and(|l| l.floating.is_none())) {return None;}let layout = layout_of(app);@@ -635,127 +673,24 @@ fn open_floating_group(app: &mut DesignApp, params: &Value) -> Option<Result<Val}let (w, h) = (290.0, 340.0);let (x, y) = app.canvas_rect.map_or((400.0, 140.0), |r| ((r.right() - w - 24.0).max(r.left()), r.top() + 96.0));- let before = (app.ui.docking.clone(), app.ui.docking_hidden.clone(), app.ui.floating.clone(), app.ui.open_panel.clone());- // The dock's tab in front stays in front (opening a panel passes through the dock).- let front = front_tabs(&layout);let open = |app: &mut DesignApp| -> Result<Value, String> {- let first = group.first().ok_or("empty panel group")?;- change(app, "float", &json!({"panel": first, "x": x, "y": y, "width": w, "height": h}))?;- for p in group.get(1..).unwrap_or_default() {- change(app, "move", &json!({"panel": p, "anchor": first}))?;- }- change(app, "activate", &json!({"panel": panel}))+ let mut txn = Transaction::begin(app)?;+ let panels: Vec<String> = group.iter().map(|p| (*p).to_string()).collect();+ let active = group.iter().position(|p| *p == panel).unwrap_or(0);+ let mut layout = txn.workspace.layout.clone();+ layout.floating.push(Floating::single(panels, active, [x, y, w, h]));+ layout.validate().map_err(|e| e.to_string())?;+ txn.workspace.layout = layout;+ txn.workspace.hidden.retain(|(p, _)| !group.contains(&p.as_str()));+ Ok(txn.commit(app, Vec::new(), Some(panel.to_string())))};- let result = open(app);- if result.is_ok()- && let Some(layout) = app.ui.docking.as_mut()- {- restore_front_tabs(layout, &front);- }- if result.is_err() {- // All or nothing.- (app.ui.docking, app.ui.docking_hidden, app.ui.floating, app.ui.open_panel) = before;- }- Some(result)-}--fn change(app: &mut DesignApp, operation: &str, params: &Value) -> Result<Value, String> {- let panel = params.get("panel").and_then(Value::as_str).and_then(normalize).ok_or("panel must name a registered panel")?;- if app.ui.docking.as_ref().is_some_and(|layout| !valid(layout)) {- return Err("saved panel layout is invalid; reset the workspace first".into());- }- let mut layout = layout_of(app);- let mut hidden: std::collections::BTreeMap<_, _> =- app.ui.docking_hidden.iter().filter(|(id, _)| normalize(id).is_some()).take(64).map(|(id, at)| (id.clone(), at.clone())).collect();- let mut restored = false;- if operation == "dock"- && params.get("anchor").or_else(|| params.get("onto")).is_none()- && let Some(location) = hidden.get(panel).filter(|location| {- location.floating.is_none()- && location.anchor.as_ref().is_none_or(|anchor| Layout { root: layout.root.clone(), floating: Vec::new() }.contains(anchor))- })- {- let mut candidate = layout.clone();- if candidate.contains(&panel.to_string()) {- apply(&mut candidate, Action::Close { panel: panel.into() })?;- }- if candidate.restore(panel.into(), location).is_ok() {- layout = candidate;- restored = true;- hidden.remove(panel);- }- }- match operation {- "dock" if restored => {}- "float" => {- let rect = [number(params, "x", 400.0)?, number(params, "y", 140.0)?, number(params, "width", 300.0)?, number(params, "height", 400.0)?];- ensure(&mut layout, panel)?;- if let Ok(location) = layout.location(&panel.to_string())- && location.floating.is_none()- {- hidden.insert(panel.into(), location);- }- apply(&mut layout, Action::Float { panel: panel.into(), rect })?;- }- "move" | "dock" => {- if operation == "move" && params.get("anchor").or_else(|| params.get("onto")).is_none() {- return Err("move requires a destination panel".into());- }- let anchor = match params.get("anchor").or_else(|| params.get("onto")) {- Some(v) => Some(v.as_str().and_then(normalize).ok_or("anchor must name a registered panel")?.to_string()),- None => first_dock_panel(&layout, panel),- };- if let Some(anchor) = anchor {- let placement = placement(params, &layout, &anchor, crate::i18n::is_rtl(&app.ui.language))?;- ensure(&mut layout, panel)?;- apply(&mut layout, Action::Move { panel: panel.into(), anchor, placement })?;- } else if operation == "dock" {- if layout.contains(&panel.to_string()) {- apply(&mut layout, Action::Close { panel: panel.into() })?;- }- apply(&mut layout, Action::Open { panel: panel.into(), anchor: None })?;- } else {- return Err("move requires an existing destination panel".into());- }- }- "close" => {- hidden.insert(panel.into(), layout.location(&panel.to_string()).map_err(|e| e.to_string())?);- apply(&mut layout, Action::Close { panel: panel.into() })?;- }- _ => {- if !layout.contains(&panel.to_string())- && let Some(location) = hidden.get(panel)- {- // A missing neighbor is allowed: the normal visible dock becomes the fallback.- let _ = layout.restore(panel.into(), location);- }- ensure(&mut layout, panel)?;- hidden.remove(panel);- // Iconic columns open no flyouts yet, so showing a panel there expands its column.- if in_iconic_column(&layout, panel) {- apply(&mut layout, Action::SetIconic { panel: panel.into(), iconic: false })?;- }- }- }- app.ui.docking = Some(layout);- app.ui.docking_hidden = hidden;- if operation == "close" {- release_closed(app, &[panel.to_owned()]);- }- keep_float_only(app);- app.ui.open_panel = None;- app.ui.docking_opened = if operation == "close" { None } else { Some(panel.to_owned()) };- app.ui.docking_raise = if operation == "close" { None } else { Some(panel.to_owned()) };- if operation != "close" {- app.ui.dock_expanded = true;- }- Ok(json!({"panel": panel, "floating": floating_panels(app), "layout": app.ui.docking}))+ Some(open(app))}/// Forget what DesignCraft keeps about panels that just closed: the focus, the panel last/// opened (for `ui.set closePanel`) and a pending raise.fn release_closed(app: &mut DesignApp, closed: &[String]) {- for slot in [&mut app.ui.docking_focused, &mut app.ui.docking_opened, &mut app.ui.docking_raise] {+ for slot in [&mut app.ui.docking_focused, &mut app.ui.docking_opened, &mut app.ui.docking_raise, &mut app.ui.docking_flyout] {if slot.as_ref().is_some_and(|panel| closed.contains(panel)) {*slot = None;}@@ -810,13 +745,18 @@ pub(crate) fn show(app: &mut DesignApp, ui: &mut egui::Ui) {blocked.push(rect);}let style = dock_style(ui, &app.ui.language);- let mut dock = craft_ui::docking::DockArea::new(area).blocked_rects(&blocked);+ let mut dock = craft_ui::docking::DockArea::new(area).blocked_rects(&blocked).auto_collapse_iconic(app.ui.dock_auto_collapse);if let Some(panel) = raise {dock = dock.raise_panel(panel);}- let mut content = PanelContent(app, Vec::new());- let output = dock.show_content(ui, &layout, &style, &mut content);- let floats = content.1;+ let icons = crate::panel_icons::panel_icons(ui.ctx(), style.icon_size);+ let output = dock.show_content(ui, &layout, &style, &mut PanelContent { app: &mut *app, icons });+ app.ui.docking_flyout = craft_ui::docking::flyout::<String>(ui.ctx(), area);+ for event in &output.events {+ if *event == craft_ui::docking::DockEvent::ToggleAutoCollapse {+ app.ui.dock_auto_collapse = !app.ui.dock_auto_collapse;+ }+ }if let Some(panel) = output.focused {if panel != CANVAS {app.ui.docking_opened = Some(panel.clone());@@ -826,7 +766,7 @@ pub(crate) fn show(app: &mut DesignApp, ui: &mut egui::Ui) {if let Some(error) = output.error {app.ui.status = error.to_string();}- for action in output.actions.into_iter().chain(floats) {+ for action in output.actions {if let Err(error) = app.run("window.panel.layout", json!({"action": action})) {app.ui.status = error;}@@ -834,15 +774,21 @@ pub(crate) fn show(app: &mut DesignApp, ui: &mut egui::Ui) {}/// What the control channel reports: the layout in use (craft-ui's serialized `Layout`),-/// whether it is the workspace's default, the panel (or `canvas`) last clicked or selected, and-/// the panels closed with a remembered place.-pub(crate) fn inspect(app: &DesignApp) -> Value {+/// whether it is the workspace's default, the panel (or `canvas`) last clicked or selected, the+/// panels closed with a remembered place, the panel whose flyout is open, and where each+/// docking gesture starts in the last frame (`hitRects`).+pub(crate) fn inspect(app: &DesignApp, ctx: &egui::Context) -> Value {+ let hits = craft_ui::docking::DockArea::<String>::hit_rects(ctx, egui::Id::new("designcraft-panel-docking"));+ let hit_rects: Vec<Value> = hits.iter().map(|(hit, r)| json!({"hit": hit, "rect": [r.left(), r.top(), r.width(), r.height()]})).collect();json!({"layout": layout_of(app),"customized": app.ui.docking.is_some(),"focused": app.ui.docking_focused,+ "flyout": app.ui.docking_flyout,+ "autoCollapse": app.ui.dock_auto_collapse,"rightToLeft": crate::i18n::is_rtl(&app.ui.language),"hidden": app.ui.docking_hidden.keys().collect::<Vec<_>>(),+ "hitRects": hit_rects,})}@@ -865,7 +811,7 @@ fn dock_style(ui: &egui::Ui, language: &str) -> craft_ui::docking::DockStyle {const DOCK_LABELS: &[(&str, &str)] = &[("dock.float", "Float Panel"),("dock.close", "Close"),- ("dock.move", "Group with"),+ ("dock.movePanelTo", "Group with"),("dock.panels", "Panels"),("dock.resize", "Resize panels"),("dock.resizeWindow", "Resize panel window"),@@ -874,10 +820,12 @@ const DOCK_LABELS: &[(&str, &str)] = &[("dock.minimize", "Minimize"),("dock.expand", "Expand"),("dock.floatGroup", "Float Tab Group"),- ("dock.groupWith", "Group Tab Group with"),+ ("dock.moveGroupTo", "Group Tab Group with"),("dock.moveColumn", "Move Panel Column"),("dock.collapseToIcons", "Collapse to Icons"),("dock.expandPanels", "Expand Panels"),+ ("dock.collapseColumn", "Collapse to Icons"),+ ("dock.expandColumn", "Expand Panels"),("dock.moveWindow", "Move Panel Window"),("dock.closeWindow", "Close Panel Window"),("dock.undock", "Undock Panel"),@@ -887,6 +835,7 @@ const DOCK_LABELS: &[(&str, &str)] = &[("dock.maximize", "Maximize Frame"),("dock.restoreFrame", "Restore Frame Size"),("dock.newWindow", "Move Panel to New Window"),+ ("dock.autoCollapse", "Auto-Collapse Iconic Panels"),];/// The menu behind a panel's three-line button: the panel's own commands, then its docking@@ -952,65 +901,33 @@ fn floating_size(panel: &str) -> egui::Vec2 {}}-/// The panels' content, and the floats released over the canvas this frame.-struct PanelContent<'a>(&'a mut DesignApp, Vec<Action<String>>);+/// The panels' content and icons.+struct PanelContent<'a> {+ app: &'a mut DesignApp,+ icons: std::collections::HashMap<String, egui::ImageSource<'static>>,+}impl craft_ui::docking::DockContent<String> for PanelContent<'_> {- /// A panel or group released over the document area floats there, as in InDesign, instead of- /// splitting the canvas. The window's edge bands still make new docks and root splits.- fn resolve_drag(- &mut self,- _: &egui::Context,- style: &craft_ui::docking::DockStyle,- request: &craft_ui::docking::DropRequest<'_, String>,- ) -> Option<craft_ui::docking::DropFeedback> {- let pointer = request.pointer;- let over_canvas = request.targets.iter().rev().find(|t| t.rect.contains(pointer)).is_some_and(|t| t.anchor == CANVAS);- let band = style.edge_band.max(style.new_dock_band);- if !over_canvas || !request.workspace.shrink(band).contains(pointer) {- return None;- }- // A floating window moving live has no float rect; it moves as before.- if request.whole_group && request.floating_rect.is_none() {- return None;- }- if request.released- && let Some(r) = request.floating_rect- {- let rect = [r.left(), r.top(), r.width(), r.height()];- let panel = request.panel.clone();- self.1.push(if request.whole_group {- Action::MoveGroup { panel, to: Target::Float { rect: Some(rect) } }- } else {- Action::Float { panel, rect }- });- }- Some(craft_ui::docking::DropFeedback { preview: request.floating_rect, insertion: None })- }fn body(&mut self, ui: &mut egui::Ui, id: &String) {if id == CANVAS {let fill = crate::theme::Tokens::get(ui.ctx()).pasteboard;ui.painter().rect_filled(ui.max_rect(), 0.0, fill);- // A bare panel has no tab to report focus through, so the canvas reports its own.- if ui.input(|i| i.pointer.any_pressed()) && ui.ui_contains_pointer() {- self.0.ui.docking_focused = Some(CANVAS.to_string());- }- self.0.canvas_area(ui, false);+ self.app.canvas_area(ui, false);return;}egui::Frame::NONE.inner_margin(egui::Margin::same(8)).show(ui, |ui| {if crate::dock::scrolls_itself(id) {- crate::dock::panel_body(self.0, ui, id);+ crate::dock::panel_body(self.app, ui, id);return;}egui::ScrollArea::vertical().id_salt(("shared-panel-body", id)).auto_shrink([false, false])- .show(ui, |ui| crate::dock::panel_body(self.0, ui, id));+ .show(ui, |ui| crate::dock::panel_body(self.app, ui, id));});}fn logical_label(&self, id: &String) -> String {let english = crate::dock::DOCK_TABS.iter().chain(crate::dock::ICON_PANELS).find(|p| p.0 == id).map_or(id.as_str(), |p| p.1);- crate::i18n::tr(&self.0.ui.language, english).to_owned()+ crate::i18n::tr(&self.app.ui.language, english).to_owned()}fn permissions(&self, id: &String) -> Permissions {model_permissions(id)@@ -1022,6 +939,9 @@ impl craft_ui::docking::DockContent<String> for PanelContent<'_> {fn floating_size(&self, id: &String) -> Option<egui::Vec2> {Some(floating_size(id))}+ fn icon(&self, id: &String) -> Option<egui::ImageSource<'static>> {+ self.icons.get(id).cloned()+ }fn bare(&self, id: &String) -> bool {id == CANVAS}@@ -1030,7 +950,7 @@ impl craft_ui::docking::DockContent<String> for PanelContent<'_> {}fn group_header(&mut self, ui: &mut egui::Ui, _: &[String], active: &String, _: bool) {if let Some(panel) = normalize(active) {- three_line_button(self.0, ui, panel);+ three_line_button(self.app, ui, panel);}}fn label(&mut self, ui: &egui::Ui, _: &String, logical: &str, font: &egui::FontId, color: egui::Color32) -> egui::WidgetText {@@ -1074,7 +994,7 @@ fn tab_commands(app: &mut DesignApp, ui: &mut egui::Ui, panel: &'static str) {/// Close the last explicitly opened panel through the same validated layout transaction.pub(crate) fn close_visible(app: &mut DesignApp) -> Result<(), String> {if let Some(panel) = app.ui.docking_opened.clone() {- change(app, "close", &json!({"panel": panel}))?;+ shared_command(app, "window.panel.close", &json!({"panel": panel}))?;}app.ui.open_panel = None;Ok(())diff --git a/crates/ui-egui/src/panel_docking_tests.rs b/crates/ui-egui/src/panel_docking_tests.rsindex b44265e7d..f182bf644 100644--- a/crates/ui-egui/src/panel_docking_tests.rs+++ b/crates/ui-egui/src/panel_docking_tests.rs@@ -311,7 +311,10 @@ fn properties_stroke_link_opens_the_stroke_panel_in_a_custom_workspace() {h.run_steps(1);}h.run_steps(2);- assert!(!in_iconic_column(h.state().ui.docking.as_ref().unwrap(), "stroke"));+ // Stroke stays in the iconic column and opens as its flyout.+ assert!(in_iconic_column(h.state().ui.docking.as_ref().unwrap(), "stroke"));+ assert_eq!(h.state().ui.docking_flyout.as_deref(), Some("stroke"));+ assert!(showing(h.state(), "stroke"));assert_eq!(h.state().ui.docking_opened.as_deref(), Some("stroke"));}@@ -399,7 +402,7 @@ fn table_and_control_visibility_work_after_customization_without_document_edits(assert!(!app.ui.dock_expanded);assert!(!app.ui.docking.as_ref().unwrap().contains(&"table".into()));app.run("window.panel", json!({"panel":"properties"})).unwrap();- assert!(app.ui.dock_expanded);+ assert_eq!(app.ui.docking_flyout.as_deref(), Some("properties"), "it opens as a flyout from the collapsed dock");assert_eq!(app.ui.docking_raise.as_deref(), Some("properties"));assert_eq!(serde_json::to_value(&app.session.active().unwrap().doc).unwrap(), doc);assert_eq!(app.session.active().unwrap().history.undo.len(), undo);@@ -591,9 +594,12 @@ fn collapse_to_icons_shrinks_the_dock_to_its_icons() {assert!(app.ui.dock_expanded);app.run("window.collapseToIcons", json!({})).unwrap();assert!(!app.ui.dock_expanded);- // A panel chosen from Window opens the dock again.+ // A panel chosen from Window opens as a flyout beside its icon; the dock stays collapsed.app.run("window.panel", json!({"panel":"pages"})).unwrap();- assert!(app.ui.dock_expanded);+ assert_eq!(app.ui.docking_flyout.as_deref(), Some("pages"));+ assert_eq!(app.ui.docking_raise.as_deref(), Some("pages"));+ assert!(showing(&app, "pages"));+ assert!(in_iconic_column(app.ui.docking.as_ref().unwrap(), "pages"));}#[test]@@ -627,7 +633,8 @@ fn paragraph_styles_open_floating_with_character_styles() {assert_eq!(group.panels, ["characterStyles", "paragraphStyles"]);assert_eq!(group.panels[group.active], "paragraphStyles", "the one chosen is in front");// The dock still shows Properties in front.- assert!(front_tabs(&layout).iter().any(|p| p == "properties"), "{:?}", layout.root);+ assert_eq!(layout.panel_state(&"properties".to_string()), craft_ui::docking::PanelState::Front, "{:?}", layout.root);+ assert_eq!(layout.floating.len(), 1, "one floating window holds both tabs");// Other panels from Window leave it open.app.run("window.panel", json!({"panel":"color"})).unwrap();app.run("window.panel", json!({"panel":"links"})).unwrap();@@ -830,3 +837,138 @@ fn ui_docking_reports_the_layout_and_the_focused_panel() {assert_eq!(v["result"]["customized"], true);assert_eq!(v["result"]["hidden"], json!(["layers"]));}++fn hits(h: &Harness<'static, DesignApp>) -> Vec<(craft_ui::docking::Hit<String>, egui::Rect)> {+ craft_ui::docking::DockArea::<String>::hit_rects(&h.ctx, egui::Id::new("designcraft-panel-docking"))+}++/// `window.panel.*` ids and DesignCraft's aliases go through craft-ui's `DockCommand`.+#[test]+fn shared_panel_commands_float_dock_and_reject_atomically() {+ let mut app = app();+ let docked = default_layout(&app.ui);+ app.run("window.floatPanel", json!({"panel": "Layers", "x": 60, "y": 90})).unwrap();+ let layout = app.ui.docking.clone().unwrap();+ let window = layout.floating.iter().find(|w| w.contains(&"layers".to_string())).expect("Layers floats");+ assert_eq!(window.rect, [60.0, 90.0, 300.0, 420.0], "at the given place, at its own size");+ app.run("window.dockPanel", json!({"panel": "layers"})).unwrap();+ let layout = app.ui.docking.clone().unwrap();+ assert!(layout.floating.is_empty());+ assert_eq!(+ layout.root,+ docked.root.map(|mut root| {+ // Back in its place, in front of its group.+ if let Node::Split { second, .. } = &mut root+ && let Node::Dock { columns, .. } = &mut **second+ && let Some(group) = columns.first_mut().and_then(|c| c.groups.first_mut())+ {+ group.active = 2;+ }+ root+ }),+ "Dock Panel returns it where it floated from"+ );+ // A whole group, by any of its panels, then into a new column of the end dock.+ app.run("window.panel.float", json!({"panel": "pages", "group": true, "x": 80, "y": 80, "width": 300, "height": 400})).unwrap();+ let layout = app.ui.docking.clone().unwrap();+ assert_eq!(layout.floating.len(), 1);+ assert_eq!(layout.floating[0].groups[0].panels, ["properties", "pages", "layers"]);+ app.run("window.panel.dock", json!({"panel": "pages", "group": true, "side": "End"})).unwrap();+ let layout = app.ui.docking.clone().unwrap();+ assert!(layout.floating.is_empty());+ assert_eq!(tab_group(&layout, "pages"), ["properties", "pages", "layers"]);+ // A lone panel to a new dock at the start edge.+ app.run("window.panel.float", json!({"panel": "stroke"})).unwrap();+ app.run("window.panel.dock", json!({"panel": "stroke", "side": "Start"})).unwrap();+ assert!(+ matches!(&app.ui.docking.as_ref().unwrap().root, Some(Node::Split { first, .. }) if matches!(&**first, Node::Dock { side: Side::Start, .. }))+ );+ // Close Others and Minimize are shared commands too.+ app.run("window.panel.closeOthers", json!({"panel": "pages"})).unwrap();+ assert_eq!(tab_group(app.ui.docking.as_ref().unwrap(), "pages"), ["pages"]);+ assert!(app.ui.docking_hidden.contains_key("properties") && app.ui.docking_hidden.contains_key("layers"));+ app.run("window.panel.minimize", json!({"panel": "pages"})).unwrap();+ let location = app.ui.docking.as_ref().unwrap().location(&"pages".to_string()).unwrap();+ assert!(location.group.is_some_and(|g| g.minimized));+ // Rejected commands change nothing.+ let before = (app.ui.docking.clone(), app.ui.docking_hidden.clone());+ for (id, params) in [+ ("window.workspace.lock", json!({})),+ ("window.panel.window", json!({"panel": "pages"})),+ ("window.panel.move", json!({"panel": "stroke", "anchor": "pages", "zone": "left", "before": "pages"})),+ ("window.panel.dock", json!({"panel": "stroke", "side": "Middle"})),+ ] {+ assert!(app.run(id, params).is_err(), "{id}");+ assert_eq!((app.ui.docking.clone(), app.ui.docking_hidden.clone()), before, "{id}");+ }+ // Every shared id is registered for the command list and MCP.+ for id in craft_ui::docking::DockCommand::<String>::IDS {+ assert!(crate::menus::UI_COMMANDS.iter().any(|c| c.0 == *id), "{id} is not registered");+ }+}++/// A tab released over the canvas floats there (craft-ui: the protected canvas takes no tabs or+/// splits); a lone panel released in the window's left edge band makes a new dock there.+#[test]+fn tabs_dropped_on_the_canvas_float_and_at_the_far_edge_make_a_dock() {+ let mut h = harness(app(), vec2(1280.0, 800.0));+ let tab = |h: &Harness<'static, DesignApp>, panel: &str| {+ hits(h).into_iter().find(|(hit, _)| *hit == craft_ui::docking::Hit::Tab(panel.into())).map(|(_, r)| r)+ };+ let layers = tab(&h, "layers").expect("the Layers tab");+ drag(&mut h, layers.center(), egui::pos2(500.0, 400.0));+ let layout = h.state().ui.docking.clone().unwrap();+ assert!(layout.floating.iter().any(|w| w.contains(&"layers".to_string())), "{layout:?}");+ // A new dock takes a panel that is alone in its group: the floating Layers, by its title bar.+ // The harness's area starts 8 pt in from the window edge.+ let title = hits(&h).into_iter().find(|(hit, _)| *hit == craft_ui::docking::Hit::Title("layers".into())).expect("the title bar").1;+ drag(&mut h, title.center(), egui::pos2(12.0, 400.0));+ let layout = h.state().ui.docking.clone().unwrap();+ assert!(valid(&layout));+ let mut docks = Vec::new();+ let mut nodes: Vec<&Node<String>> = layout.root.iter().collect();+ while let Some(node) = nodes.pop() {+ match node {+ Node::Split { first, second, .. } => nodes.extend([&**first, &**second]),+ Node::Dock { side, columns } => {+ docks.push((*side, columns.iter().flat_map(|c| &c.groups).flat_map(|g| g.panels.clone()).collect::<Vec<_>>()))+ }+ _ => {}+ }+ }+ assert!(docks.iter().any(|(side, panels)| *side == Side::Start && panels == &["layers"]), "{docks:?} {:?}", layout.floating);+}++/// `ui.docking` lists where each gesture starts: tabs, drag bars and the iconic column's icons.+#[test]+fn ui_docking_reports_hit_rects() {+ let h = harness(app(), vec2(1280.0, 800.0));+ let v = crate::panel_docking::inspect(h.state(), &h.ctx);+ let rects = v["hitRects"].as_array().expect("hitRects");+ let rect_of = |hit: Value| {+ let entry = rects.iter().find(|r| r["hit"] == hit).unwrap_or_else(|| panic!("no {hit} in {rects:?}"));+ let r: Vec<f32> = serde_json::from_value(entry["rect"].clone()).unwrap();+ egui::Rect::from_min_size(egui::pos2(r[0], r[1]), vec2(r[2], r[3]))+ };+ let tab = rect_of(json!({"Tab": "pages"}));+ let bar = rect_of(json!({"DragBar": "properties"}));+ let icon = rect_of(json!({"Icon": "stroke"}));+ assert!(tab.width() > 20.0 && bar.width() >= 24.0 && icon.width() > 20.0, "{tab:?} {bar:?} {icon:?}");+ assert!((tab.center().y - bar.center().y).abs() < 1.0, "the bar is in the tab strip");+ assert!(icon.left() > 640.0, "the iconic column is at the end edge");+}++/// Clicking an icon in the iconic column opens its panel as a flyout on the canvas side; a+/// second click closes it.+#[test]+fn clicking_an_iconic_column_icon_opens_its_flyout() {+ let mut h = harness(app(), vec2(1280.0, 800.0));+ let icon = hits(&h).into_iter().find(|(hit, _)| *hit == craft_ui::docking::Hit::Icon("swatches".into())).expect("the Swatches icon").1;+ click(&mut h, icon.center(), PointerButton::Primary);+ assert_eq!(h.state().ui.docking_flyout.as_deref(), Some("swatches"));+ let tab = hits(&h).into_iter().find(|(hit, _)| *hit == craft_ui::docking::Hit::Tab("swatches".into())).expect("the flyout's tab").1;+ assert!(tab.right() <= icon.left() + 1.0, "the flyout is beside the column, on the canvas side: {tab:?} {icon:?}");+ assert!(showing(h.state(), "swatches"));+ click(&mut h, icon.center(), PointerButton::Primary);+ assert!(h.state().ui.docking_flyout.is_none());+}diff --git a/crates/ui-egui/src/panel_icons.rs b/crates/ui-egui/src/panel_icons.rsnew file mode 100644index 000000000..5093d5ae1--- /dev/null+++ b/crates/ui-egui/src/panel_icons.rs@@ -0,0 +1,168 @@+//! Panel icons as textures, for craft-ui's iconic columns, which draw an `ImageSource`.+//!+//! DesignCraft draws its icons in code ([`crate::icons::paint`]). Each panel's icon is painted+//! once, white, into a scratch egui context; the shapes are tessellated there and the triangles+//! filled on the CPU. The column tints the texture with its text colour.++use std::collections::HashMap;++use egui::{+ Color32, ColorImage, Context, Id, ImageSource, LayerId, Pos2, RawInput, Rect, TextureHandle, TextureId, TextureOptions,+ epaint::{ImageData, Mesh, Primitive},+ load::SizedTexture,+ pos2, vec2,+};++/// Icons per row of the scratch canvas.+const COLUMNS: usize = 8;++#[derive(Clone, Default)]+struct Cache {+ /// Side of each texture in pixels.+ px: usize,+ textures: Vec<(String, TextureHandle)>,+}++fn cache_id() -> Id {+ Id::new("designcraft-panel-icon-textures")+}++/// Every dock panel's icon at `size` points, keyed by panel id. Textures are made once per+/// pixel size and kept in the context.+pub(crate) fn panel_icons(ctx: &Context, size: f32) -> HashMap<String, ImageSource<'static>> {+ let scale = size * ctx.pixels_per_point();+ let px = if scale.is_finite() { scale.round().clamp(8.0, 128.0) as usize } else { 20 };+ let cached = ctx.data(|d| d.get_temp::<Cache>(cache_id())).filter(|cache| cache.px == px);+ let cache = cached.unwrap_or_else(|| {+ let panels: Vec<(&str, &str)> = crate::dock::DOCK_TABS.iter().chain(crate::dock::ICON_PANELS).map(|(id, _, icon)| (*id, *icon)).collect();+ let images = render(px, &panels);+ let textures = panels+ .iter()+ .zip(images)+ .map(|((id, _), image)| ((*id).to_string(), ctx.load_texture(format!("designcraft-panel-icon-{id}"), image, TextureOptions::LINEAR)))+ .collect();+ let cache = Cache { px, textures };+ ctx.data_mut(|d| d.insert_temp(cache_id(), cache.clone()));+ cache+ });+ cache+ .textures+ .iter()+ .map(|(id, texture)| (id.clone(), ImageSource::Texture(SizedTexture::new(texture.id(), vec2(px as f32, px as f32)))))+ .collect()+}++/// The icons of `panels` (id, icon name), white on transparent, `px` pixels square.+fn render(px: usize, panels: &[(&str, &str)]) -> Vec<ColorImage> {+ let cell = px as f32;+ let rows = panels.len().div_ceil(COLUMNS).max(1);+ let (width, height) = (COLUMNS * px, rows * px);+ let cell_rect = |i: usize| Rect::from_min_size(pos2((i % COLUMNS) as f32 * cell, (i / COLUMNS) as f32 * cell), vec2(cell, cell));+ let scratch = Context::default();+ scratch.set_fonts(crate::theme::font_definitions(&[], "en"));+ let input = RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(width as f32, height as f32))), ..Default::default() };+ let mut output = scratch.run_ui(input, |ui| {+ let painter = ui.ctx().layer_painter(LayerId::background());+ for (i, (_, icon)) in panels.iter().enumerate() {+ let rect = cell_rect(i);+ crate::icons::paint(&painter.with_clip_rect(rect), rect, icon, Color32::WHITE);+ }+ });+ let atlas =+ output.textures_delta.set.get(&TextureId::default()).and_then(|deltas| deltas.iter().find(|delta| delta.pos.is_none())).map(|delta| {+ match &delta.image {+ ImageData::Color(image) => image.clone(),+ }+ });+ let shapes = std::mem::take(&mut output.shapes);+ let primitives = scratch.tessellate(shapes, output.pixels_per_point);+ output.textures_delta.clear();+ let mut canvas = vec![[0.0f32; 4]; width * height];+ for primitive in &primitives {+ if let Primitive::Mesh(mesh) = &primitive.primitive {+ fill(&mut canvas, width, height, mesh, primitive.clip_rect, atlas.as_deref());+ }+ }+ (0..panels.len())+ .map(|i| {+ let origin = cell_rect(i).min;+ let (x0, y0) = (origin.x as usize, origin.y as usize);+ let mut pixels = Vec::with_capacity(px * px * 4);+ for y in y0..y0 + px {+ for x in x0..x0 + px {+ let [r, g, b, a] = canvas.get(y * width + x).copied().unwrap_or_default();+ pixels.extend([r, g, b, a].map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8));+ }+ }+ ColorImage::from_rgba_premultiplied([px, px], &pixels)+ })+ .collect()+}++/// Fill `mesh`'s triangles into a premultiplied RGBA canvas, sampling the font atlas for text.+/// Pixel centres inside a triangle take its interpolated colour; egui's feathered edges give+/// the anti-aliasing.+fn fill(canvas: &mut [[f32; 4]], width: usize, height: usize, mesh: &Mesh, clip: Rect, atlas: Option<&ColorImage>) {+ let bounds = clip.intersect(Rect::from_min_size(Pos2::ZERO, vec2(width as f32, height as f32)));+ if !bounds.is_positive() {+ return;+ }+ let texel = |u: f32, v: f32| -> [f32; 4] {+ if mesh.texture_id != TextureId::default() {+ return [1.0; 4];+ }+ let Some(atlas) = atlas else { return [1.0; 4] };+ let [w, h] = atlas.size;+ let x = ((u * w as f32) as usize).min(w.saturating_sub(1));+ let y = ((v * h as f32) as usize).min(h.saturating_sub(1));+ atlas.pixels.get(y * w + x).map_or([1.0; 4], |c| c.to_array().map(|v| f32::from(v) / 255.0))+ };+ let edge = |a: Pos2, b: Pos2, p: Pos2| (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x);+ for triangle in mesh.indices.as_chunks::<3>().0 {+ let vertex = |i: usize| triangle.get(i).and_then(|&index| mesh.vertices.get(index as usize));+ let (Some(a), Some(b), Some(c)) = (vertex(0), vertex(1), vertex(2)) else { continue };+ let area = edge(a.pos, b.pos, c.pos);+ if !area.is_finite() || area.abs() < 1e-6 {+ continue;+ }+ let min = a.pos.min(b.pos).min(c.pos).max(bounds.min);+ let max = a.pos.max(b.pos).max(c.pos).min(bounds.max);+ if !(min.x < max.x && min.y < max.y) {+ continue;+ }+ let colors = [a.color, b.color, c.color].map(|c| c.to_array().map(|v| f32::from(v) / 255.0));+ for y in min.y.floor() as usize..(max.y.ceil() as usize).min(height) {+ for x in min.x.floor() as usize..(max.x.ceil() as usize).min(width) {+ let p = pos2(x as f32 + 0.5, y as f32 + 0.5);+ let wa = edge(b.pos, c.pos, p) / area;+ let wb = edge(c.pos, a.pos, p) / area;+ let wc = 1.0 - wa - wb;+ if wa < 0.0 || wb < 0.0 || wc < 0.0 {+ continue;+ }+ let u = wa * a.uv.x + wb * b.uv.x + wc * c.uv.x;+ let v = wa * a.uv.y + wb * b.uv.y + wc * c.uv.y;+ let t = texel(u, v);+ let src: [f32; 4] = std::array::from_fn(|k| (wa * colors[0][k] + wb * colors[1][k] + wc * colors[2][k]) * t[k]);+ if let Some(dst) = canvas.get_mut(y * width + x) {+ let keep = 1.0 - src[3];+ *dst = std::array::from_fn(|k| src[k] + dst[k] * keep);+ }+ }+ }+ }+}++#[cfg(test)]+mod tests {+ #[test]+ fn panel_icons_are_painted_into_their_textures() {+ let images = super::render(20, &[("pages", "panel-pages"), ("character", "panel-character")]);+ assert_eq!(images.len(), 2);+ for image in &images {+ assert_eq!(image.size, [20, 20]);+ let inked = image.pixels.iter().filter(|p| p.a() > 128).count();+ assert!(inked > 10 && inked < 300, "{inked} inked pixels");+ }+ }+}diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rsindex 37a70c3d6..6e5f599b0 100644--- a/crates/ui-egui/src/prefs.rs+++ b/crates/ui-egui/src/prefs.rs@@ -1,11 +1,9 @@//! Compatibility recovery at the saved-preferences boundary. Command deserialization stays strict.-use std::collections::BTreeMap;-use craft_ui::docking::{Layout, Location};use serde_json::Value;-use crate::{SavedWorkspace, UiState, panel_docking};+use crate::{HiddenPanels, SavedWorkspace, UiState, panel_docking};/// Saved preferences, and whether reading them discarded anything.pub struct ReadPreferences {@@ -52,7 +50,12 @@ fn recover_docking(saved: &mut Value) -> bool {intact = false;}if let Some(hidden) = fields.get_mut("dockingHidden") {- if let Some(entries) = hidden.as_object_mut() {+ // `[[panel, location], …]`, or an object keyed by panel from older files.+ if let Some(entries) = hidden.as_array_mut() {+ let before = entries.len();+ entries.retain(|entry| serde_json::from_value::<(String, Location<String>)>(entry.clone()).is_ok());+ intact &= entries.len() == before;+ } else if let Some(entries) = hidden.as_object_mut() {let before = entries.len();entries.retain(|_, value| serde_json::from_value::<Location<String>>(value.clone()).is_ok());intact &= entries.len() == before;@@ -70,7 +73,7 @@ fn recover_docking(saved: &mut Value) -> bool {fn migrate(docking: &mut Option<Layout<String>>,floating: &mut Vec<(String, [f32; 2])>,- hidden: &BTreeMap<String, Location<String>>,+ hidden: &HiddenPanels,dock_expanded: bool,icon_groups: Option<&[Vec<String>]>,) {@@ -149,8 +152,8 @@ mod tests {fn unreadable_hidden_origin_does_not_discard_other_origins() {let original = populated();let mut saved = serde_json::to_value(&original).unwrap();- saved["dockingHidden"]["futurePanel"] = json!({"FutureLocation":{}});- saved["customWorkspaces"][0]["dockingHidden"]["futurePanel"] = json!(false);+ saved["dockingHidden"].as_array_mut().unwrap().push(json!(["futurePanel", {"FutureLocation":{}}]));+ saved["customWorkspaces"][0]["dockingHidden"].as_array_mut().unwrap().push(json!(false));let loaded = UiState::from_preferences_json(&serde_json::to_vec(&saved).unwrap()).unwrap();assert!(!original.docking_hidden.is_empty());assert_eq!(loaded.docking_hidden, original.docking_hidden);@@ -295,6 +298,32 @@ mod tests {assert_eq!(again.docking, app.ui.docking);}+ /// `dockingHidden` as an object keyed by panel (files before craft-ui's `Workspace::hidden`+ /// list) loads as the list, drops only its unreadable entries and saves as the list.+ #[test]+ fn hidden_panels_keyed_by_panel_load_as_the_workspace_list() {+ let place = json!({"floating": null, "anchor": "layers", "placement": {"Split": "Bottom"}, "size": {"Ratio": 0.5}, "stack": null});+ let saved = json!({+ "dockingHidden": {"color": place, "swatches": place, "futurePanel": {"FutureLocation": {}}},+ "customWorkspaces": [{"name": "Old", "dockingHidden": {"stroke": place}}],+ });+ let read = UiState::read_preferences(&serde_json::to_vec(&saved).unwrap()).unwrap();+ assert!(!read.intact, "the unreadable entry is reported so the file is kept");+ let ui = read.ui;+ assert_eq!(ui.docking_hidden.keys().collect::<Vec<_>>(), ["color", "swatches"]);+ assert_eq!(ui.custom_workspaces[0].docking_hidden.keys().collect::<Vec<_>>(), ["stroke"]);+ let written = serde_json::to_value(&ui).unwrap();+ assert_eq!(written["dockingHidden"][0][0], "color");+ let workspace: craft_ui::docking::Workspace<String> =+ serde_json::from_value(json!({"layout": {"root": null, "floating": []}, "hidden": written["dockingHidden"]})).unwrap();+ assert_eq!(workspace.hidden, ui.docking_hidden.0, "the same shape as craft-ui's Workspace::hidden");+ let mut app = DesignApp::new(designcraft_engine::Session::new(), Default::default());+ app.ui = ui;+ app.run("window.panel", json!({"panel": "color"})).unwrap();+ assert!(app.ui.docking.as_ref().unwrap().contains(&"color".to_string()));+ assert!(!app.ui.docking_hidden.contains_key("color"));+ }+#[test]fn unrelated_malformed_preferences_are_still_rejected() {assert!(UiState::from_preferences_json(br#"{"uiScale":"invalid","docking":false}"#).is_err());diff --git a/docs/control-protocol.md b/docs/control-protocol.mdindex 446460981..41dc02a01 100644--- a/docs/control-protocol.md+++ b/docs/control-protocol.md@@ -36,7 +36,7 @@ so only enable it while you use it. Transport: `apps/designcraft/src/control_ser| `engine.commands` | — | Every command: id, label, menu path, shortcut, params doc, enabled || `document.inspect` | — | Pages, spreads, items, stories (overset), styles, swatches, selection || `ui.inspect` | — | Tool, UI state, view (zoom/origin), canvas rect, panel layout (`docking`), perf |-| `ui.docking` | — | The panel layout in use and the focused panel (see Shared panel docking) |+| `ui.docking` | — | The panel layout in use, the focused panel and the docking hit rects (see Shared panel docking) || `ui.menu.list` / `ui.tool.list` | — | Menu tree / Tools panel groups || `ui.tool.select` | `{tool}` | Select a tool (`selection`, `type`, `rectangleFrame`, …) || `ui.pointer` | `{events:[{kind: down\|drag\|up\|move\|doubleclick, x, y, space?: "screen"\|"canvas", clicks?}], mods?}` | Drive the active tool through the same code path as the mouse; `clicks` on a `down` is the press count (3 = triple click); returns the selection, the tool and its cursor at the last event (e.g. `LoadedText`, `ThreadLink`, `Unthread`) |@@ -94,23 +94,47 @@ panels (or the workspace's named groups) in the iconic column and its floating whidden-panel positions kept. A `ui.json` the app cannot read in full is copied to`ui.unreadable.json` before it is saved again.-- `window.panel.move {panel, anchor, zone?, before?}` moves a panel into the target group.- `zone` is `tab` (default), `center`, `left`, `right`, `top`, or `bottom`; `before` reorders- tabs by panel ID. The destination must already be visible. Beside a panel in a dock column,- `top` and `bottom` add a group above or below its group and `left` and `right` add a column- on that side; in a floating window, `top` and `bottom` add a group and `left` and `right`- are errors.-- `window.panel.float {panel, x?, y?, width?, height?}` (and `window.floatPanel {panel, x?, y?}`)- detaches a panel.-- `window.panel.dock {panel, anchor?, zone?, before?}` (and `window.dockPanel {panel}`)- returns a panel to its previous dock placement when possible, or to the supplied- destination. For the float-only Tabs panel (`tabs`), which has its own window outside the- layout, float opens that window and dock closes it.+The `window.panel.*`, `window.workspace.*` and `ui.dock` commands are craft-ui's shared+docking commands (`DockCommand`), with the same ids and params in every craft app. `panel`,+`anchor`, `target` and `before` take a panel ID or its English name in any case; `onto` is+read as `anchor`.++- `window.panel.move {panel, anchor, zone?, before?, group?, placement?}` moves a panel into+ the target group. `zone` is `tab` (default), `center`, `left`, `right`, `top`, `bottom`,+ `above` or `below`; `before` reorders tabs by panel ID (`null` appends). Beside a panel in a+ dock column, `top` and `bottom` add a group above or below its group and `left` and `right`+ add a column on that side; in a floating window, `top` and `bottom` add a group and `left`+ and `right` are errors (craft-ui's `Placement::for_zone`). `group: true` moves the panel's+ whole tab group; `placement` is a serialized craft-ui `Placement` and takes precedence over+ `zone` and `before`.+- `window.panel.float {panel, x?, y?, width?, height?, group?, column?}` (and+ `window.floatPanel`) detaches a panel, its tab group (`group`) or its dock column+ (`column`). A panel floats at 400, 140 at its own size unless the params say otherwise; a+ panel already alone in a floating window moves or resizes.+- `window.panel.dock {panel, anchor?, zone?, before?, group?, column?, side?}` (and+ `window.dockPanel`) docks beside `anchor`, or in a new column of the dock at `side`+ (`Start` or `End`; a new dock when there is none). Without either, a panel that floated from+ the dock goes back to that place, and another floating panel joins the first dock group. For+ the float-only Tabs panel (`tabs`), which has its own window outside the layout, float opens+ that window and dock closes it.- `window.panel.activate {panel}` (and `window.panel {panel}`) reveals and selects a panel,- restoring its saved position when possible; a panel in an iconic column expands that- column. `window.panel.close {panel}` hides it.-- `window.panel.closeGroup {panel}` hides the panel and the panels tabbed with it (craft-ui's- `CloseGroup`); the result lists them in `closed`.+ restoring its saved position when possible; a panel in an iconic column opens as a flyout+ beside its icon. `window.panel.close {panel}` hides it.+- `window.panel.closeGroup {panel}` hides the panel and the panels tabbed with it, and+ `window.panel.closeOthers {panel}` hides the panels tabbed with it; the result lists them in+ `closed`.+- `window.panel.minimize {panel, minimized?}` minimizes the panel's group to its tab strip and+ `window.panel.iconic {panel, iconic?}` collapses its dock column to icons; without the flag+ they toggle.+- `window.workspace.new {name}`, `window.workspace.delete {name}` and `window.workspace.reset`+ (also `ui.dock.reset`) are `window.newWorkspace`, `window.deleteWorkspace` and+ `window.resetWorkspace`. `window.workspace {name}` switches workspaces as before.+- `ui.dock {action}` or `ui.dock {operation, …}` is the shape LightCraft, PDFCraft, CADCraft+ and SoundCraft use: `open`, `close`, `activate`, `float {rect}`, `moveFloating {rect}`,+ `move {target, zone?, before?}`, `setStackOpen {open}`, `resizeStack {height}` and+ `resizeSplit {path, size}`, with `rect` as `[x, y, width, height]`.+- `window.panel.window` (native panel windows) and `window.workspace.lock` are not available+ in DesignCraft and return an error.- `window.collapseToIcons` collapses every dock column to icons.Panel IDs are stable across themes. Invalid IDs, non-finite or invalid geometry, and@@ -130,6 +154,10 @@ closes the last explicitly opened panel; `dockExpanded:false` collapses every doto icons and `dockExpanded:true` expands the outer column. Activating a floating panel alsoraises its group. These operations change only UI layout.+Clicking an icon in an iconic column opens its group as a flyout beside the column, on the+canvas side; clicking the icon again closes it. With Auto-Collapse Iconic Panels on (the+default; a column bar's menu toggles it), Escape or a click outside the flyout closes it too.+`ui.docking` returns the panel layout in use; `ui.inspect` includes the same object as`docking`:@@ -142,9 +170,20 @@ raises its group. These operations change only UI layout.{"groups": [{"panels": ["stroke"], "active": 0}, …], "width": 260.0, "iconic": true,"iconic_width": 37.0}]}}}},"floating": []},- "customized": false, "focused": "canvas", "rightToLeft": false, "hidden": []}+ "customized": false, "focused": "canvas", "flyout": null, "autoCollapse": true,+ "rightToLeft": false, "hidden": [],+ "hitRects": [{"hit": {"Tab": "properties"}, "rect": [983.0, 0.0, 74.0, 27.0]},+ {"hit": {"DragBar": "properties"}, "rect": [1190.0, 0.0, 56.0, 27.0]},+ {"hit": {"Icon": "stroke"}, "rect": [1243.0, 14.0, 37.0, 30.0]}, …]}````layout` is craft-ui's serialized `Layout`; `customized` is false while the workspace'sdefault layout is in use; `focused` is the panel (or `canvas`) last clicked or selected, or-null; `hidden` lists closed panels that remember their place.+null; `flyout` is the panel whose iconic-column flyout is open; `autoCollapse` is the+Auto-Collapse Iconic Panels setting; `hidden` lists closed panels that remember their place.+`hitRects` lists where each docking gesture starts in the last frame, from craft-ui's+`DockArea::hit_rects`: `hit` is a serialized craft-ui `Hit` (`Tab`, `DragBar`, `Border`,+`Overflow`, `ColumnBar`, `Collapse`, `StackToggle`, `Title`, `Close`, `Icon`, `IconGrip`,+`Resize` with its edge, or `Divider`), naming groups, columns and windows by their first panel;+`rect` is `[x, y, width, height]` in points. Drag from a rect's centre with `ui.drag`, or click+it with `ui.click`, to script a gesture.