DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Docking trial: migrate ui.json, delete the classic dock
aiongg84e4032c114d
diff --git a/ROADMAP.md b/ROADMAP.mdindex 9bd0274ef..815ac6cc3 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -163,7 +163,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope- Pathfinder (Object › Pathfinder and a Pathfinder panel): Add, Subtract, Intersect, Exclude Overlap, Minus Back; curves stay curves (flo_curves); `object.pathfinder`.- Make / Release Compound Path (⌘8; nested paths become holes), Create Outlines (⇧⌘O; one path per text colour), Scissors tool (C) with `path.split`.- Transform Again / Individually / Sequence Again (⌥⌘3; a moved copy repeats like Step and Repeat), Clear Transformations; Layers: Merge, Delete Unused, Hide/Lock Others, Show/Unlock All; Break Link to Style (paragraph and character).-- Floating panels: tear a panel off the dock (its float button, or drag its header away) into a movable, resizable window; Dock puts it back; positions persist; `window.floatPanel` / `window.dockPanel`.+- Floating panels: drag a panel's tab, or a group by its drag bar, off the dock (or choose Float Panel) into a movable, resizable floating window; Dock Panel puts it back where it was; positions persist; `window.panel.float` / `window.panel.dock` (aliases `window.floatPanel` / `window.dockPanel`).- Place SVG (vector in PDF export via krilla-svg, resvg on screen, text in the bundled fonts), Photoshop (.psd/.psb composite in its colour mode — Bitmap, Grayscale, Duotone, Indexed, RGB, CMYK, Lab, 8/16-bit — with merged transparency; extra alpha and spot channels don't change the image), BMP, and Illustrator files saved with PDF compatibility (.ai). New `designcraft-images` crate (L2) for sniffing, sizes and decoding. EPS is still missing.- View › Display Performance: Fast (grey boxes, no effects, ⌥⇧⌘Z), Typical (72 ppi proxies, ⌥⌘Z), High Quality (⌥⌘H, our default — the renderer is fast enough).- OpenType menu (Character panel): discretionary ligatures, fractions, ordinal, swash, titling, contextual alternates, slashed zero, the four figure styles and stylistic sets 1–20; `type.openType`; mapped to IDML's OTF attributes.diff --git a/apps/designcraft/src/main.rs b/apps/designcraft/src/main.rsindex b56878176..3c5a79f20 100644--- a/apps/designcraft/src/main.rs+++ b/apps/designcraft/src/main.rs@@ -143,15 +143,47 @@ fn prefs_path() -> Option<std::path::PathBuf> {profile::config_dir().map(|b| b.join("ui.json"))}+/// Set when `ui.json` could not be read in full and no copy of it could be kept: the file is+/// then left as it is rather than overwritten.+static KEEP_UI_PREFS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);++/// Copy an unreadable (or partly unreadable) `ui.json` beside it, as `ui.unreadable.json` or the+/// first free `ui.unreadable-N.json`, before the next save replaces it. A newer DesignCraft may+/// have written it.+fn keep_unreadable_prefs(path: &std::path::Path, bytes: &[u8]) {+ use std::io::Write as _;+ for n in 1..100u32 {+ let name = if n == 1 { "ui.unreadable.json".to_string() } else { format!("ui.unreadable-{n}.json") };+ match std::fs::OpenOptions::new().write(true).create_new(true).open(path.with_file_name(name)) {+ Ok(mut file) => {+ if file.write_all(bytes).is_ok() {+ return;+ }+ break;+ }+ Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}+ Err(_) => break,+ }+ }+ KEEP_UI_PREFS.store(true, std::sync::atomic::Ordering::Relaxed);+}+fn load_prefs(app: &mut DesignApp) {if no_prefs() {return;}if let Some(p) = prefs_path()&& let Ok(bytes) = std::fs::read(&p)- && let Ok(ui) = designcraft_ui_egui::UiState::from_preferences_json(&bytes){- app.ui = ui;+ match designcraft_ui_egui::UiState::read_preferences(&bytes) {+ Ok(read) => {+ app.ui = read.ui;+ if !read.intact {+ keep_unreadable_prefs(&p, &bytes);+ }+ }+ Err(_) => keep_unreadable_prefs(&p, &bytes),+ }}// Engine preferences (Preferences dialog, favourites…) live beside the UI state.if let Some(p) = prefs_path().map(|p| p.with_file_name("prefs.json"))@@ -168,7 +200,9 @@ fn save_prefs(app: &DesignApp) {}if let Some(p) = prefs_path() {let _ = std::fs::create_dir_all(p.parent().unwrap_or(std::path::Path::new(".")));- if let Ok(bytes) = serde_json::to_vec_pretty(&app.ui) {+ if !KEEP_UI_PREFS.load(std::sync::atomic::Ordering::Relaxed)+ && let Ok(bytes) = serde_json::to_vec_pretty(&app.ui)+ {let _ = std::fs::write(&p, bytes);}if let Ok(bytes) = serde_json::to_vec_pretty(&app.session.prefs) {@@ -556,6 +590,22 @@ fn main() -> std::process::ExitCode {#[cfg(test)]mod tests {+ #[test]+ fn an_unreadable_ui_json_is_kept_beside_it() {+ let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();+ let dir = std::env::temp_dir().join(format!("designcraft-ui-prefs-{}-{stamp}", std::process::id()));+ std::fs::create_dir(&dir).unwrap();+ let path = dir.join("ui.json");+ super::keep_unreadable_prefs(&path, b"{\"docking\": {\"root\": {\"FutureLayout\": {}}}}");+ super::keep_unreadable_prefs(&path, b"not json");+ let first = std::fs::read(dir.join("ui.unreadable.json")).unwrap();+ let second = std::fs::read(dir.join("ui.unreadable-2.json")).unwrap();+ let _ = std::fs::remove_dir_all(&dir);+ assert!(first.starts_with(b"{\"docking\""), "the first copy is not replaced");+ assert_eq!(second, b"not json");+ assert!(!super::KEEP_UI_PREFS.load(std::sync::atomic::Ordering::Relaxed), "ui.json can be saved once a copy is kept");+ }+#[test]fn relink_open_dialog_lists_graphics() {let filters = super::open_filters("relink");diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rsindex 1f865a3dc..eea906ee6 100644--- a/crates/ui-egui/src/chrome.rs+++ b/crates/ui-egui/src/chrome.rs@@ -735,12 +735,9 @@ pub fn doc_tabs(app: &mut DesignApp, ui: &mut egui::Ui) {}}-/// Show the Preflight panel. `window.panel` toggles a panel that is already open, so it runs-/// only when Preflight isn't showing.+/// Show the Preflight panel.fn show_preflight(app: &mut DesignApp) {- if app.ui.open_panel.as_deref() != Some("preflight")- && let Err(e) = app.run("window.panel", json!({"panel": "preflight"}))- {+ if let Err(e) = app.run("window.panel", json!({"panel": "preflight"})) {app.status(e);}}diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rsindex a825e3502..0528cfdd6 100644--- a/crates/ui-egui/src/dock.rs+++ b/crates/ui-egui/src/dock.rs@@ -1,16 +1,16 @@-//! The right dock: an expanded panel group (Properties · Pages · Layers) and a collapsed icon-//! column whose panels open as flyouts beside the dock.+//! The panels: their ids, names, icons and contents, and the windows of the float-only panels.+//! `panel_docking` places the others in the docking layout.-use egui::{Color32, Sense, Stroke, vec2};+use egui::{Sense, vec2};use crate::theme::{Tokens, semibold};-use crate::{DesignApp, icons, panels};+use crate::{DesignApp, panels};-/// (id, label, icon) of the tabs in the expanded group.+/// (id, label, icon) of the Properties · Pages · Layers group of the default dock.pub const DOCK_TABS: &[(&str, &str, &str)] =&[("properties", "Properties", "panel-properties"), ("pages", "Pages", "panel-pages"), ("layers", "Layers", "panel-layers")];-/// Panels in the collapsed icon column.+/// (id, label, icon) of the other dock panels, which start in the iconic column.pub const ICON_PANELS: &[(&str, &str, &str)] = &[("stroke", "Stroke", "panel-stroke"),("swatches", "Swatches", "panel-swatches"),@@ -50,7 +50,7 @@ pub const ICON_PANELS: &[(&str, &str, &str)] = &[("dataMerge", "Data Merge", "panel-datamerge"),];-/// Panels that only float (they open from a menu, not from the icon column).+/// Panels that only float, outside the docking layout (they open from a menu).pub const FLOATING_PANELS: &[(&str, &str)] = &[("tabs", "Tabs")];/// The English name of panel `id`.@@ -58,197 +58,6 @@ pub fn panel_label(id: &str) -> &'static str {DOCK_TABS.iter().chain(ICON_PANELS).map(|p| (p.0, p.1)).chain(FLOATING_PANELS.iter().copied()).find(|p| p.0 == id).map_or("Panel", |p| p.1)}-/// The classic dock, replaced by the docking layout (`panel_docking::show`) and no longer drawn.-pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) {- let t = Tokens::get(ui.ctx());- // Expanded panel stack (outermost, 253 pt) — declared first so it sits at the far right.- if app.ui.dock_expanded {- egui::Panel::right("dock").default_size(253.0).size_range(220.0..=420.0).resizable(true).frame(egui::Frame::NONE.fill(t.panel)).show(- ui,- |ui| {- dock_header(ui, &t, "»");- // Tab strip (27 pt).- let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), 27.0), Sense::hover());- ui.painter().rect_filled(strip, 0.0, t.tab_strip);- let mut x = strip.min.x;- for (id, label, _) in DOCK_TABS {- let active = app.ui.dock_tab == *id;- let g = crate::rtl::plain(- ui.ctx(),- crate::i18n::tr(&app.ui.language, label),- semibold(11.5),- if active { t.text_strong } else { t.text_dim },- );- let w = g.size().x + 26.0;- let r = egui::Rect::from_min_size(egui::pos2(x, strip.min.y), vec2(w, 27.0));- if active {- ui.painter().rect_filled(r, 0.0, t.panel);- }- ui.painter().galley(egui::pos2(r.min.x + 13.0, r.center().y - g.size().y / 2.0), g, Color32::WHITE);- ui.painter().line_segment([r.right_top(), r.right_bottom()], Stroke::new(1.0, t.border));- let response = craft_ui::tabs::Tab::new(ui.id().with(("docktab", *id)), label, active).sense(Sense::click_and_drag()).show_at(- ui,- r,- |_, _| {},- );- if response.clicked() {- app.ui.dock_tab = id.to_string();- }- crate::panel_docking::legacy_tab(app, ui, id, &response);- x += w;- }- let menu_r = egui::Rect::from_min_size(egui::pos2(strip.max.x - 24.0, strip.min.y + 4.0), vec2(18.0, 18.0));- let menu = ui.interact(menu_r, ui.id().with("dock-menu"), Sense::click());- if menu.hovered() {- ui.painter().rect_filled(menu_r, 3.0, t.hover);- }- icons::paint(ui.painter(), menu_r, "menu", t.icon);- let tab = app.ui.dock_tab.clone();- egui::Popup::menu(&menu)- .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)- .show(|ui| crate::panel_docking::three_line_menu(app, ui, &tab));- egui::Frame::NONE.inner_margin(egui::Margin { left: 10, right: 10, top: 4, bottom: 6 }).show(ui, |ui| {- // The Pages panel scrolls its parts itself and keeps its footer at the bottom.- if app.ui.dock_tab == "pages" {- panels::pages::show(app, ui);- return;- }- egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| match app.ui.dock_tab.as_str() {- "layers" => panels::layers::show(app, ui),- _ => panels::properties::show(app, ui),- });- });- },- );- }- // Collapsed icon strip (37 pt) to the left of the panel stack; a workspace's iconic groups- // (Essentials Classic) show their names.- let groups = app.ui.icon_groups.clone();- egui::Panel::right("icon_column").exact_size(icon_column_width(app)).resizable(false).frame(egui::Frame::NONE.fill(t.panel)).show(ui, |ui| {- dock_header(ui, &t, "«");- ui.add_space(4.0);- match &groups {- Some(groups) => {- for (i, group) in groups.iter().enumerate() {- if i > 0 {- let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 7.0), Sense::hover());- ui.painter().line_segment([r.left_center(), r.right_center()], Stroke::new(1.0, t.border));- }- for (id, label, icon) in group.iter().filter_map(|id| panel_entry(id)) {- let on = app.ui.open_panel.as_deref() == Some(id) || app.ui.floating.iter().any(|(p, _)| p == id);- let (r, response) = ui.allocate_exact_size(vec2(ui.available_width(), 26.0), Sense::click_and_drag());- if on {- ui.painter().rect_filled(r.shrink2(vec2(3.0, 1.0)), 3.0, t.tool_active);- } else if response.hovered() {- ui.painter().rect_filled(r.shrink2(vec2(3.0, 1.0)), 3.0, t.hover);- }- icons::paint(ui.painter(), egui::Rect::from_min_size(r.min + vec2(8.0, 4.0), vec2(18.0, 18.0)), icon, t.icon);- crate::rtl::paint(- ui.painter(),- r.left_center() + vec2(32.0, 0.0),- egui::Align2::LEFT_CENTER,- crate::i18n::tr(&app.ui.language, label),- semibold(11.5),- t.text,- );- icon_clicked(app, ui, id, &response);- }- }- }- None => {- ui.vertical_centered(|ui| {- for (id, label, icon) in ICON_PANELS {- let on = app.ui.open_panel.as_deref() == Some(*id) || app.ui.floating.iter().any(|(p, _)| p == id);- let response = icons::button(ui, icon, 28.0, on, crate::i18n::tr(&app.ui.language, label)).interact(Sense::click_and_drag());- icon_clicked(app, ui, id, &response);- ui.add_space(1.0);- }- });- }- }- });-}--/// Width of the icon column: icons only, or icons with names for a workspace's groups.-fn icon_column_width(app: &DesignApp) -> f32 {- if app.ui.icon_groups.is_some() { 150.0 } else { 37.0 }-}--/// (id, label, icon) of any dock panel.-fn panel_entry(id: &str) -> Option<(&'static str, &'static str, &'static str)> {- DOCK_TABS.iter().chain(ICON_PANELS).find(|p| p.0 == id).copied()-}--/// A click on a panel's icon: raise it when it floats, else open or close its flyout.-fn icon_clicked(app: &mut DesignApp, ui: &mut egui::Ui, id: &str, response: &egui::Response) {- if response.clicked() {- if app.ui.floating.iter().any(|(p, _)| p == id) {- ui.ctx().move_to_top(egui::LayerId::new(egui::Order::Middle, egui::Id::new(("floating_panel", id))));- } else {- let open = app.ui.open_panel.as_deref() == Some(id);- app.ui.open_panel = if open { None } else { Some(id.to_string()) };- }- }- crate::panel_docking::legacy_tab(app, ui, id, response);-}--/// 11 pt dock header strip with a collapse chevron.-fn dock_header(ui: &mut egui::Ui, t: &Tokens, chevron: &str) {- let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 11.0), Sense::hover());- ui.painter().rect_filled(r, 0.0, t.tab_strip);- ui.painter().text(egui::pos2(r.max.x - 8.0, r.center().y), egui::Align2::RIGHT_CENTER, chevron, egui::FontId::proportional(9.0), t.text_dim);- ui.painter().line_segment([r.left_bottom(), r.right_bottom()], Stroke::new(1.0, t.border));-}--/// A panel opened from the icon column, shown as a floating flyout next to the dock.-pub fn flyout(app: &mut DesignApp, ctx: &egui::Context) {- if app.ui.docking.is_some() {- return;- }- let Some(id) = app.ui.open_panel.clone() else { return };- let t = Tokens::get(ctx);- let label = crate::i18n::tr(&app.ui.language, panel_label(&id)).to_owned();- let screen = ctx.content_rect();- let dock_w = if app.ui.dock_expanded { ctx.memory(|m| m.area_rect(egui::Id::new("dock")).map(|r| r.width())).unwrap_or(280.0) } else { 0.0 };- let pos = egui::pos2(screen.max.x - icon_column_width(app) - dock_w - 262.0, 120.0);- let mut open = true;- egui::Area::new(egui::Id::new("panel_flyout")).order(egui::Order::Foreground).fixed_pos(pos).show(ctx, |ui| {- egui::Frame::popup(ui.style()).fill(t.panel).inner_margin(egui::Margin::same(0)).show(ui, |ui| {- ui.set_width(256.0);- // A previous shorter flyout must not constrain the next panel's scroll viewport.- ui.set_max_height((screen.max.y - pos.y - 12.0).max(80.0));- let (strip, _) = ui.allocate_exact_size(vec2(256.0, 26.0), Sense::hover());- ui.painter().rect_filled(strip, 0.0, t.panel_darker);- crate::rtl::paint(ui.painter(), strip.min + vec2(10.0, 13.0), egui::Align2::LEFT_CENTER, &label, semibold(12.0), t.text_strong);- let close = egui::Rect::from_min_size(egui::pos2(strip.max.x - 22.0, strip.min.y + 4.0), vec2(18.0, 18.0));- if ui.interact(close, ui.id().with("flyclose"), Sense::click()).clicked() {- open = false;- }- ui.painter().text(close.center(), egui::Align2::CENTER_CENTER, "×", egui::FontId::proportional(15.0), t.text_dim);- // Float: the button beside the close box, or drag the header away from the dock.- let float_r = egui::Rect::from_min_size(egui::pos2(strip.max.x - 44.0, strip.min.y + 4.0), vec2(18.0, 18.0));- let fr = ui.interact(float_r, ui.id().with("flyfloat"), Sense::click()).on_hover_ui(|ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Float panel"));- });- float_glyph(ui.painter(), float_r, t.text_dim);- let head = egui::Rect::from_min_max(strip.min, egui::pos2(float_r.min.x - 2.0, strip.max.y));- let hr = ui.interact(head, ui.id().with("flyhead"), Sense::drag());- let torn = hr.drag_stopped() && hr.total_drag_delta().is_some_and(|d| d.length() > 24.0);- if fr.clicked() || torn {- let at = if torn { ui.ctx().pointer_latest_pos().unwrap_or(pos) - vec2(20.0, 10.0) } else { pos - vec2(30.0, -30.0) };- float_panel(app, &id, at);- return;- }- egui::Frame::NONE.inner_margin(egui::Margin::same(10)).show(ui, |ui| {- scrolled_body(app, ui, &id, screen.height() - 220.0);- });- });- });- if !open {- app.ui.open_panel = None;- }-}-/// A panel's contents at most `max_h` tall, scrolling past that. The Pages panel scrolls its/// parts itself and keeps its footer at the bottom, so it gets the height instead.fn scrolled_body(app: &mut DesignApp, ui: &mut egui::Ui, id: &str, max_h: f32) {@@ -315,41 +124,16 @@ pub(crate) fn float_only(id: &str) -> bool {FLOATING_PANELS.iter().any(|p| p.0 == id)}-/// Tear panel `id` off the dock into a floating window at `at`.-pub fn float_panel(app: &mut DesignApp, id: &str, at: egui::Pos2) {- if float_only(id) {- app.ui.floating.retain(|(p, _)| p != id);- app.ui.floating.push((id.to_string(), [at.x, at.y]));- return;- }- if let Some(Err(error)) = crate::panel_docking::command(app, "window.panel.float", &serde_json::json!({"panel":id,"x":at.x,"y":at.y})) {- app.status(error);- }-}--/// Put a floating panel back in the dock's icon column.-pub fn dock_panel(app: &mut DesignApp, id: &str) {- if !float_only(id) {- if let Some(Err(error)) = crate::panel_docking::command(app, "window.panel.dock", &serde_json::json!({"panel":id})) {- app.status(error);- }- return;- }- app.ui.floating.retain(|(p, _)| p != id);-}--/// Floating panels: movable, resizable windows; "Dock" returns one to the icon column.-pub fn floating(app: &mut DesignApp, ctx: &egui::Context) {- // The docking layout draws its own floating groups; float-only panels are drawn here.+/// The float-only panels' windows (the Tabs panel). The docking layout draws the other+/// floating panels.+pub fn float_only_windows(app: &mut DesignApp, ctx: &egui::Context) {let t = Tokens::get(ctx);for (id, at) in app.ui.floating.clone() {if !float_only(&id) {continue;}let label = crate::i18n::tr(&app.ui.language, panel_label(&id)).to_owned();- let docks = !float_only(&id);let mut open = true;- let mut dock = false;let mut w = egui::Window::new(label.clone()).id(egui::Id::new(("floating_panel", &id))).title_bar(false)@@ -364,7 +148,7 @@ pub fn floating(app: &mut DesignApp, ctx: &egui::Context) {w = w.current_pos(pos).min_width(width).max_width(width);}let r = w.show(ctx, |ui| {- // Header strip (drag it to move the panel): name, Dock, close.+ // Header strip (drag it to move the panel): name and close.let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width().max(200.0), 24.0), Sense::hover());ui.painter().rect_filled(strip, 0.0, t.panel_darker);crate::rtl::paint(ui.painter(), strip.min + vec2(10.0, 12.0), egui::Align2::LEFT_CENTER, &label, semibold(12.0), t.text_strong);@@ -379,20 +163,6 @@ pub fn floating(app: &mut DesignApp, ctx: &egui::Context) {open = false;}ui.painter().text(close.center(), egui::Align2::CENTER_CENTER, "×", egui::FontId::proportional(15.0), t.text_dim);- let dock_r = egui::Rect::from_min_size(egui::pos2(strip.max.x - 44.0, strip.min.y + 3.0), vec2(18.0, 18.0));- if docks- && ui- .interact(dock_r, ui.id().with("fdock"), Sense::click())- .on_hover_ui(|ui| {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Dock panel"));- })- .clicked()- {- dock = true;- }- if docks {- dock_glyph(ui.painter(), dock_r, t.text_dim);- }egui::Frame::NONE.inner_margin(egui::Margin::same(10)).show(ui, |ui| {scrolled_body(app, ui, &id, ctx.content_rect().height() - 160.0);});@@ -403,29 +173,16 @@ pub fn floating(app: &mut DesignApp, ctx: &egui::Context) {{f.1 = [r.response.rect.min.x, r.response.rect.min.y];}- if !open || dock {- dock_panel(app, &id);+ if !open {+ app.ui.floating.retain(|(p, _)| *p != id);}}}-/// Two overlapping boxes: "float this panel".-fn float_glyph(p: &egui::Painter, r: egui::Rect, c: Color32) {- let s = Stroke::new(1.0, c);- p.rect_stroke(egui::Rect::from_min_size(r.min + vec2(3.5, 6.5), vec2(9.0, 8.0)), 0.0, s, egui::StrokeKind::Middle);- p.rect_stroke(egui::Rect::from_min_size(r.min + vec2(6.5, 3.5), vec2(9.0, 8.0)), 0.0, s, egui::StrokeKind::Middle);-}--/// A box with a bar on its right: "back into the dock".-fn dock_glyph(p: &egui::Painter, r: egui::Rect, c: Color32) {- let b = egui::Rect::from_min_size(r.min + vec2(3.5, 4.5), vec2(11.0, 9.0));- p.rect_stroke(b, 0.0, Stroke::new(1.0, c), egui::StrokeKind::Middle);- p.rect_filled(egui::Rect::from_min_max(egui::pos2(b.max.x - 3.5, b.min.y), b.max), 0.0, c);-}-#[cfg(test)]mod visual_regressions {use super::*;+ use egui::Color32;fn scaled_input(size: egui::Vec2, scale: f32) -> egui::RawInput {let mut input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)), ..Default::default() };@@ -441,9 +198,7 @@ mod visual_regressions {for brightness in crate::theme::Brightness::ALL {for width in [800.0, 1280.0] {for scale in [1.0, 1.5, 2.0] {- let mut app = DesignApp::new(designcraft_engine::Session::new(), Default::default());- app.ui.dock_expanded = true;- app.ui.dock_tab = "properties".into();+ let app = DesignApp::new(designcraft_engine::Session::new(), Default::default());let mut ready = false;let mut harness =egui_kittest::Harness::builder().with_size(vec2(width, 640.0)).with_pixels_per_point(scale).wgpu().build_ui_state(@@ -454,7 +209,7 @@ mod visual_regressions {ready = true;return;}- show(app, ui);+ crate::panel_docking::show(app, ui);},app,);@@ -462,10 +217,11 @@ mod visual_regressions {harness.run_steps(4);let stem = format!("designcraft-dock-{}-{width}-{scale}x", brightness.id());harness.render().unwrap().save(directory.join(format!("{stem}.png"))).unwrap();- let panel = egui::containers::panel::PanelState::load(&harness.ctx, egui::Id::new("dock")).unwrap().outer_rect;+ let tab = egui::Id::new("designcraft-panel-docking").with(("tab", &"properties".to_string()));+ let tab = harness.ctx.read_response(tab).unwrap().rect;let region = serde_json::json!({"screen": [width, 640.0], "scale": scale,- "regions": {"dock-tabs": [panel.left(), panel.top(), panel.width(), 45.0]}+ "regions": {"dock-tabs": [tab.left(), tab.top(), (width - tab.left()), tab.height()]}});std::fs::write(directory.join(format!("{stem}.json")), serde_json::to_vec_pretty(®ion).unwrap()).unwrap();}@@ -491,9 +247,9 @@ mod visual_regressions {let tokens = Tokens::for_brightness(brightness);crate::theme::apply(&ctx, &tokens);let mut app = DesignApp::new(designcraft_engine::Session::new(), Default::default());- app.ui.dock_expanded = true;- app.ui.dock_tab = "properties".into();- let mut output = ctx.run_ui(scaled_input(vec2(width, 640.0), scale), |ui| show(&mut app, ui));+ let mut output = ctx.run_ui(scaled_input(vec2(width, 640.0), scale), |ui| crate::panel_docking::show(&mut app, ui));+ output.textures_delta.clear();+ let mut output = ctx.run_ui(scaled_input(vec2(width, 640.0), scale), |ui| crate::panel_docking::show(&mut app, ui));output.textures_delta.clear();assert_eq!(ctx.content_rect().size(), vec2(width, 640.0));assert_eq!(ctx.pixels_per_point(), scale);diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 0a76e123c..370388317 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -43,6 +43,7 @@ use serde::{Deserialize, Serialize};use serde_json::{Value, json};pub use control::{ControlRequest, ControlResponse};+pub use prefs::ReadPreferences;pub type ReadFn = Box<dyn Fn(&str) -> Result<Vec<u8>, String>>;pub type WriteFn = Box<dyn FnMut(&str, &[u8]) -> Result<(), String>>;@@ -116,7 +117,7 @@ pub struct SavedWorkspace {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>>,- /// The workspace's own icon column (see [`UiState::icon_groups`]).+ /// 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>>>,/// Saved with New Workspace › Capture › Panel Locations off: choosing the workspace leaves the@@ -253,11 +254,14 @@ pub struct UiState {pub shortcuts: std::collections::BTreeMap<String, String>,pub control_bar: bool,pub tools_double_column: bool,- /// Expanded right-dock panel group tab.+ /// The front tab of the default layout's Properties · Pages · Layers group. `dock_tab`,+ /// `open_panel`, `floating`, `dock_expanded` and `icon_groups` describe a workspace's+ /// default layout (`panel_docking::default_layout`).pub dock_tab: String,- /// Panel opened from the collapsed icon column (flyout).+ /// The panel it opens below that group (Printing and Proofing: Swatches).pub open_panel: Option<String>,- /// Panels torn off the dock into their own floating windows: (panel id, top-left position).+ /// Its floating panels, and the float-only panels' windows (Type › Tabs): (panel id,+ /// top-left position). A customized layout holds its own floating panels.pub floating: Vec<(String, [f32; 2])>,/// The panel layout once the user customizes it; `None` is the workspace's default layout/// (`panel_docking::default_layout`).@@ -274,12 +278,13 @@ pub struct UiState {/// One-frame reveal request; z-order is never persisted.#[serde(skip)]pub docking_raise: Option<String>,- /// Last explicitly revealed customized panel, for the legacy closePanel control.+ /// The panel last revealed explicitly, which `ui.set closePanel` closes.#[serde(skip)]pub docking_opened: Option<String>,+ /// 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 icon- /// column instead of every panel; `None` is the full icon column.+ /// A workspace's iconic panel groups (Essentials Classic), shown with their names in the+ /// iconic column instead of every panel; `None` is one icon per panel.#[serde(default, skip_serializing_if = "Option::is_none")]pub icon_groups: Option<Vec<Vec<String>>>,pub units: Unit,@@ -1563,7 +1568,7 @@ impl DesignApp {let t = theme::Tokens::get(&ctx);let presenting = self.ui.screen_mode == ScreenMode::Presentation;if presenting || self.ui.hidden_panels != 0 {- panel_docking::cancel_gesture(self, &ctx);+ panel_docking::cancel_gesture(&ctx);}canvas::begin_frame(&ctx);let dbg = std::env::var_os("DESIGNCRAFT_DEBUG_LAYOUT").is_some();@@ -1631,7 +1636,7 @@ impl DesignApp {}// Tab, Shift+Tab and Presentation hide the floating panels with the docked ones.if !presenting && self.ui.hidden_panels == 0 {- dock::floating(self, &ctx);+ dock::float_only_windows(self, &ctx);}story_editor::show(self, &ctx);dialogs::show(self, &ctx);diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rsindex 3558be93a..9e4ceda19 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 movable window"),+ ("window.floatPanel", "Float Panel", None, "{panel, x?, y?} — the panel in its own floating window (window.panel.float)"),("window.panel.layout","Change Panel Layout",@@ -255,7 +255,7 @@ pub const UI_COMMANDS: &[(&str, &str, Option<&str>, &str)] = &[("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.collapseToIcons", "Collapse to Icons", None, "{} — the panel dock shrinks to its column of icons"),- ("window.dockPanel", "Dock Panel", None, "{panel} — back into the dock's icon column"),+ ("window.dockPanel", "Dock Panel", None, "{panel} — back to its place in the dock (window.panel.dock)"),("window.controlBar", "Control", Some("Cmd+Alt+6"), "{}"),// Object › Fitting with InDesign's shortcuts (one `object.fit` mode each).("fit.fillFrameProportionally", "Fill Frame Proportionally", Some("Cmd+Alt+Shift+C"), "{} — object.fit {mode: fillProportionally}"),@@ -925,7 +925,7 @@ pub const MENUS: &[(&str, &[&str])] = &[pub const WORKSPACES: &[&str] =&["Advanced", "Book", "Digital Publishing", "Essentials", "Essentials Classic", "Interactive for PDF", "Printing and Proofing", "Typography"];-/// Essentials Classic's icon column: InDesign's iconic panel groups, top to bottom.+/// Essentials Classic's iconic column: InDesign's iconic panel groups, top to bottom.pub const CLASSIC_GROUPS: &[&[&str]] = &[&["pages", "layers", "links"],&["stroke", "color"],@@ -955,10 +955,10 @@ pub fn ui_label(id: &str) -> Option<(&'static str, Option<&'static str>)> {/// Type › Tabs: float the Tabs panel (placed above the selected text frame) or close it.fn toggle_tabs_panel(app: &mut DesignApp) {if app.ui.floating.iter().any(|(p, _)| p == "tabs") {- crate::dock::dock_panel(app, "tabs");+ app.ui.floating.retain(|(p, _)| p != "tabs");} else {let at = app.canvas_rect.map_or(egui::pos2(300.0, 140.0), |r| r.min + egui::vec2(80.0, 60.0));- crate::dock::float_panel(app, "tabs", at);+ app.ui.floating.push(("tabs".into(), [at.x, at.y]));app.ui.tabs_panel.snap_request = 2;}}@@ -1342,10 +1342,6 @@ fn run_ui_inner(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value};return Some(r);}- "app.tablePanel" => {- app.ui.open_panel = if app.ui.open_panel.as_deref() == Some("table") { None } else { Some("table".into()) };- Ok(Value::Null)- }"app.tabsPanel" => {toggle_tabs_panel(app);Ok(Value::Null)@@ -1647,19 +1643,13 @@ fn run_ui_inner(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Valuerun_ui(app, "window.panel", &json!({"panel": panel})).unwrap_or(Ok(Value::Null))}"app.insertCurrentPageNumber" => app.run("text.insert", json!({"text": "\u{e000}", "raw": true})),+ // `panel_docking::command` takes the dock panels (and the Window › Styles group) first."window.panel" => {- let panel = p.get("panel").and_then(Value::as_str).unwrap_or("properties").to_string();- // A panel in the workspace's icon groups opens from there (Essentials Classic's Pages).- let iconic = app.ui.icon_groups.as_ref().is_some_and(|g| g.iter().flatten().any(|p| *p == panel));- if panel == "tabs" {- toggle_tabs_panel(app);- } else if !iconic && crate::dock::DOCK_TABS.iter().any(|(id, _, _)| *id == panel) {- app.ui.dock_tab = panel;- app.ui.dock_expanded = true;- app.ui.open_panel = None;- } else if !app.ui.floating.iter().any(|(p, _)| *p == panel) {- app.ui.open_panel = if app.ui.open_panel.as_deref() == Some(panel.as_str()) { None } else { Some(panel) };+ let panel = p.get("panel").and_then(Value::as_str).unwrap_or("properties");+ if panel != "tabs" {+ return crate::panel_docking::command(app, "window.panel.activate", &json!({"panel": panel}));}+ toggle_tabs_panel(app);Ok(Value::Null)}"fit.fillFrameProportionally" | "fit.contentProportionally" | "fit.frameToContent" | "fit.contentToFrame" | "fit.centerContent" => {@@ -1737,22 +1727,6 @@ fn run_ui_inner(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Valueapp.ui.ui_scale = v.clamp(0.5, 3.0);Ok(json!({"scale": app.ui.ui_scale}))}- "window.floatPanel" | "window.dockPanel" => {- let panel = p.get("panel").and_then(Value::as_str).unwrap_or("");- if !crate::dock::ICON_PANELS.iter().any(|(id, _, _)| *id == panel) && !crate::dock::FLOATING_PANELS.iter().any(|(id, _)| *id == panel) {- return Some(Err(format!("{id}: unknown panel `{panel}`")));- }- if id == "window.floatPanel" {- let at = egui::pos2(- p.get("x").and_then(Value::as_f64).unwrap_or(400.0) as f32,- p.get("y").and_then(Value::as_f64).unwrap_or(160.0) as f32,- );- crate::dock::float_panel(app, panel, at);- } else {- crate::dock::dock_panel(app, panel);- }- Ok(json!({"floating": app.ui.floating.iter().map(|(p, _)| p.clone()).collect::<Vec<_>>()}))- }"window.controlBar" => flag(&mut app.ui.control_bar),"view.flattenerPreview" => flag(&mut app.ui.flattener_preview),"view.tagMarkers" => {@@ -1904,7 +1878,7 @@ fn run_ui_inner(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Valueapp.ui.docking = None;app.ui.docking_hidden.clear();app.ui.control_bar = matches!(name, "Advanced" | "Typography" | "Printing and Proofing" | "Book" | "Essentials Classic");- // Essentials Classic: the Control panel and an icon column of grouped panels, no+ // Essentials Classic: the Control panel and an iconic column of grouped panels, no// Properties stack.let groups = match name {"Essentials Classic" => Some(CLASSIC_GROUPS),@@ -4730,13 +4704,21 @@ mod tests {let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());let r = run_ui(&mut app, "window.floatPanel", &json!({"panel": "swatches", "x": 50, "y": 60})).unwrap().unwrap();assert_eq!(r["floating"], json!(["swatches"]));- assert_eq!(app.ui.floating[0].1, [50.0, 60.0]);- // Showing a floating panel doesn't also open its flyout.+ let window = &app.ui.docking.as_ref().unwrap().floating[0];+ assert_eq!([window.rect[0], window.rect[1]], [50.0, 60.0]);+ // Showing a floating panel leaves it where it is.run_ui(&mut app, "window.panel", &json!({"panel": "swatches"})).unwrap().unwrap();assert_eq!(app.ui.open_panel, None);- run_ui(&mut app, "window.dockPanel", &json!({"panel": "swatches"})).unwrap().unwrap();- assert!(app.ui.floating.is_empty());+ let r = run_ui(&mut app, "window.dockPanel", &json!({"panel": "swatches"})).unwrap().unwrap();+ assert_eq!(r["floating"], json!([]));+ assert!(app.ui.docking.as_ref().unwrap().floating.is_empty());assert!(run_ui(&mut app, "window.floatPanel", &json!({"panel": "nope"})).unwrap().is_err());+ // Float-only panels (Type › Tabs) have their own windows outside the layout.+ let r = run_ui(&mut app, "window.floatPanel", &json!({"panel": "tabs", "x": 10, "y": 20})).unwrap().unwrap();+ assert_eq!(r["floating"], json!(["tabs"]));+ assert_eq!(app.ui.floating, [("tabs".to_string(), [10.0, 20.0])]);+ run_ui(&mut app, "window.dockPanel", &json!({"panel": "tabs"})).unwrap().unwrap();+ assert!(app.ui.floating.is_empty());}/// One frame as the desktop app runs it: queued synthetic input, then the native menu itemdiff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rsindex 393c977e5..c0e0cfd5f 100644--- a/crates/ui-egui/src/panel_docking.rs+++ b/crates/ui-egui/src/panel_docking.rs@@ -9,36 +9,10 @@ use serde_json::{Value, json};use crate::DesignApp;-#[derive(Clone, Default)]-struct LegacyDrag {- layout: Option<Layout<String>>,- open_panel: Option<String>,- floating: Vec<(String, [f32; 2])>,- generation: u64,-}--pub(crate) fn cancel_gesture(app: &mut DesignApp, ctx: &egui::Context) {- cancel_legacy_drag(app, ctx);+pub(crate) fn cancel_gesture(ctx: &egui::Context) {craft_ui::docking::cancel_drag::<String>(ctx, egui::Id::new("designcraft-panel-docking"));}-fn cancel_legacy_drag(app: &mut DesignApp, ctx: &egui::Context) -> bool {- let key = egui::Id::new("designcraft-panel-docking").with("legacy-origin");- let previous = ctx.data_mut(|data| data.remove_temp::<LegacyDrag>(key));- if let Some(previous) = previous {- craft_ui::docking::cancel_drag::<String>(ctx, egui::Id::new("designcraft-panel-docking"));- if previous.generation != app.ui.docking_generation {- return false;- }- app.ui.open_panel = previous.open_panel;- app.ui.floating = previous.floating;- app.ui.docking = previous.layout;- true- } else {- false- }-}-fn normalize(raw: &str) -> Option<&'static str> {crate::dock::DOCK_TABS.iter()@@ -72,76 +46,174 @@ pub(crate) fn valid(layout: &Layout<String>) -> bool {&& Layout { root: layout.root.clone(), floating: Vec::new() }.contains(&CANVAS.to_string())}+/// Panels already given a place, so each appears once.+#[derive(Default)]+struct Placed(Vec<String>);++impl Placed {+ /// The registered id of `raw` if no other place holds it yet.+ fn take(&mut self, raw: &str) -> Option<String> {+ let id = normalize(raw)?;+ if self.0.iter().any(|p| p == id) {+ return None;+ }+ self.0.push(id.to_string());+ Some(id.to_string())+ }++ /// A group of the unplaced registered panels of `panels`, with the one at `active` in front+ /// when it is among them.+ fn group(&mut self, panels: &[String], active: usize) -> Option<Group<String>> {+ let front = panels.get(active).and_then(|p| normalize(p));+ let kept: Vec<String> = panels.iter().filter_map(|p| self.take(p)).collect();+ let active = front.and_then(|f| kept.iter().position(|p| p == f)).unwrap_or(0);+ (!kept.is_empty()).then(|| Group::new(kept, active))+ }+}++/// A workspace's iconic column: its named `icon_groups` (Essentials Classic, Typography), or+/// one group per panel not placed yet. Window › Styles opens the style panels as a floating+/// group, so they start outside it.+fn icon_column(icon_groups: Option<&[Vec<String>]>, placed: &mut Placed) -> Option<Column<String>> {+ let (groups, width): (Vec<Group<String>>, f32) = match icon_groups {+ Some(groups) => (groups.iter().filter_map(|g| placed.group(g, 0)).collect(), NAMED_ICON_WIDTH),+ None => (+ crate::dock::DOCK_TABS+ .iter()+ .chain(crate::dock::ICON_PANELS)+ .filter(|p| !FLOATING_GROUPS.iter().any(|g| g.contains(&p.0)))+ .filter_map(|p| placed.take(p.0))+ .map(|id| Group::new(vec![id], 0))+ .collect(),+ ICON_WIDTH,+ ),+ };+ (!groups.is_empty()).then_some(Column { groups, width: COLUMN_WIDTH, iconic: true, iconic_width: Some(width) })+}++/// The canvas beside a dock of `columns` (from the window edge inwards) at the logical end edge.+fn with_canvas(columns: Vec<Column<String>>, floating: Vec<Floating<String>>) -> Layout<String> {+ let width: f32 = columns.iter().map(|c| if c.iconic { c.iconic_width.unwrap_or(ICON_WIDTH) } else { c.width }).sum();+ Layout {+ root: Some(Node::Split {+ axis: craft_ui::layout::SplitAxis::Horizontal,+ size: craft_ui::layout::SplitSize::FixedSecond(width),+ first: Box::new(Node::Tabs { panels: vec![CANVAS.to_string()], active: 0 }),+ second: Box::new(Node::Dock { side: Side::End, columns }),+ }),+ floating,+ }+}+/// The layout of a workspace that has not been customized, from its panel settings: the/// canvas beside a dock whose outer column is the Properties · Pages · Layers group (with an-/// open flyout panel stacked below it) and whose inner column is iconic. Essentials Classic+/// the panel the workspace opens stacked below it) and whose inner column is iconic. Essentials Classic/// and Typography (`icon_groups`) have the iconic column only.pub(crate) fn default_layout(ui: &crate::UiState) -> Layout<String> {- let mut placed: Vec<String> = Vec::new();- let take = |id: &str, placed: &mut Vec<String>| -> Option<String> {- let id = normalize(id)?;- (!placed.iter().any(|p| p == id)).then(|| {- placed.push(id.to_string());- id.to_string()- })- };+ let mut placed = Placed::default();let mut floating = Vec::new();for (id, at) in &ui.floating {if at.iter().all(|v| v.is_finite())- && let Some(id) = take(id, &mut placed)+ && let Some(id) = placed.take(id){floating.push(Floating::single(vec![id], 0, [at[0], at[1], 280.0, 360.0]));}}let mut columns = Vec::new();- match &ui.icon_groups {- Some(groups) => {- let groups: Vec<Group<String>> = groups- .iter()- .map(|g| g.iter().filter_map(|id| take(id, &mut placed)).collect::<Vec<_>>())- .filter(|panels| !panels.is_empty())- .map(|panels| Group::new(panels, 0))- .collect();- if !groups.is_empty() {- columns.push(Column { groups, width: COLUMN_WIDTH, iconic: true, iconic_width: Some(NAMED_ICON_WIDTH) });- }+ if ui.icon_groups.is_none() {+ let panels: Vec<String> = crate::dock::DOCK_TABS.iter().filter_map(|p| placed.take(p.0)).collect();+ let active = panels.iter().position(|p| p == &ui.dock_tab).unwrap_or(0);+ let mut groups = Vec::new();+ if !panels.is_empty() {+ groups.push(Group::new(panels, active));}- None => {- let panels: Vec<String> = crate::dock::DOCK_TABS.iter().filter_map(|p| take(p.0, &mut placed)).collect();- let active = panels.iter().position(|p| p == &ui.dock_tab).unwrap_or(0);- let mut groups = Vec::new();- if !panels.is_empty() {- groups.push(Group::new(panels, active));- }- // The panel a workspace opens (Printing and Proofing: Swatches) goes below at a fixed- // height, so Properties keeps most of the column.- if let Some(id) = ui.open_panel.as_deref().and_then(|id| take(id, &mut placed)) {- groups.push(Group { height: Some(OPEN_PANEL_HEIGHT), ..Group::new(vec![id], 0) });- }- if !groups.is_empty() {- columns.push(Column { groups, width: COLUMN_WIDTH, iconic: !ui.dock_expanded, iconic_width: Some(ICON_WIDTH) });- }- // Window › Styles opens the style panels as a floating group, so they start outside.- let icons: Vec<Group<String>> = crate::dock::ICON_PANELS+ // The panel a workspace opens (Printing and Proofing: Swatches) goes below at a fixed+ // height, so Properties keeps most of the column.+ if let Some(id) = ui.open_panel.as_deref().and_then(|id| placed.take(id)) {+ groups.push(Group { height: Some(OPEN_PANEL_HEIGHT), ..Group::new(vec![id], 0) });+ }+ if !groups.is_empty() {+ columns.push(Column { groups, width: COLUMN_WIDTH, iconic: !ui.dock_expanded, iconic_width: Some(ICON_WIDTH) });+ }+ }+ columns.extend(icon_column(ui.icon_groups.as_deref(), &mut placed));+ with_canvas(columns, floating)+}++/// Is `layout` from before the canvas joined the panel layout? Those layouts held only the+/// right dock's panels and floating windows; every later one holds the canvas.+pub(crate) fn dock_only(layout: &Layout<String>) -> bool {+ !layout.panels().iter().any(|p| p.as_str() == CANVAS)+}++/// A [`dock_only`] layout in the current shape: its tab groups, accordions and splits become+/// the dock's expanded columns (collapsed to icons when the dock was), the panels it does not+/// hold form the iconic column, and its floating windows stay. Panels closed with a remembered+/// place (`hidden`) stay closed. None when the layout is invalid.+pub(crate) fn from_dock_only<'a>(+ old: &Layout<String>,+ hidden: impl IntoIterator<Item = &'a String>,+ dock_expanded: bool,+ icon_groups: Option<&[Vec<String>]>,+) -> Option<Layout<String>> {+ old.validate().ok()?;+ let mut placed = Placed::default();+ // Reading order (start to end); a dock lists its columns from the window edge inwards.+ let mut reading = old.root.as_ref().map(|root| dock_only_columns(root, 0, &mut placed)).unwrap_or_default();+ reading.reverse();+ let mut columns: Vec<Column<String>> =+ reading.into_iter().map(|groups| Column { groups, width: COLUMN_WIDTH, iconic: !dock_expanded, iconic_width: Some(ICON_WIDTH) }).collect();+ let mut floating = Vec::new();+ for window in &old.floating {+ let groups: Vec<Group<String>> = window+ .groups+ .iter()+ .filter_map(|g| placed.group(&g.panels, g.active).map(|kept| Group { minimized: g.minimized, height: g.height, ..kept }))+ .collect();+ if !groups.is_empty() {+ floating.push(Floating { groups, rect: window.rect, native: None });+ }+ }+ for panel in hidden {+ let _ = placed.take(panel);+ }+ columns.extend(icon_column(icon_groups, &mut placed));+ let layout = with_canvas(columns, floating);+ valid(&layout).then_some(layout)+}++/// The groups of a dock-only layout's node, column by column in reading order. A vertical split+/// stacks its parts in one column; a horizontal split puts them side by side.+fn dock_only_columns(node: &Node<String>, depth: usize, placed: &mut Placed) -> Vec<Vec<Group<String>>> {+ if depth > craft_ui::docking::MAX_DEPTH {+ return Vec::new();+ }+ let column = |groups: Vec<Group<String>>| if groups.is_empty() { Vec::new() } else { vec![groups] };+ match node {+ Node::Tabs { panels, active } => column(placed.group(panels, *active).into_iter().collect()),+ Node::Stack { entries } => column(+ entries.iter()- .filter(|p| !FLOATING_GROUPS.iter().any(|g| g.contains(&p.0)))- .filter_map(|p| take(p.0, &mut placed))- .map(|id| Group::new(vec![id], 0))- .collect();- if !icons.is_empty() {- columns.push(Column { groups: icons, width: COLUMN_WIDTH, iconic: true, iconic_width: Some(ICON_WIDTH) });+ .filter_map(|e| placed.take(&e.panel).map(|id| Group { minimized: !e.open, height: e.height, ..Group::new(vec![id], 0) }))+ .collect(),+ ),+ Node::Split { axis, first, second, .. } => {+ let mut parts = dock_only_columns(first, depth.saturating_add(1), placed);+ parts.extend(dock_only_columns(second, depth.saturating_add(1), placed));+ match axis {+ craft_ui::layout::SplitAxis::Horizontal => parts,+ _ => column(parts.into_iter().flatten().collect()),}}- }- let width: f32 = columns.iter().map(|c| if c.iconic { c.iconic_width.unwrap_or(ICON_WIDTH) } else { c.width }).sum();- Layout {- root: Some(Node::Split {- axis: craft_ui::layout::SplitAxis::Horizontal,- size: craft_ui::layout::SplitSize::FixedSecond(width),- first: Box::new(Node::Tabs { panels: vec![CANVAS.to_string()], active: 0 }),- second: Box::new(Node::Dock { side: Side::End, columns }),- }),- floating,+ Node::Dock { columns, .. } => columns+ .iter()+ .rev()+ .filter_map(|c| {+ let groups: Vec<Group<String>> = c.groups.iter().filter_map(|g| placed.group(&g.panels, g.active)).collect();+ (!groups.is_empty()).then_some(groups)+ })+ .collect(),+ _ => Vec::new(),}}@@ -184,6 +256,7 @@ fn dock_columns(layout: &Layout<String>) -> Vec<&Column<String>> {/// The panels tabbed with `panel`: its floating group, or its tab group in the dock. A panel in/// an accordion, or not in the layout, is a group of its own.+#[cfg(test)]pub(crate) fn tab_group(layout: &Layout<String>, panel: &str) -> Vec<String> {if let Some(group) = layout.floating.iter().flat_map(|w| &w.groups).find(|g| g.panels.iter().any(|p| p == panel)) {return group.panels.clone();@@ -333,7 +406,19 @@ pub(crate) fn command(app: &mut DesignApp, id: &str, params: &Value) -> Option<Rreturn Some(set_iconic(app, true));}if id == "window.panel.closeGroup" {- return Some(close_group(app, params));+ 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)@@ -432,7 +517,7 @@ fn apply_action(app: &mut DesignApp, action: Action<String>) -> Result<Value, St}app.ui.docking = Some(layout);release_closed(app, &closed);- sync_legacy(app);+ keep_float_only(app);if let Some(panel) = reveal {app.ui.docking_opened = Some(panel.clone());app.ui.docking_raise = Some(panel);@@ -441,7 +526,37 @@ fn apply_action(app: &mut DesignApp, action: Action<String>) -> Result<Value, Stapp.ui.docking_opened = None;}app.ui.open_panel = None;- Ok(json!({"layout": app.ui.docking}))+ Ok(json!({"layout": app.ui.docking, "closed": closed}))+}++/// Type › Tabs and the other float-only panels: their own windows outside the docking layout,+/// listed in `UiState::floating` with their top-left positions.+fn float_only_panel(app: &mut DesignApp, id: &str, panel: &str, params: &Value) -> Result<Value, String> {+ let at = if matches!(id, "window.floatPanel" | "window.panel.float") {+ Some([number(params, "x", 400.0)?, number(params, "y", 160.0)?])+ } else {+ None+ };+ app.ui.floating.retain(|(p, _)| p != panel);+ if let Some(at) = at {+ app.ui.floating.push((panel.to_string(), at));+ }+ Ok(json!({"panel": panel, "floating": floating_panels(app)}))+}++/// Once the layout is customized it holds every floating dock panel, so `UiState::floating`+/// keeps only the float-only panels.+fn keep_float_only(app: &mut DesignApp) {+ if app.ui.docking.is_some() {+ app.ui.floating.retain(|(id, _)| crate::dock::float_only(id));+ }+}++/// Every floating panel: the layout's floating windows, then the float-only panels.+pub(crate) fn floating_panels(app: &DesignApp) -> Vec<String> {+ let layout = layout_of(app);+ let docked = layout.floating.iter().flat_map(|w| w.panels().cloned());+ 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).@@ -627,14 +742,14 @@ fn change(app: &mut DesignApp, operation: &str, params: &Value) -> Result<Value,if operation == "close" {release_closed(app, &[panel.to_owned()]);}- sync_legacy(app);+ 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": app.ui.floating.iter().map(|(id, _)| id).collect::<Vec<_>>(), "layout": app.ui.docking}))+ Ok(json!({"panel": panel, "floating": floating_panels(app), "layout": app.ui.docking}))}/// Forget what DesignCraft keeps about panels that just closed: the focus, the panel last@@ -679,7 +794,6 @@ pub(crate) fn show(app: &mut DesignApp, ui: &mut egui::Ui) {});if changed_workspace {craft_ui::docking::cancel_drag::<String>(ui.ctx(), area);- ui.ctx().data_mut(|data| data.remove::<LegacyDrag>(area.with("legacy-origin")));}if app.ui.docking.as_ref().is_some_and(|layout| !valid(layout)) {app.ui.docking = None;@@ -775,72 +889,9 @@ const DOCK_LABELS: &[(&str, &str)] = &[("dock.newWindow", "Move Panel to New Window"),];-#[allow(dead_code)] // The classic icon rail; removed with the classic dock.-fn icon_rail(app: &mut DesignApp, ui: &mut egui::Ui) {- let t = crate::theme::Tokens::get(ui.ctx());- let column = egui::Panel::right("shared-panel-icons")- .exact_size(38.0)- .resizable(false)- .frame(egui::Frame::NONE.fill(t.panel))- .show(ui, |ui| {- egui::ScrollArea::vertical().id_salt("shared-panel-icons-scroll").show(ui, |ui| {- ui.spacing_mut().item_spacing.y = 2.0;- for &(id, label, icon) in crate::dock::DOCK_TABS.iter().chain(crate::dock::ICON_PANELS) {- if app.ui.docking.as_ref().is_some_and(|layout| {- layout.contains(&id.to_string()) && (app.ui.dock_expanded || layout.floating.iter().any(|g| g.panels().any(|p| p == id)))- }) {- continue;- }-- let response =- crate::icons::button(ui, icon, 28.0, false, crate::i18n::tr(&app.ui.language, label)).interact(egui::Sense::click_and_drag());- if response.clicked() {- let _ = app.run("window.panel.activate", json!({"panel":id}));- }- legacy_tab(app, ui, id, &response);- }- });- })- .response- .rect;- let _ = column;-}--pub(crate) fn legacy_tab(app: &mut DesignApp, ui: &mut egui::Ui, panel: &str, response: &egui::Response) {- let Some(panel) = normalize(panel) else { return };- response.context_menu(|ui| panel_menu(app, ui, panel));- if response.drag_started()- && let Some(id) = normalize(panel)- {- let mut layout = layout_of(app);- let bounds = ui.max_rect();- let source = egui::Rect::from_min_size(- egui::pos2(bounds.left(), response.rect.top()),- egui::vec2(bounds.width().clamp(240.0, 600.0), bounds.height().clamp(200.0, 600.0)),- );- if ensure(&mut layout, id).is_ok()- && craft_ui::docking::begin_drag(ui.ctx(), egui::Id::new("designcraft-panel-docking"), id.to_string(), source)- {- ui.ctx().data_mut(|data| {- data.insert_temp(- egui::Id::new("designcraft-panel-docking").with("legacy-origin"),- LegacyDrag {- layout: app.ui.docking.clone(),- open_panel: app.ui.open_panel.clone(),- floating: app.ui.floating.clone(),- generation: app.ui.docking_generation,- },- )- });- app.ui.docking = Some(layout);- app.ui.open_panel = None;- }- }-}--/// The menu behind a panel's three-line button, in either dock: the panel's own commands, then-/// its docking commands.-pub(crate) fn three_line_menu(app: &mut DesignApp, ui: &mut egui::Ui, panel: &str) {+/// The menu behind a panel's three-line button: the panel's own commands, then its docking+/// commands.+fn three_line_menu(app: &mut DesignApp, ui: &mut egui::Ui, panel: &str) {if panel == "pages" {crate::panels::pages::panel_menu(app, ui);ui.separator();@@ -990,18 +1041,6 @@ impl craft_ui::docking::DockContent<String> for PanelContent<'_> {}}-/// Close Tab Group: `panel` and the panels tabbed with it, each restorable from Window as one-/// closed with Close.-fn close_group(app: &mut DesignApp, 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")?;- let layout = layout_of(app);- let group = tab_group(&layout, panel);- for p in &group {- change(app, "close", &json!({"panel": p}))?;- }- Ok(json!({"closed": group}))-}-/// InDesign's panel tab commands at the end of a panel's three-line menu: Close, Close Tab Group,/// Minimize (an open accordion entry) and Collapse to Icons. A tab's own context menu is/// craft-ui's, which lists the same commands.@@ -1041,20 +1080,6 @@ pub(crate) fn close_visible(app: &mut DesignApp) -> Result<(), String> {Ok(())}-// Legacy inspection fields are derived from the shared layout after customization.-fn sync_legacy(app: &mut DesignApp) {- if let Some(layout) = &app.ui.docking {- // Float-only panels aren't in the layout; they keep their place in the list.- let float_only: Vec<(String, [f32; 2])> = app.ui.floating.iter().filter(|(id, _)| crate::dock::float_only(id)).cloned().collect();- app.ui.floating = layout- .floating- .iter()- .flat_map(|window| window.panels().map(|id| (id.clone(), [window.rect[0], window.rect[1]])))- .chain(float_only)- .collect();- }-}-#[cfg(test)]#[path = "panel_docking_tests.rs"]mod tests;diff --git a/crates/ui-egui/src/panel_docking_tests.rs b/crates/ui-egui/src/panel_docking_tests.rsindex abbcf1391..b44265e7d 100644--- a/crates/ui-egui/src/panel_docking_tests.rs+++ b/crates/ui-egui/src/panel_docking_tests.rs@@ -136,16 +136,7 @@ fn capture_custom_panel_docking_visual_fixtures() {ready = true;return;}- crate::dock::show(app, ui);- egui::CentralPanel::default().show(ui, |ui| {- ui.label("Custom panel workspace");- if app.ui.language == "ar" {- ui.label("Shaped action references:");- for action in ["Float Panel", "Group with", "Close Panel"] {- crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, action));- }- }- });+ egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| crate::panel_docking::show(app, ui));},app,);@@ -174,10 +165,7 @@ fn capture_custom_panel_docking_visual_fixtures() {harness.run_steps(2);assert!(egui::Popup::is_any_open(&harness.ctx), "actual tab context menu must be open");for action in ["Float Panel", "Group with", "Close Panel"] {- assert!(- harness.query_all_by_label(crate::i18n::tr("ar", action)).count() >= 2,- "both logical reference and actual menu label must exist"- );+ assert!(harness.query_all_by_label(crate::i18n::tr("ar", action)).count() >= 1, "the menu lists {action}");}harness.render().unwrap().save(directory.join(format!("designcraft-dock-context-{}-ar.png", theme.id()))).unwrap();}@@ -352,7 +340,7 @@ fn changing_workspace_during_a_drag_cancels_the_stale_gesture() {}#[test]-fn first_customization_preserves_the_visible_legacy_flyout() {+fn first_customization_keeps_the_panel_the_workspace_opened() {let mut app = app();app.ui.open_panel = Some("paragraphStyles".into());app.ui.dock_expanded = false;@@ -383,7 +371,7 @@ fn hiding_before_first_destination_frame_does_not_restore_an_old_drag_snapshot()let floating = h.state().ui.floating.clone();// The app calls this before dock rendering when panels are hidden or Presentation starts.let ctx = h.ctx.clone();- cancel_gesture(h.state_mut(), &ctx);+ cancel_gesture(&ctx);assert_eq!(h.state().ui.docking, destination);assert_eq!(h.state().ui.open_panel, open_panel);assert_eq!(h.state().ui.floating, floating);@@ -393,7 +381,7 @@ fn hiding_before_first_destination_frame_does_not_restore_an_old_drag_snapshot()}#[test]-fn legacy_table_and_control_visibility_work_after_customization_without_document_edits() {+fn table_and_control_visibility_work_after_customization_without_document_edits() {let mut app = app();app.run("file.new", json!({})).unwrap();let doc = serde_json::to_value(&app.session.active().unwrap().doc).unwrap();@@ -548,82 +536,6 @@ fn first_story_editor_frame_conservatively_blocks_owned_tab_release() {assert_eq!(serde_json::to_value(&h.state().app.session.active().unwrap().doc).unwrap(), doc);}-#[test]-fn capture_legacy_panel_menu_visual_fixture() {- let Some(directory) = std::env::var_os("CRAFT_UI_DOCKING_FIXTURES").map(std::path::PathBuf::from) else { return };- std::fs::create_dir_all(&directory).unwrap();- let mut app = app();- app.run("file.new", json!({})).unwrap();- app.run("frame.create", json!({"rect":[40,40,280,180],"content":"text","text":"Legacy Arabic menu fixture"})).unwrap();- app.run("app.language", json!({"lang":"ar"})).unwrap();- let doc = serde_json::to_value(&app.session.active().unwrap().doc).unwrap();- let mut ready = false;- let mut h = Harness::builder().with_size(vec2(800.0, 800.0)).wgpu().build_ui_state(- move |ui, app: &mut DesignApp| {- if !ready {- crate::theme::install_fonts(ui.ctx(), &app.ui.language);- crate::theme::apply(ui.ctx(), &crate::theme::Tokens::for_brightness(crate::theme::Brightness::Dark));- ready = true;- return;- }- crate::dock::show(app, ui);- egui::CentralPanel::default().show(ui, |ui| {- ui.label("Shaped legacy menu references:");- for label in ["Float Panel", "Layers"] {- crate::rtl::label(ui, crate::i18n::tr("ar", label));- }- });- },- app,- );- h.input_mut().max_texture_side = Some(8192);- h.run_steps(5);- assert!(h.state().ui.docking.is_none(), "fixture must use the actual legacy menu before customization");- let at = h.get_by_label("Properties").rect().center();- h.input_mut().events.extend([- Event::PointerMoved(at),- Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE },- ]);- h.run_steps(1);- h.input_mut().events.push(Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE });- h.run_steps(2);- assert!(egui::Popup::is_any_open(&h.ctx));- assert_eq!(h.query_all_by_label(crate::i18n::tr("ar", "Float Panel")).count(), 2, "reference and actual logical action must be accessible");- h.render().unwrap().save(directory.join("designcraft-legacy-context-dark-ar.png")).unwrap();- let group = h.get_by_label_contains(crate::i18n::tr("ar", "Group with")).rect().center();- h.hover_at(group);- h.run_steps(4);- assert_eq!(h.query_all_by_label(crate::i18n::tr("ar", "Layers")).count(), 2, "reference and actual target must be accessible");- h.render().unwrap().save(directory.join("designcraft-legacy-targets-dark-ar.png")).unwrap();- assert!(h.state().ui.docking.is_none());- let (last, last_label, _) = crate::dock::ICON_PANELS.last().unwrap();- let logical = crate::i18n::tr("ar", last_label);- let scroll_at = h.query_all_by_label(crate::i18n::tr("ar", "Layers")).find(|node| node.rect().left() > 500.0).unwrap().rect().center();- let submenu_layer = h.ctx.layer_id_at(scroll_at).unwrap();- let submenu = h.ctx.memory(|m| m.area_rect(submenu_layer.id)).unwrap();- let before = h.query_all_by_label(logical).find(|node| submenu.x_range().contains(node.rect().center().x)).map(|node| node.rect());- assert!(before.is_none_or(|rect| !submenu.contains_rect(rect)), "actual submenu must require scrolling to reach its last target");- h.input_mut().events.extend([- Event::PointerMoved(scroll_at),- Event::MouseWheel { unit: egui::MouseWheelUnit::Point, delta: vec2(0.0, -1600.0), phase: egui::TouchPhase::Move, modifiers: Modifiers::NONE },- ]);- h.run_steps(12);- let target = h.query_all_by_label(logical).find(|node| submenu.x_range().contains(node.rect().center().x)).unwrap().rect();- assert!(submenu.contains_rect(target), "last target must be inside the actual submenu after scrolling");- assert!(h.ctx.content_rect().contains_rect(target), "last target must be physically visible after wheel scrolling");- h.render().unwrap().save(directory.join("designcraft-legacy-targets-scrolled-dark-ar.png")).unwrap();- h.query_all_by_label(logical).find(|node| submenu.contains_rect(node.rect())).unwrap().click();- h.run_steps(4);- let layout = h.state().ui.docking.as_ref().unwrap();- assert_eq!(layout.panels().iter().filter(|panel| panel.as_str() == "properties").count(), 1);- assert_eq!(layout.panels().iter().filter(|panel| panel.as_str() == *last).count(), 1);- let group = group_members_for_test(layout, last);- assert!(group.iter().any(|panel| panel == "properties"));- assert_eq!(group.last().map(String::as_str), Some("properties"), "clicked destination must receive the original panel after it");- assert_eq!(serde_json::to_value(&h.state().session.active().unwrap().doc).unwrap(), doc);- h.render().unwrap().save(directory.join("designcraft-legacy-last-target-selected-dark-ar.png")).unwrap();-}-#[test]fn dock_menu_button_opens_the_active_panel_menu() {let mut app = app();@@ -757,7 +669,7 @@ fn click(h: &mut Harness<'static, DesignApp>, at: Pos2, button: PointerButton) {}/// Window › Paragraph Styles switches to the docking layout. After Window › Pages the Pages panel-/// keeps its three-line panel menu, and its tab menu lists what the classic dock's does.+/// keeps its three-line panel menu, and its tab menu lists InDesign's tab commands.#[test]fn pages_keeps_its_panel_menu_in_the_docking_layout() {let mut app = app();diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rsindex 79cf2f0e7..e216df3b3 100644--- a/crates/ui-egui/src/panels/properties.rs+++ b/crates/ui-egui/src/panels/properties.rs@@ -16,12 +16,9 @@ use crate::widgets::{};use crate::{DesignApp, icons};-/// A link to another panel. `window.panel` shows it in the docked layout or as a flyout; it-/// toggles the flyout, so a flyout that is already open is left as it is.+/// A link to another panel: `window.panel` shows it in the docking layout.fn show_panel(app: &mut DesignApp, panel: &str) {- if app.ui.open_panel.as_deref() != Some(panel) {- let _ = app.run("window.panel", json!({"panel": panel}));- }+ let _ = app.run("window.panel", json!({"panel": panel}));}fn units(app: &DesignApp) -> Unit {@@ -1692,12 +1689,8 @@ pub fn character_panel(app: &mut DesignApp, ui: &mut egui::Ui) {}}-/// Opens the Typography panel, or focuses it when it is already showing. `window.panel` toggles a-/// flyout, so it is skipped while the Typography flyout is open.+/// Opens the Typography panel, or brings it to the front when it is already open.pub fn show_typography_panel(app: &mut DesignApp) {- if app.ui.open_panel.as_deref() == Some("typography") {- return;- }let _ = app.run("window.panel", json!({"panel": "typography"}));}diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rsindex cb5a0b54c..37a70c3d6 100644--- a/crates/ui-egui/src/prefs.rs+++ b/crates/ui-egui/src/prefs.rs@@ -1,43 +1,92 @@//! 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::UiState;+use crate::{SavedWorkspace, UiState, panel_docking};++/// Saved preferences, and whether reading them discarded anything.+pub struct ReadPreferences {+ pub ui: UiState,+ /// False when unreadable docking data was dropped. The caller keeps the file it read+ /// instead of overwriting it.+ pub intact: bool,+}impl UiState {/// Read saved preferences, discarding only unreadable optional docking metadata./// A layout from a newer craft-ui version must not reset unrelated settings or named workspaces.pub fn from_preferences_json(bytes: &[u8]) -> serde_json::Result<Self> {+ Self::read_preferences(bytes).map(|read| read.ui)+ }++ /// [`Self::from_preferences_json`], also reporting whether anything was discarded. Layouts+ /// saved before the canvas joined the panel layout are converted (see+ /// [`panel_docking::from_dock_only`]); that is not a loss.+ pub fn read_preferences(bytes: &[u8]) -> serde_json::Result<ReadPreferences> {let mut saved: Value = serde_json::from_slice(bytes)?;- recover_docking(&mut saved);+ let mut intact = recover_docking(&mut saved);if let Some(workspaces) = saved.get_mut("customWorkspaces").and_then(Value::as_array_mut) {for workspace in workspaces {- recover_docking(workspace);+ intact &= recover_docking(workspace);}}- serde_json::from_value(saved)+ let mut ui: UiState = serde_json::from_value(saved)?;+ migrate(&mut ui.docking, &mut ui.floating, &ui.docking_hidden, ui.dock_expanded, ui.icon_groups.as_deref());+ for workspace in &mut ui.custom_workspaces {+ let SavedWorkspace { docking, floating, docking_hidden, dock_expanded, icon_groups, .. } = workspace;+ migrate(docking, floating, docking_hidden, *dock_expanded, icon_groups.as_deref());+ }+ Ok(ReadPreferences { ui, intact })}}-fn recover_docking(saved: &mut Value) {- let Some(fields) = saved.as_object_mut() else { return };+/// Drop docking data this version cannot read. True when nothing was dropped.+fn recover_docking(saved: &mut Value) -> bool {+ let Some(fields) = saved.as_object_mut() else { return true };+ let mut intact = true;if fields.get("docking").is_some_and(|value| serde_json::from_value::<Option<Layout<String>>>(value.clone()).is_err()) {fields.remove("docking");+ intact = false;}if let Some(hidden) = fields.get_mut("dockingHidden") {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;} else {fields.remove("dockingHidden");+ intact = false;}}+ intact+}++/// Convert a layout saved before the canvas joined the panel layout. One that cannot be+/// converted gives way to the workspace's default layout, which the workspace fields+/// (`dockTab`, `openPanel`, `floating`, `dockExpanded`, `iconGroups`) still describe.+fn migrate(+ docking: &mut Option<Layout<String>>,+ floating: &mut Vec<(String, [f32; 2])>,+ hidden: &BTreeMap<String, Location<String>>,+ dock_expanded: bool,+ icon_groups: Option<&[Vec<String>]>,+) {+ let Some(old) = docking.as_ref().filter(|layout| panel_docking::dock_only(layout)) else { return };+ *docking = panel_docking::from_dock_only(old, hidden.keys(), dock_expanded, icon_groups);+ if docking.is_some() {+ // The converted layout holds the floating dock panels.+ floating.retain(|(id, _)| crate::dock::float_only(id));+ }}#[cfg(test)]mod tests {use super::*;- use crate::{DesignApp, SavedWorkspace};+ use crate::DesignApp;+ use craft_ui::docking::{Column, Node, Side};use serde_json::json;fn populated() -> UiState {@@ -108,6 +157,144 @@ mod tests {assert_eq!(loaded.custom_workspaces[0].docking_hidden, original.custom_workspaces[0].docking_hidden);}+ #[test]+ fn unreadable_docking_is_reported_so_the_file_is_kept() {+ let mut saved = serde_json::to_value(populated()).unwrap();+ assert!(UiState::read_preferences(&serde_json::to_vec(&saved).unwrap()).unwrap().intact);+ saved["customWorkspaces"][1]["docking"] = json!({"root":{"FutureLayout":{}}});+ assert!(!UiState::read_preferences(&serde_json::to_vec(&saved).unwrap()).unwrap().intact);+ }++ /// The dock of a layout in the current shape: the canvas beside a dock at the end edge.+ fn dock(layout: &Layout<String>) -> &[Column<String>] {+ assert!(crate::panel_docking::valid(layout), "{layout:?}");+ let Some(Node::Split { first, second, .. }) = &layout.root else { panic!("expected the canvas split: {layout:?}") };+ assert!(matches!(&**first, Node::Tabs { panels, .. } if panels == &["canvas"]));+ let Node::Dock { side: Side::End, columns } = &**second else { panic!("expected an end dock: {second:?}") };+ columns+ }++ fn panels(column: &Column<String>) -> Vec<Vec<&str>> {+ column.groups.iter().map(|g| g.panels.iter().map(String::as_str).collect()).collect()+ }++ /// Hand-written pre-trial `ui.json` files: each loads through the app's path with nothing lost.+ fn load(saved: serde_json::Value) -> UiState {+ UiState::read_preferences(&serde_json::to_vec(&saved).unwrap()).map(|read| read.ui).unwrap()+ }++ #[test]+ fn classic_dock_file_loads_as_its_workspace_default_layout() {+ let ui = load(json!({+ "workspace": "Printing and Proofing", "dockTab": "layers", "dockExpanded": true, "openPanel": "swatches",+ "floating": [["glyphs", [100.0, 120.0]]],+ }));+ assert!(ui.docking.is_none());+ let layout = crate::panel_docking::default_layout(&ui);+ let columns = dock(&layout);+ assert_eq!(panels(&columns[0]), [vec!["properties", "pages", "layers"], vec!["swatches"]]);+ assert_eq!(columns[0].groups[0].active, 2, "Layers stays in front");+ assert!(!columns[0].iconic && columns[1].iconic);+ assert!(columns[1].groups.iter().all(|g| !g.panels.iter().any(|p| p == "glyphs" || p == "swatches")));+ assert_eq!(layout.floating.len(), 1);+ assert_eq!(layout.floating[0].groups[0].panels, ["glyphs"]);+ assert_eq!(&layout.floating[0].rect[..2], &[100.0, 120.0]);+ }++ #[test]+ fn dock_only_layout_becomes_the_main_column() {+ let ui = load(json!({+ "dockExpanded": true,+ "docking": {"root": {"Tabs": {"panels": ["properties", "pages", "layers", "swatches"], "active": 3}}, "floating": []},+ "customWorkspaces": [{+ "name": "Split", "dockExpanded": true,+ "docking": {"root": {"Split": {"axis": "Horizontal", "size": {"Ratio": 0.5},+ "first": {"Tabs": {"panels": ["links"], "active": 0}},+ "second": {"Split": {"axis": "Vertical", "size": {"Ratio": 0.5},+ "first": {"Tabs": {"panels": ["properties", "pages"], "active": 1}},+ "second": {"Stack": {"entries": [+ {"panel": "layers", "open": true, "height": null},+ {"panel": "swatches", "open": false, "height": 120.0}]}}}}}},+ "floating": []},+ }],+ }));+ let columns = dock(ui.docking.as_ref().unwrap());+ assert_eq!(panels(&columns[0]), [vec!["properties", "pages", "layers", "swatches"]]);+ assert_eq!(columns[0].groups[0].active, 3);+ assert!(!columns[0].iconic);+ let icons = &columns[1];+ assert!(icons.iconic && icons.groups.iter().any(|g| g.panels == ["stroke"]));+ assert!(icons.groups.iter().all(|g| g.panels != ["swatches"]), "each panel appears once");++ // Splits: a vertical split stacks groups in one column, a horizontal one adds a column+ // (the dock lists columns from the window edge inwards).+ let columns = dock(ui.custom_workspaces[0].docking.as_ref().unwrap());+ assert_eq!(panels(&columns[0]), [vec!["properties", "pages"], vec!["layers"], vec!["swatches"]]);+ assert_eq!(columns[0].groups[0].active, 1);+ assert!(columns[0].groups[2].minimized && columns[0].groups[2].height == Some(120.0), "a closed accordion entry stays minimized");+ assert_eq!(panels(&columns[1]), [vec!["links"]]);+ assert!(columns[2].iconic);+ }++ #[test]+ fn icon_groups_become_the_iconic_column_in_order() {+ let ui = load(json!({+ "dockExpanded": true,+ "iconGroups": [["pages", "layers"], ["properties", "swatches", "color"]],+ "docking": {"root": {"Tabs": {"panels": ["properties"], "active": 0}}, "floating": []},+ }));+ let columns = dock(ui.docking.as_ref().unwrap());+ assert_eq!(columns.len(), 2);+ assert_eq!(panels(&columns[0]), [vec!["properties"]]);+ assert!(columns[1].iconic);+ assert_eq!(panels(&columns[1]), [vec!["pages", "layers"], vec!["swatches", "color"]]);+ }++ #[test]+ fn collapsed_dock_makes_the_main_column_iconic() {+ let ui = load(json!({+ "dockExpanded": false,+ "docking": {"root": {"Tabs": {"panels": ["properties", "pages", "layers"], "active": 0}}, "floating": []},+ }));+ let columns = dock(ui.docking.as_ref().unwrap());+ assert_eq!(panels(&columns[0]), [vec!["properties", "pages", "layers"]]);+ assert!(columns.iter().all(|c| c.iconic));+ }++ #[test]+ fn floating_windows_and_hidden_places_survive_the_migration() {+ let saved = json!({+ "dockExpanded": true,+ "floating": [["glyphs", [40.0, 60.0]], ["character", [40.0, 60.0]], ["tabs", [10.0, 20.0]]],+ "docking": {+ "root": {"Tabs": {"panels": ["properties", "pages", "layers"], "active": 0}},+ "floating": [{"panels": ["glyphs", "character"], "active": 1, "rect": [40.0, 60.0, 300.0, 400.0]}],+ },+ "dockingHidden": {"color": {"floating": null, "anchor": "layers", "placement": {"Split": "Bottom"},+ "size": {"Ratio": 0.5}, "stack": null}},+ });+ let read = UiState::read_preferences(&serde_json::to_vec(&saved).unwrap()).unwrap();+ assert!(read.intact, "converting is not a loss");+ let ui = read.ui;+ let layout = ui.docking.clone().unwrap();+ let columns = dock(&layout);+ assert_eq!(layout.floating.len(), 1);+ assert_eq!(layout.floating[0].groups[0].panels, ["glyphs", "character"]);+ assert_eq!(layout.floating[0].groups[0].active, 1);+ assert_eq!(layout.floating[0].rect, [40.0, 60.0, 300.0, 400.0]);+ assert_eq!(ui.floating, [("tabs".to_string(), [10.0, 20.0])], "the layout holds the floating dock panels");+ assert!(ui.docking_hidden.contains_key("color") && !layout.contains(&"color".to_string()), "a closed panel stays closed");+ assert!(columns[1].groups.iter().all(|g| g.panels != ["glyphs"]));+ 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"));+ // Saved again, the file is in the current shape and loads unchanged.+ let again = UiState::from_preferences_json(&serde_json::to_vec(&app.ui).unwrap()).unwrap();+ assert_eq!(again.docking, app.ui.docking);+ }+#[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 78ef44fa3..446460981 100644--- a/docs/control-protocol.md+++ b/docs/control-protocol.md@@ -87,7 +87,12 @@ workspace opens (Printing and Proofing: Swatches) is a group below Properties ·The `canvas` panel never moves, floats, closes or takes tabs; a panel or tab group droppedover it floats there. Workspace saves retain its groups, active tabs, split sizes, floatinggeometry, and the positions of hidden panels. Resetting a built-in workspace restores its-default dock.+default dock. Preferences saved before the canvas joined the layout load with nothing lost:+the classic dock becomes the workspace's default layout, and a customized dock-only layout+becomes the dock's expanded columns (iconic if the dock was collapsed), with the remaining+panels (or the workspace's named groups) in the iconic column and its floating windows and+hidden-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@@ -95,12 +100,17 @@ default dock.`top` and `bottom` add a group above or below its group and `left` and `right` add a columnon 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?}` detaches a panel.-- `window.panel.dock {panel, anchor?, zone?, before?}` returns a panel to its previous- dock placement when possible, or to the supplied destination.+- `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.- `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 thatcolumn. `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`.- `window.collapseToIcons` collapses every dock column to icons.Panel IDs are stable across themes. Invalid IDs, non-finite or invalid geometry, anddiff --git a/docs/target-app-parity.md b/docs/target-app-parity.mdindex 4a7e9b99f..8231f8c17 100644--- a/docs/target-app-parity.md+++ b/docs/target-app-parity.md@@ -431,7 +431,7 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level- Pathfinder panel as InDesign's: Paths (Join Path `path.join`, Open/Close Path, Reverse Path), Pathfinder, Convert Shape, Convert Point (`path.convertPoints`: plain, corner, smooth, symmetrical).- Make / Release Compound Path (⌘8; nested paths become holes), Create Outlines (⇧⌘O; one path per text colour), Scissors tool (C) with `path.split`.- Transform Again / Individually / Sequence Again (⌥⌘3; a moved copy repeats like Step and Repeat), Clear Transformations; Layers: Merge, Delete Unused, Hide/Lock Others, Show/Unlock All; Break Link to Style (paragraph and character).-- Floating panels: tear a panel off the dock (its float button, or drag its header away) into a movable, resizable window; Dock puts it back; positions persist; `window.floatPanel` / `window.dockPanel`.+- Floating panels: drag a panel's tab, or a group by its drag bar, off the dock (or choose Float Panel) into a movable, resizable floating window; Dock Panel puts it back where it was; positions persist; `window.panel.float` / `window.panel.dock` (aliases `window.floatPanel` / `window.dockPanel`).- Place SVG (vector in PDF export via krilla-svg, resvg on screen, text in the bundled fonts), Photoshop (.psd/.psb composite in its colour mode — Bitmap, Grayscale, Duotone, Indexed, RGB, CMYK, Lab, 8/16-bit — with merged transparency; extra alpha and spot channels don't change the image), BMP, and Illustrator files saved with PDF compatibility (.ai). A swatch on a placed greyscale or bitmap image (IDML `<Image FillColor>`) colours it on screen and in PDF. New `designcraft-images` crate (L2) for sniffing, sizes and decoding. EPS is still missing.- View › Display Performance: Fast (grey boxes, no effects, ⌥⇧⌘Z), Typical (72 ppi proxies, ⌥⌘Z), High Quality (⌥⌘H, our default — the renderer is fast enough).- OpenType menu (Character panel): discretionary ligatures, fractions, ordinal, swash, titling, contextual alternates, slashed zero, the four figure styles and stylistic sets 1–20; `type.openType`; mapped to IDML's OTF attributes.