Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

Docking: craft-libs shared docking with native floating windows

aiongg4aa799b81c47
diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml
index c9d85253f..0d5cf7c54 100644
--- a/crates/ui-egui/Cargo.toml
+++ b/crates/ui-egui/Cargo.toml
@@ -10,7 +10,7 @@ description = "DesignCraft egui frontend (InDesign-style UI); swappable — noth
workspace = true
[dependencies]
-craft-ui = { workspace = true }
+craft-ui = { workspace = true, features = ["native-windows"] }
designcraft-geom = { workspace = true }
designcraft-color = { workspace = true }
designcraft-doc = { workspace = true }
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index 75acc32a9..ae7d8c910 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -666,9 +666,12 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) {
return;
}
let sel_rect = draw_selection(app, &painter, &xf, &doc, &layout);
+ // Where the pointer moved on to another of the app's windows, this window's last pointer
+ // position is stale: no hover feedback or tool cursor there.
+ let elsewhere = pointer_elsewhere(app, ui.ctx());
if !preview {
// Content grabbers: the selected frame's and the hovered one's (Selection tool).
- let hover = ui.ctx().pointer_hover_pos().filter(|p| screen.contains(*p)).map(|p| xf.to_canvas(p));
+ let hover = ui.ctx().pointer_hover_pos().filter(|p| screen.contains(*p) && !elsewhere).map(|p| xf.to_canvas(p));
let vi = app.view_info();
for c in app.session.content_grabbers(hover, vi) {
let c = xf.to_screen(c);
@@ -690,7 +693,7 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) {
crate::taskbar::show(app, &ui.ctx().clone(), r, screen);
}
// Cursor.
- if let Some(p) = resp.hover_pos().filter(|p| screen.contains(*p)) {
+ if let Some(p) = resp.hover_pos().filter(|p| screen.contains(*p) && !elsewhere) {
let wants_text = app.session.wants_text();
let space = navigation_space(app, ui.ctx());
let zoom = spring_zoom_mode(app, ui.ctx(), space);
@@ -726,6 +729,16 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) {
}
}
+/// Whether the pointer this canvas's window last saw is in another of the app's windows: a
+/// floating panel's OS window, or the other window of New Window.
+fn pointer_elsewhere(app: &DesignApp, ctx: &egui::Context) -> bool {
+ let mut others = crate::panel_docking::native_viewports(app, ctx);
+ if app.second_window && !ctx.embed_viewports() {
+ others.extend([egui::ViewportId::ROOT, crate::second_window_viewport()]);
+ }
+ crate::cursors::pointer_elsewhere(ctx, &others)
+}
+
/// The loaded text cursor's badge beside the system cursor: lines of text, a closed chain
/// (a click threads) or a broken one (a click unthreads). Drawn in code.
fn draw_cursor_badge(painter: &egui::Painter, p: Pos2, c: Cursor, t: &Tokens) {
@@ -2159,7 +2172,7 @@ fn draw_rulers(app: &DesignApp, ui: &egui::Ui, full: Rect, rect: Rect, xf: &Xf,
k += 1;
}
// Pointer position markers.
- if let Some(p) = ui.ctx().pointer_hover_pos().filter(|p| rect.contains(*p)) {
+ if let Some(p) = ui.ctx().pointer_hover_pos().filter(|p| rect.contains(*p) && !pointer_elsewhere(app, ui.ctx())) {
let m = Stroke::new(1.0, t.text_dim);
dashed(&painter, pos2(p.x, top.min.y), pos2(p.x, top.max.y), m, 1.5, 1.5);
dashed(&painter, pos2(left.min.x, p.y), pos2(left.max.x, p.y), m, 1.5, 1.5);
@@ -2706,36 +2719,73 @@ fn handle_input(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, r
crate::menus::activate(app, id, &params);
}
}
- egui::Event::Key { key, pressed: true, modifiers, .. } => {
- let k = match key {
- egui::Key::ArrowLeft => Some(ToolKey::Left),
- egui::Key::ArrowRight => Some(ToolKey::Right),
- egui::Key::ArrowUp => Some(ToolKey::Up),
- egui::Key::ArrowDown => Some(ToolKey::Down),
- egui::Key::Enter => Some(ToolKey::Enter),
- egui::Key::Escape => Some(ToolKey::Escape),
- egui::Key::Backspace => Some(ToolKey::Backspace),
- egui::Key::Delete => Some(ToolKey::Delete),
- egui::Key::Tab => Some(ToolKey::Tab),
- egui::Key::Home => Some(ToolKey::Home),
- egui::Key::End => Some(ToolKey::End),
- _ => None,
- };
- if let Some(k) = k {
- let m = Mods { shift: modifiers.shift, alt: modifiers.alt, cmd: modifiers.command, ctrl: modifiers.ctrl, space: false };
- let handled = app.session.tool_key(k, m, vi).unwrap_or(false);
- if !handled && k == ToolKey::Escape {
- let _ = app.run("edit.deselectAll", json!({}));
- }
- app.after_engine();
- }
- }
+ egui::Event::Key { key, pressed: true, modifiers, .. } => tool_key(app, key, modifiers, vi),
_ => {}
}
}
let _ = DVec2::ZERO;
}
+/// A key for the active tool (caret movement, nudging, Backspace); Escape it leaves alone
+/// deselects.
+fn tool_key(app: &mut DesignApp, key: egui::Key, modifiers: egui::Modifiers, vi: designcraft_engine::ViewInfo) {
+ let k = match key {
+ egui::Key::ArrowLeft => ToolKey::Left,
+ egui::Key::ArrowRight => ToolKey::Right,
+ egui::Key::ArrowUp => ToolKey::Up,
+ egui::Key::ArrowDown => ToolKey::Down,
+ egui::Key::Enter => ToolKey::Enter,
+ egui::Key::Escape => ToolKey::Escape,
+ egui::Key::Backspace => ToolKey::Backspace,
+ egui::Key::Delete => ToolKey::Delete,
+ egui::Key::Tab => ToolKey::Tab,
+ egui::Key::Home => ToolKey::Home,
+ egui::Key::End => ToolKey::End,
+ _ => return,
+ };
+ let m = Mods { shift: modifiers.shift, alt: modifiers.alt, cmd: modifiers.command, ctrl: modifiers.ctrl, space: false };
+ let handled = app.session.tool_key(k, m, vi).unwrap_or(false);
+ if !handled && k == ToolKey::Escape {
+ let _ = app.run("edit.deselectAll", json!({}));
+ }
+ app.after_engine();
+}
+
+/// The keys a floating panel's own OS window left over once the shortcuts took theirs: the
+/// clipboard and the active tool's keys, as the canvas handles them while no text is edited.
+/// `modifiers` are those held in that window; egui-winit sends ⌘C, ⌘X and ⌘V as `Copy`, `Cut`
+/// and `Paste` without their key press.
+pub(crate) fn forwarded_keys(app: &mut DesignApp, events: Vec<egui::Event>, modifiers: egui::Modifiers) {
+ if !keyboard_pane(app) || modal_open(app) || app.session.wants_text() || app.session.tool_composing() {
+ return;
+ }
+ let vi = app.view_info();
+ for e in events {
+ #[cfg(not(target_arch = "wasm32"))]
+ let chord = if matches!(e, egui::Event::Paste(_)) { crate::menus::paste_chord_command(app, modifiers) } else { None };
+ // The web keeps floating panels in the page, so nothing is forwarded there.
+ #[cfg(target_arch = "wasm32")]
+ let chord: Option<&str> = {
+ let _ = modifiers;
+ None
+ };
+ let (id, params) = match (e, chord) {
+ (egui::Event::Paste(_), Some(id)) => (id, serde_json::Value::Null),
+ (egui::Event::Copy, _) if !app.native_menu => ("edit.copy", serde_json::Value::Null),
+ (egui::Event::Cut, _) if !app.native_menu => ("edit.cut", serde_json::Value::Null),
+ (egui::Event::Paste(t), _) if !app.native_menu => ("edit.paste", json!({"text": t})),
+ (egui::Event::Key { key, pressed: true, modifiers, .. }, _) => {
+ tool_key(app, key, modifiers, vi);
+ continue;
+ }
+ _ => continue,
+ };
+ if crate::menus::enabled(app, id) {
+ crate::menus::activate(app, id, &params);
+ }
+ }
+}
+
/// A dialog or Quick Apply has the keyboard. The canvas keeps egui's focus behind a modal, and it
/// runs before the modal draws, so it must not also act on the Esc or Return that closes it.
fn modal_open(app: &DesignApp) -> bool {
@@ -5402,16 +5452,19 @@ mod tests {
let out = &h.output().platform_output;
(out.cursor_icon, out.cursor_image.clone())
};
- let (pen, direct, text) = (shown("pen"), shown("directSelection"), shown("type"));
+ let (pen, direct, text, selection) = (shown("pen"), shown("directSelection"), shown("type"), shown("selection"));
let ppp = h.ctx.pixels_per_point();
let images = &mut h.state_mut().cursors;
match crate::cursors::mode() {
crate::cursors::Mode::Os => {
assert_eq!(pen.1, images.get(Cursor::Pen, ppp), "Pen");
assert_eq!(direct.1, images.get(Cursor::ArrowHollow, ppp), "Direct Selection");
+ assert_eq!(selection.1, images.get(Cursor::Arrow, ppp), "Selection");
assert_eq!(text, (egui::CursorIcon::Text, None), "the I-beam stays a system cursor");
}
- crate::cursors::Mode::Painted => assert_eq!((pen.0, direct.0), (egui::CursorIcon::None, egui::CursorIcon::None)),
+ crate::cursors::Mode::Painted => {
+ assert_eq!((pen.0, direct.0, selection.0), (egui::CursorIcon::None, egui::CursorIcon::None, egui::CursorIcon::None));
+ }
crate::cursors::Mode::System => assert_eq!(pen, (egui::CursorIcon::Crosshair, None)),
}
}
diff --git a/crates/ui-egui/src/cursors.rs b/crates/ui-egui/src/cursors.rs
index 28f98a5e0..2e3f64252 100644
--- a/crates/ui-egui/src/cursors.rs
+++ b/crates/ui-egui/src/cursors.rs
@@ -7,6 +7,11 @@
//! so they never trail the pointer. macOS sizes a cursor bitmap in points (a Retina one would show
//! twice as big, or blurred) and a Wayland session (native or through XWayland) scales it by its own
//! rules, so there the canvas paints the glyph at the pointer. The web build keeps the system cursors.
+//!
+//! A painted glyph needs a live pointer position. macOS sends a window no pointer-left event when
+//! the pointer moves onto another of the app's windows lying over it (a panel floating in its own
+//! OS window), so the window's egui pointer stays where it was last seen; [`pointer_elsewhere`]
+//! tells the canvas to paint nothing there.
use egui::epaint::{Mesh, TessellationOptions, Tessellator, Vertex};
use egui::{Color32, CustomCursorImage, Pos2, Shape, Stroke, Vec2, pos2, vec2};
@@ -338,10 +343,78 @@ pub fn show(ctx: &egui::Context, images: &mut Images, c: Cursor, hover: Pos2) ->
}
}
+/// Whether the pointer this viewport last saw has moved on to another of the app's windows,
+/// `others` (the current viewport among them is skipped): from the frame one of them reports the
+/// pointer until this viewport gets a pointer event again. That covers the pointer moving on from
+/// the other window to the desktop too, where this one still hears nothing. Always false where
+/// egui embeds viewports, so all of them share one window's pointer.
+pub(crate) fn pointer_elsewhere(ctx: &egui::Context, others: &[egui::ViewportId]) -> bool {
+ let own = ctx.viewport_id();
+ let key = egui::Id::new(("pointer-elsewhere", own));
+ let before = ctx.data(|d| d.get_temp::<bool>(key)).unwrap_or(false);
+ let here = ctx
+ .input(|i| i.events.iter().any(|e| matches!(e, egui::Event::PointerMoved(_) | egui::Event::PointerButton { .. } | egui::Event::PointerGone)));
+ // A pointer that arrived: moving or pressing there. A pointer that only stayed (a hidden
+ // window keeps its last one) does not count, so it never takes the pointer from this window.
+ let arrived = |i: &egui::InputState| {
+ i.pointer.has_pointer() && i.events.iter().any(|e| matches!(e, egui::Event::PointerMoved(_) | egui::Event::PointerButton { .. }))
+ };
+ let separate = !ctx.embed_viewports() && others.iter().any(|&v| v != own);
+ // Where this window has pointer events of its own too, another window's report counts only
+ // if this window's pointer lies inside that window: one just outside it (its edge, where
+ // both may hear the pointer) keeps belonging here, frame after frame.
+ let at = ctx.input(|i| i.viewport().inner_rect.zip(i.pointer.latest_pos()).map(|(r, p)| r.min + p.to_vec2()));
+ let there = separate && others.iter().any(|&v| v != own && ctx.input_for(v, |i| arrived(i) && (!here || covers(i.viewport().inner_rect, at))));
+ let now = separate && elsewhere(before, here, there);
+ if now != before {
+ ctx.data_mut(|d| d.insert_temp(key, now));
+ }
+ now
+}
+
+/// Whether a window at `rect` (desktop points) lies over the desktop point `at`; unknown when
+/// either is, which counts as covering.
+fn covers(rect: Option<egui::Rect>, at: Option<egui::Pos2>) -> bool {
+ rect.zip(at).is_none_or(|(r, p)| r.contains(p))
+}
+
+/// [`pointer_elsewhere`] for one frame: whether the pointer belonged to another window `before`,
+/// whether this window got a pointer event (`here`) and whether another window reports the
+/// pointer arriving (`there`). Both in one frame mean the pointer just crossed into the other
+/// window: this window's last events come from before the crossing.
+fn elsewhere(before: bool, here: bool, there: bool) -> bool {
+ there || (before && !here)
+}
+
#[cfg(test)]
mod tests {
use super::*;
+ #[test]
+ fn the_pointer_belongs_elsewhere_from_another_windows_report_until_this_one_hears_it_again() {
+ // Main window, then a floating panel's window over it, then the desktop, then back.
+ let mut state = false;
+ let mut frame = |here, there| {
+ state = elsewhere(state, here, there);
+ state
+ };
+ assert!(!frame(true, false), "over the main window");
+ assert!(frame(true, true), "crossing into the floating window");
+ assert!(frame(false, true), "moving in the floating window");
+ assert!(frame(false, false), "on the desktop: the main window still heard nothing");
+ assert!(frame(false, false), "the next frame too");
+ assert!(!frame(true, false), "back over the main window");
+ assert!(!frame(false, false), "and resting there");
+ }
+
+ #[test]
+ fn a_pointer_just_outside_another_window_stays_this_windows() {
+ let float = Some(egui::Rect::from_min_size(egui::pos2(100.0, 100.0), egui::vec2(200.0, 300.0)));
+ assert!(covers(float, Some(egui::pos2(150.0, 150.0))), "over the floating window");
+ assert!(!covers(float, Some(egui::pos2(98.0, 150.0))), "beside its left edge");
+ assert!(covers(None, Some(egui::pos2(98.0, 150.0))) && covers(float, None), "unknown places count as covered");
+ }
+
/// Every cursor with a glyph.
const GLYPHS: [Cursor; 9] = [
Cursor::Arrow,
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 78c4977d7..d2d32e2b4 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -238,6 +238,11 @@ impl Default for PdfExportSettings {
}
}
+/// The viewport of New Window's OS window, which shows pane 1.
+pub(crate) fn second_window_viewport() -> egui::ViewportId {
+ egui::ViewportId::from_hash_of("designcraft_second_window")
+}
+
/// Persisted UI state.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
@@ -1721,7 +1726,7 @@ impl DesignApp {
let fill = t.pasteboard;
let ctx = ui.ctx().clone();
ctx.show_viewport_immediate(
- egui::ViewportId::from_hash_of("designcraft_second_window"),
+ second_window_viewport(),
egui::ViewportBuilder::default().with_title(title).with_inner_size([960.0, 720.0]),
|ui, _class| {
egui::CentralPanel::default().frame(egui::Frame::NONE.fill(fill)).show(ui, |ui| {
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index 1f9815bdd..0d4f0a78d 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -3157,93 +3157,149 @@ pub fn paste_chord_command(app: &DesignApp, modifiers: egui::Modifiers) -> Optio
pub fn shortcuts(app: &mut DesignApp, ctx: &egui::Context) {
// Only a focused text field takes the keys: the canvas (or a button) having focus after a click
// must not swallow tool shortcuts until Esc clears it.
- // While an IME composes at the text caret, the keyboard is its own. An open canvas context menu
- // takes the keys (Escape closes it), as a native menu would.
- if ctx.text_edit_focused()
- || app.ui.dialog.is_some()
- || app.ui.palette.is_some()
- || app.session.tool_composing()
- || crate::canvas::context_menu_open(ctx)
- || crate::chrome::search_had_focus(ctx)
- {
+ if ctx.text_edit_focused() || keys_taken(app, ctx) {
return;
}
let typing = app.session.wants_text();
let events = ctx.input(|i| i.events.clone());
for e in events {
let egui::Event::Key { key, pressed: true, modifiers, repeat: false, .. } = e else { continue };
- // Presentation hides every control, so Esc always leaves it, and only that: the canvas must
- // not also see the press and switch tools or deselect.
- if key == egui::Key::Escape && app.ui.screen_mode == ScreenMode::Presentation {
+ if !shortcut_key(app, key, modifiers, typing, &mut || {
ctx.input_mut(|i| i.consume_key(modifiers, key));
- let _ = app.run("view.togglePresentation", json!({}));
- continue;
+ }) {
+ escape_to_selection(app, key, modifiers, typing);
}
- // Presentation goes through the spreads with the arrow keys, Page Up/Down, Home and End.
- if app.ui.screen_mode == ScreenMode::Presentation && !modifiers.command && !modifiers.alt {
- let step = match key {
- egui::Key::ArrowRight | egui::Key::ArrowDown | egui::Key::PageDown => Some(1),
- egui::Key::ArrowLeft | egui::Key::ArrowUp | egui::Key::PageUp => Some(-1),
- egui::Key::Home => Some(isize::MIN),
- egui::Key::End => Some(isize::MAX),
- _ => None,
- };
- if let Some(step) = step {
- ctx.input_mut(|i| i.consume_key(modifiers, key));
- crate::canvas::step_spread(app, step);
+ }
+}
+
+/// Keys that a floating panel in its own OS window left over (craft-ui's
+/// `DockOutput::forwarded_events`, with the modifiers held in that window): they run the main
+/// window's shortcuts, clipboard and tool keys in the frame they arrive, so the keyboard works
+/// while a floating window has focus. craft-ui forwards nothing while one of that window's
+/// widgets has keyboard focus.
+pub fn forwarded_shortcuts(app: &mut DesignApp, ctx: &egui::Context, events: Vec<egui::Event>, modifiers: egui::Modifiers) {
+ if events.is_empty() || keys_taken(app, ctx) {
+ return;
+ }
+ let typing = app.session.wants_text();
+ let mut rest = Vec::with_capacity(events.len());
+ let mut escape = None;
+ for e in events {
+ if let egui::Event::Key { key, pressed: true, modifiers, repeat: false, .. } = e {
+ if shortcut_key(app, key, modifiers, typing, &mut || {}) {
continue;
}
- }
- // Command shortcuts.
- let mut fired: Option<(String, bool)> = None;
- let all = effective_shortcuts(app);
- for (id, sc) in &all {
- let id = id.as_str();
- if let Some((m, k)) = parse_shortcut(sc)
- && let Some(exact) = key_matches(m, k, key, modifiers)
- && (m.command || m.alt || !typing)
- && !(id == "edit.clear" && typing)
- {
- // Single-key shortcuts (W) only when not typing.
- if !m.command && !m.alt && !m.shift && typing {
- continue;
- }
- if id == "edit.clear" || (typing && matches!(id, "edit.copy" | "edit.cut" | "edit.paste" | "edit.pasteInPlace")) {
- continue; // Handled by the active tool / text clipboard events.
- }
- fired = Some((id.to_string(), exact));
- break;
+ if key == egui::Key::Escape {
+ escape = Some(modifiers);
}
}
- if let Some((id, exact)) = fired {
- // The native menu bar carries the shortcuts in effect, the user's included, and its
- // accelerator fires only for the shortcut's own key and modifiers; the Plus key standing
- // in for = never reaches it.
- if exact && app.native_shortcuts.contains(&id) {
- continue; // The native menu handles it.
+ rest.push(e);
+ }
+ crate::canvas::forwarded_keys(app, rest, modifiers);
+ if let Some(m) = escape {
+ escape_to_selection(app, egui::Key::Escape, m, typing);
+ }
+}
+
+/// Whether something other than the shortcuts has the keyboard: a dialog or Quick Apply, an input
+/// method composing at the text caret, an open canvas context menu (Escape closes it, as a
+/// native menu would) or the menu search.
+fn keys_taken(app: &DesignApp, ctx: &egui::Context) -> bool {
+ app.ui.dialog.is_some()
+ || app.ui.palette.is_some()
+ || app.session.tool_composing()
+ || crate::canvas::context_menu_open(ctx)
+ || crate::chrome::search_had_focus(ctx)
+}
+
+/// Runs the presentation key, command shortcut or tool shortcut a key press stands for. `consume`
+/// takes the press from the input where nothing else may see it. Returns whether the press was used.
+fn shortcut_key(app: &mut DesignApp, key: egui::Key, modifiers: egui::Modifiers, typing: bool, consume: &mut dyn FnMut()) -> bool {
+ // Presentation hides every control, so Esc always leaves it, and only that: the canvas must
+ // not also see the press and switch tools or deselect.
+ if key == egui::Key::Escape && app.ui.screen_mode == ScreenMode::Presentation {
+ consume();
+ let _ = app.run("view.togglePresentation", json!({}));
+ return true;
+ }
+ // Presentation goes through the spreads with the arrow keys, Page Up/Down, Home and End.
+ if app.ui.screen_mode == ScreenMode::Presentation && !modifiers.command && !modifiers.alt {
+ let step = match key {
+ egui::Key::ArrowRight | egui::Key::ArrowDown | egui::Key::PageDown => Some(1),
+ egui::Key::ArrowLeft | egui::Key::ArrowUp | egui::Key::PageUp => Some(-1),
+ egui::Key::Home => Some(isize::MIN),
+ egui::Key::End => Some(isize::MAX),
+ _ => None,
+ };
+ if let Some(step) = step {
+ consume();
+ crate::canvas::step_spread(app, step);
+ return true;
+ }
+ }
+ // Command shortcuts.
+ let mut fired: Option<(String, bool)> = None;
+ let all = effective_shortcuts(app);
+ for (id, sc) in &all {
+ let id = id.as_str();
+ if let Some((m, k)) = parse_shortcut(sc)
+ && let Some(exact) = key_matches(m, k, key, modifiers)
+ && (m.command || m.alt || !typing)
+ && !(id == "edit.clear" && typing)
+ {
+ // Single-key shortcuts (W) only when not typing.
+ if !m.command && !m.alt && !m.shift && typing {
+ continue;
}
- // The key press belongs to the shortcut: what it opens (Quick Apply's list, a dialog's
- // default button) must not see the same press as Enter or Space this frame.
- ctx.input_mut(|i| i.consume_key(modifiers, key));
- // Like choosing the menu item: "…" commands open their dialog.
- activate(app, &id, &Value::Null);
- continue;
- }
- // Tool shortcuts (single keys, Shift+key).
- if !typing && !modifiers.command && !modifiers.alt {
- let name = key.name();
- let sc = if modifiers.shift { format!("Shift+{name}") } else { name.to_string() };
- if let Some(tool) = designcraft_tools::tool_for_shortcut(&sc) {
- log::debug!("tool shortcut {sc} -> {tool}");
- if std::env::var_os("DESIGNCRAFT_DEBUG_KEYS").is_some() {
- eprintln!("tool shortcut {sc} ({key:?}, {modifiers:?}) -> {tool}");
- }
- app.select_tool(tool);
- } else if key == egui::Key::Escape && app.session.tool_id() != "selection" && !app.session.tool_busy() && app.ui.flyout.is_none() {
- app.select_tool("selection");
+ if id == "edit.clear" || (typing && matches!(id, "edit.copy" | "edit.cut" | "edit.paste" | "edit.pasteInPlace")) {
+ continue; // Handled by the active tool / text clipboard events.
+ }
+ fired = Some((id.to_string(), exact));
+ break;
+ }
+ }
+ if let Some((id, exact)) = fired {
+ // The native menu bar carries the shortcuts in effect, the user's included, and its
+ // accelerator fires only for the shortcut's own key and modifiers; the Plus key standing
+ // in for = never reaches it.
+ if exact && app.native_shortcuts.contains(&id) {
+ return true; // The native menu handles it.
+ }
+ // The key press belongs to the shortcut: what it opens (Quick Apply's list, a dialog's
+ // default button) must not see the same press as Enter or Space this frame.
+ consume();
+ // Like choosing the menu item: "…" commands open their dialog.
+ activate(app, &id, &Value::Null);
+ return true;
+ }
+ // Tool shortcuts (single keys, Shift+key).
+ if !typing && !modifiers.command && !modifiers.alt {
+ let name = key.name();
+ let sc = if modifiers.shift { format!("Shift+{name}") } else { name.to_string() };
+ if let Some(tool) = designcraft_tools::tool_for_shortcut(&sc) {
+ log::debug!("tool shortcut {sc} -> {tool}");
+ if std::env::var_os("DESIGNCRAFT_DEBUG_KEYS").is_some() {
+ eprintln!("tool shortcut {sc} ({key:?}, {modifiers:?}) -> {tool}");
}
+ app.select_tool(tool);
+ return true;
}
}
+ false
+}
+
+/// Esc with no shortcut of its own goes back to the Selection tool.
+fn escape_to_selection(app: &mut DesignApp, key: egui::Key, modifiers: egui::Modifiers, typing: bool) {
+ if key == egui::Key::Escape
+ && !typing
+ && !modifiers.command
+ && !modifiers.alt
+ && app.session.tool_id() != "selection"
+ && !app.session.tool_busy()
+ && app.ui.flyout.is_none()
+ {
+ app.select_tool("selection");
+ }
}
/// Quick Apply (⌘Return): the document's styles and every command, searched by name.
@@ -5372,7 +5428,13 @@ mod tests {
// Paragraph Styles opens floating, grouped with Character Styles, as in InDesign.
activate(&mut app, "app.paragraphStylesPanel", &Value::Null);
let layout = app.ui.docking.as_ref().unwrap();
- assert!(layout.floating.iter().flat_map(|w| &w.groups).any(|g| g.panels == ["characterStyles", "paragraphStyles"] && g.active == 1));
+ assert!(
+ layout
+ .floating
+ .iter()
+ .flat_map(crate::panel_docking::window_groups)
+ .any(|g| g.panels == ["characterStyles", "paragraphStyles"] && g.active == 1)
+ );
let story = app.run("frame.create", json!({"rect": [36, 36, 200, 100], "content": "text", "text": "Page "})).unwrap()["story"].clone();
app.run("text.select", json!({"story": story, "anchor": 5, "focus": 5})).unwrap();
activate(&mut app, "app.insertCurrentPageNumber", &Value::Null);
@@ -6099,4 +6161,29 @@ mod tests {
}
assert!(app.ui.dialog.is_some(), "clicking the empty end of the Preferences… row must choose it");
}
+
+ /// Keys a floating panel's own OS window left over run the main window's tool shortcuts,
+ /// Escape and the active tool's keys.
+ #[test]
+ fn forwarded_keys_run_shortcuts() {
+ use egui::{Event, Key, Modifiers};
+ fn press(key: Key) -> Vec<Event> {
+ [true, false].map(|pressed| Event::Key { key, physical_key: Some(key), pressed, repeat: false, modifiers: Modifiers::NONE }).to_vec()
+ }
+ let ctx = egui::Context::default();
+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.session.execute("file.new", &json!({})).unwrap();
+ let frame = app.session.execute("frame.create", &json!({"rect": [36, 36, 200, 200]})).unwrap();
+ app.session.execute("selection.set", &json!({"ids": [frame["id"]]})).unwrap();
+ forwarded_shortcuts(&mut app, &ctx, press(Key::P), Modifiers::NONE);
+ assert_ne!(app.session.tool_id(), "selection", "P picks a tool");
+ forwarded_shortcuts(&mut app, &ctx, press(Key::Escape), Modifiers::NONE);
+ assert_eq!(app.session.tool_id(), "selection", "Escape goes back to the Selection tool");
+ app.session.execute("selection.set", &json!({"ids": [frame["id"]]})).unwrap();
+ forwarded_shortcuts(&mut app, &ctx, press(Key::Delete), Modifiers::NONE);
+ assert!(
+ app.session.active().unwrap().doc.item(designcraft_doc::ItemId(frame["id"].as_u64().unwrap())).is_none(),
+ "Delete clears the selection"
+ );
+ }
}
diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs
index ab52a8017..7a9040e2e 100644
--- a/crates/ui-egui/src/panel_docking.rs
+++ b/crates/ui-egui/src/panel_docking.rs
@@ -31,6 +31,15 @@ pub(crate) fn tab_id(panel: &str) -> egui::Id {
hit_id(&craft_ui::docking::Hit::Tab(panel.to_owned()))
}
+/// The viewports of the floating windows that may have OS windows of their own. Where egui
+/// embeds viewports every floating window stays in the main window.
+pub(crate) fn native_viewports(app: &DesignApp, ctx: &egui::Context) -> Vec<egui::ViewportId> {
+ if ctx.embed_viewports() {
+ return Vec::new();
+ }
+ layout_of(app).floating.iter().map(|window| craft_ui::docking::DockArea::<String>::window_viewport(area_id(), window.id)).collect()
+}
+
/// The egui layer of the floating window whose first panel is `panel`.
#[cfg(test)]
pub(crate) fn floating_layer(panel: &str) -> egui::LayerId {
@@ -106,7 +115,7 @@ const ICON_GROUPS: &[&[&str]] = &[
&["stroke", "color", "swatches", "gradient"],
&["effects"],
&["character", "paragraph", "typography"],
- &["glyphs"],
+ &["glyphs", "story"],
&["table"],
&["textWrap"],
&["align", "pathfinder"],
@@ -170,7 +179,10 @@ pub(crate) fn default_layout(ui: &crate::UiState) -> Layout<String> {
if at.iter().all(|v| v.is_finite())
&& let Some(id) = placed.take(id)
{
- floating.push(Floating::single(vec![id], 0, [at[0], at[1], 280.0, 360.0]));
+ // The layout is rebuilt every frame, so each window keeps an id of its panel's (a
+ // native window lives as long as its id).
+ let window = default_window_id(&id);
+ floating.push(Floating::single(vec![id], 0, [at[0], at[1], 280.0, 360.0]).with_id(window));
}
}
let mut columns = Vec::new();
@@ -194,6 +206,15 @@ pub(crate) fn default_layout(ui: &crate::UiState) -> Layout<String> {
with_canvas(columns, floating)
}
+/// The window id of a default layout's floating `panel`: the same every time, with the top bit
+/// set, where craft-ui's fresh ids never reach.
+fn default_window_id(panel: &str) -> u64 {
+ use std::hash::{Hash, Hasher};
+ let mut h = std::collections::hash_map::DefaultHasher::new();
+ ("designcraft-default-float", panel).hash(&mut h);
+ h.finish() | 1 << 63
+}
+
/// 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 {
@@ -219,13 +240,8 @@ pub(crate) fn from_dock_only<'a>(
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 });
+ if let Some(root) = unplaced_tree(&window.root, 0, &mut placed) {
+ floating.push(Floating { minimized: window.minimized, ..Floating::new(root, window.rect) });
}
}
for panel in hidden {
@@ -236,6 +252,52 @@ pub(crate) fn from_dock_only<'a>(
valid(&layout).then_some(layout)
}
+/// A floating window's tree with only the panels not placed yet; a split that loses one side
+/// becomes its other side. None when no panel is left.
+fn unplaced_tree(node: &Node<String>, depth: usize, placed: &mut Placed) -> Option<Node<String>> {
+ if depth > craft_ui::docking::MAX_DEPTH {
+ return None;
+ }
+ match node {
+ Node::Tabs { panels, active } => placed.group(panels, *active).map(|g| Node::Tabs { panels: g.panels, active: g.active }),
+ Node::Stack { entries } => {
+ let entries: Vec<_> =
+ entries.iter().filter_map(|e| placed.take(&e.panel).map(|panel| craft_ui::docking::StackEntry { panel, ..e.clone() })).collect();
+ (!entries.is_empty()).then_some(Node::Stack { entries })
+ }
+ Node::Split { axis, size, first, second } => {
+ let first = unplaced_tree(first, depth.saturating_add(1), placed);
+ let second = unplaced_tree(second, depth.saturating_add(1), placed);
+ match (first, second) {
+ (Some(first), Some(second)) => Some(Node::Split { axis: *axis, size: *size, first: Box::new(first), second: Box::new(second) }),
+ (one, other) => one.or(other),
+ }
+ }
+ _ => None,
+ }
+}
+
+/// The groups of a floating window, first to last: its tab groups and accordions.
+pub(crate) fn window_groups(window: &Floating<String>) -> Vec<Group<String>> {
+ let mut out = Vec::new();
+ let mut visit = vec![(&window.root, 0usize)];
+ while let Some((node, depth)) = visit.pop() {
+ if depth > craft_ui::docking::MAX_DEPTH || out.len() > craft_ui::docking::MAX_PANELS {
+ break;
+ }
+ match node {
+ Node::Split { first, second, .. } => {
+ visit.push((second, depth.saturating_add(1)));
+ visit.push((first, depth.saturating_add(1)));
+ }
+ Node::Tabs { panels, active } => out.push(Group::new(panels.clone(), *active)),
+ Node::Stack { entries } => out.push(Group::new(entries.iter().map(|e| e.panel.clone()).collect(), 0)),
+ _ => {}
+ }
+ }
+ out
+}
+
/// 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>>> {
@@ -315,7 +377,7 @@ fn dock_columns(layout: &Layout<String>) -> Vec<&Column<String>> {
/// 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)) {
+ if let Some(group) = layout.floating.iter().flat_map(window_groups).find(|g| g.panels.iter().any(|p| p == panel)) {
return group.panels.clone();
}
let mut visit: Vec<&Node<String>> = layout.root.iter().collect();
@@ -353,7 +415,7 @@ enum Place {
fn place(layout: &Layout<String>, panel: &str) -> Option<Place> {
let has = |group: &Group<String>| group.panels.iter().any(|p| p == panel);
for (window, floating) in layout.floating.iter().enumerate() {
- if let Some(group) = floating.groups.iter().position(has) {
+ if let Some(group) = window_groups(floating).iter().position(has) {
return Some(Place::Floating { window, group });
}
}
@@ -724,6 +786,7 @@ fn known(action: &Action<String>) -> bool {
| Action::SetStackOpen { panel, .. }
| Action::ResizeStack { panel, .. } => registered(panel),
Action::ResizeSplit { path, .. } => path.len() <= craft_ui::docking::MAX_DEPTH,
+ Action::ResizeWindowSplit { panel, path, .. } => registered(panel) && path.len() <= craft_ui::docking::MAX_DEPTH,
Action::MovePanel { panel, to } | Action::MoveGroup { panel, to } | Action::MoveColumn { panel, to } | Action::MoveWindow { panel, to } => {
registered(panel)
&& match to {
@@ -738,8 +801,10 @@ fn known(action: &Action<String>) -> bool {
| Action::SetIconic { panel, .. }
| Action::ResizeColumn { panel, .. }
| Action::ResizeGroup { panel, .. }
- | Action::ResizeIconic { panel, .. } => registered(panel),
- // Native OS windows are not enabled in DesignCraft; newer actions are rejected.
+ | Action::ResizeIconic { panel, .. }
+ | Action::SetNative { panel, .. }
+ | Action::SetMonitor { panel, .. } => registered(panel),
+ // Actions newer than this list are rejected until DesignCraft checks them.
_ => false,
}
}
@@ -922,6 +987,8 @@ pub(crate) fn show(app: &mut DesignApp, ui: &mut egui::Ui) {
if let Some(panel) = focused.filter(|panel| panel == CANVAS || layout_of(app).contains(panel)) {
app.ui.docking_focused = Some(panel);
}
+ // Keys pressed in a floating panel's own OS window run the main window's shortcuts.
+ crate::menus::forwarded_shortcuts(app, ui.ctx(), output.forwarded_events, output.forwarded_modifiers.unwrap_or_default());
}
/// What the control channel reports: the layout in use (craft-ui's serialized `Layout`),
@@ -955,6 +1022,20 @@ fn dock_style(ui: &egui::Ui, language: &str) -> craft_ui::docking::DockStyle {
style.border = egui::Stroke::new(1.0, t.border);
style.accent = t.accent;
style.right_to_left = crate::i18n::is_rtl(language);
+ // InDesign's docking: new docks at the docked area's free sides, but no full-height column
+ // from the window's left or right edge; a drop on no target (the canvas) floats, and a
+ // floating window's title bar docks the whole window. No Ctrl/Cmd undock latch or hint, no
+ // Maximize Frame or Close Others items, no wheel or middle-click tab gestures.
+ style.side_edge_zones = false;
+ style.new_dock_zones = true;
+ style.float_on_empty_drop = true;
+ style.title_bar_docks = true;
+ style.command_press_floats = false;
+ style.float_hint = false;
+ style.close_others_item = false;
+ style.maximize_item = false;
+ style.wheel_selects_tabs = false;
+ style.middle_click_closes_tabs = false;
style.localized(|key| DOCK_LABELS.iter().find(|(k, _)| *k == key).map(|(_, english)| crate::i18n::tr(language, english).to_owned()))
}
@@ -979,13 +1060,9 @@ pub(crate) const DOCK_LABELS: &[(&str, &str)] = &[
("dock.expandColumn", "Expand Panels"),
("dock.moveWindow", "Move panel window"),
("dock.closeWindow", "Close panel window"),
- ("dock.undock", "Undock Panel"),
- ("dock.undockGroup", "Undock Panel Group"),
- ("dock.closePanelGroup", "Close Panel Group"),
("dock.closeOthers", "Close Other Panels in Group"),
("dock.maximize", "Maximize Frame"),
("dock.restoreFrame", "Restore Frame Size"),
- ("dock.newWindow", "Move Panel to New Window"),
("dock.autoCollapse", "Auto-Collapse Iconic Panels"),
];
@@ -1115,9 +1192,6 @@ impl craft_ui::docking::DockContent<String> for PanelContent<'_> {
crate::icons::paint(painter, rect, icon, color);
true
}
- fn bare(&self, id: &String) -> bool {
- id == CANVAS
- }
fn panel_menu(&mut self, ui: &mut egui::Ui, id: &String) {
if let Some(panel) = normalize(id) {
dock_panel_item(self.app, ui, panel);
diff --git a/crates/ui-egui/src/panel_docking_tests.rs b/crates/ui-egui/src/panel_docking_tests.rs
index e10eeb899..a8e23ce5d 100644
--- a/crates/ui-egui/src/panel_docking_tests.rs
+++ b/crates/ui-egui/src/panel_docking_tests.rs
@@ -13,7 +13,7 @@ fn panel_commands_group_split_reorder_float_and_restore_without_duplicate_owners
app.run("window.panel.move", json!({"panel":"properties", "anchor":"swatches", "before":"swatches"})).unwrap();
let before_float = app.ui.docking.clone().unwrap();
app.run("window.panel.float", json!({"panel":"properties", "x":50,"y":70,"width":330,"height":410})).unwrap();
- assert!(app.ui.docking.as_ref().unwrap().floating.iter().flat_map(|w| &w.groups).any(|g| g.panels == ["properties"]));
+ assert!(app.ui.docking.as_ref().unwrap().floating.iter().flat_map(window_groups).any(|g| g.panels == ["properties"]));
app.run("window.panel.dock", json!({"panel":"properties"})).unwrap();
assert_eq!(app.ui.docking.as_ref().unwrap(), &before_float);
app.run("window.panel.close", json!({"panel":"properties"})).unwrap();
@@ -86,12 +86,12 @@ fn ordinary_panel_tab_drag_enters_shared_docking_and_can_redock_into_another_tab
let source = h.query_all_by_label("Layers").find(|node| node.rect().height() <= 45.0).unwrap().rect().center();
drag(&mut h, source, egui::pos2(160.0, 140.0));
let layout = h.state().ui.docking.as_ref().expect("ordinary tab drag starts shared docking");
- assert!(layout.floating.iter().flat_map(|w| &w.groups).any(|g| g.panels.contains(&"layers".into())), "{layout:?}");
+ assert!(layout.floating.iter().flat_map(window_groups).any(|g| g.panels.contains(&"layers".into())), "{layout:?}");
let source = h.ctx.read_response(tab_id("layers")).unwrap().rect.center();
let destination = h.ctx.read_response(tab_id("properties")).unwrap().rect.center();
drag(&mut h, source, destination);
let layout = h.state().ui.docking.as_ref().unwrap();
- assert!(!layout.floating.iter().flat_map(|w| &w.groups).any(|g| g.panels.contains(&"layers".into())));
+ assert!(!layout.floating.iter().flat_map(window_groups).any(|g| g.panels.contains(&"layers".into())));
assert!(valid(layout));
assert_eq!(h.state().ui.docking_focused.as_deref(), Some("layers"), "the user's drag keeps the focus on the panel it moved");
}
@@ -661,7 +661,7 @@ fn paragraph_styles_open_floating_with_character_styles() {
let mut app = app();
app.run("window.panel", json!({"panel":"paragraphStyles"})).unwrap();
let layout = app.ui.docking.clone().unwrap();
- let group = layout.floating.iter().flat_map(|w| &w.groups).find(|g| g.panels.iter().any(|p| p == "paragraphStyles")).expect("a floating group");
+ let group = layout.floating.iter().flat_map(window_groups).find(|g| g.panels.iter().any(|p| p == "paragraphStyles")).expect("a floating group");
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.
@@ -671,11 +671,11 @@ fn paragraph_styles_open_floating_with_character_styles() {
app.run("window.panel", json!({"panel":"color"})).unwrap();
app.run("window.panel", json!({"panel":"links"})).unwrap();
let layout = app.ui.docking.clone().unwrap();
- assert!(layout.floating.iter().flat_map(|w| &w.groups).any(|g| g.panels == ["characterStyles", "paragraphStyles"]));
+ assert!(layout.floating.iter().flat_map(window_groups).any(|g| g.panels == ["characterStyles", "paragraphStyles"]));
// Once showing, Window › Character Styles brings that tab forward.
app.run("window.panel", json!({"panel":"characterStyles"})).unwrap();
let layout = app.ui.docking.clone().unwrap();
- let group = layout.floating.iter().flat_map(|w| &w.groups).find(|g| g.panels.iter().any(|p| p == "characterStyles")).unwrap();
+ let group = layout.floating.iter().flat_map(window_groups).find(|g| g.panels.iter().any(|p| p == "characterStyles")).unwrap();
assert_eq!(group.panels[group.active], "characterStyles");
assert_eq!(layout.panels().iter().filter(|p| p.as_str() == "characterStyles").count(), 1);
}
@@ -694,7 +694,7 @@ fn paragraph_styles_closed_from_the_dock_reopen_there() {
app.run("window.panel", json!({"panel":"paragraphStyles"})).unwrap();
let layout = app.ui.docking.clone().unwrap();
assert!(layout.contains(&"paragraphStyles".to_string()));
- assert!(layout.floating.iter().flat_map(|w| &w.groups).all(|g| !g.panels.iter().any(|p| p == "paragraphStyles")), "{:?}", layout.floating);
+ assert!(layout.floating.iter().flat_map(window_groups).all(|g| !g.panels.iter().any(|p| p == "paragraphStyles")), "{:?}", layout.floating);
}
fn click(h: &mut Harness<'static, DesignApp>, at: Pos2, button: PointerButton) {
@@ -737,18 +737,18 @@ fn pages_keeps_its_panel_menu_in_the_docking_layout() {
assert!(h.query_by_label("Panel Options…").is_none(), "the panel's own commands stay in its panel menu");
}
-fn group_with<'a>(layout: &'a Layout<String>, panel: &str) -> (bool, &'a [String], usize) {
- if let Some(g) = layout.floating.iter().flat_map(|w| &w.groups).find(|g| g.panels.iter().any(|p| p == panel)) {
- return (true, &g.panels, g.active);
+fn group_with(layout: &Layout<String>, panel: &str) -> (bool, Vec<String>, usize) {
+ if let Some(g) = layout.floating.iter().flat_map(window_groups).find(|g| g.panels.iter().any(|p| p == panel)) {
+ return (true, g.panels, g.active);
}
let mut visit: Vec<&Node<String>> = layout.root.iter().collect();
while let Some(node) = visit.pop() {
match node {
Node::Split { first, second, .. } => visit.extend([&**first, &**second]),
- Node::Tabs { panels, active } if panels.iter().any(|p| p == panel) => return (false, panels, *active),
+ Node::Tabs { panels, active } if panels.iter().any(|p| p == panel) => return (false, panels.clone(), *active),
Node::Dock { columns, .. } => {
if let Some(g) = columns.iter().flat_map(|c| &c.groups).find(|g| g.panels.iter().any(|p| p == panel)) {
- return (false, &g.panels, g.active);
+ return (false, g.panels.clone(), g.active);
}
}
_ => {}
@@ -771,13 +771,13 @@ fn dragging_a_docked_group_by_its_bar_moves_every_tab() {
let below = json!({"MoveGroup": {"panel": "characterStyles", "to": {"At": {"anchor": "properties", "placement": {"Group": {"below": true}}}}}});
app.run("window.panel.layout", json!({"action": below})).unwrap();
let styles = ["characterStyles", "paragraphStyles"];
- assert_eq!(group_with(app.ui.docking.as_ref().unwrap(), "characterStyles"), (false, &styles.map(String::from)[..], 1));
+ assert_eq!(group_with(app.ui.docking.as_ref().unwrap(), "characterStyles"), (false, styles.map(String::from).to_vec(), 1));
let mut h = harness(app, vec2(1280.0, 800.0));
let bar = drag_bar(&h, "characterStyles");
drag(&mut h, bar.center(), egui::pos2(400.0, 400.0));
let layout = h.state().ui.docking.as_ref().unwrap();
- assert_eq!(group_with(layout, "paragraphStyles"), (true, &styles.map(String::from)[..], 1), "{layout:?}");
+ assert_eq!(group_with(layout, "paragraphStyles"), (true, styles.map(String::from).to_vec(), 1), "{layout:?}");
assert!(valid(layout));
let bar = drag_bar(&h, "characterStyles");
@@ -1002,7 +1002,7 @@ fn shared_panel_commands_float_dock_and_reject_atomically() {
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"]);
+ assert_eq!(window_groups(&layout.floating[0])[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());
@@ -1157,3 +1157,44 @@ fn a_floating_window_saved_in_the_title_bar_strip_is_drawn_below_it() {
let drawn = h.ctx.memory(|m| m.area_rect(crate::panel_docking::floating_layer("properties").id)).unwrap();
assert!(drawn.min.y >= crate::chrome::MAC_APP_BAR - 0.5, "{drawn:?}");
}
+
+/// A floating window holds splits like the dock: a panel docked below another one in the
+/// window splits it, the divider between them drags, and the new size is saved.
+#[test]
+fn a_split_inside_a_floating_window_resizes_and_is_saved() {
+ let mut app = app();
+ app.run("window.panel.float", json!({"panel":"swatches", "x":300, "y":120, "width":300, "height":500})).unwrap();
+ app.run("window.panel.move", json!({"panel":"color", "anchor":"swatches", "zone":"bottom"})).unwrap();
+ let window = |app: &DesignApp| app.ui.docking.as_ref().unwrap().floating.iter().find(|w| w.contains("swatches")).cloned().unwrap();
+ let ratio = |window: &Floating<String>| match window.root {
+ Node::Split { size: craft_ui::layout::SplitSize::Ratio(r), .. } => r,
+ ref root => panic!("expected a split window: {root:?}"),
+ };
+ assert_eq!(window_groups(&window(&app)).into_iter().map(|g| g.panels).collect::<Vec<_>>(), [["swatches"], ["color"]]);
+ let before = ratio(&window(&app));
+ let mut h = harness(app, vec2(1400.0, 900.0));
+ let divider = hits(&h)
+ .into_iter()
+ .find_map(|(hit, rect)| {
+ matches!(&hit, craft_ui::docking::Hit::Divider(craft_ui::docking::Divider::WindowSplit(_, path)) if path.is_empty()).then_some(rect)
+ })
+ .expect("the window's divider");
+ drag(&mut h, divider.center(), divider.center() + vec2(0.0, 60.0));
+ let after = ratio(&window(h.state()));
+ assert!(after > before + 0.05, "{before} -> {after}");
+ let saved = serde_json::to_vec(&h.state().ui).unwrap();
+ let loaded = crate::UiState::from_preferences_json(&saved).unwrap();
+ assert_eq!(loaded.docking, h.state().ui.docking);
+}
+
+/// The default layout is rebuilt every frame: its floating windows keep their ids, so their
+/// native windows aren't opened again each frame.
+#[test]
+fn default_layout_floats_keep_their_window_ids() {
+ let mut app = app();
+ app.ui.floating = vec![("swatches".to_string(), [10.0, 20.0])];
+ let ids = |app: &DesignApp| default_layout(&app.ui).floating.iter().map(|w| w.id).collect::<Vec<_>>();
+ let first = ids(&app);
+ assert_eq!(first.len(), 1, "Swatches floats");
+ assert_eq!(ids(&app), first);
+}
diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs
index 0e7273a00..fd7f198a2 100644
--- a/crates/ui-egui/src/prefs.rs
+++ b/crates/ui-egui/src/prefs.rs
@@ -202,7 +202,7 @@ mod tests {
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!(crate::panel_docking::window_groups(&layout.floating[0])[0].panels, ["glyphs"]);
assert_eq!(&layout.floating[0].rect[..2], &[100.0, 120.0]);
}
@@ -284,8 +284,8 @@ mod tests {
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!(crate::panel_docking::window_groups(&layout.floating[0])[0].panels, ["glyphs", "character"]);
+ assert_eq!(crate::panel_docking::window_groups(&layout.floating[0])[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");
@@ -300,6 +300,40 @@ mod tests {
assert_eq!(again.docking, app.ui.docking);
}
+ /// Floating windows saved as a stack of groups (`groups`, before floating windows held split
+ /// trees) load as a vertical split of the groups in order, sized by their heights; a window
+ /// whose groups were all minimized loads minimized.
+ #[test]
+ fn floating_stacks_of_groups_load_as_split_windows() {
+ let mut saved = serde_json::to_value(UiState::default()).unwrap();
+ let mut docking = serde_json::to_value(crate::panel_docking::default_layout(&UiState::default())).unwrap();
+ docking["floating"] = json!([
+ {"groups": [
+ {"panels": ["swatches", "color"], "active": 1, "minimized": false, "height": 300.0},
+ {"panels": ["stroke"], "active": 0, "minimized": false, "height": 100.0},
+ ], "rect": [400.0, 100.0, 280.0, 440.0]},
+ {"groups": [{"panels": ["glyphs"], "active": 0, "minimized": true, "height": null}], "rect": [40.0, 60.0, 300.0, 400.0]},
+ ]);
+ docking["root"]["Split"]["second"]["Dock"]["columns"][1]["groups"] = json!([{"panels": ["effects"], "active": 0}]);
+ saved["docking"] = docking;
+ let read = UiState::read_preferences(&serde_json::to_vec(&saved).unwrap()).unwrap();
+ assert!(read.intact);
+ let layout = read.ui.docking.clone().unwrap();
+ dock(&layout);
+ let Node::Split { axis: craft_ui::layout::SplitAxis::Vertical, size: craft_ui::layout::SplitSize::Ratio(ratio), first, second } =
+ &layout.floating[0].root
+ else {
+ panic!("expected a vertical split: {:?}", layout.floating[0]);
+ };
+ assert!((ratio - 0.75).abs() < 1e-4, "{ratio}");
+ assert_eq!(**first, Node::Tabs { panels: vec!["swatches".into(), "color".into()], active: 1 });
+ assert_eq!(**second, Node::Tabs { panels: vec!["stroke".into()], active: 0 });
+ assert_eq!(layout.floating[0].rect, [400.0, 100.0, 280.0, 440.0]);
+ assert!(!layout.floating[0].minimized && layout.floating[1].minimized);
+ let again = UiState::from_preferences_json(&serde_json::to_vec(&read.ui).unwrap()).unwrap();
+ assert_eq!(again.docking, read.ui.docking);
+ }
+
/// An old layout that cannot be converted gives way to the workspace's default and is
/// reported, so the file it came from is kept.
#[test]
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 0d36c021a..dbc7c8d16 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -75,8 +75,9 @@ to finish before retrying a request that would exceed the pending-event limit.
## Shared panel docking
Panel arrangements support tab grouping and reordering, horizontal and vertical splits,
-and movable, resizable floating groups inside the application window. Drag a panel tab,
-or use its context menu. Floating groups remain within the application viewport.
+and movable, resizable floating windows inside the application window. A floating window
+holds tab groups split side by side or one above another, like the dock area. Drag a panel
+tab, or use its context menu. Floating windows remain within the application viewport.
The window is one panel layout: the protected `canvas` panel (the document area) beside a
dock at the logical end edge, the right in left-to-right languages and the left in
@@ -147,8 +148,12 @@ invalid destinations return an error without changing the arrangement.
`window.panel.layout {action}` also accepts the shared, externally tagged action schema.
For example, `{"action":{"MoveFloating":{"panel":"properties","rect":[44,66,360,450]}}}`
-updates a floating group's position and size; `{"action":{"ResizeSplit":{"path":[],"size":{"Ratio":0.35}}}}`
-resizes the root divider (`false`/`true` path entries select first/second children).
+updates a floating window's position and size; `{"action":{"ResizeSplit":{"path":[],"size":{"Ratio":0.35}}}}`
+resizes the root divider (`false`/`true` path entries select first/second children), and
+`{"action":{"ResizeWindowSplit":{"panel":"swatches","path":[],"size":{"Ratio":0.6}}}}` resizes
+a divider in the floating window that holds `panel`, by its path from the window's root.
+Floating windows saved as a stack of groups (`{"groups": […], "rect": […]}`) load as groups
+one above another, sized by their saved heights.
`Move` with `placement: {"Tab":{"before":"swatches"}}` reorders tabs, and
`SetStackOpen {panel,open}` / `ResizeStack {panel,height}` control accordion entries.
The UI dispatches these same commands. Unknown panel IDs, invalid geometry, and stale